public async Task Repository_path_can_be_passed_as_relative_path() { // ARRANGE using var temporaryDirectory = new TemporaryDirectory(); var repositoryPath = temporaryDirectory.AddSubDirectory("repo"); var git = new GitWrapper(repositoryPath, m_TestOutputHelper); await git.InitAsync(); await git.ConfigAsync("user.name", "Example"); await git.ConfigAsync("user.email", "*****@*****.**"); var commit = await git.CommitAsync("feat: Some New feature"); await git.TagAsync("v1.0.0", commit); await Task.Delay(500); var expectedOutputPath = Path.Combine(repositoryPath, "changelog.md"); // ACT var result = await RunApplicationAsync( args : new[] { "--repository", "repo" }, workingDirectory : temporaryDirectory, commandId : nameof(Repository_path_can_be_passed_as_relative_path) ); // ASSERT Assert.Equal(0, result.ExitCode); Assert.True(File.Exists(expectedOutputPath)); }
public RepositoryViewModel(string git_repository_path, RepositoryTab repository_tab, UserControls.PendingTabViewModel pendingTabViewModel, UserControls.StashTabViewModel stashTabViewModel, UserControls.BranchTabViewModel branchTabViewModel, UserControls.TagTabViewModel tagTabViewModel, UserControls.RemoteTabViewModel remoteTabViewModel) { DisplayAuthor = GlobalSetting.GetInstance().GetSignature(); Directory = git_repository_path; git_ = new GitWrapper(Directory, this); DirectoryTree = new DirectoryTreeViewModel(this); HistoryTabMember = new HistoryTabViewModel(this); _pendingTabViewModel = pendingTabViewModel; _stashTabViewModel = stashTabViewModel; _branchTabViewModel = branchTabViewModel; _tagTabViewModel = tagTabViewModel; _remoteTabViewModel = remoteTabViewModel; StashTabHeader = "Stash"; repository_tab_ = repository_tab; PushCommand = new DelegateCommand((object parameter) => OnPushCommand()); OpenExplorerCommand = new DelegateCommand(OnOpenExplorerCommand); OpenGitBashCommand = new DelegateCommand(OnOpenGitBashCommand); RefreshCommand = new DelegateCommand(async(object parameter) => await Refresh()); ViewTimelapseCommand = new DelegateCommand((object parameter) => OnViewTimeLapseCommand()); FetchAllCommand = new DelegateCommand(async(object parameter) => await OnFetchAllCommand()); PullCommand = new DelegateCommand(async(object parameter) => await OnPullCommand()); }
private void FetchAndPruneRepos() { var wrapper = new GitWrapper(); foreach (var repositoryPath in _repositoryPaths) { wrapper.FetchThenSafePrune(repositoryPath); } }
public BlamePositionModel(string filePath) { if (filePath == null) { throw new ArgumentNullException("filePath"); } m_filePath = filePath; GitWrapper.SplitRepositoryPath(filePath, out m_repoPath, out m_fileName); }
// Operations. public void SignOff() { // TODO: Refactor signoff operation into GitWrapper. string signOffMessage = "Signed-off-by: " + GitWrapper.ConfigGet("user.name") + " <" + GitWrapper.ConfigGet("user.email") + ">"; if (!commitMessage.EndsWith(signOffMessage)) { commitMessage += "\n" + signOffMessage; } }
public async Task The_expected_configuration_file_is_used(string[] configurationFilesOnDisk, string?configurationFileParameter, string expectedConfigurationFile) { // ARRANGE using var temporaryDirectory = new TemporaryDirectory(); var git = new GitWrapper(temporaryDirectory, m_TestOutputHelper); await git.InitAsync(); await git.ConfigAsync("user.name", "Example"); await git.ConfigAsync("user.email", "*****@*****.**"); // Create all configuration files with distinct output path settings var outputNames = new Dictionary <string, string>(); foreach (var configurationFilePath in configurationFilesOnDisk) { var outputName = $"{Guid.NewGuid()}.md"; temporaryDirectory.AddFile( configurationFilePath, $@"{{ ""changelog"" : {{ ""outputPath"" : ""{outputName}"" }} }}" ); outputNames.Add(configurationFilePath, outputName); } // Determine the expected output path (based on the output path we can determine which configuration file was used). // If none of the configuration file is expected to be used (expectedConfigurationFile is null), expect the changelog to be written to the default location var expectedOutputPath = expectedConfigurationFile is null ? Path.Combine(temporaryDirectory, "changelog.md") : Path.Combine(temporaryDirectory, outputNames[expectedConfigurationFile]); var args = new List <string>() { "--verbose" }; // When specified, append the configurationFilePath commandline parameter if (configurationFileParameter is not null) { args.Add("--configurationFilePath"); args.Add(configurationFileParameter); } // ACT var result = await RunApplicationAsync( args : args, workingDirectory : temporaryDirectory, commandId : $"{nameof(The_expected_configuration_file_is_used)}([{String.Join(",", configurationFilesOnDisk)}], \"{configurationFileParameter}\", \"{expectedConfigurationFile}\")" ); // ASSERT Assert.Equal(0, result.ExitCode); Assert.True(File.Exists(expectedOutputPath)); }
public void StagePath(GitWrapper.ChangeType changeType, string path) { if (changeType == GitWrapper.ChangeType.Deleted) { GitWrapper.RemovePath(path); } else { GitWrapper.StagePath(path); } isDirty = true; }
public async Task <bool> Refresh() { DateTime start = DateTime.Now; AddLog("Refreshing Directory: " + Directory); repository_tab_.EnterLoadingScreen(); if (RefreshBranch() == false) {// invalid repository repository_tab_.LeaveLoadingScreen(); repository_tab_.EnterFailedScreen(); git_ = null; return(false); } DirectoryTree.ReloadTreeView(); Task <List <string> > git_porcelain_result = git_.GetGitStatusPorcelainAllAsync(); Task <int> stashTabResult = _stashTabViewModel.RefreshAndGetStashCount(); Task branchTabResult = _branchTabViewModel.Refresh(); Task tagTabResult = _tagTabViewModel.Refresh(); Task remoteTabResult = _remoteTabViewModel.Refresh(); _pendingTabViewModel.RefreshPending(await git_porcelain_result); int stashListCount = await stashTabResult; if (stashListCount > 0) { StashTabHeader = $"Stash [{stashListCount}]"; } else { StashTabHeader = "Stash"; } NotifyPropertyChanged("StashTabHeader"); await branchTabResult; await remoteTabResult; await tagTabResult; AddLog("Refreshed"); repository_tab_.LeaveLoadingScreen(); if (System.Diagnostics.Debugger.IsAttached) { TimeSpan elapsed = DateTime.Now - start; AddLog($"Refresh elapsed: {elapsed.TotalMilliseconds}"); } return(true); }
private void RunBlame(BlamePositionModel position) { if (position == null || position.RepoPath == null) { Blame.ClearBlameResult(); } else { ProfileOptimization.StartProfile("Blame"); BlameResult blame = GitWrapper.GetBlameOutput(position.RepoPath, position.FileName, position.CommitId); Blame.SetBlameResult(blame, position.LineNumber ?? 1); } }
public static List <DownloadedRelease> Releases(string repo, string projectName) { GitWrapper project; try { project = GitWrapper.For(repo, projectName); return(project.Releases.ToList().Select(d => DownloadedRelease.MarkAsDownloadedIfDownloaded(repo, projectName, d)).ToList()); } catch (Exception ex) { return(new List <DownloadedRelease>()); } }
protected void ShowDiffView() { // TODO: Implement me!!!! if (workingSetSelectionCache.Count == 1) { if (workingSetSelectionCache.Last != lastSelectedPath) { lastSelectedPath = workingSetSelectionCache.Last; lastDiff = GitWrapper.GetDiff(lastSelectedPath, true); } GUILayout.BeginHorizontal(GitStyles.FileListBox); scrollPosition = DiffGUI.ScrollableWordDiff(scrollPosition, lastDiff, false); GUILayout.EndHorizontal(); } else { GUILayout.Box(GUIHelper.NoContent, GitStyles.FileListBox, GUIHelper.ExpandWidth, GUIHelper.ExpandHeight); } }
public async Task When_no_repository_is_specified_the_repository_is_located_from_the_current_directory(string relativeWorkingDirectoryPath) { // ARRANGE using var temporaryDirectory = new TemporaryDirectory(); var workingDirectory = temporaryDirectory.AddSubDirectory(relativeWorkingDirectoryPath); var git = new GitWrapper(temporaryDirectory, m_TestOutputHelper); await git.InitAsync(); await git.ConfigAsync("user.name", "Example"); await git.ConfigAsync("user.email", "*****@*****.**"); var commit = await git.CommitAsync("feat: Some New feature"); await git.TagAsync("v1.0.0", commit); await Task.Delay(500); var expectedOutputPath = Path.Combine(temporaryDirectory, "changelog.md"); var expectedOutput = String.Join(Environment.NewLine, "# Change Log", "", "## 1.0.0", "", $"#### <a id=\"changelog-heading-{commit.Id.Id}\"></a> Some New feature", "", $"- Commit: `{commit.Id.AbbreviatedId}`", ""); // ACT var result = await RunApplicationAsync( args : new[] { "--verbose" }, workingDirectory : workingDirectory, commandId : $"{nameof(When_no_repository_is_specified_the_repository_is_located_from_the_current_directory)}(\"{relativeWorkingDirectoryPath}\")" ); // ASSERT Assert.Equal(0, result.ExitCode); Assert.True(File.Exists(expectedOutputPath)); Assert.Equal(expectedOutput, File.ReadAllText(expectedOutputPath)); }
public async Task Change_log_is_generated_from_the_specified_repository() { // ARRANGE using var temporaryDirectory = new TemporaryDirectory(); var git = new GitWrapper(temporaryDirectory, m_TestOutputHelper); await git.InitAsync(); await git.ConfigAsync("user.name", "Example"); await git.ConfigAsync("user.email", "*****@*****.**"); var commit = await git.CommitAsync("feat: Some New feature"); await git.TagAsync("v1.0.0", commit); await Task.Delay(500); var expectedOutputPath = Path.Combine(temporaryDirectory, "changelog.md"); var expectedOutput = String.Join(Environment.NewLine, "# Change Log", "", "## 1.0.0", "", $"#### <a id=\"changelog-heading-{commit.Id.Id}\"></a> Some New feature", "", $"- Commit: `{commit.Id.AbbreviatedId}`", ""); // ACT var result = await RunApplicationAsync( args : new[] { "--repository", temporaryDirectory }, commandId : nameof(Change_log_is_generated_from_the_specified_repository) ); // ASSERT Assert.Equal(0, result.ExitCode); Assert.True(File.Exists(expectedOutputPath)); Assert.Equal(expectedOutput, File.ReadAllText(expectedOutputPath)); }
static int ProcessMergeRequests(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string gitRepoPath, string localGitDir, string branchName, string tracker, SyncHistoryWrapper syncHistory, string userName) { var project = gitLabWrapper.FindProject(gitRepoPath); TrackBranch branch = GetBranch(branchName, tracker, vcsWrapper); if (branch == null) { Log.Error($"Specified branch {branchName} not found in track file."); return 1; } var mergeRequests = GetMergeRequests(gitLabWrapper, branchName, userName, project); if (!mergeRequests.Any()) { Log.Message("Zero registered merge requests."); return 0; } int result = 0; foreach (var mergeRequest in mergeRequests) { var mergeRequestResult = ProcessMergeRequest(vcsWrapper, gitWrapper, gitLabWrapper, users, defaultUser, localGitDir, branch, mergeRequest, syncHistory); if (mergeRequestResult == MergeRequestResult.Failed) return 1; if (mergeRequestResult == MergeRequestResult.CheckoutFailed || mergeRequestResult == MergeRequestResult.Conflicts || mergeRequestResult == MergeRequestResult.InvalidState) result = 1; } return result; }
static GitWrapper CreateGitWrapper(string gitRepoPath, string localGitDir, string branchName, string username, string password) { try { var gitWrapper = new GitWrapper(localGitDir, gitRepoPath, branchName, new GitCredentials { User = username, Password = password }); Log.Message($"Branch {branchName} initialized."); return gitWrapper; } catch (Exception e) { Log.Error("Git Wrapper was not created: " + e.Message, e); return null; } }
protected GitWrapper.ChangeType WorkingSetFetcher(GitWrapper.Change change) { return change.workingStatus; }
public void UnstagePath(GitWrapper.ChangeType changeType, string path) { GitWrapper.UnstagePath(path); isDirty = true; }
public ServerUpdater(ILogger <ServerUpdater> logger, IByondWrapper byond, GitWrapper git) { _logger = logger; _byond = byond; _git = git; }
static ProcessHistoryResult ProcessHistory(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, RegisteredUsers users, User defaultUser, string gitRepoPath, string localGitDir, TrackBranch branch, int commitsCount, SyncHistoryWrapper syncHistory, bool mergeCommits) { IList<CommitItem> commits = GenerateCommits(vcsWrapper, branch, syncHistory, mergeCommits); if (commits.Count > commitsCount) { Log.Message($"Commits generated. First {commitsCount} of {commits.Count} commits taken."); commits = commits.Take(commitsCount).ToList(); } else { Log.Message($"Commits generated. {commits.Count} commits taken."); } if (commits.Count > 0) ProcessHistoryInternal(vcsWrapper, gitWrapper, users, defaultUser, localGitDir, branch, commits, syncHistory); Log.Message($"Importing history from vcs completed."); return commits.Count > commitsCount ? ProcessHistoryResult.NotEnough : ProcessHistoryResult.Success; }
protected bool ShowFile(ListView state, string path, GitWrapper.ChangeType status, WholeFileCommand cmd) { Event current = Event.current; bool isChanged = false; bool isSelected = state.selection.IsSelected(path); GUIStyle style = isSelected ? (panelHasFocus && state.hasFocus ? GitStyles.FileLabelSelected : GitStyles.FileLabelSelectedUnfocused) : GitStyles.FileLabel; GUIContent tmp = null; if(!iconCache.ContainsKey(path)) { tmp = new GUIContent() { image = AssetDatabase.GetCachedIcon(path), text = null }; if(tmp.image == null) tmp.image = DEFAULT_FILE_ICON; iconCache[path] = tmp; } tmp = (GUIContent)iconCache[path]; GUILayout.BeginHorizontal(); GUILayout.Label(tmp, style, ICON_WIDTH, ITEM_HEIGHT); Rect iconPosition = GUILayoutUtility.GetLastRect(); Color c = GUI.contentColor; GUI.contentColor = ColorForChangeType(status); Rect labelPosition = EditorGUILayout.BeginVertical(style, MAX_ITEM_HEIGHT); GUILayout.FlexibleSpace(); GUILayout.Label(path, style); GUILayout.Space(ITEM_BASELINE); EditorGUILayout.EndVertical(); GUI.contentColor = c; GUILayout.EndHorizontal(); if(current.type == EventType.MouseDown) { if(iconPosition.Contains(current.mousePosition)) { isChanged = true; cmd(status, path); state.selection.Unselect(path); } else if(labelPosition.Contains(current.mousePosition)) { isChanged = true; isSelected = !isSelected; bool addToSelection = false, rangeSelection = false; if(Event.current.command && Application.platform == RuntimePlatform.OSXEditor) addToSelection = true; else if(Event.current.control && Application.platform == RuntimePlatform.WindowsEditor) addToSelection = true; if(Event.current.shift) rangeSelection = true; if(!addToSelection && !rangeSelection) state.selection.Clear(); state.selection.Set(path, isSelected); // TODO: For range selection we need the list of files, index of last selection, etc. } } return isChanged; }
public Color ColorForChangeType(GitWrapper.ChangeType status) { Color c = Color.red; switch(status) { case GitWrapper.ChangeType.Modified: c = GitStyles.ModifiedColor; break; case GitWrapper.ChangeType.Added: c = GitStyles.AddedColor; break; case GitWrapper.ChangeType.Deleted: c = GitStyles.DeletedColor; break; case GitWrapper.ChangeType.Renamed: c = GitStyles.RenamedColor; break; case GitWrapper.ChangeType.Copied: c = GitStyles.CopiedColor; break; case GitWrapper.ChangeType.Untracked: c = GitStyles.UntrackedColor; break; default: Debug.Log("Should not have gotten this status: " + status); break; } return c; }
public void StagePath(GitWrapper.ChangeType changeType, string path) { if(changeType == GitWrapper.ChangeType.Deleted) { GitWrapper.RemovePath(path); } else { GitWrapper.StagePath(path); } isDirty = true; }
protected string InitNewRepository(string path) { var wrapper = new GitWrapper(path, testUrl, "master", testCredentials); return(wrapper.GitDirectory); }
protected GitWrapper.ChangeType IndexSetFetcher(GitWrapper.Change change) { return change.indexStatus; }
protected string InitNewRepository(string path) { var wrapper = new GitWrapper(path, testUrl, "master", testCredentials); return wrapper.GitDirectory; }
static MergeRequestResult ProcessMergeRequest(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, MergeRequest mergeRequest, SyncHistoryWrapper syncHistory) { switch (mergeRequest.State) { case "reopened": case "opened": return ProcessOpenedMergeRequest(vcsWrapper, gitWrapper, gitLabWrapper, users, defaultUser, localGitDir, branch, mergeRequest, syncHistory); } return MergeRequestResult.InvalidState; }
static MergeRequestResult ProcessOpenedMergeRequest(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, GitLabWrapper gitLabWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, MergeRequest mergeRequest, SyncHistoryWrapper syncHistory) { string autoSyncToken = syncHistory.CreateNewToken(); var lastHistoryItem = syncHistory.GetHead(); Log.Message($"Start merging mergerequest {mergeRequest.Title}"); Log.ResetErrorsAccumulator(); var changes = gitLabWrapper.GetMergeRequestChanges(mergeRequest).ToList(); if (changes.Count >= MaxChangesCount) { Log.Error($"Merge request contains more than {MaxChangesCount} changes and cannot be processed. Split it into smaller merge requests"); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(null)); return MergeRequestResult.Failed; } var genericChange = changes .Where(x => branch.TrackItems.FirstOrDefault(track => CheckItemForChangeSet(x, track)) != null) .Select(x => ProcessMergeRequestChanges(mergeRequest, x, localGitDir, branch, autoSyncToken)).ToList(); bool ignoreValidation = gitLabWrapper.ShouldIgnoreSharedFiles(mergeRequest); if (!ValidateMergeRequestChanges(gitLabWrapper, mergeRequest, ignoreValidation) || !vcsWrapper.ProcessCheckout(genericChange, ignoreValidation, branch)) { Log.Error("Merging merge request failed because failed validation."); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(genericChange)); vcsWrapper.ProcessUndoCheckout(genericChange); return MergeRequestResult.CheckoutFailed; } CommentWrapper comment = CalcComment(mergeRequest, branch, autoSyncToken); mergeRequest = gitLabWrapper.ProcessMergeRequest(mergeRequest, comment.ToString()); if (mergeRequest.State == "merged") { Log.Message("Merge request merged successfully."); gitWrapper.Pull(); gitWrapper.LFSPull(); var gitCommit = gitWrapper.FindCommit(x => CommentWrapper.Parse(x.Message).Token == autoSyncToken); long timeStamp = lastHistoryItem.VcsCommitTimeStamp; if (gitCommit != null && vcsWrapper.ProcessCheckIn(genericChange, comment.ToString())) { var checkinHistory = vcsWrapper.GenerateHistory(branch, new DateTime(timeStamp)).Where(x => x.ActionDate.Ticks > timeStamp); var lastCommit = checkinHistory.OrderBy(x => x.ActionDate).LastOrDefault(); long newTimeStamp = lastCommit?.ActionDate.Ticks ?? timeStamp; var mergeRequestResult = MergeRequestResult.Success; if (!ValidateMergeRequest(vcsWrapper, branch, lastHistoryItem, defaultUser)) mergeRequestResult = MergeRequestResult.Mixed; if (!ValidateChangeSet(genericChange)) mergeRequestResult = MergeRequestResult.Mixed; syncHistory.Add(gitCommit.Sha, newTimeStamp, autoSyncToken, mergeRequestResult == MergeRequestResult.Success ? SyncHistoryStatus.Success : SyncHistoryStatus.Mixed); syncHistory.Save(); Log.Message("Merge request checkin successfully."); return mergeRequestResult; } Log.Error("Merge request checkin failed."); if (gitCommit == null) Log.Error($"Can`t find git commit with token {autoSyncToken}"); var failedHistory = vcsWrapper.GenerateHistory(branch, new DateTime(timeStamp)); var lastFailedCommit = failedHistory.OrderBy(x => x.ActionDate).LastOrDefault(); syncHistory.Add(gitCommit.Sha, lastFailedCommit?.ActionDate.Ticks ?? timeStamp, autoSyncToken, SyncHistoryStatus.Failed); syncHistory.Save(); return MergeRequestResult.Failed; } Log.Message($"Merge request merging failed due conflicts. Resolve conflicts manually."); vcsWrapper.ProcessUndoCheckout(genericChange); AssignBackConflictedMergeRequest(gitLabWrapper, users, mergeRequest, CalcCommentForFailedCheckoutMergeRequest(genericChange)); return MergeRequestResult.Conflicts; }
protected bool WorkingSetFilter(GitWrapper.Change change) { return change.workingStatus != GitWrapper.ChangeType.Unmodified; }
static void ProcessHistoryInternal(DXVcsWrapper vcsWrapper, GitWrapper gitWrapper, RegisteredUsers users, User defaultUser, string localGitDir, TrackBranch branch, IList<CommitItem> commits, SyncHistoryWrapper syncHistory) { ProjectExtractor extractor = new ProjectExtractor(commits, (item) => { var localCommits = vcsWrapper.GetCommits(item.TimeStamp, item.Items).Where(x => !IsLabel(x)).ToList(); bool hasModifications = false; GitCommit last = null; string token = syncHistory.CreateNewToken(); foreach (var localCommit in localCommits) { string localProjectPath = Path.Combine(localGitDir, localCommit.Track.ProjectPath); DirectoryHelper.DeleteDirectory(localProjectPath); string trackPath = branch.GetTrackRoot(localCommit.Track); vcsWrapper.GetProject(vcsServer, trackPath, localProjectPath, item.TimeStamp); Log.Message($"git stage {localCommit.Track.ProjectPath}"); gitWrapper.Stage(localCommit.Track.ProjectPath); string author = CalcAuthor(localCommit, defaultUser); var comment = CalcComment(localCommit, author, token); User user = users.GetUser(author); try { gitWrapper.Commit(comment.ToString(), user, localCommit.TimeStamp, false); last = gitWrapper.FindCommit(x => true); hasModifications = true; } catch (Exception) { Log.Message($"Empty commit detected for {localCommit.Author} {localCommit.TimeStamp}."); } } if (hasModifications) { gitWrapper.PushEverything(); syncHistory.Add(last.Sha, item.TimeStamp.Ticks, token); } else { var head = syncHistory.GetHead(); syncHistory.Add(head.GitCommitSha, item.TimeStamp.Ticks, token); string author = CalcAuthor(item, defaultUser); Log.Message($"Push empty commits rejected for {author} {item.TimeStamp}."); } syncHistory.Save(); }); int i = 0; while (extractor.PerformExtraction()) Log.Message($"{++i} from {commits.Count} push to branch {branch.Name} completed."); }
public void UnstagePath(GitWrapper.ChangeType changeType, string path) { GitWrapper.UnstagePath(path); isDirty = true; }
public BlamePositionModel(string filePath) { FilePath = filePath ?? throw new ArgumentNullException(nameof(filePath)); GitWrapper.SplitRepositoryPath(filePath, out m_repoPath, out m_fileName); }
protected bool IndexSetFilter(GitWrapper.Change change) { return change.indexStatus != GitWrapper.ChangeType.Unmodified && change.indexStatus != GitWrapper.ChangeType.Untracked; }