public void IsGitDir_With_Valid_GitDir_Should_Return_True () { SetupGitRepos (InitialGitStatus.BareAheadOfHome); var configEntry = MakeConfigEntry (); var gitService = new GitService (); Assert.IsTrue(gitService.IsGitDir(configEntry.Local)); }
public void API_Exploring_Getting_MoreInfos_From_NGitPullResponse() { SetupGitRepos (InitialGitStatus.BareAheadOfHome); var configEntry = MakeConfigEntry (); var gitService = new GitService (); // Method under test: // PullResult result = gitService.Pull(configEntry); // // // Assert.IsTrue (result.IsSuccessful()); // // // MergeResult // MergeCommandResult mergeCommandResult = result.GetMergeResult(); // // MergeStatus // MergeStatus mergeStatus = mergeCommandResult.GetMergeStatus(); // Assert.IsTrue (mergeStatus.IsSuccessful()); // // MergeConflicts //// IDictionary<string, int[][]> conflicts = mergeCommandResult.GetConflicts(); //// // //// NGit.ObjectId[] mergedCommits = mergeCommandResult.GetMergedCommits(); // // // Fetched From // string fetchedFrom = result.GetFetchedFrom(); // Assert.AreEqual ("origin", fetchedFrom); // // // FetchResults // Assert.IsNotNull(result.GetFetchResult()); // NGit.Transport.FetchResult fetchResult = result.GetFetchResult(); // Assert.IsNotNullOrEmpty(fetchResult.GetMessages()); }
public void Pull_With_ValidGitDirs_ShouldNot_ThrowException () { var result = SetupGitRepos (InitialGitStatus.BareAheadOfHome); Assert.IsTrue (result.Success); var service = base.InitJsonService(); var config = service.SyncConfig; var gitService = new GitService (); foreach (var entry in config.Entries) { Assert.DoesNotThrow(() => gitService.Pull (entry)); Assert.DoesNotThrow(() => gitService.Push (entry)); } }
public void ShowBranchs(string repositoryName) { RepositoryVO repository = this.Solution.GetRepositoryByName(repositoryName); List <string> branchs = GitService.ListBranchs(repository); string branch = WindowManager.ShowDialogList("Branchs", branchs); if (string.IsNullOrEmpty(branch)) { return; } GitService.UpdateStatus(this.Solution, true); if (!EnsureHasNoChanges()) { return; } GitService.CheckoutBranch(this.Solution, branch); GitService.UpdateStatus(this.Solution, true); this.RefreshUI(); }
/// <summary>更新仓库统计信息</summary> /// <param name="project"></param> private void UpdateRepo(String owner, String project) { using (var git = new GitService(project)) { // 修正提交数、分支、参与人等 var commit = git.Repository.Head.Tip; var ancestors = git.Repository.Commits.QueryBy(new CommitFilter { IncludeReachableFrom = commit }); var set = new HashSet <String>(); var cms = 0; var cts = 0; foreach (var ancestor in ancestors) { cms++; if (set.Add(ancestor.Author.ToString())) { cts++; } } var repo = NewLife.GitCandy.Entity.Repository.FindByOwnerAndName(owner, project); if (repo != null) { if (cms > 0) { repo.Commits = cms; } repo.Branches = git.Repository.Branches.Count(); if (cts > 0) { repo.Contributors = cts; } var size = 0L; repo.Files = FilesInCommit(commit, out size); repo.Size = size; repo.LastCommit = commit.Committer.When.LocalDateTime; repo.SaveAsync(); } } }
public ActionResult Commits(String owner, String name, String path, Int32?page) { using (var git = new GitService(owner, name)) { var model = git.GetCommits(path, page ?? 1, UserConfiguration.Current.Commits); //if (model == null) // throw new HttpException((int)HttpStatusCode.NotFound, String.Empty); ViewBag.Pager = Pager.Items(model.ItemCount) .PerPage(UserConfiguration.Current.Commits) .Move(model.CurrentPage) .Segment(5) .Center(); model.Owner = owner; model.Name = name; return(View(model)); } }
public ActionResult Commits(string name, string path, int?page) { using (var git = new GitService(name)) { var model = git.GetCommits(path, page ?? 1, UserConfiguration.Current.NumberOfCommitsPerPage); if (model == null) { throw new HttpException((int)HttpStatusCode.NotFound, string.Empty); } ViewBag.Pager = Pager.Items(model.ItemCount) .PerPage(UserConfiguration.Current.NumberOfCommitsPerPage) .Move(model.CurrentPage) .Segment(5) .Center(); model.RepositoryName = name; return(View(model)); } }
public ActionResult Edit(SettingModel model) { var needRestart = false; if (ModelState.IsValid) { var verify = GitService.VerifyGit(model.GitExePath); if (!verify) { ModelState.AddModelError("GitExePath", string.Format(SR.Validation_Filepath, "GitExePath", "git.exe")); return(View(model)); } var config = UserConfiguration.Current; needRestart = (config.CachePath != model.CachePath); config.IsPublicServer = model.IsPublicServer; config.ForceSsl = model.ForceSsl; config.SslPort = model.SslPort; config.LocalSkipCustomError = model.LocalSkipCustomError; config.AllowRegisterUser = model.AllowRegisterUser; config.AllowRepositoryCreation = model.AllowRepositoryCreation; config.RepositoryPath = model.RepositoryPath; config.CachePath = model.CachePath; config.GitExePath = model.GitExePath; config.NumberOfCommitsPerPage = model.NumberOfCommitsPerPage; config.NumberOfItemsPerList = model.NumberOfItemsPerList; config.Save(); ModelState.Clear(); } Logger.Info("Settings updated by {0}#{1}", Token.Username, Token.UserID); if (needRestart) { HttpRuntime.UnloadAppDomain(); } return(View(model)); }
public ActionResult Archive(String owner, String name, String path) { using (var git = new GitService(owner, name)) { var repo = Repository.FindByOwnerAndName(owner, name); if (repo != null) { repo.Downloads++; repo.Save(); } var cacheFile = git.GetArchiveFilename(path, out var referenceName); if (cacheFile == null) { throw new HttpException((Int32)HttpStatusCode.NotFound, String.Empty); } var filename = name + "-" + referenceName; return(File(cacheFile, "application/zip", filename + ".zip")); } }
public void Unsure_A_Propperly_Formatted_User_Is_Returned() { var logger = A.Fake <ILogger>(); var restClient = A.Fake <IRestClient>(); var avatarUrl = "https://avatars.githubusercontent.com/u/78586?v=3"; var name = "Rob Conery"; var location = "Seattle, WA"; A.CallTo(() => restClient.Execute(null)).WithAnyArguments().Returns(UserJson()); var userResult = new GitService(logger, restClient).GetGitUser(new GetGitUserRequest("Username")); Assert.IsNotNull(userResult); Assert.IsNotNull(userResult.User); Assert.AreEqual(avatarUrl, userResult.User.AvatarUrl); Assert.AreEqual(name, userResult.User.Name); Assert.AreEqual(location, userResult.User.Location); A.CallTo(() => logger.Error(string.Empty)).MustNotHaveHappened(); }
public ActionResult Blob(String owner, String name, String path) { using (var git = new GitService(owner, name)) { var model = git.GetBlob(path); if (model == null) { throw new HttpException((Int32)HttpStatusCode.NotFound, String.Empty); } // 修正Markdown if (model.Name.EndsWithIgnoreCase(".md")) { model.FixMarkdown($"/{owner}/{name}"); } model.Name = name; return(View(model)); } }
public void Branch_With_Remote() { using (var temp = new TempRepository()) { var repository = temp.Repository; var owner = "owner"; var remoteName = "remoteName"; var remote = repository.Network.Remotes.Add(remoteName, $"https://github.com/{owner}/VisualStudio"); var localBranch = repository.Head; repository.Branches.Update(temp.Repository.Head, b => b.Remote = remote.Name, b => b.UpstreamBranch = localBranch.CanonicalName); var path = temp.Directory.FullName; var target = new GitService(new RepositoryFacade()); var localRepository = target.CreateLocalRepositoryModel(path); var branch = target.GetBranch(localRepository); Assert.That(branch.TrackedRemoteName, Is.EqualTo(remoteName)); } }
public void Master_Branch() { using (var temp = new TempRepository()) { var signature = new Signature("Me", "*****@*****.**", DateTimeOffset.Now); temp.Repository.Commit("First", signature, signature); var expectSha = temp.Repository.Head.Tip.Sha; var path = temp.Directory.FullName; var target = new GitService(new RepositoryFacade()); var localRepository = target.CreateLocalRepositoryModel(path); var branch = target.GetBranch(localRepository); Assert.That(branch.Name, Is.EqualTo("master")); Assert.That(branch.DisplayName, Is.EqualTo("master")); Assert.That(branch.Id, Is.EqualTo("/master")); // We don't know owner Assert.That(branch.IsTracking, Is.EqualTo(false)); Assert.That(branch.TrackedSha, Is.EqualTo(null)); Assert.That(branch.Sha, Is.EqualTo(expectSha)); } }
public async Task HeadAndRemoteOnSameCommit_ReturnCommitSha() { using (var temp = new TempDirectory()) { string expectSha; var dir = temp.Directory.FullName; using (var repo = new Repository(Repository.Init(dir))) { AddCommit(repo); // First commit var commit = AddCommit(repo); expectSha = commit.Sha; AddTrackedBranch(repo, repo.Head, commit); } var target = new GitService(new RepositoryFacade()); var sha = await target.GetLatestPushedSha(dir).ConfigureAwait(false); Assert.That(sha, Is.EqualTo(expectSha)); } }
public ActionResult Contributors(String owner, String name, String path) { using (var git = new GitService(name)) { var model = git.GetContributors(path); if (model == null) { throw new HttpException((int)HttpStatusCode.NotFound, String.Empty); } // 修正文件数 var repo = Repository.FindByOwnerAndName(owner, name); if (repo != null) { repo.Files = model.Statistics.Current.NumberOfFiles; repo.SaveAsync(); } return(View(model)); } }
public ActionResult Edit(String owner, String name, RepositoryModel model) { if (String.IsNullOrEmpty(name)) { throw new HttpException((Int32)HttpStatusCode.NotFound, String.Empty); } if (ModelState.IsValid) { if (!RepositoryService.Update(owner, model)) { throw new HttpException((Int32)HttpStatusCode.NotFound, String.Empty); } using (var git = new GitService(owner, name)) { git.SetHeadBranch(model.DefaultBranch); } return(RedirectToAction("Detail", new { name })); } return(View(model)); }
public ActionResult Archive(string name, string path, string eol = null) { using (var git = new GitService(name)) { string newline = null; switch (eol) { case "LF": newline = "\n"; break; case "CR": newline = "\r"; break; case "CRLF": newline = "\r\n"; break; default: eol = null; break; } string referenceName; var cacheFile = git.GetArchiveFilename(path, newline, out referenceName); if (cacheFile == null) { throw new HttpException((int)HttpStatusCode.NotFound, string.Empty); } var filename = name + "-" + referenceName; if (eol != null) { filename += "-" + eol; } return(File(cacheFile, "application/zip", filename + ".zip")); } }
public Result Apply(string markdown, Context context) { var pattern = @"\{\{\W*GIT_VERSIONS\W*\}\}"; var result = markdown; if (Regex.IsMatch(markdown, pattern, RegexOptions.IgnoreCase)) { var changes = GitService.GetVersions(_sourceFilePath, _ignoreGitCommitsSince).ToList(); string replacement; if (changes.Any()) { replacement = "| Datum | Person | Version | Änderung" + Environment.NewLine + "|-|-|-|-|"; for (var i = 0; i < changes.Count; i++) { var change = changes[i]; // if we have the same message multiple times in a row, just use the latest commit if (i > 0 && (changes[i - 1].Message ?? "").Equals(change.Message, StringComparison.OrdinalIgnoreCase)) { continue; } replacement += Environment.NewLine + $"| {change.Date.ToString("dd. MM. yyyy", new CultureInfo("de-DE")).Replace(" ", " ")} |" + $" {change.Author.Replace(" ", " ")} |" + $" {change.ShaShort} |" + $" {change.MessageShort} {(string.IsNullOrWhiteSpace(change.Message) ? "" : $"<span class=\"git-version-details\"><br />{change.Message.Substring(change.MessageShort.Length).Replace("\r", "").Replace("\n", "").Trim()}")}</span>"; } } else { replacement = "{{!}} Dieses Dokument befindet sich nicht in Versionskontrolle."; } result = Regex.Replace(result, pattern, replacement, RegexOptions.IgnoreCase); } return(new Result(result, context)); }
public void Unsure_A_Propperly_Formatted_UserRepository_Is_Returned() { var logger = A.Fake <ILogger>(); var restClient = A.Fake <IRestClient>(); var jsonResult = RepositoryJson(); A.CallTo(() => restClient.Execute(null)).WithAnyArguments().Returns(jsonResult); var userRepository = new GitService(logger, restClient).GetGitUserRepositories(new GetGitRepositoriesRequest() { Username = "******" }); Assert.IsNotNull(userRepository); Assert.IsNotNull(userRepository.Repositories.Any()); foreach (var repo in userRepository.Repositories) { } A.CallTo(() => logger.Error(string.Empty)).MustNotHaveHappened(); }
public async Task <IActionResult> GetTreeView(string userName, string repoName, string id, string path) { XTrace.UseConsole(); var DCRepositoriesService = Ioc.Create <IDCRepositoriesService>(); repoName = Path.Combine(userName, repoName); Repository repo = DCRepositoriesService.GetRepository(repoName); Commit commit = repo.Branches[id]?.Tip ?? repo.Lookup <Commit>(id); if (commit == null) { return(View("Init")); } using (var git = new GitService(repoName)) { if (!path.IsNullOrEmpty()) { path = id + "/" + path; } var model = await git.GetTree(path); if (model == null) { return(NotFound()); } if (model.Entries == null && model.ReferenceName != "HEAD") { return(RedirectToAction("Tree", new { path = model.ReferenceName })); } XTrace.WriteLine(model.ToJson()); return(View("Tree", model)); } }
/// <inheritdoc/> public Action <IApplicationBuilder> Configure(Action <IApplicationBuilder> next) { if (ApplicationOptions.Username != null || ApplicationOptions.Password != null) { if (ApplicationOptions.Username == null) { throw new ApplicationException("Error in configuration: Password set without Username"); } else if (ApplicationOptions.Password == null) { throw new ApplicationException("Error in configuration: Username set without Password"); } } try { YamlConfigurationService.LoadConfiguration(); var repositories = YamlConfigurationService.Repositories ?? Enumerable.Empty <RepositoryDescriptor>(); foreach (var repository in repositories) { Logger.LogInformation("Initializing repository '{repository}'", repository.Name); GitService.InitializeRepository(repository); } NotificationsService.ConfigureRepositories(YamlConfigurationService.YamlConfiguration?.RefreshInterval ?? 5, repositories); } catch (Exception exc) { throw new ApplicationException("Error loading configuration: " + exc.Message + (exc.InnerException is null ? string.Empty : $" ({exc.InnerException.Message})")); } return(next); }
public void CreateBranch() { if (this.Solution == null) { return; } if (this.WorkItem == null) { MessageBox.ErrorQuery(50, 7, "VSTS", "You must select a work item first", "Ok"); return; } if (!EnsureHasNoChanges()) { return; } WindowManager.ShowLog(); GitService.CheckoutBranch(this.Solution, this.BranchBase); GitService.Pull(this.Solution); GitService.CreateBranch(this.Solution, this.WorkItem); GitService.UpdateStatus(this.Solution, true); WindowManager.CloseLog(); this.RefreshUI(); }
/// <summary> /// This is called on a background thread. Do not do synchronous GetService calls here. /// </summary> /// <param name="active"></param> /// <param name="refresh"></param> async void UIContextChanged(bool active, bool refresh) { Debug.Assert(ServiceProvider != null, "UIContextChanged called before service provider is set"); if (ServiceProvider == null) { return; } if (active) { if (ActiveRepo == null || refresh) { ActiveRepo = await System.Threading.Tasks.Task.Run(() => { var repos = GitService.ActiveRepositories; // Looks like this might return null after a while, for some unknown reason // if it does, let's refresh the GitService instance in case something got wonky // and try again. See issue #23 if (repos == null) { log.Error("Error 2001: ActiveRepositories is null. GitService: '{GitService}'", GitService); GitService.Refresh(ServiceProvider); repos = GitService.ActiveRepositories; if (repos == null) { log.Error("Error 2002: ActiveRepositories is null. GitService: '{GitService}'", GitService); } } return(repos?.FirstOrDefault()); }); } } else { ActiveRepo = null; } }
private SelectableAction[] GetActions(string path) { var actions = new List <SelectableAction> { new SelectableAction("Open", () => FolderService.OpenLocation(path)), }; //if (false) // Disable until I can figure it out //{ // actions.Add(new SelectableAction("Terminal", () => TerminalService.OpenTerminal(path))); //} var hasGit = GitService.TryGetRemoteGitLocation(path, out string uri); if (hasGit) { actions.Add(new SelectableAction("Web", () => StartProgramService.StartProgram(uri))); } foreach (var type in m_programTypesToStart) { actions.Add(new SelectableAction(type, () => StartProgramService.StartProgramOfType(type, path, true))); } foreach (var type in m_programTypesTopFolderToStart) { actions.Add(new SelectableAction(type, () => StartProgramService.StartProgramOfType(type, path, false))); } foreach (var script in m_scripts) { actions.Add(new SelectableAction(script.Key, () => StartProgramService.RunScript(script, path))); } return(actions.ToArray()); }
private void Button_Click(object sender, RoutedEventArgs e) { if (string.IsNullOrEmpty(TokenInputBox.Text)) { MessageBox.Show("No token"); } else { HttpClient client = new HttpClient(); client.BaseAddress = new Uri("https://api.github.com"); var token = TokenInputBox.Text; var service = new GitService(token); if (service.AuthenticateUser(token)) { Home home = new Home(token); home.Show(); this.Close(); } else { MessageBox.Show("Bad Token"); } } }
public async Task BehindRemoteBranch_ReturnRemoteCommitSha(string remoteName, bool expectFound) { using (var temp = new TempDirectory()) { string expectSha; var dir = temp.Directory.FullName; using (var repo = new Repository(Repository.Init(dir))) { AddCommit(repo); // First commit var commit1 = AddCommit(repo); var commit2 = AddCommit(repo); var branchA = repo.Branches.Add("branchA", commit2); repo.Reset(ResetMode.Hard, commit1); expectSha = expectFound ? commit1.Sha : null; AddTrackedBranch(repo, branchA, commit2, remoteName: remoteName); } var target = new GitService(new RepositoryFacade()); var sha = await target.GetLatestPushedSha(dir).ConfigureAwait(false); Assert.That(sha, Is.EqualTo(expectSha)); } }
public async Task BranchForkedFromMaster_ReturnRemoteCommitSha() { using (var temp = new TempDirectory()) { string expectSha; var dir = temp.Directory.FullName; using (var repo = new Repository(Repository.Init(dir))) { AddCommit(repo); // First commit var commit1 = AddCommit(repo); AddTrackedBranch(repo, repo.Head, commit1); var branch = repo.Branches.Add("branch", commit1); Commands.Checkout(repo, branch); var commit2 = AddCommit(repo); expectSha = commit1.Sha; } var target = new GitService(new RepositoryFacade()); var sha = await target.GetLatestPushedSha(dir).ConfigureAwait(false); Assert.That(sha, Is.EqualTo(expectSha)); } }
public ActionResult Tree(string name, string path) { using (var git = new GitService(name)) { var model = git.GetTree(path); if (model == null) { throw new HttpException((int)HttpStatusCode.NotFound, string.Empty); } if (model.Entries == null && model.ReferenceName != "HEAD") { return(RedirectToAction("Tree", new { path = model.ReferenceName })); } model.GitUrls = GetGitUrl(name); model.RepositoryName = name; if (model.IsRoot) { var m = RepositoryService.GetRepositoryModel(name); model.Description = m.Description; } return(View(model)); } }
protected ActionResult ExecutePack(string project, string service) { Response.Charset = ""; Response.ContentType = String.Format(CultureInfo.InvariantCulture, "application/x-{0}-result", service); SetNoCache(); try { using (var git = new GitService(GitService.GetDirectoryInfo(project).FullName)) { var svc = service.Substring(4); git.ExecutePack(svc, GetInputStream(), Response.OutputStream); } return(new EmptyResult()); } catch (RepositoryNotFoundException e) { throw new HttpException((int)HttpStatusCode.NotFound, string.Empty, e); } catch (Exception e) { throw new HttpException((int)HttpStatusCode.InternalServerError, string.Empty, e); } }
public ActionResult Create(RepositoryModel model) { if (ModelState.IsValid) { try { var repo = RepositoryService.Create(model); if (repo != null) { //var success = GitService.CreateRepository(model.Owner, model.Name); var remoteUrl = model.HowInit.EqualIgnoreCase("Import") ? model.RemoteUrl : null; var success = GitService.CreateRepository(model.Owner, model.Name, remoteUrl); if (!success) { RepositoryService.Delete(Token?.Name, model.Name); repo = null; } } if (repo != null) { return(RedirectToAction("Tree", "Repository", new { owner = model.Owner, name = repo.Name })); } } catch (ArgumentException ex) { //ModelState.AddModelError(ex.ParamName, SR.Repository_AlreadyExists); ModelState.AddModelError(ex.ParamName, ex.Message); } catch (Exception ex) { ModelState.AddModelError("", ex); } } return(CreateView(model)); }
public void Push_WithInvalid_GitDirs_Should_ThrowException () { var result = SetupGitRepos (InitialGitStatus.BareAheadOfHome); Assert.IsTrue (result.Success); var configEntry = MakeConfigEntry(); configEntry.Local = configEntry.Local + "_invalid"; configEntry.Remote = configEntry.Remote; var gitService = new GitService (); var ex = Assert.Throws<JGitInternalException>(() => gitService.Push (configEntry)); Assert.That (ex.InnerException is NoRemoteRepositoryException); }
public void Push_WithValid_Setup_Should_Return_SuccessTrue() { var result = SetupGitRepos (InitialGitStatus.HomeAheadOfBare); Assert.IsTrue (result.Success); var service = base.InitJsonService(); var config = service.SyncConfig; var gitService = new GitService (); foreach (var entry in config.Entries) { var resultFromPush = gitService.Push (entry); Assert.That(resultFromPush.Msg.Contains("STATUS: OK")); Assert.IsTrue(resultFromPush.Success); } }
public CreateRepo(GitService git) { InitializeComponent(); this.git = git; CloseButton.Click += (s, e) => Close(); }
public GenerateTocHandler(GitService aGitService) { GitService = aGitService; }
public RepoViewModel(GitService gitService, IFolderDialogService folderDialogService) { this.gitService = gitService; this.folderDialogService = folderDialogService; }