Example #1
1
		public RepositoryFile(IRepository repository, String path, RepositoryStatus contentsStatus, RepositoryStatus propertiesStatus)
		{
			if (path == null)
				throw new ArgumentNullException("path");
			if (path.Trim().Length == 0)
				throw new ArgumentException("Path must be set to a valid path", "path");
			if (path[path.Length-1] == '/')
				throw new ArgumentException("Path must be set to a file, not a directory", "path");
			if (propertiesStatus == RepositoryStatus.Added ||
				propertiesStatus == RepositoryStatus.Deleted)
			{
				throw new ArgumentException("Properties status cannot be set to Added or Deleted, use Updated", "propertiesStatus");
			}
			
			this.contentsStatus = contentsStatus;
			this.propertiesStatus = propertiesStatus;
			this.repository = repository;
			SetPathRelatedFields(path);

			if (fileName.EndsWith(" "))
				throw new ArgumentException("Filename cannot end with trailing spaces", "path");

			if (fileName.StartsWith(" "))
				throw new ArgumentException("Filename cannot begin with leading spaces", "path");

		}
Example #2
0
        public void CanRetrieveTheStatusOfARelativeWorkingDirectory()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                const string file      = "just_a_dir/other.txt";
                const string otherFile = "just_a_dir/another_dir/other.txt";

                Touch(repo.Info.WorkingDirectory, file);
                Touch(repo.Info.WorkingDirectory, otherFile);

                RepositoryStatus status = repo.RetrieveStatus(new StatusOptions()
                {
                    PathSpec = new[] { "just_a_dir" }
                });
                Assert.Equal(2, status.Count());
                Assert.Equal(2, status.Untracked.Count());

                status = repo.RetrieveStatus(new StatusOptions()
                {
                    PathSpec = new[] { "just_a_dir/another_dir" }
                });
                Assert.Equal(1, status.Count());
                Assert.Equal(1, status.Untracked.Count());
            }
        }
Example #3
0
        public void CanRetrieveTheStatusOfRenamedFilesInWorkDir()
        {
            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, "old_name.txt",
                      "This is a file with enough data to trigger similarity matching.\r\n" +
                      "This is a file with enough data to trigger similarity matching.\r\n" +
                      "This is a file with enough data to trigger similarity matching.\r\n" +
                      "This is a file with enough data to trigger similarity matching.\r\n");

                Commands.Stage(repo, "old_name.txt");

                File.Move(Path.Combine(repo.Info.WorkingDirectory, "old_name.txt"),
                          Path.Combine(repo.Info.WorkingDirectory, "rename_target.txt"));

                RepositoryStatus status = repo.RetrieveStatus(
                    new StatusOptions()
                {
                    DetectRenamesInIndex   = true,
                    DetectRenamesInWorkDir = true
                });

                Assert.Equal(FileStatus.NewInIndex | FileStatus.RenamedInWorkdir, status["rename_target.txt"].State);
                Assert.Equal(100, status["rename_target.txt"].IndexToWorkDirRenameDetails.Similarity);
            }
        }
Example #4
0
 public static bool HasUnstagedChanges(this RepositoryStatus status)
 {
     return(status.Untracked.Any() ||
            status.Modified.Any() ||
            status.Missing.Any() ||
            status.RenamedInWorkDir.Any());
 }
Example #5
0
        /// <summary>
        /// Méthode qui réalise la commande pull de Git
        /// Cette méthode prend en priorité le fichier sur le serveur
        /// en cas de conflit
        /// </summary>
        public void pullContent()
        {
            if (_gitRepoIsOk)
            {
                try
                {
                    RepositoryStatus repoStatus = _repository.RetrieveStatus();

                    if (!repoStatus.IsDirty)
                    {
                        PullOptions pullOptions = new PullOptions()
                        {
                            MergeOptions = new MergeOptions()
                            {
                                FastForwardStrategy  = FastForwardStrategy.Default,
                                FileConflictStrategy = CheckoutFileConflictStrategy.Theirs
                            }
                        };

                        LibGit2Sharp.Commands.Pull(_repository, _signature, pullOptions);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error PULL : \n" + e.ToString());
                }
            }
        }
Example #6
0
 public static bool HasStagedChanges(this RepositoryStatus status)
 {
     return(status.Added.Any() ||
            status.Staged.Any() ||
            status.Removed.Any() ||
            status.RenamedInIndex.Any());
 }
        public RepositoryFile(IRepository repository, String path, RepositoryStatus contentsStatus, RepositoryStatus propertiesStatus)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if (path.Trim().Length == 0)
            {
                throw new ArgumentException("Path must be set to a valid path", "path");
            }
            if (path[path.Length - 1] == '/')
            {
                throw new ArgumentException("Path must be set to a file, not a directory", "path");
            }
            if (propertiesStatus == RepositoryStatus.Added ||
                propertiesStatus == RepositoryStatus.Deleted)
            {
                throw new ArgumentException("Properties status cannot be set to Added or Deleted, use Updated", "propertiesStatus");
            }

            this.contentsStatus   = contentsStatus;
            this.propertiesStatus = propertiesStatus;
            this.repository       = repository;
            SetPathRelatedFields(path);

            if (fileName.EndsWith(" "))
            {
                throw new ArgumentException("Filename cannot end with trailing spaces", "path");
            }

            if (fileName.StartsWith(" "))
            {
                throw new ArgumentException("Filename cannot begin with leading spaces", "path");
            }
        }
Example #8
0
        public void RetrievingTheStatusOfARepositoryReturnNativeFilePaths()
        {
            // Build relative path
            string relFilePath = Path.Combine("directory", "Testfile.txt");

            // Open the repository
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Touch(repo.Info.WorkingDirectory, relFilePath, "Anybody out there?");

                // Add the file to the index
                Commands.Stage(repo, relFilePath);

                // Get the repository status
                RepositoryStatus repoStatus = repo.RetrieveStatus();

                Assert.Equal(1, repoStatus.Count());
                StatusEntry statusEntry = repoStatus.Single();

                Assert.Equal(relFilePath, statusEntry.FilePath);

                Assert.Equal(statusEntry.FilePath, repoStatus.Added.Select(s => s.FilePath).Single());
            }
        }
Example #9
0
        public void commit()
        {
            Commit commit = null;

            try {
                using (Repository repo = new Repository(solution_path))
                {
                    RepositoryStatus status = repo.RetrieveStatus();
                    var author = new Signature(page.author, page.email, DateTimeOffset.Now);
                    if (status.IsDirty)
                    {
                        Func <IEnumerable <StatusEntry>, IEnumerable <string> > get_file_paths = entries => entries.Select(mods => mods.FilePath);
                        List <string> file_paths = get_file_paths(status.Missing)
                                                   .Union(get_file_paths(status.Modified))
                                                   .Union(get_file_paths(status.Removed))
                                                   .Union(get_file_paths(status.RenamedInIndex))
                                                   .Union(get_file_paths(status.RenamedInWorkDir))
                                                   .Union(get_file_paths(status.Untracked))
                                                   .ToList();
                        Commands.Stage(repo, file_paths);
                        commit = repo.Commit(string.Format("auto commit - updated: {0}", string.Join(",", file_paths)), author, author);
                    }
                }
            }
            catch (Exception ex)
            {
                _alert(string.Format(CultureInfo.CurrentCulture, "Commit {0} Error {1}", commit, ex.Message));
            }
        }
