public CommitWrapper(LibGit2Sharp.Commit commit) { this.commit = commit; Sha = commit.Sha; MessageShort = commit.MessageShort; Message = commit.Message; Author = commit.Author; Committer = commit.Committer; Tree = (async (i) => commit.Tree); Parents = (async (i) => commit.Parents.Select((p) => new CommitWrapper(p))); }
static Branch[] CalculateWhenMultipleParents(IRepository repository, Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repository.Branches.Where(b => !b.IsRemote && b.Tip == parents[1]).ToList(); if (branches.Count == 1) { var branch = branches[0]; excludedBranches = new[] { currentBranch, branch }; currentBranch = branch; } else if (branches.Count > 1) { currentBranch = branches.FirstOrDefault(b => b.Name == "master") ?? branches.First(); } else { var possibleTargetBranches = repository.Branches.Where(b => !b.IsRemote && b.Tip == parents[0]).ToList(); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.Name == "master") ?? possibleTargetBranches.First(); } else { currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch; } } Logger.WriteInfo("HEAD is merge commit, this is likely a pull request using " + currentBranch.Name + " as base"); return excludedBranches; }
public IEnumerable <CommitAggregate> Get() { ICommitLog commitLog = _repo.Commits.QueryBy(new CommitFilter()); IEnumerator <LibGit2Sharp.Commit> commitEnumerator = commitLog.GetEnumerator(); commitEnumerator.MoveNext(); LibGit2Sharp.Commit previousCommit = commitEnumerator.Current; while (commitEnumerator.MoveNext()) { // As the enumerator reads the history top down, the current enumerator value // is the older commit. Therefore, the previousCommit is the newer commit. Tree olderCommitTree = commitEnumerator.Current.Tree; Tree newerCommmitTree = previousCommit.Tree; Patch patch = _repo.Diff.Compare <Patch>(olderCommitTree, newerCommmitTree); previousCommit = commitEnumerator.Current; yield return(new CommitAggregate { Commit = commitEnumerator.Current, Changes = patch }); } }
/// <summary> /// Commit changes for repository /// </summary> /// <param name="commitInfo">Information about the commit</param> public void Commit(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); using (LibGit2Sharp.Repository repo = new LibGit2Sharp.Repository(localServiceRepoFolder)) { string remoteUrl = FindRemoteRepoLocation(commitInfo.Org, commitInfo.Repository); Remote remote = repo.Network.Remotes["origin"]; if (!remote.PushUrl.Equals(remoteUrl)) { // This is relevant when we switch beteen running designer in local or in docker. The remote URL changes. // Requires adminstrator access to update files. repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl); } Commands.Stage(repo, "*"); // Create the committer's signature and commit LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext), "@jugglingnutcase", DateTime.Now); LibGit2Sharp.Signature committer = author; // Commit to the repository LibGit2Sharp.Commit commit = repo.Commit(commitInfo.Message, author, committer); } }
/// <summary> /// Answer is file was modified in current commit (in compare with all parent commits) /// </summary> /// <param name="commit">Current commit</param> /// <param name="file">File path</param> /// <returns>True if file was modified</returns> private bool IsFileWasUpdated(LibGit2Sharp.Commit commit, string file) { // File not exist if (commit.Tree[file] == null) { return(false); } // TODO: File was deleted or renamed: if (commit.Tree[file] == null && commit.Parents.Count() > 0 && commit.Parents.All(e => e.Tree[file] != null)) return true; // It's first commit so file was just created. if (!commit.Parents.Any()) { return(true); } // Did not exist before if (commit.Parents.All(e => e.Tree[file] == null)) { return(true); } // Nothing related to parent files if (commit.Parents.All(e => e.Tree[file] == null || e.Tree[file].Target.Id != commit.Tree[file].Target.Id)) { return(true); } return(false); }
private static IEnumerable<Commit> GetIntermediateCommits(IRepository repo, Commit baseCommit, Commit headCommit) { if (baseCommit == null) yield break; if (intermediateCommitCache == null || intermediateCommitCache.LastOrDefault() != headCommit) { var filter = new CommitFilter { Since = headCommit, SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Reverse }; intermediateCommitCache = repo.Commits.QueryBy(filter).ToList(); } var found = false; foreach (var commit in intermediateCommitCache) { if (commit.Sha == baseCommit.Sha) found = true; if (found) yield return commit; } }
public SemanticVersion FindVersion(IRepository repository, Commit tip) { int major; int minor; int patch; foreach (var tag in repository.TagsByDate(tip)) { if (ShortVersionParser.TryParse(tag.Name, out major, out minor, out patch)) { return BuildVersion(repository, tip, major, minor, patch); } } var semanticVersion = new SemanticVersion(); string versionString; if (MergeMessageParser.TryParse(tip, out versionString)) { if (ShortVersionParser.TryParse(versionString, out major, out minor, out patch)) { semanticVersion = BuildVersion(repository, tip, major, minor, patch); } } semanticVersion.OverrideVersionManuallyIfNeeded(repository); if (semanticVersion == null || semanticVersion.IsEmpty()) { throw new WarningException("The head of a support branch should always be a merge commit if you follow gitflow. Please create one or work around this by tagging the commit with SemVer compatible Id."); } return semanticVersion; }
public CommitModel(Commit commit) { Hash = commit.Id.Sha; Who = commit.Author.Name; When = commit.Author.When; What = commit.MessageShort; }
/// <summary> /// Load file cotent from specified commit /// </summary> public static string GetFileFromCommit(LibGit2Sharp.Commit commit, string path) { try { var gitFile = commit[path]; if (gitFile == null || !(gitFile.Target is Blob)) { // TODO: Compare with previous file path/name // File was renamed or moved. return(string.Empty); } else { var blob = (Blob)gitFile.Target; // TODO: probably use commit.Encoding using (var reader = new StreamReader(blob.GetContentStream(), Encoding.UTF8)) { return(reader.ReadToEnd()); } } } catch (Exception ex) { return(string.Empty); } return(string.Empty); }
public TagCommit( Commit c, ReleaseTagVersion first ) { Debug.Assert( c != null && first != null && first.IsValid ); _commitSha = c.Sha; _contentSha = c.Tree.Sha; _thisTag = first; }
public int NumberOfCommitsOnBranchSinceCommit(Branch branch, Commit commit) { var olderThan = branch.Tip.Committer.When; return branch.Commits .TakeWhile(x => x != commit) .Count(); }
public void Visit(Commit commit) { Dictionary<DateTime, List<CommitDetails>> commitsOnDay = null; if (!commitsByAuthor.TryGetValue(commit.Author.Email, out commitsOnDay)) { commitsOnDay = new Dictionary<DateTime, List<CommitDetails>>(); commitsByAuthor.Add(commit.Author.Email, commitsOnDay); } DateTime commitDate = commit.Committer.When.DateTime.Round(TimeSpan.FromDays(1)); List<CommitDetails> commitDetails = null; if (!commitsOnDay.TryGetValue(commitDate, out commitDetails)) { commitDetails = new List<CommitDetails>(); commitsOnDay[commitDate] = commitDetails; } commitDetails.Add(new CommitDetails() { Id = commit.Id.Sha.Substring(0, 7), Author = commit.Author.Email, Message = commit.Message, CommitTime = commit.Committer.When.DateTime }); }
public static KeyValuePair<string, BranchConfig> GetBranchConfiguration(Commit currentCommit, IRepository repository, bool onlyEvaluateTrackedBranches, Config config, Branch currentBranch, IList<Branch> excludedInheritBranches = null) { var matchingBranches = LookupBranchConfiguration(config, currentBranch); if (matchingBranches.Length == 0) { var branchConfig = new BranchConfig(); ConfigurationProvider.ApplyBranchDefaults(config, branchConfig); return new KeyValuePair<string, BranchConfig>(string.Empty, branchConfig); } if (matchingBranches.Length == 1) { var keyValuePair = matchingBranches[0]; var branchConfiguration = keyValuePair.Value; if (branchConfiguration.Increment == IncrementStrategy.Inherit) { return InheritBranchConfiguration(onlyEvaluateTrackedBranches, repository, currentCommit, currentBranch, keyValuePair, branchConfiguration, config, excludedInheritBranches); } return keyValuePair; } const string format = "Multiple branch configurations match the current branch branchName of '{0}'. Matching configurations: '{1}'"; throw new Exception(string.Format(format, currentBranch.Name, string.Join(", ", matchingBranches.Select(b => b.Key)))); }
private Commit Convert_Commit(IList <Author> authors, LibGit2Sharp.Commit commit) { var result = new Commit { Author = Find_Commit_Author(authors, commit), When = commit.Committer.When.DateTime }; foreach (var commitParent in commit.Parents) { var fileChanges = _repository.Diff.Compare <LibGit2Sharp.Patch>(commitParent.Tree, commit.Tree); foreach (var fileChange in fileChanges) { result.Patch.Add(new Patch { LinesAdded = fileChange.LinesAdded, LinesRemoved = fileChange.LinesDeleted, Contents = fileChange.Patch, ChangeType = Set_Status(fileChange.Status) }); } } return(result); }
/// <inheritdoc /> public Designer.Models.Commit GetInitialCommit(string org, string repository) { string localServiceRepoFolder = _settings.GetServicePath(org, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); Designer.Models.Commit commit = null; using var repo = new LibGit2Sharp.Repository(localServiceRepoFolder); if (repo.Commits.Any() && repo.Commits.Last() != null) { LibGit2Sharp.Commit firstCommit = repo.Commits.Last(); commit = new Designer.Models.Commit(); commit.Message = firstCommit.Message; commit.MessageShort = firstCommit.MessageShort; commit.Encoding = firstCommit.Encoding; commit.Sha = firstCommit.Sha; commit.Author = new Designer.Models.Signature(); commit.Author.Email = firstCommit.Author.Email; commit.Author.Name = firstCommit.Author.Name; commit.Author.When = firstCommit.Author.When; commit.Comitter = new Designer.Models.Signature(); commit.Comitter.Name = firstCommit.Committer.Name; commit.Comitter.Email = firstCommit.Committer.Email; commit.Comitter.When = firstCommit.Committer.When; } else { _logger.LogWarning($" // SourceControlSI // GetInitialCommit // Did not find any commits in repo {localServiceRepoFolder}"); } return(commit); }
/* * /// <summary> * /// Reserve position for the current branch. Any branch on the same position should move right. * /// </summary> * /// <param name="snapshot">Comit that claims position</param> * private void ReserveBranchOffset(Snapshot snapshot) { * for (int i = snapshot.VisibleOrder + 1; i < snapshots.Where(e => e.IsCommitVisible).Count(); i++) { * if (snapshots[i].TreeOffset == snapshot.TreeOffset) { * snapshots[i].TreeOffset++; * ReserveBranchOffset(snapshots[i]); * } * } * } */ /// <summary> /// Verify is file had the same name in the previous commit or was renamed/moved /// </summary> /// <param name="snapshot">Observable snapshot</param> /// <param name="diff">Commits comparer</param> /// <param name="commit">Current commit</param> /// <param name="name">Current file name</param> /// <returns>File name in previous commit</returns> private string GetPreviousCommitFileName(Snapshot snapshot, Diff diff, LibGit2Sharp.Commit commit, string name) { // When you git commit normally, the current commit // becomes the parent commit of the new commit that's introduced by the command. // When you git merge two commits (or branches, whatever) without fast-forwarding, // a new commit will be created with both commits as parents. // You can merge more than two commits in that way, so the new commit may have more than two parents. if (!commit.Parents.Any()) { // No parent commits. Stop history looping. Probably is't already last (first) commit. snapshot.FilePathState = FilePathState.Unknown; return(string.Empty); } foreach (var parent in commit.Parents) { var treeComparer = diff.Compare <TreeChanges>(parent.Tree, commit.Tree); // If file was renamed than continue to work with previous name foreach (var f in treeComparer.Renamed) { if (name == f.Path) { snapshot.FilePathState |= FilePathState.Changed; snapshot.PreviousFilePath = f.OldPath; } } // If file was just added than nothing to continue foreach (var f in treeComparer.Added) { if (name == f.Path) { snapshot.FilePathState |= FilePathState.Added; } } // TODO: Probably we should set branch source in commit // TODO: Not sure about files conflicts (paralel creating the same file and moving to one branch!) // TODO: Add notificaton message: Added/Removed/Updated Code // Renamed/Moved/Created File // TODO: Investigate: // - treeComparer.TypeChanged // - treeComparer.Copied } if (snapshot.FilePathState == FilePathState.Added) { return(string.Empty); } if (snapshot.FilePathState == FilePathState.Changed) { return(snapshot.PreviousFilePath); } // No path/name changes was found. snapshot.FilePathState = FilePathState.NotChanged; return(name); }
/// <inheritdoc /> public Altinn.Studio.Designer.Models.Commit GetInitialCommit(string org, string repository) { List <Altinn.Studio.Designer.Models.Commit> commits = new List <Altinn.Studio.Designer.Models.Commit>(); string localServiceRepoFolder = _settings.GetServicePath(org, repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); using (var repo = new LibGit2Sharp.Repository(localServiceRepoFolder)) { LibGit2Sharp.Commit firstCommit = repo.Commits.Last(); Designer.Models.Commit commit = new Designer.Models.Commit(); commit.Message = firstCommit.Message; commit.MessageShort = firstCommit.MessageShort; commit.Encoding = firstCommit.Encoding; commit.Sha = firstCommit.Sha; commit.Author = new Designer.Models.Signature(); commit.Author.Email = firstCommit.Author.Email; commit.Author.Name = firstCommit.Author.Name; commit.Author.When = firstCommit.Author.When; commit.Comitter = new Designer.Models.Signature(); commit.Comitter.Name = firstCommit.Committer.Name; commit.Comitter.Email = firstCommit.Committer.Email; commit.Comitter.When = firstCommit.Committer.When; return(commit); } }
private void ImportTag(string name, LibGit2Sharp.Commit commit, bool isRelease) { Debug.WriteLine("ImportTag({0}, {1}, {2})", name, commit.Sha, isRelease); int?commitId = ImportCommit(commit); if (commitId == null) { return; } TaggedCommit tag = db.GetTag(name, isRelease); if (tag != null) { if (tag.CommitId == commitId) { return; } Debug.WriteLine("Update " + (isRelease ? "tag" : "branch") + " " + name + " (commit " + commit.Sha + ")"); tag.CommitId = commitId.Value; } else { Debug.WriteLine("Import " + (isRelease ? "tag" : "branch") + " " + name + " (commit " + commit.Sha + ")"); tag = new TaggedCommit(); tag.CommitId = commitId.Value; tag.Name = name; tag.IsRelease = isRelease; db.Context.TaggedCommits.AddObject(tag); } db.Context.SaveChanges(); }
public BisectStep(Commit c, int result) { commit = c; if (-1 <= result && result <= 1) i = result; else i = Result.NOTSET; }
/// <summary> /// Create a TAR archive of the given commit. /// </summary> /// <param name="odb">The object database.</param> /// <param name="commit">commit.</param> /// <param name="archivePath">The archive path.</param> public static void Archive(this ObjectDatabase odb, Commit commit, string archivePath) { using (var output = new FileStream(archivePath, FileMode.Create)) using (var archiver = new TarArchiver(output)) { odb.Archive(commit, archiver); } }
public BaseVersion(string source, bool shouldIncrement, SemanticVersion semanticVersion, Commit baseVersionSource, string branchNameOverride) { Source = source; ShouldIncrement = shouldIncrement; SemanticVersion = semanticVersion; BaseVersionSource = baseVersionSource; BranchNameOverride = branchNameOverride; }
public static GraphEntry FromCommit(GraphEntry previous, Commit commit) { if (previous == null) { return CreateFirstEntry(commit); } return CreateEntryFromCommit(previous, commit); }
internal GitCommit(Commit commit) { Sha = commit.Sha; Author = new GitSignature(commit.Author.Email, commit.Author.Name, commit.Author.When); Committer = new GitSignature(commit.Committer.Email, commit.Committer.Name, commit.Committer.When); Message = commit.Message; MessageShort = commit.MessageShort; }
private bool AfterDate(Commit commit) { if (from != null) { return commit.Committer.When.Date >= from; } return true; }
private bool ContainsComment(Commit commit) { if (!string.IsNullOrEmpty(comment)) { return commit.Message.ToLower().Contains(comment.ToLower()) || commit.MessageShort.ToLower().Contains(comment.ToLower()); ; } return true; }
private bool ContainsUser(Commit commit) { if (!string.IsNullOrEmpty(user)) { return commit.Committer.Name.Equals(user); } return true; }
private bool BeforeDate(Commit commit) { if (to != null) { return commit.Committer.When.Date <= to; } return true; }
private bool HighlightCommit(Commit commit) { CommitVertex commitVertex = GetCommitVertex(commit); if (commitVertex.OnCurrentBranch) return false; commitVertex.OnCurrentBranch = true; return true; }
public ChangeSet GetChangeSet(string id) { using (var repo = new LibGit2Sharp.Repository(RepositoryPath)) { LibGit2Sharp.Commit commit = repo.Lookup <LibGit2Sharp.Commit>(id); return(commit == null ? null : new ChangeSet(commit.Sha, commit.Author.Name, commit.Author.Email, commit.Message, commit.Author.When)); } }
public CommitItem( Commit commit ) { d = commit.Author.When; //commitMessage = commit.Message.Split( "\r\n".ToCharArray() )[ 0 ]; commitMessage = commit.MessageShort; hour = ( d.Hour.ToString().Length == 1 ) ? "0" + d.Hour : d.Hour.ToString(); minute = ( d.Minute.ToString().Length == 1 ) ? "0" + d.Minute : d.Minute.ToString(); second = ( d.Second.ToString().Length == 1 ) ? "0" + d.Second : d.Second.ToString(); dateString = d.Month + "/" + d.Day + "/" + d.Year + " " + hour + ":" + minute + ":" + second; }
public GitDiffDirectory(Commit commit) { var files = new List<IDiffFile>(); GitMergeOperation.WalkTree(commit.Tree, (path, blob) => { files.Add(new GitDiffFile(blob) { Path = path }); }); _files = files; }
/// <summary> /// Initializes a new instance of the <see cref="SimpleCommit" /> class. /// </summary> /// <param name="rocket">The rocket.</param> /// <param name="commit">The commit.</param> /// <exception cref="System.ArgumentNullException">commit</exception> internal SimpleCommit(RocketFilterApp rocket, Commit commit) { if (commit == null) throw new ArgumentNullException("commit"); this.rocket = rocket; this.commit = commit; // Update all properties Reset(); }
public static async Task<Patch> GetChangeSet(Repository repo, Commit commit) { return await new Task<Patch>(() => { var commitTree = commit.Tree; // Main Tree var parentCommitTree = commit.Parents.Single().Tree; // Secondary Tree return repo.Diff.Compare<Patch>(parentCommitTree, commitTree); // Difference }); }
public void Visit(Commit commit) { DateTime commitDate = commit.Committer.When.DateTime.Round(TimeSpan.FromDays(1)); if (!commitCountByDate.ContainsKey(commitDate)) { commitCountByDate[commitDate] = 0; } commitCountByDate[commitDate] += 1; totalCommitCount++; }
internal HistoryDivergence(Repository repo, Commit one, Commit another) { commonAncestor = new Lazy<Commit>(() => repo.Commits.FindCommonAncestor(one, another)); Tuple<int?, int?> div = Proxy.git_graph_ahead_behind(repo.Handle, another, one); One = one; Another = another; AheadBy = div.Item1; BehindBy = div.Item2; }
public static bool TryParse(Commit mergeCommit, Config configuration, out SemanticVersion shortVersion) { string versionPart; if (Inner(mergeCommit, out versionPart)) { return SemanticVersion.TryParse(versionPart, configuration.TagPrefix, out shortVersion); } shortVersion = null; return false; }
public List<TreeEntryChanges> GetFilesForCommit(Commit commit) { var thisCommit = commit.Tree; var parentCommit = commit.Parents.First().Tree; var modifiedSourceFiles = gitRepo.Diff.Compare<TreeChanges>(parentCommit, thisCommit) .Where(m => m.Path.EndsWith(".cs")) .ToList(); return modifiedSourceFiles; }
int NumberOfCommitsOnBranchSinceCommit(GitVersionContext context, Commit commit) { var qf = new CommitFilter { Since = context.CurrentCommit, Until = commit, SortBy = CommitSortStrategies.Topological | CommitSortStrategies.Time }; return context.Repository.Commits.QueryBy(qf).Count(); }
SemanticVersion BuildVersion(IRepository repository, Commit tip, int major, int minor, int patch) { var releaseDate = ReleaseDateFinder.Execute(repository, tip.Sha, patch); return new SemanticVersion { Major = major, Minor = minor, Patch = patch, BuildMetaData = new SemanticVersionBuildMetaData(null, "support", releaseDate) }; }
public CommitWrapper(LibGit2Sharp.Commit commit) { this.commit = commit; Sha = commit.Sha; MessageShort = commit.MessageShort; Message = commit.Message; Author = commit.Author; Committer = commit.Committer; Tree = (async(i) => commit.Tree); Parents = (async(i) => commit.Parents.Select((p) => new CommitWrapper(p))); }
protected override bool IsValidTag(GitVersionContext context, string branchName, Tag tag, Commit commit) { if (!string.IsNullOrWhiteSpace(branchName)) { if (context.Configuration.TrackMergeTarget) { return IsDirectMergeFromCommit(tag, commit); } } return base.IsValidTag(context, branchName, tag, commit); }
private static IList <string> GetChangedFiles(Repository repo, Commit commit) { var files = new HashSet <string>(); var parent = commit.Parents.First(); foreach (var change in repo.Diff.Compare <TreeChanges>(parent.Tree, commit.Tree)) { files.Add(Path.GetFullPath(change.Path)); files.Add(Path.GetFullPath(change.OldPath)); } return(files.ToList()); }
public CommitRewriteInfo ThisUser(Commit commit) { var sg = new Signature(string.IsNullOrEmpty(_user.Name) ? _user.Login : _user.Name, _user.Email, commit.Author.When); return(new CommitRewriteInfo { Author = sg, Committer = sg, Message = commit.Message }); }
/** * Save the locally modified files into the local repository */ private static void GitCommit(LibGit2Sharp.Repository repo) { Commands.Stage(repo, "*"); LibGit2Sharp.Signature author = new LibGit2Sharp.Signature("GitSheller", "@cornerpirate", DateTime.Now); LibGit2Sharp.Signature committer = author; // This line throws a LibGit2Sharp.EmptyCommitException when the file has not been altered. try { LibGit2Sharp.Commit commit = repo.Commit("Committed", author, committer); } catch (LibGit2Sharp.EmptyCommitException ece) { // No changes detected. } }
private static string GetFileContent(LibGit2Sharp.Commit commit, string fileName) { // get content from commit var blob = (Blob)commit.Tree[fileName].Target; string content = blob.GetContentText(); // strip BOM (U+FEFF) if present if (content.Length > 0 && content[0] == '\uFEFF') { content = content.Substring(1); } return(content); }
private Commit GetCommitFromGitCommit(GitCommit gitCommit, string repositoryPath) { List <Changes> changes = GetChanges(gitCommit, repositoryPath); Commit newCommit = new Commit() { Revision = gitCommit.Sha, Author = gitCommit.Author.Name, Date = gitCommit.Author.When.DateTime, Email = gitCommit.Author.Email, Message = gitCommit.MessageShort }; changes.ForEach(change => newCommit.AddChanges(change)); return(newCommit); }
public static Stream ContentStreamFromPath(LibGit2Sharp.Commit commit, string path) { var treeItem = commit.Tree[path]; if (treeItem == null) { return(null); } var blob = commit.Tree[path].Target as Blob; if (blob == null) { return(null); } return(blob.GetContentStream()); }
private static void HandleCheckout(LibGit2Sharp.Commit checkoutCommit, string projectName, string projectPath, string branchName) { using (var context = new BadSmellMinerDbContext()) { if (context.Commits.Any(q => q.CommitId == checkoutCommit.Sha)) { return; } var organicAnalysisFilePath = RunOrganic(checkoutCommit.Sha, projectName, projectPath); var project = CreateProject(projectName, context); var organicClasses = ExtractOrganicClasses(organicAnalysisFilePath); CreateNewCommit(project, organicClasses, branchName, checkoutCommit, context); } }
private Commit Convert_First_Commit(LibGit2Sharp.Commit commit, IList <Author> authors) { var result = new Commit(); var fileChanges = _repository.Diff.Compare <PatchStats>(null, commit.Tree); foreach (var fileChange in fileChanges) { result.Patch.Add(new Patch { LinesRemoved = fileChange.LinesDeleted, LinesAdded = fileChange.LinesAdded, Contents = string.Empty, // todo : get the contents properly, ChangeType = ChangeType.Added }); } return(result); }
/// <summary> /// Add all changes in service repo and push to remote /// </summary> /// <param name="commitInfo">the commit information for the service</param> public void PushChangesForRepository(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); var watch = System.Diagnostics.Stopwatch.StartNew(); using (Repository repo = new Repository(localServiceRepoFolder)) { // Restrict users from empty commit if (repo.RetrieveStatus().IsDirty) { string remoteUrl = FindRemoteRepoLocation(commitInfo.Org, commitInfo.Repository); Remote remote = repo.Network.Remotes["origin"]; if (!remote.PushUrl.Equals(remoteUrl)) { // This is relevant when we switch beteen running designer in local or in docker. The remote URL changes. // Requires adminstrator access to update files. repo.Network.Remotes.Update("origin", r => r.Url = remoteUrl); } Commands.Stage(repo, "*"); // Create the committer's signature and commit LibGit2Sharp.Signature author = new LibGit2Sharp.Signature(AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext), "@jugglingnutcase", DateTime.Now); LibGit2Sharp.Signature committer = author; // Commit to the repository LibGit2Sharp.Commit commit = repo.Commit(commitInfo.Message, author, committer); PushOptions options = new PushOptions(); options.CredentialsProvider = (_url, _user, _cred) => new UsernamePasswordCredentials { Username = GetAppToken(), Password = string.Empty }; repo.Network.Push(remote, @"refs/heads/master", options); } } watch.Stop(); _logger.Log(Microsoft.Extensions.Logging.LogLevel.Information, "push cahnges - {0} ", watch.ElapsedMilliseconds); }
public List <Changes> GetChanges(GitCommit commit, string repositoryPath) { List <Changes> changes = new List <Changes>(); using (GitRepository gitRepositoryInfo = new GitRepository(repositoryPath)) { bool isInitial = false; var firstCommit = commit.Parents.FirstOrDefault(); if (firstCommit == null) { isInitial = true; } Tree rootCommitTree = gitRepositoryInfo.Lookup <GitCommit>(commit.Id.ToString()).Tree; Patch patch; if (!isInitial) { Tree commitTreeWithUpdatedFile = gitRepositoryInfo.Lookup <GitCommit>(commit.Parents.FirstOrDefault().Sha).Tree; patch = gitRepositoryInfo.Diff.Compare <Patch>(commitTreeWithUpdatedFile, rootCommitTree); } else { patch = gitRepositoryInfo.Diff.Compare <Patch>(null, rootCommitTree); } foreach (var change in patch) { changes.Add(new Changes() { Type = ConvertChangeKindToChangeType(change.Status), Path = change.Path, ChangeContent = change.Patch }); } } return(changes); }
private void OnViewChangeDetails(LibGit2Sharp.Commit p, ObjectId blob, int secondsToTimeout) { // Task.Factory.StartNew(() => // { // _mediator.NotifyColleaguesAsync<BeginBusyEvent>("Downloading change details..."); // Task.Factory.StartNew(() => // { // using(var client = new SvnClient()) // { // try // { // SvnInfoEventArgs info; // var absolutePath = Path.Combine(repoPath.ToString(), p.RepositoryPath.ToString()); // client.GetInfo(absolutePath, out info); // using(MemoryStream latest = new MemoryStream(), previous = new MemoryStream()) // { // client.Write(new SvnUriTarget(absolutePath, latestRevision), latest); // client.Write(new SvnUriTarget(absolutePath, new SvnRevision(latestRevision.Revision - 1)), previous); // latest.Seek(0, SeekOrigin.Begin); // previous.Seek(0, SeekOrigin.Begin); // var ext = Path.HasExtension(p.Path) ? Path.GetExtension(p.Path) : ".txt"; // string latFileOnDisk = Path.Combine(ApplicationSettings.Instance.DiffDirectory, string.Format("{0}_{1}.{2}", Path.GetFileNameWithoutExtension(p.Path), latestRevision.Revision, ext)); // using(var latestFile = File.OpenWrite(latFileOnDisk)) // { // latest.WriteTo(latestFile); // latestFile.Flush(); // } // string prevFileOnDisk = Path.Combine(ApplicationSettings.Instance.DiffDirectory, string.Format("{0}_{1}.{2}", Path.GetFileNameWithoutExtension(p.Path), (latestRevision.Revision - 1), ext)); // using(var previousFile = File.OpenWrite(prevFileOnDisk)) // { // previous.WriteTo(previousFile); // previousFile.Flush(); // } // _mediator.NotifyColleaguesAsync<EndBusyEvent>(null); // // background this so that our callbacks are not waiting on this complete (unnecessary) // Task.Factory.StartNew(() => // { // var process = _diffService.ShowDiff(prevFileOnDisk, latFileOnDisk); // if(process != null) // { // process.WaitForExit(); // } // File.Delete(prevFileOnDisk); // File.Delete(latFileOnDisk); // }); // } // } // catch(Exception) // { // // log it? // } // } // }); // // TODO: either cleanly handle a cancel or just let it go forever... // //if(!task.Wait(new TimeSpan(0, 0, 0, secondsToTimeout))) // //{ // // token.Cancel(); // // _messageBoxService.ShowError("Diff download timed out. Please increase the timeout if you continue to receive this error."); // // _mediator.NotifyColleaguesAsync<EndBusyEvent>(null); // //} // }); }
int?FinishImportCommit(LibGit2Sharp.Commit gitCommit, List <int> parentCommits) { string commitHash = gitCommit.Sha; var commit = new DataAccess.Collector.Commit(); commit.Hash = commitHash; commit.CommitDate = gitCommit.Committer.When.UtcDateTime; db.Context.Commits.AddObject(commit); db.Context.SaveChanges(); Debug.WriteLine("Imported commit " + commitHash + " as " + commit.Id); // Fix existing sessions referencing this commit: int?svnRevision = null; if (EnableGitSvnImport) { foreach (string messageLine in gitCommit.Message.Split('\n', '\r')) { Match m = gitSvnRegex.Match(messageLine); if (m.Success) { // determine SVN revision numbers for commits imported from SVN svnRevision = int.Parse(m.Groups[1].Value); break; } } } if (svnRevision != null) { svnRevisionToCommitIdMapping[svnRevision.Value] = commit.Id; } else { var sessionsThatNeedUpdate = from s in db.Context.Sessions join ed in db.Context.EnvironmentDatas on s.Id equals ed.SessionId join edn in db.Context.EnvironmentDataNames on ed.EnvironmentDataNameId equals edn.Id join edv in db.Context.EnvironmentDataValues on ed.EnvironmentDataValueId equals edv.Id where edn.Name == "commit" && edv.Name == commitHash select s; int updatedSessionsCount = 0; foreach (var session in sessionsThatNeedUpdate) { session.CommitId = commit.Id; updatedSessionsCount++; } if (updatedSessionsCount > 0) { Debug.WriteLine("Updated " + updatedSessionsCount + " sessions referencing this commit"); } } // Now create the relation to the parent commits: foreach (int parentCommit in parentCommits) { CommitRelation r = new CommitRelation(); r.ParentCommit = parentCommit; r.ChildCommit = commit.Id; db.Context.CommitRelations.AddObject(r); } db.Context.SaveChanges(); return(commit.Id); }
int?ImportCommit(LibGit2Sharp.Commit startingCommit) { // Using an explicit stack, because we would run into StackOverflowException when writing this // as a recursive method. See comment above "class Frame" for the recursive implementation. int? result = null; // variable used to store the return value (passed from one stack frame to the calling frame) Stack <Frame> stack = new Stack <Frame>(); stack.Push(new Frame(startingCommit)); while (stack.Count > 0) { Frame f = stack.Peek(); switch (f.state) { case 0: // Test whether this commit is already imported var commit = db.GetCommitByHash(f.gitCommit.Sha); if (commit != null) { result = commit.Id; stack.Pop(); break; } // Test whether the commit is too old to be imported if (f.gitCommit.Committer.When < EarliestCommitDate) { result = null; stack.Pop(); break; } f.parentCommitIds = new List <int>(); f.loopIndex = 0; goto case 1; // proceed to first loop iteration case 1: // check the loop condition (whether we have imported all necessary commits) if (f.loopIndex < f.gitCommit.Parents.Count()) { // recursive invocation (to fetch the commit ID of the parent) f.state = 2; stack.Push(new Frame(f.gitCommit.Parents.ElementAt(f.loopIndex))); break; } else { // we are done with the loop; all parent commit IDs were collected result = FinishImportCommit(f.gitCommit, f.parentCommitIds); stack.Pop(); break; } case 2: // store result from recursive invocation if (result != null) { f.parentCommitIds.Add(result.Value); } f.loopIndex++; goto case 1; // proceed to next loop iteration } } return(result); }
public Frame(LibGit2Sharp.Commit gitCommit) { this.gitCommit = gitCommit; }
private bool First_Commit(LibGit2Sharp.Commit commit) { return(!commit.Parents.Any()); }
private static Author Find_Commit_Author(IList <Author> authors, LibGit2Sharp.Commit commit) { return(authors.FirstOrDefault(x => x.Emails.Contains(commit.Author.Email))); }
/// <summary> /// Performs the job as a background task /// </summary> public override void ExecuteWork() { // Retrieve the hash tag if (LastCommit != null) { Repository repository = GetRepository(); string dictionaryDirectory = Path.GetDirectoryName(Dictionary.FilePath); if (dictionaryDirectory != null) { dictionaryDirectory = dictionaryDirectory.Substring(RepositoryPath.Length + 1, dictionaryDirectory.Length - RepositoryPath.Length - 1); History history = Dictionary.EFSSystem.History; if (history.Commit(LastCommit.Sha) == null) { // Processes all commits until the one that has been selected Dictionary currentVersion = Dictionary; Dictionary previousVersion = null; Commit previousCommit = null; Commit commitToRefer = null; foreach (Commit commit in repository.Commits) { // Always compare the current version with the first commit in the repository // since changes may have been applied to the current version if (previousVersion == null || !history.CommitExists(commit.Sha)) { if (previousCommit == null) { if (previousVersion != Dictionary && currentVersion != previousVersion) { CleanUpDictionary(previousVersion); } previousVersion = currentVersion; } else { previousVersion = DictionaryByVersion(previousCommit); Comparer.ensureGuidDictionary(previousVersion, currentVersion); } bool changesAvailable = true; if (commitToRefer != null) { changesAvailable = false; TreeChanges changes = repository.Diff.Compare(commit.Tree, commitToRefer.Tree); foreach (TreeEntryChanges entry in changes.Modified) { if (entry.Path.StartsWith(dictionaryDirectory)) { changesAvailable = true; break; } } } if (changesAvailable) { if (commitToRefer != null) { string message = commitToRefer.Message.Trim(); if (message.Length > 132) { message = message.Substring(0, 132) + "..."; } Dialog.UpdateMessage("Processing " + message + " (" + commitToRefer.Sha + ")"); } else { Dialog.UpdateMessage("Processing current version..."); } currentVersion = DictionaryByVersion(commit); if (currentVersion != null) { VersionDiff versionDiff = new VersionDiff(); if (commitToRefer != null) { versionDiff.setCommitter(commitToRefer.Author.Name); versionDiff.setDate(commitToRefer.Author.When.ToString()); versionDiff.setHash(commitToRefer.Sha); versionDiff.setMessage(commitToRefer.Message); } Comparer.ensureGuidDictionary(previousVersion, currentVersion); Comparer.compareDictionary(previousVersion, currentVersion, versionDiff); history.AppendOrReplaceCommit(versionDiff); history.save(); } else { DialogResult result = MessageBox.Show( "Cannot open file for commit\n" + commit.MessageShort + " (" + commit.Sha + ")\nplease see log file (GUI.Log) for more information.\nPress OK to continue.", "Cannot open file", MessageBoxButtons.OKCancel, MessageBoxIcon.Error); if (result == DialogResult.OK) { // Stick back to the previous version to continue the process currentVersion = previousVersion; } else { // Stop the process break; } } } else { currentVersion = previousVersion; } previousCommit = null; } else { previousCommit = commit; } if (commit == LastCommit) { break; } commitToRefer = commit; } } history.UpdateBlame(); } } }
private static void ApplyPatch(RepositoryInfo sourceRepository, RepositoryInfo targetRepository, string patch, Commit commit) { var sourceSlashIgnore = 1 + sourceRepository.SharedPath.Count(c => c == '\\') + 1; var result = Runner.RunCommand("git", $"-c \"user.name={s_mirrorSignatureUserName}\" -C \"{targetRepository.Path}\" am --signoff --reject --3way -p{sourceSlashIgnore} --directory=\"{targetRepository.SharedPath.Replace('\\', '/')}\"", s_logger, patch); s_logger.Debug(result.Output); if (result.ExitCode != 0) { s_logger.Error($"The commit being applied is ${commit.Sha} ${commit.MessageShort} {commit.Author}"); s_logger.Error( $"patching failed, please open '{targetRepository.Path}' and resolve the conflicts then press any key"); s_emailManager.Email("Merge Conflicts", $"Merge Conflicts in {targetRepository.Name} while applying commit {commit} from repo {sourceRepository.Name}"); Console.ReadKey(); } }
private static void CreateNewCommit(Project project, OrganicClass[] organicClasses, string branchName, LibGit2Sharp.Commit checkoutCommit, BadSmellMinerDbContext context) { var commit = new DomainModels.Commit(project.Id, checkoutCommit.Sha, organicClasses); commit.AuthorName = checkoutCommit.Committer.Email; commit.FullMessage = checkoutCommit.Message; commit.ShortMessage = checkoutCommit.MessageShort; commit.DateTime = checkoutCommit.Committer.When.DateTime; commit.BranchName = branchName; context.Commits.Add(commit); context.SaveChanges(); }