protected override void Context() { alreadyCommitted = BuildCommitStub(HeadStreamRevision, HeadCommitSequence); beyondEndOfStream = BuildCommitStub(BeyondEndOfStreamRevision, HeadCommitSequence + 1); hook.PostCommit(alreadyCommitted); }
public virtual void Commit(Commit attempt) { if (!attempt.IsValid() || attempt.IsEmpty()) { Logger.Debug(Resources.CommitAttemptFailedIntegrityChecks); return; } foreach (var hook in _pipelineHooks) { Logger.Debug(Resources.InvokingPreCommitHooks, attempt.CommitId, hook.GetType()); if (hook.PreCommit(attempt)) { continue; } Logger.Info(Resources.CommitRejectedByPipelineHook, hook.GetType(), attempt.CommitId); return; } Logger.Info(Resources.CommittingAttempt, attempt.CommitId, attempt.Events.Count); _persistence.Commit(attempt); foreach (var hook in _pipelineHooks) { Logger.Debug(Resources.InvokingPostCommitPipelineHooks, attempt.CommitId, hook.GetType()); hook.PostCommit(attempt); } }
public IStorableObject ToGitObject(Repository repo, string sha) { using (GitObjectReader objectReader = new GitObjectReader(Content)) { IStorableObject obj; switch (Type) { case ObjectType.Commit: obj = new Commit(repo, sha); break; case ObjectType.Tree: obj = new Tree(repo, sha); break; case ObjectType.Blob: obj = new Blob(repo, sha); break; case ObjectType.Tag: obj = new Tag(repo, sha); break; default: throw new NotImplementedException(); } obj.Deserialize(objectReader); return obj; } }
public DeploymentsClientTests() { var github = Helper.GetAuthenticatedClient(); _deploymentsClient = github.Repository.Deployment; _context = github.CreateRepositoryContext("public-repo").Result; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = github.Git.Blob.Create(_context.RepositoryOwner, _context.RepositoryName, blob).Result; var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = "README.md", Sha = blobResult.Sha }); var treeResult = github.Git.Tree.Create(_context.RepositoryOwner, _context.RepositoryName, newTree).Result; var newCommit = new NewCommit("test-commit", treeResult.Sha); _commit = github.Git.Commit.Create(_context.RepositoryOwner, _context.RepositoryName, newCommit).Result; }
/// <summary> /// Get all the commits in a CVS log ordered by date. /// </summary> public IEnumerable<Commit> GetCommits() { var lookup = new Dictionary<string, Commit>(); using (var commitsByMessage = new CommitsByMessage(m_log)) { foreach (var revision in m_fileRevisions) { if (revision.IsAddedOnAnotherBranch) { revision.File.BranchAddedOn = GetBranchAddedOn(revision.Message); } else if (revision.CommitId.Length == 0) { commitsByMessage.Add(revision); } else { Commit commit; if (lookup.TryGetValue(revision.CommitId, out commit)) { commit.Add(revision); } else { commit = new Commit(revision.CommitId) { revision }; lookup.Add(commit.CommitId, commit); } } } return lookup.Values.Concat(commitsByMessage.Resolve()).OrderBy(c => c.Time).ToList(); } }
public virtual void Commit(Commit attempt) { lock (this.commits) { if (this.commits.Contains(attempt)) throw new DuplicateCommitException(); if (this.commits.Any(c => c.StreamId == attempt.StreamId && c.StreamRevision == attempt.StreamRevision)) throw new ConcurrencyException(); this.stamps[attempt.CommitId] = attempt.CommitStamp; this.commits.Add(attempt); lock (this.undispatched) this.undispatched.Add(attempt); lock (this.heads) { var head = this.heads.FirstOrDefault(x => x.StreamId == attempt.StreamId); this.heads.Remove(head); var snapshotRevision = head == null ? 0 : head.SnapshotRevision; this.heads.Add(new StreamHead(attempt.StreamId, attempt.StreamRevision, snapshotRevision)); } } }
public DeploymentsClientTests() { var gitHubClient = Helper.GetAuthenticatedClient(); _deploymentsClient = gitHubClient.Repository.Deployment; var newRepository = new NewRepository(Helper.MakeNameWithTimestamp("public-repo")) { AutoInit = true }; _repository = gitHubClient.Repository.Create(newRepository).Result; _repositoryOwner = _repository.Owner.Login; var blob = new NewBlob { Content = "Hello World!", Encoding = EncodingType.Utf8 }; var blobResult = gitHubClient.GitDatabase.Blob.Create(_repositoryOwner, _repository.Name, blob).Result; var newTree = new NewTree(); newTree.Tree.Add(new NewTreeItem { Type = TreeType.Blob, Mode = FileMode.File, Path = "README.md", Sha = blobResult.Sha }); var treeResult = gitHubClient.GitDatabase.Tree.Create(_repositoryOwner, _repository.Name, newTree).Result; var newCommit = new NewCommit("test-commit", treeResult.Sha); _commit = gitHubClient.GitDatabase.Commit.Create(_repositoryOwner, _repository.Name, newCommit).Result; }
private static void AppendVersion(Commit commit, int index) { var busMessage = commit.Events[index].Body as IMessage; busMessage.SetHeader(AggregateIdKey, commit.StreamId.ToString()); busMessage.SetHeader(CommitVersionKey, commit.StreamRevision.ToString()); busMessage.SetHeader(EventVersionKey, GetSpecificEventVersion(commit, index).ToString()); }
public virtual bool PreCommit(Commit attempt) { Logger.Debug(Resources.OptimisticConcurrencyCheck, attempt.StreamId); Commit head = GetStreamHead(attempt.StreamId); if (head == null) { return true; } if (head.CommitSequence >= attempt.CommitSequence) { throw new ConcurrencyException(); } if (head.StreamRevision >= attempt.StreamRevision) { throw new ConcurrencyException(); } if (head.CommitSequence < attempt.CommitSequence - 1) { throw new StorageException(); // beyond the end of the stream } if (head.StreamRevision < attempt.StreamRevision - attempt.Events.Count) { throw new StorageException(); // beyond the end of the stream } Logger.Debug(Resources.NoConflicts, attempt.StreamId); return true; }
public virtual Commit Select(Commit committed) { foreach (var eventMessage in committed.Events) eventMessage.Body = this.Convert(eventMessage.Body); return committed; }
public void SingleBranch_PlaysInSequence() { var now = DateTime.Now; var file1 = new FileInfo("file1"); var file2 = new FileInfo("file2").WithBranch("branch", "1.1.0.2"); var commit0 = new Commit("id0") { Index = 1 } .WithRevision(file1, "1.1", time: now) .WithRevision(file2, "1.1", time: now); var commit1 = new Commit("id1") { Index = 2 } .WithRevision(file1, "1.2", time: now + TimeSpan.FromMinutes(2)) .WithRevision(file2, "1.2", time: now + TimeSpan.FromMinutes(2), mergepoint: "1.1.2.1"); var commit2 = new Commit("branch0") { Index = 3 } .WithRevision(file2, "1.1.2.1", time: now + TimeSpan.FromMinutes(1)); var commits = new[] { commit0, commit1, commit2 }; var branchpoints = new Dictionary<string, Commit>() { { "branch", commit0 } }; var branches = new BranchStreamCollection(commits, branchpoints); commit1.MergeFrom = commit2; var player = new CommitPlayer(MockRepository.GenerateStub<ILogger>(), branches); var result = player.Play().Select(c => c.CommitId).ToList(); Assert.IsTrue(result.SequenceEqual("id0", "branch0", "id1")); }
public virtual void Commit(Commit attempt) { this.ThrowWhenDisposed(); Logger.Debug(Resources.AttemptingToCommit, attempt.CommitId, attempt.StreamId, attempt.CommitSequence); lock (Commits) { if (Commits.Contains(attempt)) throw new DuplicateCommitException(); if (Commits.Any(c => c.StreamId == attempt.StreamId && c.StreamRevision == attempt.StreamRevision)) throw new ConcurrencyException(); Stamps[attempt.CommitId] = attempt.CommitStamp; Commits.Add(attempt); Undispatched.Add(attempt); var head = Heads.FirstOrDefault(x => x.StreamId == attempt.StreamId); Heads.Remove(head); Logger.Debug(Resources.UpdatingStreamHead, attempt.StreamId); var snapshotRevision = head == null ? 0 : head.SnapshotRevision; Heads.Add(new StreamHead(attempt.StreamId, attempt.StreamRevision, snapshotRevision)); } }
public String CreateCommit() { var reader = new StreamReader(Request.InputStream); var data = reader.ReadToEnd(); reader.Close(); var dataValue = ParsePostData(data); var userId = dataValue["userId"]; var repositoryId = int.Parse(dataValue["repositoryId"]); var message = dataValue["message"]; Guid userGuid; if (!IsUserAuthenticated(userId, out userGuid)) return null; var repository = DataManager.GetInstance().GetRepository(repositoryId); if (!repository.Owner.Equals(UserManager.GetInstance().GetUser(userGuid))) return null; if (String.IsNullOrWhiteSpace(message)) return null; var commit = new Commit(UserManager.GetInstance().GetUser(userGuid), message); var newCommit = DataManager.GetInstance().AddCommit(commit, repository); var commitPath = GetTempCommitPath(repository, newCommit.Id); Directory.CreateDirectory(commitPath); return newCommit.Id.ToString(CultureInfo.InvariantCulture); }
public SemanticReleaseNotes ScanCommitMessagesForReleaseNotes(GitReleaseNotesArguments arguments, Commit[] commitsToScan) { var repoParts = arguments.Repo.Split('/'); var organisation = repoParts[0]; var repository = repoParts[1]; var issueNumbersToScan = _issueNumberExtractor.GetIssueNumbers(arguments, commitsToScan, @"#(?<issueNumber>\d+)"); var since = commitsToScan.Select(c=>c.Author.When).Min(); var potentialIssues = _gitHubClient.Issue.GetForRepository(organisation, repository, new RepositoryIssueRequest { Filter = IssueFilter.All, Since = since, State = ItemState.Closed }).Result; var closedMentionedIssues = potentialIssues .Where(i => issueNumbersToScan.Contains(i.Number.ToString(CultureInfo.InvariantCulture))) .ToArray(); return new SemanticReleaseNotes(closedMentionedIssues.Select(i=> { var labels = i.Labels == null ? new string[0] : i.Labels.Select(l=>l.Name).ToArray(); return new ReleaseNoteItem(i.Title, string.Format("#{0}", i.Number), i.HtmlUrl, labels); })); }
public void MergedFiles_None() { var commit = new Commit("abc") .WithRevision(m_f1, "1.2"); var result = commit.MergedFiles; Assert.IsFalse(result.Any()); }
public Block(int startLine, int lineCount, Commit commit, string fileName, int originalStartLine) { m_startLine = startLine; m_lineCount = lineCount; m_commit = commit; m_fileName = fileName; m_originalStartLine = originalStartLine; }
public static void AddEventsOrClearOnSnapshot( this ICollection<object> events, Commit commit, bool applySnapshot) { if (applySnapshot && commit.Snapshot != null) events.Clear(); else events.AddEvents(commit); }
public virtual void Commit(Commit attempt) { var clock = Stopwatch.StartNew(); this.persistence.Commit(attempt); clock.Stop(); this.counters.CountCommit(attempt.Events.Count, clock.ElapsedMilliseconds); }
internal AfterRebaseStepInfo(RebaseStepInfo stepInfo, Commit commit, long completedStepIndex, long totalStepCount) { StepInfo = stepInfo; Commit = commit; WasPatchAlreadyApplied = false; CompletedStepIndex = completedStepIndex; TotalStepCount = totalStepCount; }
public virtual void Dispatch(Commit commit) { ThreadPool.QueueUserWorkItem(state => { this.bus.Publish(commit); this.persistence.MarkCommitAsDispatched(commit); }); }
public void ShouldBeAbleToReadAuthorDate2() { using (var repos = GetTrashRepository()) { var commit = new Commit(repos, KnownCommit); Assert.AreEqual(_expectedDate, commit.AuthorDate); } }
public static void Dispatch(Commit commit) { for (var i = 0; i < commit.Events.Count; i++) { //var eventMessage = commit.Events[i]; //var busMessage = eventMessage.Body as IMessage; RunAtStartup.Bus.Publish(new EventStoreDispatchMessage()); } }
/// <summary> /// Constructor. /// </summary> public LatestBuildResult( Commit commit, BuildResult buildResult, TimeSpan? estimatedBuildDuration) { Commit = commit; BuildResult = buildResult; EstimatedBuildDuration = estimatedBuildDuration; }
private void SelectCommit(Commit commit) { if (commit == null || commit.Tree == null) return; m_commit_view.Commit = commit; m_tree.ItemsSource = commit.Tree.Children; m_tree_title.Content = "Repository tree of Commit " + commit.ShortHash; m_commit_diff.Init(commit.Parent, commit); }
/// <summary> /// Build a <see cref="CommitRewriteInfo"/> from the <see cref="Commit"/> passed in /// </summary> /// <param name="commit">The <see cref="Commit"/> whose information is to be copied</param> /// <returns>A new <see cref="CommitRewriteInfo"/> object that matches the info for the <paramref name="commit"/>.</returns> public static CommitRewriteInfo From(Commit commit) { return new CommitRewriteInfo { Author = commit.Author, Committer = commit.Committer, Message = commit.Message }; }
public void MergedFiles_All() { var commit = new Commit("abc") .WithRevision(m_f1, "1.2", mergepoint: "1.1.2.1") .WithRevision(m_f2, "1.3", mergepoint: "1.1.4.2"); var result = commit.MergedFiles; Assert.AreEqual(result.Count(), 2); }
public void MergedFiles_Mixture() { var commit = new Commit("abc") .WithRevision(m_f1, "1.2", mergepoint: "1.1.2.1") .WithRevision(m_f2, "1.3"); var result = commit.MergedFiles; Assert.AreEqual(result.Single().File.Name, "f1"); }
public virtual void Track(Commit committed) { TrackedStream stream; lock (this.streams) if (!this.streams.TryGetValue(committed.StreamId, out stream)) this.streams[committed.StreamId] = stream = new TrackedStream(this.commitsToTrackPerStream); stream.Track(committed); }
public void Branch_from_a_commit_in_history() { using (Repository repo = GetTrashRepository()) { var c = new Commit(repo, "master^^"); var b = Branch.Create(repo, "foo", c); Assert.AreEqual(c, b.CurrentCommit); Assert.AreEqual("master", repo.CurrentBranch.Name); // creating a new branch does not switch to it by default. } }
public Commit MapToEntity(CommitsResponseModel model) { var result = new Commit(); result.Author = model.Commit.Author; result.AuthorAvatar = model.Author.AvatarUrl; result.Committer = model.Commit.Committer; result.Message = model.Commit.Message; result.SHA = model.SHA; return result; }
public async Task DeploySite() { StatusUpdate?.Invoke("Starting deploy...", StatusType.Status); if (_githubToken == string.Empty) { // TODO: Send an error message StatusUpdate?.Invoke("No GitHub token configured.", StatusType.Error); return; } if (_repoName == string.Empty) { StatusUpdate?.Invoke("No repository configured.", StatusType.Error); return; } string[] splitRepoName = _repoName.Split('/'); if (splitRepoName.Length != 2) { StatusUpdate?.Invoke("Repository name format invalid.", StatusType.Error); return; } if (_repoDestination == string.Empty) { StatusUpdate?.Invoke("No destination configured.", StatusType.Error); return; } StatusUpdate?.Invoke("Getting repository...", StatusType.Status); long repoId = (await _github.Repository.Get(splitRepoName[0], splitRepoName[1])).Id; string headMasterRef = "heads/" + _repoBranch; Reference masterReference; try { masterReference = await _github.Git.Reference.Get(repoId, headMasterRef); } catch (Exception ex) { if (ex is NotFoundException) { // This probably means the branch hasn't been created yet // https://github.com/octokit/octokit.net/issues/1098 StatusUpdate?.Invoke("Creating branch " + _repoBranch + "...", StatusType.Status); Reference master = await _github.Git.Reference.Get(repoId, "heads/master"); masterReference = await _github.Git.Reference.Create(repoId, new NewReference("refs/" + headMasterRef, master.Object.Sha)); } else { throw; } } StatusUpdate?.Invoke("Getting current commit...", StatusType.Status); GitHubCommit currentCommit = (await _github.Repository.Commit.GetAll(repoId)).First(); string currentTreeSha = currentCommit.Commit.Tree.Sha; NewTree newTree = new NewTree(); if (_repoDirectory != string.Empty) { TreeResponse currentTree = await _github.Git.Tree.Get(repoId, currentTreeSha); // Copy the current tree to the new tree StatusUpdate?.Invoke("Copying current tree to new tree...", StatusType.Status); newTree = (await CopySubtree(_github, currentTree, repoId, _repoDirectory)).Tree; } // Now, create all of the files in the tree StatusUpdate?.Invoke("Uploading compiled pages and adding to tree...", StatusType.Status); await _context.CompiledPages.ToList().ForEachAsync(async page => { NewBlob newBlob = new NewBlob { Content = MiscUtils.Base64Encode(page.Contents), Encoding = EncodingType.Base64 }; BlobReference newBlobCreated = await _github.Git.Blob.Create(repoId, newBlob); string newBlobSha = newBlobCreated.Sha; newTree.Tree.Add(new NewTreeItem { Mode = "100644", Type = TreeType.Blob, Sha = newBlobSha, Path = Path.Join(_repoDirectory, page.Title + ".html") }); }); // Upload all of the files from the wwwroot directory StatusUpdate?.Invoke("Uploading other files and adding to tree...", StatusType.Status); (await CopyDirectoryIntoTree(_github, repoId, _repoDirectory)).ForEach(item => { newTree.Tree.Add(item); }); StatusUpdate?.Invoke("Creating commit...", StatusType.Status); string newTreeSha = (await _github.Git.Tree.Create(repoId, newTree)).Sha; NewCommit newCommit = new NewCommit("Automated deploy from webweb", newTreeSha, masterReference.Object.Sha); Commit createdCommit = await _github.Git.Commit.Create(repoId, newCommit); await _github.Git.Reference.Update(repoId, headMasterRef, new ReferenceUpdate(createdCommit.Sha)); StatusUpdate?.Invoke("Deploy complete.", StatusType.Success); }
public static ushort GetTruncatedCommitIdAsUInt16(this Commit commit) { Requires.NotNull(commit, nameof(commit)); return(BinaryPrimitives.ReadUInt16BigEndian(commit.Id.RawId)); }
private static bool IsVersionHeightMismatch(Version version, VersionOptions versionOptions, Commit commit, GitWalkTracker tracker) { Requires.NotNull(version, nameof(version)); Requires.NotNull(versionOptions, nameof(versionOptions)); Requires.NotNull(commit, nameof(commit)); // The version.Build or version.Revision MAY represent the version height. var position = versionOptions.VersionHeightPosition; if (position.HasValue && position.Value <= SemanticVersion.Position.Revision) { int expectedVersionHeight = SemanticVersion.ReadVersionPosition(version, position.Value); var actualVersionOffset = versionOptions.VersionHeightOffsetOrDefault; var actualVersionHeight = GetCommitHeight(commit, tracker, c => CommitMatchesVersion(c, version, position.Value - 1, tracker)); return(expectedVersionHeight != actualVersionHeight + actualVersionOffset); } // It's not a mismatch, since for this commit, the version height wasn't recorded in the 4-integer version. return(false); }
private static bool IsCommitIdMismatch(Version version, VersionOptions versionOptions, Commit commit) { Requires.NotNull(version, nameof(version)); Requires.NotNull(versionOptions, nameof(versionOptions)); Requires.NotNull(commit, nameof(commit)); // The version.Revision MAY represent the first 2 bytes of the git commit ID, but not if 3 integers were specified in version.json, // since in that case the 4th integer is the version height. But we won't know till we read the version.json file, so for now, var position = versionOptions.GitCommitIdPosition; if (position.HasValue && position.Value <= SemanticVersion.Position.Revision) { // prepare for it to be the commit ID. // The revision is a 16-bit unsigned integer, but is not allowed to be 0xffff. // So if the value is 0xfffe, consider that the actual last bit is insignificant // since the original git commit ID could have been either 0xffff or 0xfffe. var expectedCommitIdLeadingValue = SemanticVersion.ReadVersionPosition(version, position.Value); if (expectedCommitIdLeadingValue != -1) { ushort objectIdLeadingValue = (ushort)expectedCommitIdLeadingValue; ushort objectIdMask = (ushort)(objectIdLeadingValue == MaximumBuildNumberOrRevisionComponent ? 0xfffe : 0xffff); // Accept a big endian match or a little endian match. // Nerdbank.GitVersioning up to v3.4 would produce versions based on the endianness of the CPU it ran on (typically little endian). // Starting with v3.5, it deterministically used big endian. In order for `nbgv get-commits` to match on versions computed before and after the change, // we match on either endian setting. return(!(commit.Id.StartsWith(objectIdLeadingValue, bigEndian: true, objectIdMask) || commit.Id.StartsWith(objectIdLeadingValue, bigEndian: false, objectIdMask))); } } // It's not a mismatch, since for this commit, the commit ID wasn't recorded in the 4-integer version. return(false); }
private static int GetCommitHeight(Commit startingCommit, GitWalkTracker tracker, Func <Commit, bool>?continueStepping) { Requires.NotNull(startingCommit, nameof(startingCommit)); Requires.NotNull(tracker, nameof(tracker)); if (continueStepping is object && !continueStepping(startingCommit)) { return(0); } var commitsToEvaluate = new Stack <Commit>(); bool TryCalculateHeight(Commit commit) { // Get max height among all parents, or schedule all missing parents for their own evaluation and return false. int maxHeightAmongParents = 0; bool parentMissing = false; foreach (Commit parent in commit.Parents) { if (!tracker.TryGetVersionHeight(parent, out int parentHeight)) { if (continueStepping is object && !continueStepping(parent)) { // This parent isn't supposed to contribute to height. continue; } commitsToEvaluate.Push(parent); parentMissing = true; } else { maxHeightAmongParents = Math.Max(maxHeightAmongParents, parentHeight); } } if (parentMissing) { return(false); } var versionOptions = tracker.GetVersion(commit); var pathFilters = versionOptions?.PathFilters; var includePaths = pathFilters ?.Where(filter => !filter.IsExclude) .Select(filter => filter.RepoRelativePath) .ToList(); var excludePaths = pathFilters?.Where(filter => filter.IsExclude).ToList(); var ignoreCase = commit.GetRepository().Config.Get <bool>("core.ignorecase")?.Value ?? false; bool ContainsRelevantChanges(IEnumerable <TreeEntryChanges> changes) => excludePaths?.Count == 0 ? changes.Any() // If there is a single change that isn't excluded, // then this commit is relevant. : changes.Any(change => !excludePaths.Any(exclude => exclude.Excludes(change.Path, ignoreCase))); int height = 1; if (includePaths is not null) { // If there are no include paths, or any of the include // paths refer to the root of the repository, then do not // filter the diff at all. var diffInclude = includePaths.Count == 0 || pathFilters.Any(filter => filter.IsRoot) ? null : includePaths; // If the diff between this commit and any of its parents // touches a path that we care about, bump the height. // A no-parent commit is relevant if it introduces anything in the filtered path. var relevantCommit = commit.Parents.Any() ? commit.Parents.Any(parent => ContainsRelevantChanges(commit.GetRepository().Diff .Compare <TreeChanges>(parent.Tree, commit.Tree, diffInclude, DiffOptions))) : ContainsRelevantChanges(commit.GetRepository().Diff .Compare <TreeChanges>(null, commit.Tree, diffInclude, DiffOptions)); if (!relevantCommit) { height = 0; } } tracker.RecordHeight(commit, height + maxHeightAmongParents); return(true); } commitsToEvaluate.Push(startingCommit); while (commitsToEvaluate.Count > 0) { Commit commit = commitsToEvaluate.Peek(); if (tracker.TryGetVersionHeight(commit, out _) || TryCalculateHeight(commit)) { commitsToEvaluate.Pop(); } } Assumes.True(tracker.TryGetVersionHeight(startingCommit, out int result)); return(result); }
public MergeResult Merge(Commit commit, Signature merger) { throw new System.NotImplementedException(); }
internal void RecordHeight(Commit commit, int height) => this.heights.Add(commit.Id, height);
public void ChangeHead(Commit newTarget) { string headPath = Path.Combine(path, HEAD_PATH); HeadFileManager.ChangeHead(headPath, newTarget); }
internal static DateTimeOffset GetDate(this Commit commit) => (commit.Author ?? commit.Committer).When;
protected virtual bool IsValidTag(Tag tag, Commit commit) { return(tag.PeeledTarget() == commit); }
public VersionTaggedCommit(Commit commit, SemanticVersion semVer, string tag) { Tag = tag; Commit = commit; SemVer = semVer; }
public Branch Checkout(Commit commit, CheckoutModifiers checkoutModifiers, CheckoutProgressHandler onCheckoutProgress, CheckoutNotificationOptions checkoutNotificationOptions) { throw new System.NotImplementedException(); }
public void Dispatch(Commit commit) { commit.Events.ToList().ForEach(e => _domainEvents.Add(e.Body as DomainEvent)); }
internal bool TryGetVersionHeight(Commit commit, out int height) => this.heights.TryGetValue(commit.Id, out height);
private Commit FindCommitByChangesetId(int changesetId, string remoteRef = null) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository..."); if (remoteRef == null) { string sha; if (changesetsCache.TryGetValue(changesetId, out sha)) { Trace.WriteLine("Changeset " + changesetId + " found at " + sha); return(_repository.Lookup <Commit>(sha)); } if (cacheIsFull) { Trace.WriteLine("Looking for changeset " + changesetId + " in git repository: CacheIsFull, stopped looking."); return(null); } } var reachableFromRemoteBranches = new CommitFilter { IncludeReachableFrom = _repository.Branches.Where(p => p.IsRemote), SortBy = CommitSortStrategies.Time }; if (remoteRef != null) { var query = _repository.Branches.Where(p => p.IsRemote && p.CanonicalName.EndsWith(remoteRef)); Trace.WriteLine("Looking for changeset " + changesetId + " in git repository: Adding remotes:"); foreach (var reachable in query) { Trace.WriteLine(reachable.CanonicalName + "reachable from " + remoteRef); } reachableFromRemoteBranches.IncludeReachableFrom = query; } var commitsFromRemoteBranches = _repository.Commits.QueryBy(reachableFromRemoteBranches); Commit commit = null; foreach (var c in commitsFromRemoteBranches) { int id; if (TryParseChangesetId(c.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } else { foreach (var note in c.Notes) { if (TryParseChangesetId(note.Message, out id)) { changesetsCache[id] = c.Sha; if (id == changesetId) { commit = c; break; } } } } } if (remoteRef == null && commit == null) { cacheIsFull = true; // repository fully scanned } Trace.WriteLine((commit == null) ? " => Commit " + changesetId + " not found!" : " => Commit " + changesetId + " found! hash: " + commit.Sha); return(commit); }
public static bool Run(CompressimagesParameters parameters) { CredentialsHandler credentialsProvider = (url, user, cred) => new UsernamePasswordCredentials { Username = KnownGitHubs.Username, Password = parameters.Password }; // clone var cloneOptions = new CloneOptions { CredentialsProvider = credentialsProvider, }; Repository.Clone(parameters.CloneUrl, parameters.LocalPath, cloneOptions); var repo = new Repository(parameters.LocalPath); var remote = repo.Network.Remotes["origin"]; // check if we have the branch already or this is empty repo try { if (repo.Network.ListReferences(remote, credentialsProvider).Any() == false) { return(false); } if (repo.Network.ListReferences(remote, credentialsProvider).Any(x => x.CanonicalName == $"refs/heads/{KnownGitHubs.BranchName}")) { return(false); } } catch { // ignore } var repoConfiguration = new RepoConfiguration(); try { // see if .imgbotconfig exists in repo root var repoConfigJson = File.ReadAllText(parameters.LocalPath + Path.DirectorySeparatorChar + ".imgbotconfig"); if (!string.IsNullOrEmpty(repoConfigJson)) { repoConfiguration = JsonConvert.DeserializeObject <RepoConfiguration>(repoConfigJson); } } catch { // ignore } if (Schedule.ShouldOptimizeImages(repoConfiguration, repo) == false) { return(false); } // check out the branch repo.CreateBranch(KnownGitHubs.BranchName); var branch = Commands.Checkout(repo, KnownGitHubs.BranchName); // optimize images var imagePaths = ImageQuery.FindImages(parameters.LocalPath, repoConfiguration); var optimizedImages = OptimizeImages(repo, parameters.LocalPath, imagePaths); if (optimizedImages.Length == 0) { return(false); } // create commit message based on optimizations var commitMessage = CommitMessage.Create(optimizedImages); // commit var signature = new Signature(KnownGitHubs.ImgBotLogin, KnownGitHubs.ImgBotEmail, DateTimeOffset.Now); repo.Commit(commitMessage, signature, signature); // We just made a normal commit, now we are going to capture all the values generated from that commit // then rewind and make a signed commit var commitBuffer = Commit.CreateBuffer( repo.Head.Tip.Author, repo.Head.Tip.Committer, repo.Head.Tip.Message, repo.Head.Tip.Tree, repo.Head.Tip.Parents, true, null); var signedCommitData = CommitSignature.Sign(commitBuffer + "\n", parameters.PgpPrivateKeyStream, parameters.PgPPassword); repo.Reset(ResetMode.Soft, repo.Head.Commits.Skip(1).First().Sha); var commitToKeep = repo.ObjectDatabase.CreateCommitWithSignature(commitBuffer, signedCommitData); repo.Refs.UpdateTarget(repo.Refs.Head, commitToKeep); var branchAgain = Commands.Checkout(repo, KnownGitHubs.BranchName); repo.Reset(ResetMode.Hard, commitToKeep.Sha); // push to GitHub repo.Network.Push(remote, $"refs/heads/{KnownGitHubs.BranchName}", new PushOptions { CredentialsProvider = credentialsProvider, }); return(true); }