Example #10
0
        void Window_Loaded(object sender, RoutedEventArgs e)
        {
            args = Environment.GetCommandLineArgs();
            gitCommand.DoEvents(this.Dispatcher);
            if (args.Count() > 0)
            {
                this.Title = "Agregando archivos al indice";
                gitCommand       g      = new gitCommand(args[1].ToString());
                RepositoryStatus status = g.getStatus();

                var estados = from y in status
                              where y.State == FileStatus.Untracked
                              select y;

                int total = estados.Count();
                if (total == 0)
                {
                    this.Close();
                }
                else
                {
                    lblEstado.Content += total.ToString();
                }
            }
        }
Example #11
0
        /// <summary>
        /// Gets the modifications.
        /// </summary>
        /// <param name="from">From.</param>
        /// <param name="to">To.</param>
        /// <returns>List of modifications since the last run.</returns>
        /// <remarks></remarks>
        public override Modification[] GetModifications(IIntegrationResult from, IIntegrationResult to)
        {
            RepositoryStatus result = HgCreateLocalRepository(to);

            if (result == RepositoryStatus.Created)
            {
                Log.Debug("[Mercurial] new repository created.");
                return(new Modification[0]);
            }

            if (!string.IsNullOrEmpty(Repository))
            {
                HgPull(to);
            }

            int parent = GetSmallestParentId(to);
            int tip    = GetTipId(to);

            if (result == RepositoryStatus.AlreadyExists && (parent == tip))
            {
                Log.Debug("[Mercurial] no new changesets detected.");
                return(new Modification[0]);
            }

            Modification[] modifications = ParseModifications(HgLog(to, parent + 1, tip), from.StartTime, to.StartTime);

            if (UrlBuilder != null)
            {
                UrlBuilder.SetupModification(modifications);
            }

            return(modifications);
        }
        /// <summary>
        /// Gives the complete repository status
        /// </summary>
        /// <param name="org">Unique identifier of the organisation responsible for the app.</param>
        /// <param name="repository">The name of repository</param>
        /// <returns>The repository status</returns>
        public RepoStatus RepositoryStatus(string org, string repository)
        {
            RepoStatus repoStatus = new RepoStatus();

            repoStatus.ContentStatus = new List <RepositoryContent>();
            string localServiceRepoFolder = _settings.GetServicePath(org, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext));

            using (var repo = new LibGit2Sharp.Repository(localServiceRepoFolder))
            {
                RepositoryStatus status = repo.RetrieveStatus(new LibGit2Sharp.StatusOptions());
                foreach (StatusEntry item in status)
                {
                    RepositoryContent content = new RepositoryContent();
                    content.FilePath   = item.FilePath;
                    content.FileStatus = (Altinn.Studio.Designer.Enums.FileStatus)(int) item.State;
                    if (content.FileStatus == Enums.FileStatus.Conflicted)
                    {
                        repoStatus.RepositoryStatus = Enums.RepositoryStatus.MergeConflict;
                        repoStatus.HasMergeConflict = true;
                    }

                    repoStatus.ContentStatus.Add(content);
                }

                LibGit2Sharp.Branch branch = repo.Branches.FirstOrDefault(b => b.IsTracking == true);
                if (branch != null)
                {
                    repoStatus.AheadBy  = branch.TrackingDetails.AheadBy;
                    repoStatus.BehindBy = branch.TrackingDetails.BehindBy;
                }
            }

            return(repoStatus);
        }
        private async Task GitCode()
        {
            CloneOptions options = new CloneOptions();

            options.RepositoryOperationCompleted = new LibGit2Sharp.Handlers.RepositoryOperationCompleted(GotCode);
            Progress = 0;
            if (!Directory.Exists($"./{SelectedConfig.Name}"))
            {
                Repository.Clone(SelectedConfig.Git, $"./{SelectedConfig.Name}", options);
            }
            else
            {
                if (!Repository.IsValid($"./{SelectedConfig.Name}"))
                {
                    Directory.Delete($"./{SelectedConfig.Name}", true);
                    Repository.Clone(SelectedConfig.Git, $"./{SelectedConfig.Name}", options);
                }
                else
                {
                    using (Repository repo = new Repository($"./{SelectedConfig.Name}"))
                    {
                        RepositoryStatus status = repo.RetrieveStatus();
                        if (status.IsDirty)
                        {
                            repo.Reset(ResetMode.Hard);
                        }
                        Commands.Pull(repo, new Signature(new Identity("random", "*****@*****.**"), DateTimeOffset.Now), new PullOptions());
                    }
                    CompileSketch();
                }
            }
        }
Example #14
0
        public void git_commit(string name, string email, string message)
        {
            feed.Logs.WriteText("Commit", "Se hace commit normal de " + this.NombreProyecto);
            //repo.Index.Remove(estado.FilePath,false);
            Commit           newC   = null;
            RepositoryStatus status = getStatus();

            if (status.Modified.Count() > 0)
            {
                foreach (var archivo in status.Modified)
                {
                    repo.Index.Stage(archivo);
                }
            }

            if (status.Modified.Count() > 0 || status.Staged.Count() > 0 ||
                status.Removed.Count() > 0 || status.Added.Count() > 0 || status.Missing.Count() > 0)
            {
                Signature signature = new Signature(name, email, DateTimeOffset.Now);
                try
                {
                    newC = repo.Commit(message, signature, signature, false);
                    // newC.Parents
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    newC = repo.Commit(message, signature, signature, true);
                }
            }
        }
Example #15
0
 public override void Run(Result result, ScanResult scanResult)
 {
     foreach (var gitRepository in scanResult.Repositories)
     {
         using (var repo = new Repository(gitRepository.DirectoryInfo.FullName))
         {
             StatusOptions options = new StatusOptions();
             options.Show = StatusShowOption.IndexAndWorkDir;
             options.DetectRenamesInIndex   = true;
             options.DetectRenamesInWorkDir = true;
             options.RecurseIgnoredDirs     = true;
             RepositoryStatus status = repo.RetrieveStatus(options);
             if (!status.IsDirty)
             {
                 string gitPath = ConfigurationManager.AppSettings["GitPath"];
                 if (!String.IsNullOrWhiteSpace(gitPath))
                 {
                     ProcessStartInfo psi = new ProcessStartInfo();
                     psi.FileName         = gitPath;
                     psi.WorkingDirectory = gitRepository.DirectoryInfo.FullName;
                     psi.Arguments        = String.Format("clean -xdf \"{0}\"", gitRepository.DirectoryInfo.FullName);
                     Process.Start(psi);
                 }
             }
             else
             {
                 result.AddResultItem(gitRepository, Domain.Enums.EMessageLevel.Warning, "Cannot clean - there are uncommitted changes");
             }
         }
     }
 }
