/// <summary> /// Add all changes in app repo and push to remote /// </summary> /// <param name="commitInfo">the commit information for the app</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 (LibGit2Sharp.Repository repo = new LibGit2Sharp.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 async Task <FileMetadata> WriteFile(byte[] fileContent, string filename) { try { var commitInfo = new CommitInfo(filename, WriteMode.Overwrite.Instance, false, DateTime.Now); using (var client = GetClient()) { var metadata = await client.Files.UploadAsync(commitInfo, new MemoryStream(fileContent)); return(metadata); } } #pragma warning disable CS0168 // La variabile 'ex' è dichiarata, ma non viene mai usata catch (Exception ex) #pragma warning restore CS0168 // La variabile 'ex' è dichiarata, ma non viene mai usata { Crashes.TrackError(ex); return(null); } }
private void ProcessBlame(GitRevision revision, List <string> children, Control controlToMask, int scrollpos) { var blameCommitter = new StringBuilder(); var blameFile = new StringBuilder(); for (int i = 0; i < _blame.Lines.Count; i++) { GitBlameLine blameLine = _blame.Lines[i]; GitBlameHeader blameHeader = _blame.FindHeaderForCommitGuid(blameLine.CommitGuid); if (i > 0 && _blame.Lines[i - 1].CommitGuid == blameLine.CommitGuid) { blameCommitter.AppendLine(new string(' ', 200)); } else { blameCommitter.AppendLine( (blameHeader.Author + " - " + blameHeader.AuthorTime + " - " + blameHeader.FileName + new string(' ', 100)).Trim(new[] { '\r', '\n' })); } if (blameLine.LineText == null) { blameFile.AppendLine(""); } else { blameFile.AppendLine(blameLine.LineText.Trim(new[] { '\r', '\n' })); } } BlameCommitter.ViewText("committer.txt", blameCommitter.ToString()); BlameFile.ViewText(_fileName, blameFile.ToString()); BlameFile.ScrollPos = scrollpos; CommitInfo.SetRevisionWithChildren(revision, children); if (controlToMask != null) { controlToMask.UnMask(); } }
private async void HandleCommitCreated(object sender, CommitInfo info) { var updatedStream = await Client.StreamGet(Stream.id); Branches = updatedStream.branches.items; if (IsSenderCard) { return; } var binfo = Branches.FirstOrDefault(b => b.name == info.branchName); var cinfo = binfo.commits.items.FirstOrDefault(c => c.id == info.id); if (Branch.name == info.branchName) { Branch = binfo; } ServerUpdateSummary = $"{cinfo.authorName} sent new data on branch {info.branchName}: {info.message}"; ServerUpdates = true; }
public async Task UploadProfilePicture(string fileName) { Console.WriteLine("Uploading file..."); Console.WriteLine("------------------------------"); try { CommitInfo commmitInfo = new CommitInfo(ProfilesFolder + "/" + "avatar.png", null, true); var fileStream = new FileStream(fileName, FileMode.Open); await this.client.Files.UploadAsync(commmitInfo, fileStream); Console.WriteLine("File {0} uploaded", fileName); } catch (Exception ex) { Console.WriteLine("File {0} not uploaded", fileName); Console.WriteLine(ex.Message); } Console.WriteLine("------------------------------"); }
public ActionResult ApiMethod(string user, string repo) { string apiKey = WebConfigurationManager.AppSettings["credentials"]; string username = "******"; string CommitUri = $"https://api.github.com/repos/{user}/{repo}/commits"; Console.WriteLine(CommitUri); string test = $"{user}{repo}"; Console.WriteLine(test); string json = SendRequest(CommitUri, apiKey, username); JArray jsonArray = JArray.Parse(json); List <CommitInfo> commitInfos = new List <CommitInfo>(); for (int i = 0; i < jsonArray.Count; i++) { JObject ComObj = JObject.Parse(jsonArray[i].ToString()); CommitInfo commitInfo = new CommitInfo { Sha = (string)ComObj.SelectToken("sha"), Committer = (string)ComObj.SelectToken("commit.committer.name"), CommitMessage = (string)ComObj.SelectToken("commit.message"), TimeStamp = (DateTime)ComObj.SelectToken("commit.committer.date"), CommitHtmlURL = (string)ComObj.SelectToken("html_url") }; commitInfos.Add(commitInfo); } commitInfos.Sort((x, y) => x.TimeStamp.CompareTo(y.TimeStamp)); string jsonString = JsonConvert.SerializeObject(commitInfos, Formatting.Indented); return(new ContentResult { Content = jsonString, ContentType = "application/json", ContentEncoding = System.Text.Encoding.UTF8 }); }
public RequestProcessResult TryFormat(JObject request, out string message) { if (request == null) { throw new ArgumentNullException(nameof(request)); } var errors = new JTokenErrors(); JToken projectNode = request.RequireChild(GitlabKeys.Project, errors); JToken attributesNode = request.RequireChild(GitlabKeys.ObjectAttributes, errors); JToken commitNode = request.RequireChild(GitlabKeys.Commit, errors); ProjectInfo project = ProjectInfo.TryRead(projectNode, errors); string branchName = attributesNode?.RequireString(GitlabKeys.Ref, errors); string pipelineId = attributesNode?.RequireString(GitlabKeys.Id, errors); CommitInfo commit = CommitInfo.TryRead(commitNode, errors); RequestProcessResult result; if (errors.HasAny) { string error = errors.Compose(); this.logger.LogDebug("The request processing was rejected with error: \"{0}\"", error); message = null; result = RequestProcessResult.CreateFailure(error); } else { message = $"[{project.Name}]({project.Url}). The pipeline [{pipelineId}]({project.Url}/pipelines/{pipelineId}) has failed for the branch [{branchName}]({project.Url}/tree/{branchName})!\r\n\r\n" + $"The last commit [{commit.Hash}]({commit.Url}) by *{commit.AuthorName}*\r\n{commit.Message}"; this.logger.LogTrace("Composed the message: \"{0}\"", message); result = RequestProcessResult.CreateSuccess(); } return(result); }
/// <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, "*"); LibGit2Sharp.Signature signature = GetDeveloperSignature(); repo.Commit(commitInfo.Message, signature, signature); } }
private void UpdateChaches(GitRepoStatus status) { try { //update all branches cachedBranches = gitManager.Repository.Branches.Select(b => new BranchInfo(b)).ToArray(); //update selected branch SetSelectedBranch(selectedBranchName); int commitCount = 0; CommitInfo[] newCachedCommits = null; if (selectedBranch != null) { //update commits and limit them depending on settings var loadedBranch = selectedBranch.LoadBranch(gitManager); if (loadedBranch != null && loadedBranch.Commits != null) { Commit[] commits = loadedBranch.Commits.Take(maxCommitsCount).ToArray(); newCachedCommits = new CommitInfo[commits.Length]; for (int i = 0; i < commits.Length; i++) { newCachedCommits[i] = new CommitInfo(commits[i], cachedBranches.Where(b => b.Tip.Id == commits[i].Id).ToArray()); } commitCount = newCachedCommits.Length; } } commitRects = new Rect[commitCount]; cachedCommits = newCachedCommits; hasConflicts = status.Any(s => s.Status == FileStatus.Conflicted); } catch (Exception e) { Debug.LogException(e); } }
/// <summary> /// <para>Create a new file with the contents provided in the request.</para> /// </summary> /// <param name="path">Path in the user's Dropbox to save the file.</param> /// <param name="mode">Selects what to do if the file already exists.</param> /// <param name="autorename">If there's a conflict, as determined by <paramref /// name="mode" />, have the Dropbox server try to autorename the file to avoid /// conflict.</param> /// <param name="clientModified">The value to store as the <paramref /// name="clientModified" /> timestamp. Dropbox automatically records the time at which /// the file was written to the Dropbox servers. It can also record an additional /// timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of /// when the file was actually created or modified.</param> /// <param name="mute">Normally, users are made aware of any file modifications in /// their Dropbox account via notifications in the client software. If <c>true</c>, /// this tells the clients that this modification shouldn't result in a user /// notification.</param> /// <param name="body">The document to upload</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadError}">Thrown if there is an error /// processing the request; This will contain a <see cref="UploadError"/>.</exception> public t.Task<FileMetadata> UploadAsync(string path, WriteMode mode = null, bool autorename = false, sys.DateTime? clientModified = null, bool mute = false, io.Stream body = null) { var commitInfo = new CommitInfo(path, mode, autorename, clientModified, mute); return this.UploadAsync(commitInfo, body); }
public TaskProxy(CommitInfo zd, Context cx) { commitInfo = zd; context = cx; }
private void Client_OnCommitDeleted(object sender, CommitInfo e) { CommitDeletedInfo = e; }
public ExpectingAnotherEventOrCommit(CommitInfo commit, CommitBuilder instance) { _commit = commit; _instance = instance; }
private void RevisionInfo_CommandClick(object sender, CommitInfo.CommandEventArgs e) { if (e.Command == "gotocommit") { var revision = new GitRevision(Module, e.Data); var found = RevisionGrid.SetSelectedRevision(revision); // When 'git log --first-parent' filtration is used, user can click on child commit // that is not present in the shown git log. User still wants to see the child commit // and to make it possible we add explicit branch filter and refresh. if (AppSettings.ShowFirstParent && !found) { _filterBranchHelper.SetBranchFilter(revision.Guid, refresh: true); RevisionGrid.SetSelectedRevision(revision); } } else if (e.Command == "gotobranch" || e.Command == "gototag") { string error = ""; CommitData commit = CommitData.GetCommitData(Module, e.Data, ref error); if (commit != null) RevisionGrid.SetSelectedRevision(new GitRevision(Module, commit.Guid)); } else if (e.Command == "navigatebackward") { RevisionGrid.NavigateBackward(); } else if (e.Command == "navigateforward") { RevisionGrid.NavigateForward(); } }
/// <summary> /// Asynchronously uploads the file. /// </summary> /// <returns></returns> protected override async Task<SerializableAPIResult<CloudStorageServiceAPIFile>> UploadFileAsync() { SerializableAPIResult<CloudStorageServiceAPIFile> result = new SerializableAPIResult<CloudStorageServiceAPIFile>(); try { byte[] content = Util.GZipCompress(SettingsFileContentByteArray).ToArray(); CommitInfo commitInfo = new CommitInfo($"/{SettingsFileNameWithoutExtension}", WriteMode.Overwrite.Instance); using (DropboxClient client = GetClient()) using (Stream stream = Util.GetMemoryStream(content)) { await client.Files.UploadAsync(commitInfo, stream).ConfigureAwait(false); return result; } } catch (ApiException<UploadError> ex) { result.Error = new SerializableAPIError { ErrorMessage = ex.Message }; } catch (AuthException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (BadInputException exc) { IsAuthenticated = false; result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } catch (Exception exc) { result.Error = new SerializableAPIError { ErrorMessage = exc.Message }; } return result; }
private void DoCommit(Rect rect, Rect scrollRect, CommitInfo commit) { GitProfilerProxy.BeginSample("Git History Window Commit GUI", this); Event current = Event.current; if (rect.y > scrollRect.height + historyScroll.y || rect.y + scrollRect.height < historyScroll.y) { return; } BranchInfo[] branches = commit.Branches; bool isHead = commit.IsHead; bool isRemote = commit.IsRemote; Color branchColor = Color.white; if (branches != null) { foreach (var branch in branches) { if (branch.IsRemote) { branchColor = remoteColor; break; } if (branch.IsCurrentRepositoryHead) { branchColor = headColor; break; } UnityEngine.Random.InitState(branch.CanonicalName.GetHashCode()); branchColor = UnityEngine.Random.ColorHSV(0, 1, 0, 1); } } GUI.backgroundColor = new Color(1, 1, 1, 0.4f); GUI.Box(new Rect(24, rect.y + 5, 16, 16), GUIContent.none, styles.commitArrow); GUI.backgroundColor = branchColor; GUI.Box(new Rect(9, rect.y + 6, 12, 12), GUIContent.none, styles.historyKnobNormal); GUI.backgroundColor = Color.white; float y = 8; float x = 12; if (isHead) { //GUI.Box(new Rect(commitRect.x + 4, commitRect.y, commitRect.width - 8, commitRect.height - 8), GUIContent.none, "TL SelectionButton PreDropGlow"); } GUI.Box(rect, GUIContent.none, styles.commitBg); if (isHead || isRemote) { GUI.color = branchColor; GUI.DrawTexture(new Rect(rect.x + 4, rect.y, rect.width - 8, 5), Texture2D.whiteTexture); GUI.color = Color.white; y += 4; } if (gitManager.Settings.UseGavatar && Application.internetReachability != NetworkReachability.NotReachable) { Texture2D avatar = GetProfilePixture(commit.Committer.Email); GUI.Box(new Rect(rect.x + x, rect.y + y, 32, 32), avatar != null ? GitGUI.GetTempContent(avatar) : GitOverlay.icons.loadingIconSmall, styles.avatar); } else { UnityEngine.Random.InitState(commit.Committer.Name.GetHashCode()); GUI.contentColor = UnityEngine.Random.ColorHSV(0, 1, 0.6f, 0.6f, 0.8f, 1, 1, 1); GUI.Box(new Rect(rect.x + x, rect.y + y, 32, 32), GitGUI.GetTempContent(commit.Committer.Name.Substring(0, 1).ToUpper()), styles.avatarName); GUI.contentColor = Color.white; } x += 38; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(commit.Committer.Name), EditorStyles.boldLabel); y += 16; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(FormatRemainningTime(commit.Committer.When.UtcDateTime))); y += EditorGUIUtility.singleLineHeight + 3; int firstNewLineIndex = commit.Message.IndexOf(Environment.NewLine); EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x - 10, EditorGUIUtility.singleLineHeight + 4), GitGUI.GetTempContent(firstNewLineIndex > 0 ? commit.Message.Substring(0, firstNewLineIndex) : commit.Message), styles.commitMessage); y += 8; if (branches != null) { if (branches.Length > 0) { y += EditorGUIUtility.singleLineHeight; } foreach (var branch in branches) { GUIStyle style = styles.otherCommitTag; if (branch.IsRemote) { GUI.backgroundColor = remoteColor; } else if (branch.IsCurrentRepositoryHead) { GUI.backgroundColor = headColor; } else { UnityEngine.Random.InitState(branch.CanonicalName.GetHashCode()); GUI.backgroundColor = UnityEngine.Random.ColorHSV(0, 1, 0, 1); } GUIContent labelContent = GitGUI.GetTempContent(branch.FriendlyName, branch.CanonicalName); float labelWidth = style.CalcSize(labelContent).x; Rect branchIconRect = new Rect(rect.x + x, rect.y + y, labelWidth, EditorGUIUtility.singleLineHeight); GUI.Label(branchIconRect, labelContent, style); x += labelWidth + 4; GUI.backgroundColor = Color.white; if (Event.current.type == EventType.ContextClick && branchIconRect.Contains(Event.current.mousePosition)) { GenericMenu branchContextMenu = new GenericMenu(); BranchInfo b = branch; branchContextMenu.AddItem(new GUIContent("View branch"), false, () => { ViewBranchCallback(b); }); if (!b.IsRemote && !b.IsCurrentRepositoryHead) { branchContextMenu.AddItem(new GUIContent("Switch To Branch"), false, () => { SwitchToBranchCallback(b, new Rect(branchIconRect.x - historyScroll.x, branchIconRect.y - historyScroll.y, branchIconRect.width, branchIconRect.height)); }); } else { branchContextMenu.AddDisabledItem(new GUIContent("Switch To Branch")); } branchContextMenu.ShowAsContext(); } } } x = 12; y += EditorGUIUtility.singleLineHeight * 1.5f; GUI.Box(new Rect(rect.x + x, rect.y + y, rect.width - x - x, EditorGUIUtility.singleLineHeight), GUIContent.none, styles.commitHashSeparator); y += EditorGUIUtility.singleLineHeight / 3; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(commit.Id.Sha)); x += GUI.skin.label.CalcSize(GitGUI.GetTempContent(commit.Id.Sha)).x + 8; Rect buttonRect = new Rect(rect.x + x, rect.y + y, 64, EditorGUIUtility.singleLineHeight); x += 64; if (GUI.Button(buttonRect, GitGUI.GetTempContent("Options"), EditorStyles.miniButtonLeft)) { GenericMenu menu = new GenericMenu(); if (selectedBranch.IsCurrentRepositoryHead && !isHead) { var rect1 = buttonRect; menu.AddItem(new GUIContent("Reset"), false, () => { if (externalManager.TakeReset(gitManager.Repository.Lookup <Commit>(commit.Id))) { gitManager.Callbacks.IssueAssetDatabaseRefresh(); gitManager.MarkDirty(); } else { popupsQueue.Enqueue(new KeyValuePair <Rect, PopupWindowContent>(rect1, new ResetPopupWindow(gitManager, gitManager.Repository.Lookup <Commit>(commit.Id)))); } }); } else { menu.AddDisabledItem(new GUIContent("Reset")); } var rect2 = buttonRect; menu.AddItem(new GUIContent("Branch Out"), false, () => { popupsQueue.Enqueue(new KeyValuePair <Rect, PopupWindowContent>(rect2, new GitCreateBranchWindow(gitManager.Repository.Lookup <Commit>(commit.Id), null, gitManager))); }); menu.DropDown(buttonRect); } GUI.enabled = true; buttonRect = new Rect(rect.x + x, rect.y + y, 64, EditorGUIUtility.singleLineHeight); if (GUI.Button(buttonRect, GitGUI.GetTempContent("Details"), EditorStyles.miniButtonRight)) { PopupWindow.Show(buttonRect, new GitCommitDetailsWindow(gitManager, externalManager, gitManager.Repository.Lookup <Commit>(commit.Id))); } if (rect.Contains(current.mousePosition)) { if (current.type == EventType.ContextClick) { current.Use(); } } GitProfilerProxy.EndSample(); }
public static CommitInfo ShouldBeAReferenceTo(this CommitInfo commitInfo, string hash) { commitInfo.hash.ShouldBe(hash); return(commitInfo); }
public ChunkUploadStream(DropboxClient client, CommitInfo commitInfo) { _client = client ?? throw new ArgumentNullException(nameof(client)); _commitInfo = commitInfo; }
protected bool Equals(CommitInfo other) { return CommitId.Equals(other.CommitId) && string.Equals(Context, other.Context) && Equals(Stream, other.Stream); }
public ExpectingEvent(CommitInfo commit, CommitBuilder instance) { _commit = commit; _instance = instance; }
public Task <long> IncrementAsync(string bucketName, CommitInfo lastCommit) { return(Task.FromResult(lastCommit?.BucketRevision + 1 ?? 1)); }
private void ProcessBlame(string filename, GitRevision revision, IReadOnlyList <ObjectId> children, Control controlToMask, int lineNumber, int scrollpos) { var gutter = new StringBuilder(capacity: 4096); var body = new StringBuilder(capacity: 4096); GitBlameCommit lastCommit = null; // NOTE EOL white-space supports highlight on mouse-over. // Highlighting is done via text background colour. // If it could be done with a solid rectangle around the text, // the extra spaces added here could be omitted. foreach (var line in _blame.Lines) { if (line.Commit == lastCommit) { gutter.Append(' ', 120).AppendLine(); } else { gutter.Append(line.Commit.Author); gutter.Append(" - "); gutter.Append(line.Commit.AuthorTime.ToString(CultureInfo.CurrentCulture)); var authorLength = line.Commit.Author?.Length ?? 0; if (filename != line.Commit.FileName) { gutter.Append(" - "); gutter.Append(line.Commit.FileName); gutter.Append(' ', Math.Max(0, 95 - authorLength - line.Commit.FileName.Length)).AppendLine(); } else { gutter.Append(' ', Math.Max(0, 98 - authorLength)).AppendLine(); } } body.AppendLine(line.Text); lastCommit = line.Commit; } ThreadHelper.JoinableTaskFactory.RunAsync( () => BlameCommitter.ViewTextAsync("committer.txt", gutter.ToString())); ThreadHelper.JoinableTaskFactory.RunAsync( () => BlameFile.ViewTextAsync(_fileName, body.ToString())); if (lineNumber > 0) { BlameFile.GoToLine(lineNumber - 1); } else { BlameFile.VScrollPosition = scrollpos; } _clickedBlameLine = null; _blameId = revision.ObjectId; CommitInfo.SetRevisionWithChildren(revision, children); controlToMask?.UnMask(); }
/// <summary> /// Checks if someone else is writing on the same bucket /// </summary> /// <param name="streamId">Unique stream identifier</param> /// <param name="expectedStreamRevision">Expected revision of the provided stream</param> /// <param name="lastCommit">Last commit of the bucket</param> private async Task CheckStreamConsistencyBeforeWriting(Guid streamId, int expectedStreamRevision, CommitInfo lastCommit) { if (!_eventStore.CheckStreamRevisionBeforeWriting) { return; } if (lastCommit == null) { return; } var lastStreamRevision = lastCommit.StreamId == streamId ? lastCommit.StreamRevisionEnd : await this.GetStreamRevisionAsync(streamId) .ConfigureAwait(false); // Note: this check doesn't ensure that in case of real concurrency no one can insert the same commit // the real check is done via a mongo index "StreamRevision". This check basically just ensure to do not write // revision with holes if (lastStreamRevision > expectedStreamRevision) { throw new ConcurrencyWriteException("Someone else is working on the same bucket or stream"); } if (lastStreamRevision < expectedStreamRevision) // Ensure to write commits sequentially { throw new ArgumentOutOfRangeException(nameof(expectedStreamRevision)); } }
/// <summary> /// Add all changes in app repo and push to remote /// </summary> /// <param name="commitInfo">the commit information for the app</param> public void PushChangesForRepository(CommitInfo commitInfo) { string localServiceRepoFolder = _settings.GetServicePath(commitInfo.Org, commitInfo.Repository, AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext)); CommitAndPushToBranch(commitInfo.Org, commitInfo.Repository, "master", localServiceRepoFolder, commitInfo.Message); }
private async Task <string> ChunkUploadStreamAsync(Stream stream, string filepath, ulong size, DateTime lastModified) { int chunkSize = this.context.HttpChunkSize; int chunkCount = (int)Math.Ceiling((double)size / chunkSize); string serverRev = null; byte[] buffer = new byte[chunkSize]; string sessionId = null; var commitInfo = new CommitInfo(filepath, WriteMode.Overwrite.Instance, false, lastModified); DateTime start = DateTime.Now; for (var index = 0; index < chunkCount; index++) { var read = await stream .ReadAsync(buffer, 0, chunkSize) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpReadTimeoutInSeconds)); var offset = (ulong)(chunkSize * index); this.ProgressUpdate(filepath, size, offset, start); using (MemoryStream memoryStream = new MemoryStream(buffer, 0, read)) { if (chunkCount == 1) { var result = await this.Client.Files .UploadAsync(commitInfo, memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); serverRev = result.Rev; } else if (index == 0) { var result = await this.Client.Files .UploadSessionStartAsync(body : memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); sessionId = result.SessionId; } else { UploadSessionCursor cursor = new UploadSessionCursor(sessionId, offset); bool isLastChunk = index == chunkCount - 1; if (!isLastChunk) { await this.Client.Files .UploadSessionAppendV2Async(cursor, body : memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); } else { var result = await this.Client.Files .UploadSessionFinishAsync(cursor, commitInfo, memoryStream) .WithTimeout(TimeSpan.FromSeconds(this.context.HttpWriteTimeoutInSeconds)); serverRev = result.Rev; } } } } return(serverRev); }
public void LoadBlame(GitRevision revision, List <string> children, string fileName, RevisionGrid revGrid, Control controlToMask, Encoding encoding) { string guid = revision.Guid; //refresh only when something changed if (guid.Equals(CommitInfo.Revision) && fileName.Equals(fileName) && revGrid == _revGrid && encoding == _encoding) { return; } if (controlToMask != null) { controlToMask.Mask(); } var scrollpos = BlameFile.ScrollPos; var blameCommitter = new StringBuilder(); var blameFile = new StringBuilder(); _revGrid = revGrid; _fileName = fileName; _encoding = encoding; blameLoader.Load(() => { _blame = Module.Blame(fileName, guid, encoding); }, () => { for (int i = 0; i < _blame.Lines.Count; i++) { GitBlameLine blameLine = _blame.Lines[i]; GitBlameHeader blameHeader = _blame.FindHeaderForCommitGuid(blameLine.CommitGuid); if (i > 0 && _blame.Lines[i - 1].CommitGuid == blameLine.CommitGuid) { blameCommitter.AppendLine(new string(' ', 200)); } else { blameCommitter.AppendLine((blameHeader.Author + " - " + blameHeader.AuthorTime + " - " + blameHeader.FileName + new string(' ', 100)).Trim(new[] { '\r', '\n' })); } if (blameLine.LineText == null) { blameFile.AppendLine(""); } else { blameFile.AppendLine(blameLine.LineText.Trim(new char[] { '\r', '\n' })); } } BlameCommitter.ViewText("committer.txt", blameCommitter.ToString()); BlameFile.ViewText(fileName, blameFile.ToString()); BlameFile.ScrollPos = scrollpos; CommitInfo.SetRevisionWithChildren(revision, children); if (controlToMask != null) { controlToMask.UnMask(); } }); }
public void CommitAndPushRepo([FromBody] CommitInfo commitInfo) { _sourceControl.PushChangesForRepository(commitInfo); }
/// <summary> /// Create commit object that will be persisted to Mongo /// </summary> /// <param name="streamId">Unique stream identifier</param> /// <param name="expectedStreamRevision">Expected revision of the provided stream</param> /// <param name="eventsArray">List of events to commit</param> /// <param name="lastCommit">Last commit written to current bucket</param> /// <returns>CommitData object</returns> private async Task <CommitData <T> > CreateCommitAsync(Guid streamId, int expectedStreamRevision, T[] eventsArray, CommitInfo lastCommit) { var bucketRevision = await _eventStore.AutonIncrementStrategy .IncrementAsync(BucketName, lastCommit) .ConfigureAwait(false); var commit = new CommitData <T> { BucketRevision = bucketRevision, Dispatched = false, Events = eventsArray, StreamId = streamId, StreamRevisionStart = expectedStreamRevision, StreamRevisionEnd = expectedStreamRevision + eventsArray.Length }; return(commit); }
public ButtonEventArgs(CommitInfo _cinf, string branchname) { BranchName = branchname; CINF = _cinf; }
public IActionResult PushChanges(CommitInfo commitInfo) { _sourceControl.PushChangesForRepository(commitInfo); return(RedirectToAction("index", new { commitInfo.Org })); }
public void Commit(CommitInfo commitInfo) { throw new NotImplementedException(); }
private void RevisionInfo_CommandClick(object sender, CommitInfo.CommandEventArgs e) { if (e.Command == "gotocommit") { RevisionGrid.SetSelectedRevision(new GitRevision(Module, e.Data)); } else if (e.Command == "gotobranch" || e.Command == "gototag") { string error = ""; CommitData commit = CommitData.GetCommitData(Module, e.Data, ref error); if (commit != null) RevisionGrid.SetSelectedRevision(new GitRevision(Module, commit.Guid)); } else if (e.Command == "navigatebackward") { RevisionGrid.NavigateBackward(); } else if (e.Command == "navigateforward") { RevisionGrid.NavigateForward(); } }
public void PushChangesForRepository(CommitInfo commitInfo) { throw new NotImplementedException(); }
static async Task Main(string[] args) { try { var token = args[0]; var localDirectory = Path.GetFullPath(args[1]); if (!IsEndingWithSeparator(localDirectory)) { localDirectory += Path.DirectorySeparatorChar; } var dropboxDirectory = args[2]; if (!IsEndingWithSeparator(dropboxDirectory)) { dropboxDirectory += Path.AltDirectorySeparatorChar; } string password = args[3]; var newFiles = new HashSet <string>( Directory.GetFiles(localDirectory, "*", SearchOption.AllDirectories) .Select(f => f.Substring(localDirectory.Length)), StringComparer.OrdinalIgnoreCase); var filesToDelete = new HashSet <string>(); using (var dropbox = new DropboxClient(token)) { try { await dropbox.Files.CreateFolderV2Async(dropboxDirectory.TrimEnd('/')); } catch { } var existingFiles = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); var existingFolders = new HashSet <string>(StringComparer.InvariantCultureIgnoreCase); existingFolders.Add(""); for (var list = await dropbox.Files.ListFolderAsync(dropboxDirectory.TrimEnd('/'), true, limit: 2000); list != null; list = list.HasMore ? await dropbox.Files.ListFolderContinueAsync(list.Cursor) : null) { foreach (var entry in list.Entries) { if (!entry.IsFile) { if (entry.IsFolder) { existingFolders.Add(entry.AsFolder.PathLower); } continue; } existingFiles.Add(entry.PathLower); var relativePath = entry.PathLower.Substring(dropboxDirectory.Length); if (!relativePath.EndsWith(".zip")) { continue; } var withoutZip = relativePath.Substring(0, relativePath.Length - 4).Replace("/", Path.DirectorySeparatorChar + ""); if (newFiles.Contains(withoutZip)) { var info = new FileInfo(Path.Combine(localDirectory, withoutZip)); if ((info.LastWriteTimeUtc - entry.AsFile.ClientModified).TotalSeconds < 1f) { newFiles.Remove(withoutZip); } } else { filesToDelete.Add(entry.PathLower); } } } await DeleteFilesBatchAsync(); ulong deletingAccumulatedSize = 0; async Task DeleteFilesBatchAsync() { if (filesToDelete.Count > 0) { Console.WriteLine($"Deleting files: \n{string.Join("\n", filesToDelete)}"); var j = await dropbox.Files.DeleteBatchAsync(filesToDelete.Select(x => new DeleteArg(x))); if (j.IsAsyncJobId) { for (DeleteBatchJobStatus r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value); r.IsInProgress; r = await dropbox.Files.DeleteBatchCheckAsync(j.AsAsyncJobId.Value)) { Thread.Sleep(5000); } } filesToDelete.Clear(); deletingAccumulatedSize = 0; } } if (newFiles.Count > 0) { Console.WriteLine($"Uploading files: {newFiles.Count}"); ZipStrings.UseUnicode = true; ZipStrings.CodePage = 65001; var entryFactory = new ZipEntryFactory(); byte[] msBuffer = new byte[1000 * 1000 * 150]; int bufferSize = 1000 * 1000 * 140; using var reader = new AsyncMultiFileReader(bufferSize, (f, t) => new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, true)); var newFilesList = newFiles.ToList(); for (int i = 0; i < newFilesList.Count; i++) { var relativePath = newFilesList[i]; Console.Write($" {relativePath}"); string fullPath = Path.Combine(localDirectory, relativePath); reader.NextFile = (fullPath, null); reader.OpenNextFile(); if (i < newFilesList.Count - 1) { reader.NextFile = (Path.Combine(localDirectory, newFilesList[i + 1]), null); } var info = new FileInfo(fullPath); var clientModifiedAt = info.LastWriteTimeUtc; using (var zipWriterUnderlyingStream = new CopyStream()) { var bufferStream = new MemoryStream(msBuffer); bufferStream.SetLength(0); UploadSessionStartResult session = null; long offset = 0; using (var zipWriter = new ZipOutputStream(zipWriterUnderlyingStream, bufferSize) { IsStreamOwner = false, Password = password, UseZip64 = UseZip64.On }) { try { zipWriterUnderlyingStream.CopyTo = bufferStream; zipWriter.SetLevel(0); var entry = entryFactory.MakeFileEntry(fullPath, '/' + Path.GetFileName(relativePath), true); entry.AESKeySize = 256; zipWriter.PutNextEntry(entry); int read; while ((read = reader.ReadNextBlock()) > 0) { Console.Write($"\r {relativePath} {offset / (double) info.Length * 100:F0}%"); zipWriter.Write(reader.CurrentBuffer, 0, read); zipWriter.Flush(); bufferStream.Position = 0; var length = bufferStream.Length; if (session == null) { session = await dropbox.Files.UploadSessionStartAsync(new UploadSessionStartArg(), bufferStream); } else { await dropbox.Files.UploadSessionAppendV2Async(new UploadSessionCursor(session.SessionId, (ulong)offset), false, bufferStream); } offset += length; zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer); bufferStream.SetLength(0); } Console.Write($"\r {relativePath} 100%"); Console.WriteLine(); zipWriter.CloseEntry(); zipWriter.Finish(); zipWriter.Close(); } catch { // disposing ZipOutputStream causes writing to bufferStream if (!bufferStream.CanRead && !bufferStream.CanWrite) { zipWriterUnderlyingStream.CopyTo = bufferStream = new MemoryStream(msBuffer); } throw; } } bufferStream.Position = 0; var commitInfo = new CommitInfo(Path.Combine(dropboxDirectory, relativePath.Replace("\\", "/")) + ".zip", WriteMode.Overwrite.Instance, false, clientModifiedAt); if (session == null) { await dropbox.Files.UploadAsync(commitInfo, bufferStream); } else { await dropbox.Files.UploadSessionFinishAsync(new UploadSessionCursor(session.SessionId, (ulong)offset), commitInfo, bufferStream); } } } } Console.WriteLine("Recycling deleted files for endless storage"); const ulong deletingBatchSize = 1024UL * 1024 * 1024 * 32; for (var list = await dropbox.Files.ListFolderAsync(dropboxDirectory.TrimEnd('/'), true, limit: 2000, includeDeleted: true); list != null; list = list.HasMore ? await dropbox.Files.ListFolderContinueAsync(list.Cursor) : null) { foreach (var entry in list.Entries) { if (!entry.IsDeleted || existingFiles.Contains(entry.PathLower)) { continue; } var parentFolder = entry.PathLower; int lastSlash = parentFolder.LastIndexOf('/'); if (lastSlash == -1) { continue; } parentFolder = parentFolder.Substring(0, lastSlash); if (!existingFolders.Contains(parentFolder)) { continue; } ListRevisionsResult rev; try { rev = await dropbox.Files.ListRevisionsAsync(entry.AsDeleted.PathLower, ListRevisionsMode.Path.Instance, 1); } catch { // get revisions doesn't work for folders but no way to check if it's a folder beforehand continue; } if (!(DateTime.UtcNow - rev.ServerDeleted >= TimeSpan.FromDays(15)) || (DateTime.UtcNow - rev.ServerDeleted > TimeSpan.FromDays(29))) { // don't need to restore too young // can't restore too old continue; } Console.WriteLine("Restoring " + entry.PathDisplay); var restored = await dropbox.Files.RestoreAsync(entry.PathLower, rev.Entries.First().Rev); if (restored.AsFile.Size >= deletingBatchSize && filesToDelete.Count == 0) { Console.WriteLine("Deleting " + entry.PathDisplay); await dropbox.Files.DeleteV2Async(restored.PathLower, restored.Rev); } else { // warning: rev not included, concurrent modification changes may be lost filesToDelete.Add(restored.PathLower); deletingAccumulatedSize += restored.Size; if (deletingAccumulatedSize >= deletingBatchSize) { await DeleteFilesBatchAsync(); } } } } await DeleteFilesBatchAsync(); } Console.WriteLine("All done"); } catch (Exception e) { // redirecting error to normal output Console.WriteLine(e); throw; } }
/// <summary> /// <para>Finish an upload session and save the uploaded data to the given file /// path.</para> /// </summary> /// <param name="cursor">Contains the upload session ID and the offset.</param> /// <param name="commit">Contains the path and other optional modifiers for the /// commit.</param> /// <param name="body">The document to upload</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadSessionFinishError}">Thrown if /// there is an error processing the request; This will contain a <see /// cref="UploadSessionFinishError"/>.</exception> public t.Task<FileMetadata> UploadSessionFinishAsync(UploadSessionCursor cursor, CommitInfo commit, io.Stream body) { var uploadSessionFinishArg = new UploadSessionFinishArg(cursor, commit); return this.UploadSessionFinishAsync(uploadSessionFinishArg, body); }
private void Blame_CommandClick(object sender, CommitInfo.CommandEventArgs e) { if (e.Command == "gotocommit") { FileChanges.SetSelectedRevision(new GitRevision(Module, e.Data)); } else if (e.Command == "gotobranch" || e.Command == "gototag") { string error = ""; CommitData commit = CommitData.GetCommitData(Module, e.Data, ref error); if (commit != null) FileChanges.SetSelectedRevision(new GitRevision(Module, commit.Guid)); } }
/// <summary> /// <para>Create a new file with the contents provided in the request.</para> /// </summary> /// <param name="commitInfo">The request parameters</param> /// <param name="body">The content to upload.</param> /// <returns>The task that represents the asynchronous send operation. The TResult /// parameter contains the response from the server.</returns> /// <exception cref="Dropbox.Api.ApiException{UploadError}">Thrown if there is an error /// processing the request; This will contain a <see cref="UploadError"/>.</exception> public t.Task<FileMetadata> UploadAsync(CommitInfo commitInfo, io.Stream body) { return this.Transport.SendUploadRequestAsync<CommitInfo, FileMetadata, UploadError>(commitInfo, body, "content", "/files/upload", CommitInfo.Encoder, FileMetadata.Decoder, UploadError.Decoder); }
/// <summary> /// <para>Begins an asynchronous send to the upload session finish route.</para> /// </summary> /// <param name="cursor">Contains the upload session ID and the offset.</param> /// <param name="commit">Contains the path and other optional modifiers for the /// commit.</param> /// <param name="body">The document to upload</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUploadSessionFinish(UploadSessionCursor cursor, CommitInfo commit, io.Stream body, sys.AsyncCallback callback, object callbackState = null) { var uploadSessionFinishArg = new UploadSessionFinishArg(cursor, commit); return this.BeginUploadSessionFinish(uploadSessionFinishArg, body, callback, callbackState); }
public RepositoryViewModel(Repository repository) { this.repository = repository; this.latestCommit = repository.GetLatestCommit(); }
/// <summary> /// <para>Begins an asynchronous send to the upload route.</para> /// </summary> /// <param name="commitInfo">The request parameters.</param> /// <param name="body">The content to upload.</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="state">A user provided object that distinguished this send from other /// send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUpload(CommitInfo commitInfo, io.Stream body, sys.AsyncCallback callback, object state = null) { var task = this.UploadAsync(commitInfo, body); return enc.Util.ToApm(task, callback, state); }
private void label1_Click_1(object sender, EventArgs e) { bool test = true; Process compiler = new Process(); compiler.StartInfo.FileName = "svn"; compiler.StartInfo.Arguments = "log"; compiler.StartInfo.UseShellExecute = false; compiler.StartInfo.RedirectStandardOutput = true; compiler.Start(); string output = compiler.StandardOutput.ReadToEnd(); FileInfo testOutput = new FileInfo(@"c:\temp\output.txt"); StreamReader projectsXmlFileReader = new StreamReader(testOutput.FullName); output = projectsXmlFileReader.ReadToEnd(); string[] splitArray = null; try { splitArray = Regex.Split(output, @"-{72}", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline); } catch (ArgumentException ex) { Debug.Print(ex.Message); } List <CommitInfo> commits = new List <CommitInfo>(); foreach (string commit in splitArray) { if (commit.Length > 3) { string header = commit.Trim(); string coHeader = ""; if (header.IndexOf("\r\n", 0) < 0) { coHeader = header; } else { coHeader = header.Substring(0, header.IndexOf("\r\n", 0)); } string[] headers = coHeader.Split('|'); string id = headers[0].Trim(); string name = headers[1].Trim(); string date = headers[2].Trim(); string lineCount = headers[3].Trim(); if (test) { FileInfo cmdOutput = new FileInfo(@"c:\temp\logwithfiles.txt"); StreamReader reader = new StreamReader(cmdOutput.FullName); string commitFiles = reader.ReadToEnd(); List <string> resultList = new List <string>(); try { Regex regexObj = new Regex(@"([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?", RegexOptions.IgnoreCase | RegexOptions.Multiline); Match matchResult = regexObj.Match(commitFiles); while (matchResult.Success) { resultList.Add(matchResult.Value); matchResult = matchResult.NextMatch(); } } catch (ArgumentException ex) { Debug.Print(ex.Message); } foreach (string commit2 in resultList) { CommitInfo co = new CommitInfo(); co.Id = id; co.Who = name; co.Date = date; co.LineCount = lineCount; co.Path = commit2; commits.Add(co); } test = false; } } } CommitedFilesSelection selectionDialog = new CommitedFilesSelection(commits); selectionDialog.Show(); }
/// <summary> /// <para>Begins an asynchronous send to the upload route.</para> /// </summary> /// <param name="path">Path in the user's Dropbox to save the file.</param> /// <param name="mode">Selects what to do if the file already exists.</param> /// <param name="autorename">If there's a conflict, as determined by <paramref /// name="mode" />, have the Dropbox server try to autorename the file to avoid /// conflict.</param> /// <param name="clientModified">The value to store as the <paramref /// name="clientModified" /> timestamp. Dropbox automatically records the time at which /// the file was written to the Dropbox servers. It can also record an additional /// timestamp, provided by Dropbox desktop clients, mobile clients, and API apps of /// when the file was actually created or modified.</param> /// <param name="mute">Normally, users are made aware of any file modifications in /// their Dropbox account via notifications in the client software. If <c>true</c>, /// this tells the clients that this modification shouldn't result in a user /// notification.</param> /// <param name="body">The document to upload</param> /// <param name="callback">The method to be called when the asynchronous send is /// completed.</param> /// <param name="callbackState">A user provided object that distinguished this send /// from other send requests.</param> /// <returns>An object that represents the asynchronous send request.</returns> public sys.IAsyncResult BeginUpload(string path, WriteMode mode = null, bool autorename = false, sys.DateTime? clientModified = null, bool mute = false, io.Stream body = null, sys.AsyncCallback callback = null, object callbackState = null) { var commitInfo = new CommitInfo(path, mode, autorename, clientModified, mute); return this.BeginUpload(commitInfo, body, callback, callbackState); }
private void DoCommit(Rect rect, Rect scrollRect, CommitInfo commit) { GitProfilerProxy.BeginSample("Git History Window Commit GUI", this); Event current = Event.current; if (rect.y > scrollRect.height + historyScroll.y || rect.y + scrollRect.height < historyScroll.y) { return; } BranchInfo[] branches = commit.Branches; bool isHead = commit.IsHead; bool isRemote = commit.IsRemote; GUI.Box(new Rect(8, rect.y + 6, 16, 16), GUIContent.none, "AC LeftArrow"); GUI.Box(new Rect(8, rect.y + 6, 16, 16), GUIContent.none, branches != null && branches.Length > 0 ? isHead ? styles.historyKnobHead : isRemote ? styles.historyKnobRemote : styles.historyKnobOther : styles.historyKnobNormal); float y = 8; float x = 12; if (isHead) { //GUI.Box(new Rect(commitRect.x + 4, commitRect.y, commitRect.width - 8, commitRect.height - 8), GUIContent.none, "TL SelectionButton PreDropGlow"); } GUI.Box(rect, GUIContent.none, "RegionBg"); if (isHead || isRemote) { GUI.Box(new Rect(rect.x + 4, rect.y, rect.width - 8, 5), GUIContent.none, isHead ? styles.commitLineHead : styles.commitLineRemote); y += 4; } if (GitManager.Settings.UseGavatar && Application.internetReachability != NetworkReachability.NotReachable) { Texture2D avatar = GetProfilePixture(commit.Committer.Email); if (avatar != null) { GUI.Box(new Rect(rect.x + x, rect.y + y, 32, 32), GitGUI.GetTempContent(avatar), styles.avatar); } else { GUI.Box(new Rect(rect.x + x, rect.y + y, 32, 32), GitManager.icons.loadingIconSmall, styles.avatar); } } else { UnityEngine.Random.InitState(commit.Committer.Name.GetHashCode()); GUI.contentColor = UnityEngine.Random.ColorHSV(0, 1, 0.6f, 0.6f, 0.8f, 1, 1, 1); GUI.Box(new Rect(rect.x + x, rect.y + y, 32, 32), GitGUI.GetTempContent(commit.Committer.Name.Substring(0, 1).ToUpper()), styles.avatarName); GUI.contentColor = Color.white; } //if (avatar != null) //{ //GUI.DrawTexture(new Rect(rect.x + x, rect.y + y, 32, 32), avatar); //} x += 38; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(commit.Committer.Name), EditorStyles.boldLabel); y += 16; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(FormatRemainningTime(commit.Committer.When.UtcDateTime))); y += EditorGUIUtility.singleLineHeight + 3; int firstNewLineIndex = commit.Message.IndexOf(Environment.NewLine); EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x - 10, EditorGUIUtility.singleLineHeight + 4), GitGUI.GetTempContent(firstNewLineIndex > 0 ? commit.Message.Substring(0, firstNewLineIndex) : commit.Message), styles.commitMessage); y += 8; if (branches != null) { if (branches.Length > 0) { y += EditorGUIUtility.singleLineHeight; } foreach (var branch in branches) { GUIStyle style = branch.IsRemote ? styles.remoteCommitTag : branch.IsCurrentRepositoryHead ? styles.headCommitTag : styles.otherCommitTag; GUIContent labelContent = GitGUI.GetTempContent(branch.FriendlyName); float labelWidth = style.CalcSize(labelContent).x; GUI.Label(new Rect(rect.x + x, rect.y + y, labelWidth, EditorGUIUtility.singleLineHeight), labelContent, style); x += labelWidth + 4; } } x = 12; y += EditorGUIUtility.singleLineHeight * 1.5f; GUI.Box(new Rect(rect.x + x, rect.y + y, rect.width - x - x, EditorGUIUtility.singleLineHeight), GUIContent.none, "EyeDropperHorizontalLine"); y += EditorGUIUtility.singleLineHeight / 3; EditorGUI.LabelField(new Rect(rect.x + x, rect.y + y, rect.width - x, EditorGUIUtility.singleLineHeight), GitGUI.GetTempContent(commit.Id.Sha)); x += GUI.skin.label.CalcSize(GitGUI.GetTempContent(commit.Id.Sha)).x + 8; Rect buttonRect = new Rect(rect.x + x, rect.y + y, 64, EditorGUIUtility.singleLineHeight); x += 64; GUI.enabled = selectedBranch.IsCurrentRepositoryHead && !isHead; if (GUI.Button(buttonRect, GitGUI.GetTempContent("Reset", "Reset changes made up to this commit"), "minibuttonleft")) { if (GitExternalManager.TakeReset(GitManager.Repository.Lookup <Commit>(commit.Id))) { AssetDatabase.Refresh(); GitManager.MarkDirty(); } else { PopupWindow.Show(buttonRect, new ResetPopupWindow(GitManager.Repository.Lookup <Commit>(commit.Id))); } } GUI.enabled = true; buttonRect = new Rect(rect.x + x, rect.y + y, 64, EditorGUIUtility.singleLineHeight); if (GUI.Button(buttonRect, GitGUI.GetTempContent("Details"), "minibuttonright")) { PopupWindow.Show(buttonRect, new GitCommitDetailsWindow(GitManager.Repository.Lookup <Commit>(commit.Id))); } if (rect.Contains(current.mousePosition)) { if (current.type == EventType.ContextClick) { //GenericMenu commitContexMenu = new GenericMenu(); //commitContexMenu.ShowAsContext(); current.Use(); } } GitProfilerProxy.EndSample(); }