Example #16
0
        public void RetrievingTheStatusOfARepositoryReturnNativeFilePaths()
        {
            // Initialize a new repository
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();

            const string directoryName = "directory";
            const string fileName      = "Testfile.txt";

            // Create a file and insert some content
            string directoryPath = Path.Combine(scd.RootedDirectoryPath, directoryName);
            string filePath      = Path.Combine(directoryPath, fileName);

            Directory.CreateDirectory(directoryPath);
            File.WriteAllText(filePath, "Anybody out there?");

            // Open the repository
            using (Repository repo = Repository.Init(scd.DirectoryPath))
            {
                // Add the file to the index
                repo.Index.Stage(filePath);

                // Get the repository status
                RepositoryStatus repoStatus = repo.Index.RetrieveStatus();

                Assert.Equal(1, repoStatus.Count());
                StatusEntry statusEntry = repoStatus.Single();

                Assert.Equal(Path.Combine(directoryName, fileName), statusEntry.FilePath);

                Assert.Equal(statusEntry.FilePath, repoStatus.Added.Single());
            }
        }
Example #17
0
        protected override void ProcessRecord()
        {
            using (RepositoryParameter container = UseOrDiscoverRepository(Repository))
            {
                String[] paths = ArrayUtil.Combine(Path, LiteralPath);

                if (paths != null)
                {
                    foreach (String path in paths)
                    {
                        FileStatus state = container.Repository.RetrieveStatus(path);
                        WriteObject(new GitFileSystemStatusEntry(container.Repository.Info.WorkingDirectory, SessionState.Path.CurrentFileSystemLocation.Path, path, state));
                    }
                }
                else
                {
                    RepositoryStatus status = container.Repository.RetrieveStatus();

                    foreach (StatusEntry entry in status)
                    {
                        WriteObject(new GitFileSystemStatusEntry(container.Repository.Info.WorkingDirectory, SessionState.Path.CurrentFileSystemLocation.Path, entry.FilePath, entry.State));
                    }
                }
            }
        }
Example #18
0
 public void Combine(RepositoryStatus other)
 {
     foreach (var otherEntry in other)
     {
         Update(otherEntry.FilePath, otherEntry.State);
     }
 }
Example #19
0
        public void AddAll_New_File_And_New_Directory_With_File()
        {
            // test AddAll with one file, one new directory and a new file inside that directory
            var workingDirectory = Path.Combine(trash.FullName, "test");

            using (var repo = Repository.Init(workingDirectory))
            {
                var filePath  = Path.Combine(repo.WorkingDirectory, "testfile.txt");
                var dirPath   = Path.Combine(repo.WorkingDirectory, "testdir");
                var filePath2 = Path.Combine(dirPath, "testfile.txt");
                File.WriteAllText(filePath, "Unadded file");
                Directory.CreateDirectory(dirPath);
                File.WriteAllText(filePath2, "Unadded file");
                repo.Index.AddAll();
                var status = new RepositoryStatus(repo);
                Assert.IsTrue(status.AnyDifferences);
                // there should be 2 added files
                Assert.AreEqual(2, status.Added.Count);
                // the added file must be the file that was just added
                status.Added.Contains(filePath);
                status.Added.Contains(filePath2);
                status.Added.Contains(dirPath);
                // no other changes
                Assert.AreEqual(0, status.Untracked.Count);
                Assert.AreEqual(0, status.Staged.Count);
                Assert.AreEqual(0, status.Missing.Count);
                Assert.AreEqual(0, status.Modified.Count);
                Assert.AreEqual(0, status.Removed.Count);
            }
        }
Example #20
0
        public void AddAll_Ignore_Files()
        {
            // test AddAll files added to the DOT_IGNORE file
            var workingDirectory = Path.Combine(trash.FullName, "test");

            using (var repo = Repository.Init(workingDirectory))
            {
                var ignoreFilePath = Path.Combine(repo.WorkingDirectory, GitSharp.Core.Constants.GITIGNORE_FILENAME);
                // add the name of the test file to the ignore list
                File.WriteAllText(ignoreFilePath, "*.txt");
                repo.Index.Add(ignoreFilePath);
                repo.Commit("Committing .gitignore file so it won't show up as untracked file");
                var filePath = Path.Combine(repo.WorkingDirectory, "testfile.txt");
                File.WriteAllText(filePath, "Unadded file");
                repo.Index.AddAll();
                var status = new RepositoryStatus(repo);
                // no changes are the file should be ignored
                Assert.IsFalse(status.AnyDifferences);
                // there should be 0 added file
                Assert.AreEqual(0, status.Added.Count);
                // no other changes
                Assert.AreEqual(0, status.Untracked.Count);
                Assert.AreEqual(0, status.Staged.Count);
                Assert.AreEqual(0, status.Missing.Count);
                Assert.AreEqual(0, status.Modified.Count);
                Assert.AreEqual(0, status.Removed.Count);
            }
        }
Example #21
0
        public static List <RepositoryStatus> GetGitReposInDir(string rootFolder)
        {
            var detectedRepos = new List <RepositoryStatus>();

            if (Directory.Exists(rootFolder))
            {
                var repos = Directory.GetDirectories(rootFolder);

                foreach (var repo in repos)
                {
                    var path = $"{repo}\\.git";

                    if (Directory.Exists(path))
                    {
                        var repoName = GetRepoName(rootFolder, repo);

                        var repoStatus = new RepositoryStatus(repoName, path);

                        detectedRepos.Add(repoStatus);
                    }
                }
            }

            return(detectedRepos);
        }
Example #22
0
        public void RetrievingTheStatusOfARepositoryReturnNativeFilePaths()
        {
            // Initialize a new repository
            SelfCleaningDirectory scd = BuildSelfCleaningDirectory();

            const string directoryName = "directory";
            const string fileName      = "Testfile.txt";

            // Create a file and insert some content
            string directoryPath = Path.Combine(scd.RootedDirectoryPath, directoryName);
            string filePath      = Path.Combine(directoryPath, fileName);

            Directory.CreateDirectory(directoryPath);
            File.WriteAllText(filePath, "Anybody out there?");

            // Open the repository
            using (var repo = Repository.Init(scd.DirectoryPath))
            {
                // Add the file to the index
                repo.Index.Stage(filePath);

                // Get the repository status
                RepositoryStatus repoStatus = repo.Index.RetrieveStatus();

                repoStatus.Count().ShouldEqual(1);
                var statusEntry = repoStatus.Single();

                string expectedPath = string.Format("{0}{1}{2}", directoryName, Path.DirectorySeparatorChar, fileName);
                statusEntry.FilePath.ShouldEqual(expectedPath);

                repoStatus.Added.Single().ShouldEqual(statusEntry.FilePath);
            }
        }
Example #23
0
        public void RetrievingTheStatusOfTheRepositoryHonorsTheGitIgnoreDirectivesThroughoutDirectories()
        {
            char dirSep = Path.DirectorySeparatorChar;

            string path = SandboxStandardTestRepo();

            using (var repo = new Repository(path))
            {
                Touch(repo.Info.WorkingDirectory, "bin/look-ma.txt", "I'm going to be ignored!");
                Touch(repo.Info.WorkingDirectory, "bin/what-about-me.txt", "Huh?");

                const string gitIgnore = ".gitignore";
                Touch(repo.Info.WorkingDirectory, gitIgnore, "bin");

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/look-ma.txt"));
                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/what-about-me.txt"));

                RepositoryStatus newStatus = repo.RetrieveStatus();
                Assert.Equal(new[] { "bin" + dirSep }, newStatus.Ignored.Select(s => s.FilePath));

                var sb = new StringBuilder();
                sb.AppendLine("bin/*");
                sb.AppendLine("!bin/w*");
                Touch(repo.Info.WorkingDirectory, gitIgnore, sb.ToString());

                Assert.Equal(FileStatus.Ignored, repo.RetrieveStatus("bin/look-ma.txt"));
                Assert.Equal(FileStatus.NewInWorkdir, repo.RetrieveStatus("bin/what-about-me.txt"));

                newStatus = repo.RetrieveStatus();

                Assert.Equal(new[] { "bin" + dirSep + "look-ma.txt" }, newStatus.Ignored.Select(s => s.FilePath));
                Assert.True(newStatus.Untracked.Select(s => s.FilePath).Contains("bin" + dirSep + "what-about-me.txt"));
            }
        }
Example #24
0
        public static string ToCommitMessage(this RepositoryStatus status)
        {
            var stringBuilder = new StringBuilder();
            var lastState     = (string)null;

            foreach (var state in status.OrderBy(s => s.State))
            {
                var thisState = state.State.ToReadableString();
                if (thisState == lastState)
                {
                    stringBuilder.Append($", {Path.GetFileName(state.FilePath)}");
                    continue;
                }

                stringBuilder.Append($"{(lastState == null ? string.Empty : ", ")}{thisState}: {Path.GetFileName(state.FilePath)}");
                lastState = thisState;
            }

            var commitMessage = stringBuilder.ToString();

            if (commitMessage.Length <= MaxCommitMessageLength)
            {
                return(commitMessage);
            }

            const string newlineInsert = "...\n\n";

            commitMessage = commitMessage[..(MaxCommitMessageLength - 3)] + newlineInsert + commitMessage[(MaxCommitMessageLength - 3)..];
        protected override void ExecuteImpl(string[] args)
        {
            var diffs = FindChangedVersions();

            if (diffs.Count != 1)
            {
                throw new UserErrorException($"Can only automate a single-package release commit with exactly 1 release. Found {diffs.Count}. Did you mean 'commit-multiple'?");
            }
            var diff = diffs[0];

            if (diff.NewVersion is null)
            {
                throw new UserErrorException($"Cannot automate a release commit for a deleted API.");
            }

            var historyFilePath = HistoryFile.GetPathForPackage(diff.Id);

            if (!File.Exists(historyFilePath))
            {
                throw new UserErrorException($"Cannot automate a release commit without a version history file.");
            }

            var historyFile = HistoryFile.Load(historyFilePath);
            var section     = historyFile.Sections.FirstOrDefault(s => s.Version?.ToString() == diff.NewVersion);

            if (section is null)
            {
                throw new UserErrorException($"Unable to find history file section for {diff.NewVersion}. Cannot automate a release commit in this state.");
            }

            string header  = $"Release {diff.Id} version {diff.NewVersion}";
            var    message = string.Join("\n", new[] { header, "", "Changes in this release:", "" }.Concat(section.Lines.Skip(2)));

            var root = DirectoryLayout.DetermineRootDirectory();

            using (var repo = new Repository(root))
            {
                RepositoryStatus status = repo.RetrieveStatus();
                // TODO: Work out whether this is enough, and whether we actually need all of these.
                // We basically want git add --all.
                AddAll(status.Modified);
                AddAll(status.Missing);
                AddAll(status.Untracked);
                repo.Index.Write();
                var signature = repo.Config.BuildSignature(DateTimeOffset.UtcNow);
                var commit    = repo.Commit(message, signature, signature);
                Console.WriteLine($"Created commit {commit.Sha}. Review the message and amend if necessary.");

                void AddAll(IEnumerable <StatusEntry> entries)
                {
                    foreach (var entry in entries)
                    {
                        repo.Index.Add(entry.FilePath);
                    }
                }
            }
        }
Example #26
0
        private void ValidateNoChanges(Repository repo)
        {
            RepositoryStatus status = repo.RetrieveStatus();

            if (status.IsDirty)
            {
                throw new UserErrorException($"Cannot execute '{Command}' command while the local repository contains uncommitted changes.");
            }
        }
Example #27
0
        void VerCambiosPendientes_Loaded(object sender, RoutedEventArgs e)
        {
            Label            lbl    = null;
            RepositoryStatus status = Proyecto.getStatus();

            Constantes.DoEvents(vparent.Dispatcher);
            Constantes.DoEvents(vparent.pnlNavegacion.Dispatcher);
            logic.Constantes.DoEvents(this.Dispatcher);

            System.Diagnostics.Process.Start("\"nanDesktop.gitAdd.exe\"", "\"" + Proyecto.Path + "\"");

            foreach (var archivo in status)
            {
                lbl           = new Label();
                lbl.Content   = archivo.FilePath;
                lbl.MinWidth  = 350;
                lbl.MinHeight = 25;
                //(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));
                Constantes.DoEvents(vparent.Dispatcher);
                Constantes.DoEvents(vparent.pnlNavegacion.Dispatcher);
                logic.Constantes.DoEvents(this.Dispatcher);

                if (archivo.State == FileStatus.Added)
                {
                    lbl.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFAAEB81"));
                }
                else if (archivo.State == FileStatus.Modified)
                {
                    lbl.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFC5DB50"));
                }
                else if (archivo.State == FileStatus.Removed)
                { //#FFDB7878
                    lbl.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFDB7878"));
                }
                else if (archivo.State == FileStatus.Ignored)
                {
                    lbl.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FF3FAAB1"));
                }
                else if (archivo.State == FileStatus.Untracked)
                {
                    lbl.Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#FFDB7878"));
                }

                lbl.Content = "[" + archivo.State.ToString() + "] " + lbl.Content;


                if (archivo.State != FileStatus.Ignored && archivo.State != FileStatus.Missing && archivo.State != FileStatus.Untracked)
                {
                    //Proyecto.git_trackFile(archivo.FilePath);
                    stkArchivos.Children.Add(lbl);
                }
                else
                {
                    stkArchivosIgnorados.Children.Add(lbl);
                }
            }
        }
Example #28
0
        static bool IsCheckoutBlockingDirty(RepositoryStatus status)
        {
            if (status.IsDirty)
            {
                return(status.Any(entry => IsCheckoutBlockingChange(entry)));
            }

            return(false);
        }
Example #29
0
        /// <summary>
        /// 提交被忽略的文件列表
        /// </summary>
        private void StageIgnoreFile()
        {
            RepositoryStatus status            = _repository.RetrieveStatus();
            List <string>    filePaths_Ignored = status.Ignored.Select(mods => mods.FilePath).ToList();

            foreach (var item in filePaths_Ignored)
            {
                _repository.Index.Add(item);
                _repository.Index.Write();
            }
        }
Example #30
0
        public void CanResetTheIndexWhenARenameExists()
        {
            using (var repo = new Repository(SandboxStandardTestRepo()))
            {
                repo.Move("branch_file.txt", "renamed_branch_file.txt");
                repo.Reset(repo.Lookup <Commit>("32eab9c"));

                RepositoryStatus status = repo.RetrieveStatus();
                Assert.Equal(0, status.Where(IsStaged).Count());
            }
        }
Example #31
0
        public ChangesViewModel(Repository repository, RepositoryStatus status)
        {
            Repository = repository;
            Status     = status;

            UnstagedFiles = status.Untracked.Concat(status.Missing).Concat(status.Modified).Select(x => x.FilePath).ToImmutableList();
            StagedFiles   = status.Staged.Select(x => x.FilePath).ToImmutableList();

            this.Listen(x => x.SelectedStagedFile).Then(WhenSelectedStagedFileChanged);
            this.Listen(x => x.SelectedUnstagedFile).Then(WhenSelectedUnstagedFileChanged);
        }
Example #32
0
        public void Check_cloned_repo_git()
        {
            string toPath = Path.Combine(trash.FullName, "test");
            string fromUrl = "git://github.com/henon/TestGitRepository.git";

            using (Repository repo = Git.Clone(fromUrl, toPath))
            {
                var status = new RepositoryStatus(repo, new RepositoryStatusOptions { ForceContentCheck = false });
                Assert.IsFalse(status.AnyDifferences);

                status = new RepositoryStatus(repo, new RepositoryStatusOptions { ForceContentCheck = true });
                Assert.IsFalse(status.AnyDifferences);

                Assert.IsTrue(Repository.IsValid(repo.Directory));
                //Verify content is in the proper location
                var readme = Path.Combine(repo.WorkingDirectory, "master.txt");
                Assert.IsTrue(new FileInfo(readme).Exists);
            }
        }
Example #33
0
 private void doDisplayMergeConflict(RepositoryStatus status)
 {
     foreach (string hash in status.MergeConflict)
     {
         OutputStream.WriteLine(hash+": needs merge");
     }
 }
Example #34
0
 private void doDisplayStaged(RepositoryStatus status)
 {
     Dictionary<string, int> statusList = GetStagedList(status);
     if (statusList.Count > 0)
     {
         OutputStream.WriteLine("# Changes to be committed:");
         OutputStream.WriteLine("#   (use \"git reset HEAD (file)...\" to unstage)");
         OutputStream.WriteLine("#");
         displayStatusList(statusList);
         OutputStream.WriteLine("#");
     }
 }
Example #35
0
		public void AddAll_New_Directory()
		{
			// test AddAll with one new direcotry is flagged as a new add
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var dirPath = Path.Combine(repo.WorkingDirectory, "testdir");
				Directory.CreateDirectory(dirPath);
				repo.Index.AddAll();
				var status = new RepositoryStatus(repo);
				Assert.IsFalse(status.AnyDifferences);
				// there should be 0 added file
				Assert.AreEqual(0, status.Added.Count);
				// the added direcotry must be the directory that was just added
				status.Added.Contains(dirPath);
				// no other changes
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #36
0
        private static string FormatWorkingDirStatus(RepositoryStatus index)
        {
            var untracked = index.Untracked.Count();
            var modified = index.Modified.Count();
            var missing = index.Missing.Count();
            if (untracked == 0 && modified == 0 && missing == 0)
                return "";

            return $" +{untracked} ~{modified} -{missing}";
        }
Example #37
0
        private Dictionary<string, int> GetStagedList(RepositoryStatus status)
        {
            //Create a single list to sort and display the staged files by filename.
            //Sorting in this manner causes additional speed overhead so should be considered optional.
            //With all the additional testing currently added, please keep in mind it will run twice as fast
            //once the tests are removed.
            Dictionary<string, int> stagedList = new Dictionary<string, int>();
            HashSet<string> hset = null;

            if (status.MergeConflict.Count > 0)
            {
                hset = new HashSet<string>(status.MergeConflict);
                foreach (string hash in hset)
                {
                    //Merge conflicts are only displayed in the modified non-staged area.
                    status.Modified.Remove(hash);
                    status.Staged.Remove(hash);
                }
            }
            if (status.Missing.Count > 0)
            {
                hset = new HashSet<string>(status.Staged);
                hset.IntersectWith(status.Missing);
                foreach (string hash in hset)
                    stagedList.Add(hash, 1);
            }

            if (status.Removed.Count > 0)
            {
                hset = new HashSet<string>(status.Staged);
                hset.IntersectWith(status.Removed);
                foreach (string hash in hset)
                    stagedList.Add(hash, 2);
            }

            if (status.Modified.Count > 0)
            {
                hset = new HashSet<string>(status.Staged);
                hset.IntersectWith(status.Modified);
                foreach (string hash in hset)
                    stagedList.Add(hash, 3);
            }

            if (status.Added.Count > 0)
            {
                hset = new HashSet<string>(status.Staged);
                hset.IntersectWith(status.Added);
                foreach (string hash in hset)
                    stagedList.Add(hash, 4);
            }

            stagedList.OrderBy(v => v.Key);
            return stagedList;
        }
Example #38
0
        public override void Execute()
        {
            RepositoryStatus status = new RepositoryStatus(Repository);
            IgnoreRules rules;

            //Read ignore file list and remove from the untracked list
            try
            {
                rules = new IgnoreRules(Path.Combine(Repository.WorkingDirectory, ".gitignore"));
            }
            catch (FileNotFoundException)
            {
                //.gitignore file does not exist for a newly initialized repository.
                string[] lines = {};
                rules = new IgnoreRules(lines);
            }

            foreach (string hash in status.Untracked)
            {
                string path = Path.Combine(Repository.WorkingDirectory, hash);
                if (!rules.IgnoreFile(Repository.WorkingDirectory, path) && !rules.IgnoreDir(Repository.WorkingDirectory, path))
                {
                    UntrackedList.Add(hash);
                }
            }

            if (status.AnyDifferences || UntrackedList.Count > 0)
            {
                // Files use the following states: removed, missing, added, and modified.
                // If a file has been staged, it is also added to the RepositoryStatus.Staged HashSet.
                //
                // The remaining StatusType known as "Untracked" is determined by what is *not* staged or modified.
                // It is then intersected with the .gitignore list to determine what should be listed as untracked.
                // Using intersections will accurately display the "bucket" each file was added to.

                // Note: In standard git, they use cached references so the following scenario is possible.
                //    1) Filename = a.txt; StatusType=staged; FileState=added
                //    2) Filename = a.txt; StatusType=modified; FileState=added
                // Notice that the same filename exists in two separate status's because it points to a reference
                // Todo: This test has failed so far with this command.

                HashSet<string> stagedRemoved = new HashSet<string>(status.Staged);
                stagedRemoved.IntersectWith(status.Removed);
                HashSet<string> stagedMissing = new HashSet<string>(status.Staged);
                stagedMissing.IntersectWith(status.Missing);
                HashSet<string> stagedAdded = new HashSet<string>(status.Staged);
                stagedAdded.IntersectWith(status.Added);
                HashSet<string> stagedModified = new HashSet<string>(status.Staged);
                stagedModified.IntersectWith(status.Modified);
                stagedModified.ExceptWith(status.MergeConflict);

                HashSet<string> Removed = new HashSet<string>(status.Removed);
                Removed.ExceptWith(status.Staged);
                HashSet<string> Missing = new HashSet<string>(status.Missing);
                Missing.ExceptWith(status.Staged);
                HashSet<string> Added = new HashSet<string>(status.Added);
                Added.ExceptWith(status.Staged);
                HashSet<string> Modified = new HashSet<string>(status.Modified);
                Modified.ExceptWith(status.Staged);

                // The output below is used to display both where the file is being added and specifying the file.
                // Unit testing is still pending.
                /*OutputStream.WriteLine("# Staged Tests: StageType + status.Staged");
                OutputStream.WriteLine("# Staged Total: " + (stagedModified.Count + stagedRemoved.Count + stagedMissing.Count + stagedAdded.Count));
                OutputStream.WriteLine("# Test:     Modified Object Count: " + stagedModified.Count);
                OutputStream.WriteLine("# Test:      Removed Object Count: " + stagedRemoved.Count);
                OutputStream.WriteLine("# Test:      Missing Object Count: " + stagedMissing.Count);
                OutputStream.WriteLine("# Test:        Added Object Count: " + stagedAdded.Count);
                OutputStream.WriteLine("#");
                OutputStream.WriteLine("# Modified Tests: StageType w/o status.Staged");
                OutputStream.WriteLine("# Modified Total: " + (Modified.Count+Removed.Count+Missing.Count+Added.Count));
                OutputStream.WriteLine("# Test:      Changed Object Count: " + Modified.Count);
                OutputStream.WriteLine("# Test:      Removed Object Count: " + Removed.Count);
                OutputStream.WriteLine("# Test:      Missing Object Count: " + Missing.Count);
                OutputStream.WriteLine("# Test:        Added Object Count: " + Added.Count);
                OutputStream.WriteLine("#");
                OutputStream.WriteLine("# MergeConflict Tests: " + status.MergeConflict.Count);
                OutputStream.WriteLine("# Test:              Object Count: " + status.MergeConflict.Count);
                OutputStream.WriteLine("#");
                OutputStream.WriteLine("# UnTracked Tests: status.Untracked");
                OutputStream.WriteLine("# Test:    Untracked Object Count: " + status.Untracked.Count);
                OutputStream.WriteLine("# Test:      Ignored Object Count: Pending");
                OutputStream.WriteLine("#");*/

                //Display the stages of all files
                doDisplayMergeConflict(status);
                OutputStream.WriteLine("# On branch " + Repository.CurrentBranch.Name);
                //OutputStream.WriteLine("# Your branch is ahead of 'xxx' by x commits."); //Todo
                OutputStream.WriteLine("#");

                doDisplayStaged(status);
                doDisplayUnstaged(status);
                doDisplayUntracked(status);
                if (status.Staged.Count <= 0)
                {
                    OutputStream.WriteLine("no changes added to commit (use \"git add\" and/or \"git commit -a\")");
                }
            }
            else if (status.IndexSize <= 0)
            {
                OutputStream.WriteLine("# On branch " + Repository.CurrentBranch.Name);
                OutputStream.WriteLine("#");
                OutputStream.WriteLine("# Initial commit");
                OutputStream.WriteLine("#");
                OutputStream.WriteLine("# nothing to commit (create/copy files and use \"git add\" to track)");
            }
            else
            {
                OutputStream.WriteLine("# nothing to commit (working directory clean)");
            }
            //Leave this in until completed.
            throw new NotImplementedException("The implementation is not yet complete. autocrlf support is not added.");
        }
Example #39
0
        public void UpdateStatus(bool limit = false)
        {
            // Limit checks to x/second.
            if (limit && Status.directoriesToVerify != null && (DateTime.Now - updateLimiterLast) < TimeSpan.FromSeconds(3))
                return;

            updateLimiterLast = DateTime.Now;

            RepositoryStatus ret = new RepositoryStatus();

            IEnumerable<Manifest.SyncItem>
                outdated = new List<Manifest.SyncItem>(),
                dirsToCheck = new List<Manifest.SyncItem>(),
                filesToCheck = new List<Manifest.SyncItem>();

            if (!AlwaysAssumeCurrent)
            {
                outdated = LatestManifest.sync;

                if (CurrentManifest != null)
                    outdated = outdated.Where(f => !f.isCurrent(this));

                dirsToCheck  = outdated.Where(f => f.name.EndsWith("/"));
                filesToCheck = outdated.Where(f => !f.name.EndsWith("/"));

                ret.guesstimatedBytesToVerify = outdated.Sum(n => n.ToTransfer(this)).Clamp(0);
                ret.maxBytesToVerify = outdated.Sum(n => n.size).Clamp(0);

                ret.directoryCountToVerify = dirsToCheck.Count();
                ret.fileCountToVerify = dirsToCheck.Sum(n => n.count) + filesToCheck.Count();
            }

            ret.directoriesToVerify = dirsToCheck.ToList();
            ret.filesToVerify = filesToCheck.ToList();

            ret.sizeOnRemote = LatestManifest.sync.Sum(n => n.size);
            ret.sizeOnDisk = LatestManifest.sync.Sum(n => n.SizeOnDisk(this));

            ret.current = LatestManifest != null && CurrentManifest != null &&
                ret.fileCountToVerify == 0 &&
                ret.directoryCountToVerify == 0;

            this.Status = ret;
        }
Example #40
0
        void AssertStatus(RepositoryStatus results, List<string> filesToCheck, string file, params HashSet<string>[] fileStatuses)
        {
            Assert.IsNotNull(results);

            var allStatus = new HashSet<string> [] {
                results.Added,
                results.MergeConflict,
                results.Missing,
                results.Modified,
                results.Removed,
                results.Staged,
                results.Untracked
            };

            var allStatusName = new string[] {
                "Added",
                "MergeConflict",
                "Missing",
                "Modified",
                "Removed",
                "Staged",
                "Untracked"
            };

            if (!filesToCheck.Contains (file))
                fileStatuses = new HashSet<string>[0];

            for (int n=0; n<allStatus.Length; n++) {
                var status = allStatus [n];
                if (((IList)fileStatuses).Contains (status))
                    Assert.IsTrue (status.Contains (file), "File " + file + " not found in " + allStatusName[n] + " collection");
                else
                    Assert.IsFalse (status.Contains (file), "File " + file + " should no be in " + allStatusName[n] + " collection");
            }
        }
Example #41
0
		public void AddAll_No_New_Files()
		{
			// test AddAll with empty directory results in no differences
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var status = new RepositoryStatus(repo);
				Assert.IsFalse(status.AnyDifferences);
				// verify AddAll does nothing as there have been no changes made
				repo.Index.AddAll();
				Assert.IsFalse(status.AnyDifferences);
				Assert.AreEqual(0, status.Added.Count);
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #42
0
		public void AddAll_New_Files()
		{
			// test AddAll with one new file in the directory retults in one added file and is flagged as a difference
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var filePath = Path.Combine(repo.WorkingDirectory, "testfile.txt");
				File.WriteAllText(filePath, "Unadded file");
				repo.Index.AddAll();
				var status = new RepositoryStatus(repo);
				Assert.IsTrue(status.AnyDifferences);
				// there should be 1 added file
				Assert.AreEqual(1, status.Added.Count);
				// the added file must be the file that was just added
				status.Added.Contains(filePath);
				// no other changes
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #43
0
        public void UpdateStatus(bool limit = false)
        {
            // Limit checks to x/second.
            if (limit && Status.directoriesToVerify != null && (DateTime.Now - updateLimiterLast) < TimeSpan.FromSeconds(1))
                return;

            updateLimiterLast = DateTime.Now;

            RepositoryStatus ret = new RepositoryStatus();

            IEnumerable<Manifest.SyncItem>
                outdated = new List<Manifest.SyncItem>(),
                dirsToCheck = new List<Manifest.SyncItem>(),
                filesToCheck = new List<Manifest.SyncItem>();

            if (!AlwaysAssumeCurrent)
            {
                outdated = LatestManifest.sync;

                if (CurrentManifest != null)
                {
                    outdated = outdated.Where(f => {

                        if (f.revision != 0)
                        {
                            var f_old = CurrentManifest.sync.Find(_f_old => _f_old.name == f.name);
                            // No old sync item: new item
                            if (f_old == null)
                                return !f.isCurrent(this);

                            // No old revision: fallback to old check (and don't trigger force updates)
                            if (f_old != null && f_old.revision == 0)
                                return !f.isCurrent(this);

                            // Mismatching revision: always force check
                            if (f_old != null && f_old.revision != f.revision)
                                return true;

                            // Matching revisions still incur the regular check to catch deleted/touched files
                        }

                        return !f.isCurrent(this);
                    });
                }

                dirsToCheck  = outdated.Where(f => f.name.EndsWith("/"));
                filesToCheck = outdated.Where(f => !f.name.EndsWith("/"));

                long outdatedSizeLocally = outdated.Select(n => n.SizeOnDisk(this)).Sum();
                long outdatedSizeRemote = outdated.Select(n => n.size).Sum();

                ret.guesstimatedBytesToVerify = outdatedSizeRemote - outdatedSizeLocally;
                ret.maxBytesToVerify = outdatedSizeRemote;

                ret.guesstimatedBytesToVerify = ret.guesstimatedBytesToVerify.Clamp(0);
                ret.maxBytesToVerify = ret.maxBytesToVerify.Clamp(0);

                ret.directoryCountToVerify = dirsToCheck.Count();
                ret.fileCountToVerify = dirsToCheck.Select(n => n.count).Sum() + filesToCheck.Count();
            }

            ret.directoriesToVerify = dirsToCheck.ToList();
            ret.filesToVerify = filesToCheck.ToList();

            ret.sizeOnRemote = LatestManifest.sync.Select(n => n.size).Sum();
            ret.sizeOnDisk = LatestManifest.sync.Select(n => n.SizeOnDisk(this)).Sum();

            ret.current = LatestManifest != null && CurrentManifest != null &&
                ret.fileCountToVerify == 0 &&
                ret.directoryCountToVerify == 0;

            this.Status = ret;
        }
Example #44
0
        private Dictionary<string, int> GetModifiedList(RepositoryStatus status)
        {
            //Create a single list to sort and display the modified (non-staged) files by filename.
            //Sorting in this manner causes additional speed overhead. Performance enhancements should be considered.
            Dictionary<string, int> modifiedList = new Dictionary<string, int>();
            HashSet<string> hset = null;

            if (status.MergeConflict.Count > 0)
            {
                hset = new HashSet<string>(status.MergeConflict);
                foreach (string hash in hset)
                {
                    modifiedList.Add(hash, 5);
                    status.Modified.Remove(hash);
                    status.Staged.Remove(hash);
                }
            }

            if (status.Missing.Count > 0)
            {
                hset = new HashSet<string>(status.Missing);
                hset.ExceptWith(status.Staged);
                foreach (string hash in hset)
                    modifiedList.Add(hash, 1);
            }

            if (status.Removed.Count > 0)
            {
                hset = new HashSet<string>(status.Removed);
                hset.ExceptWith(status.Staged);
                foreach (string hash in hset)
                    modifiedList.Add(hash, 2);
            }

            if (status.Modified.Count > 0)
            {
                hset = new HashSet<string>(status.Modified);
                hset.ExceptWith(status.Staged);
                foreach (string hash in hset)
                    modifiedList.Add(hash, 3);
            }

            if (status.Added.Count > 0)
            {
                hset = new HashSet<string>(status.Added);
                hset.ExceptWith(status.Staged);
                foreach (string hash in hset)
                    modifiedList.Add(hash, 4);
            }

            modifiedList.OrderBy(v => v.Key);
            return modifiedList;
        }
Example #45
0
        private static string FormatWorkingDirStatus(RepositoryStatus index)
        {
            var untracked = index.Untracked.Count();
            var modified = index.Modified.Count();
            var missing = index.Missing.Count();
            if (untracked == 0 && modified == 0 && missing == 0)
                return "";

            return string.Format(" +{0} ~{1} -{2}", untracked, modified, missing);
        }
Example #46
0
 private void doDisplayUntracked(RepositoryStatus status)
 {
     if (UntrackedList.Count > 0)
     {
         OutputStream.WriteLine("# Untracked files:");
         OutputStream.WriteLine("#   (use \"git add (file)...\" to include in what will be committed)");
         OutputStream.WriteLine("#");
         UntrackedList.OrderBy(v => v.ToString());
         foreach (string hash in UntrackedList)
             OutputStream.WriteLine("#       " + hash);
     }
 }
 public void AlternativeCallbackApiTest()
 {
     using (var repo = new Repository(trash.FullName))
     {
         repo.Head.Reset(ResetBehavior.Mixed);
         writeTrashFile("untracked", "");
         writeTrashFile("added", "");
         repo.Index.Add("added");
         writeTrashFile("a/a1", "modified");
         repo.Index.AddContent("a/a1.txt", "staged");
         repo.Index.Remove("b/b2.txt");
         var status = repo.Status;
         Assert.AreEqual(1, status.Added.Count);
         Assert.AreEqual(1, status.Staged.Count);
         Assert.AreEqual(6, status.Missing.Count);
         Assert.AreEqual(1, status.Modified.Count);
         Assert.AreEqual(1, status.Removed.Count);
         Assert.AreEqual(1, status.Untracked.Count);
         var stati = new List<PathStatus>();
         var s = new RepositoryStatus(repo, new RepositoryStatusOptions
         {
             PerPathNotificationCallback = path_status =>
             {
                 stati.Add(path_status);
                 switch (path_status.WorkingPathStatus)
                 {
                     case WorkingPathStatus.Missing:
                         Assert.IsTrue(status.Missing.Contains(path_status.Path));
                         break;
                     case WorkingPathStatus.Modified:
                         Assert.IsTrue(status.Modified.Contains(path_status.Path));
                         break;
                     case WorkingPathStatus.Untracked:
                         Assert.IsTrue(status.Untracked.Contains(path_status.Path));
                         break;
                 }
                 switch (path_status.IndexPathStatus)
                 {
                     case IndexPathStatus.Added:
                         Assert.IsTrue(status.Added.Contains(path_status.Path));
                         break;
                     case IndexPathStatus.Removed:
                         Assert.IsTrue(status.Removed.Contains(path_status.Path));
                         break;
                     case IndexPathStatus.Staged:
                         Assert.IsTrue(status.Staged.Contains(path_status.Path));
                         break;
                 }
             }
         });
         var dict = stati.ToDictionary(p => p.Path);
         Assert.IsTrue(dict.ContainsKey("untracked"));
         Assert.IsTrue(dict.ContainsKey("added"));
         Assert.IsTrue(dict.ContainsKey("a/a1"));
         Assert.IsTrue(dict.ContainsKey("a/a1.txt"));
         Assert.IsTrue(dict.ContainsKey("b/b2.txt"));
     }
 }
Example #48
0
 private void doDisplayUnstaged(RepositoryStatus status)
 {
     Dictionary<string, int> statusList = GetModifiedList(status);
     if (statusList.Count > 0)
     {
         OutputStream.WriteLine("# Changed but not updated:");
         OutputStream.WriteLine("#   (use \"git add (file)...\" to update what will be committed)");
         OutputStream.WriteLine("#   (use \"git checkout -- (file)...\" to discard changes in working directory)");
         OutputStream.WriteLine("#");
         displayStatusList(statusList);
         OutputStream.WriteLine("#");
     }
 }
Example #49
0
		public WorkingTree(string path, RepositoryStatus status)
		{
			Path = path;
			RelativePath = "";
			RepositoryStatus = status;
		}
Example #50
0
		public void AddAll_New_File_And_New_Directory_With_File()
		{
			// test AddAll with one file, one new directory and a new file inside that directory
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var filePath = Path.Combine(repo.WorkingDirectory, "testfile.txt");
				var dirPath = Path.Combine(repo.WorkingDirectory, "testdir");
				var filePath2 = Path.Combine(dirPath, "testfile.txt");
				File.WriteAllText(filePath, "Unadded file");
				Directory.CreateDirectory(dirPath);
				File.WriteAllText(filePath2, "Unadded file");
				repo.Index.AddAll();
				var status = new RepositoryStatus(repo);
				Assert.IsTrue(status.AnyDifferences);
				// there should be 2 added files
				Assert.AreEqual(2, status.Added.Count);
				// the added file must be the file that was just added
				status.Added.Contains(filePath);
				status.Added.Contains(filePath2);
				status.Added.Contains(dirPath);
				// no other changes
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #51
0
		public void AddAll_Directory_Recursive()
		{
			// test AddAll with one new directory with a directory within it and each these directories containing a new file within it
			// root folder also contains one new file
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var dirPath = Path.Combine(repo.WorkingDirectory, "testdir");
				var dirPath2 = Path.Combine(dirPath, "testdir2");
				var filePath = Path.Combine(repo.WorkingDirectory, "testfile.txt");
				var filePath2 = Path.Combine(dirPath, "testfile.txt");
				var filePath3 = Path.Combine(dirPath2, "testfile.txt");
				Directory.CreateDirectory(dirPath);
				Directory.CreateDirectory(dirPath2);
				File.WriteAllText(filePath, "Unadded file");
				File.WriteAllText(filePath2, "Unadded file");
				File.WriteAllText(filePath3, "Unadded file");
				repo.Index.AddAll();
				var status = new RepositoryStatus(repo);
				Assert.IsTrue(status.AnyDifferences);
				// there should be 3 added files
				Assert.AreEqual(3, status.Added.Count);
				// the added file must be the file that was just added
				status.Added.Contains(dirPath);
				status.Added.Contains(dirPath2);
				status.Added.Contains(filePath);
				status.Added.Contains(filePath2);
				status.Added.Contains(filePath3);
				// no other changes
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #52
0
        public override void Execute()
        {
            RepositoryStatus status = new RepositoryStatus(Repository);

            IgnoreRules rules;

            //Read ignore file list and remove from the untracked list
            try
            {
                rules = new IgnoreRules(Path.Combine(Repository.WorkingDirectory, ".gitignore"));
            }
            catch (FileNotFoundException)
            {
                //.gitignore file does not exist for a newly initialized repository.
                string[] lines = {};
                rules = new IgnoreRules(lines);
            }

            foreach (string hash in status.Untracked)
            {
                string path = Path.Combine(Repository.WorkingDirectory, hash);
                if (!rules.IgnoreFile(Repository.WorkingDirectory, path) && !rules.IgnoreDir(Repository.WorkingDirectory, path))
                {
                    results.UntrackedList.Add(hash);
                }
            }

            if (status.AnyDifferences || results.UntrackedList.Count > 0)
            {
                // Files use the following StatusTypes: removed, missing, added, and modified, modified w/staged, and merge conflict.
                // The following StatusStates are defined for each type:
                //              Modified -> Unstaged
                //         MergeConflict -> Unstaged
                //                 Added -> Staged
                //        ModifiedStaged -> Staged
                //               Removed -> Staged
                //               Missing -> Staged
                // The StatusState known as "Untracked" is determined by what is *not* defined in any state.
                // It is then intersected with the .gitignore list to determine what should be listed as untracked.

                HashSet<string> hset = new HashSet<string>(status.MergeConflict);
                foreach (string hash in hset)
                {
                    results.ModifiedList.Add(hash, StatusType.MergeConflict);
                    status.Staged.Remove(hash);
                    status.Modified.Remove(hash);
                }

                hset = new HashSet<string>(status.Missing);
                foreach (string hash in hset)
                    results.ModifiedList.Add(hash, StatusType.Missing);

                hset = new HashSet<string>(status.Modified);
                foreach (string hash in hset)
                    results.ModifiedList.Add(hash, StatusType.Modified);

                hset = new HashSet<string>(status.Staged);
                foreach (string hash in hset)
                    results.StagedList.Add(hash, StatusType.ModifiedStaged);

                hset = new HashSet<string>(status.Added);
                foreach (string hash in hset)
                    results.StagedList.Add(hash, StatusType.Added);

                hset = new HashSet<string>(status.Removed);
                foreach (string hash in hset)
                    results.StagedList.Add(hash, StatusType.Removed);

                results.UntrackedList.Sort();
                results.ModifiedList.OrderBy(v => v.Key);
                results.StagedList.OrderBy(v => v.Key);
            }

            IndexSize = Repository.Index.Size;
        }
Example #53
0
		public void AddAll_Ignore_Files()
		{
			// test AddAll files added to the DOT_IGNORE file
			var workingDirectory = Path.Combine(trash.FullName, "test");
			using (var repo = Repository.Init(workingDirectory))
			{
				var ignoreFilePath = Path.Combine(repo.WorkingDirectory, GitSharp.Core.Constants.GITIGNORE_FILENAME);
				// add the name of the test file to the ignore list
				File.WriteAllText(ignoreFilePath, "*.txt");
				repo.Index.Add(ignoreFilePath);
				repo.Commit("Committing .gitignore file so it won't show up as untracked file");
				var filePath = Path.Combine(repo.WorkingDirectory, "testfile.txt");
				File.WriteAllText(filePath, "Unadded file");
				repo.Index.AddAll();
				var status = new RepositoryStatus(repo);
				// no changes are the file should be ignored
				Assert.IsFalse(status.AnyDifferences);
				// there should be 0 added file
				Assert.AreEqual(0, status.Added.Count);
				// no other changes
				Assert.AreEqual(0, status.Untracked.Count);
				Assert.AreEqual(0, status.Staged.Count);
				Assert.AreEqual(0, status.Missing.Count);
				Assert.AreEqual(0, status.Modified.Count);
				Assert.AreEqual(0, status.Removed.Count);
			}
		}
Example #54
0
		public WorkingFile(string path, RepositoryStatus status)
			: base(path, status)
		{
		}