/// <summary> /// Initializes a new instance of the <see cref="CommitSummaryViewModel"/> class. /// </summary> /// <param name="commit">The commit model.</param> public CommitSummaryViewModel(CommitModel commit) { AbbreviatedOid = commit.AbbreviatedOid; Author = new ActorViewModel(commit.Author); Header = commit.MessageHeadline; Oid = commit.Oid; }
private async void ButtonCommitAndPush_Click(object sender, RoutedEventArgs e) { if (await CommitModel.CommitChangesToRepository(true)) { if (string.IsNullOrEmpty(mmApp.Configuration.Git.GitName)) { mmApp.Configuration.Git.GitName = CommitModel.GitUsername; mmApp.Configuration.Git.GitEmail = CommitModel.GitEmail; } if (AppModel.Configuration.Git.CloseAfterCommit) { Close(); AppModel.Window.ShowStatusSuccess("Files have been committed and pushed to the remote."); } else { CommitModel.CommitMessage = string.Empty; Dispatcher.Invoke(() => { // reload settings CommitModel.GetRepositoryChanges(); }, DispatcherPriority.ApplicationIdle); StatusBar.ShowStatusSuccess("Files have been committed and pushed to the remote."); } if (AppModel.WindowLayout.IsLeftSidebarVisible) { UpdateFolderBrowserGitStatus(); } mmApp.Configuration.Git.GitCommitBehavior = GitCommitBehaviors.CommitAndPush; } }
private void GitCommitDialog_Loaded(object sender, RoutedEventArgs e) { string defaultText = null; if (AppModel.Configuration.Git.GitCommitBehavior == GitCommitBehaviors.CommitAndPush) { ButtonCommitAndPush.IsDefault = true; ButtonCommitAndPush.FontWeight = FontWeight.FromOpenTypeWeight(600); ButtonCommit.Opacity = 0.6; defaultText = "commit and push"; } else { ButtonCommit.IsDefault = true; ButtonCommit.FontWeight = FontWeight.FromOpenTypeWeight(600); ButtonCommitAndPush.Opacity = 0.6; defaultText = "commit"; } CommitModel.GetRepositoryChanges(); DataContext = CommitModel; ShowStatus($"Press Ctrl-Enter to quickly {defaultText}.", 8000); TextCommitMessage.Focus(); }
/// <summary> /// 指定したコミットIDのコミット詳細を取得する。 /// 対象リポジトリが存在しない場合はnullが返る。 /// </summary> /// <param name="gitMap">Git情報</param> /// <param name="repositoryName">リポジトリ名</param> /// <param name="owner">オーナー名</param> /// <param name="commitId">コミットID</param> /// <returns>コミット詳細</returns> public async Task <Result <CommitModel, string> > GetCommitByIdAsync(UserTenantGitMap gitMap, string repositoryName, string owner, string commitId) { // API呼び出しパラメータ作成 var projectId = await GetProjectIdAsync(gitMap, repositoryName, owner); if (projectId.IsSuccess == false) { return(Result <CommitModel, string> .CreateErrorResult(projectId.Error)); } RequestParam param = CreateRequestParam(gitMap); param.ApiPath = $"/api/v4/projects/{projectId.Value}/repository/commits/{commitId}"; // API 呼び出し Result <string, string> response = await this.SendGetRequestAsync(param); if (response.IsSuccess) { var result = JsonConvert.DeserializeObject <GetCommitModel>(response.Value); var commit = new CommitModel() { CommitId = result.id, Comment = result.message, CommitAt = result.committed_date.ToLocalFormatedString(), CommitterName = result.committer_name }; return(Result <CommitModel, string> .CreateResult(commit)); } else { LogError(response.Error); return(Result <CommitModel, string> .CreateErrorResult(response.Error)); } }
public static Uri GenerateGravatarUrl(this CommitModel x) { if (x == null) { return(null); } try { if (x.Author != null && !string.IsNullOrEmpty(x.Author.AvatarUrl)) { return(new Uri(x.Author.AvatarUrl)); } var inputBytes = Encoding.UTF8.GetBytes(x.Commit.Author.Email.Trim().ToLower()); var hash = MD5.Create().ComputeHash(inputBytes); var sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("x2")); } return(new Uri(string.Format("http://www.gravatar.com/avatar/{0}?d={1}", sb, GitHubDefaultGravitar))); } catch { return(null); } }
/// <summary> /// 指定したコミットIDのコミット詳細を取得する。 /// 対象リポジトリが存在しない場合はnullが返る。 /// </summary> /// <param name="gitMap">Git情報</param> /// <param name="repositoryName">リポジトリ名</param> /// <param name="owner">オーナー名</param> /// <param name="commitId">コミットID</param> /// <returns>コミット詳細</returns> public async Task <Result <CommitModel, string> > GetCommitByIdAsync(UserTenantGitMap gitMap, string repositoryName, string owner, string commitId) { // API呼び出しパラメータ作成 RequestParam param = CreateRequestParam(gitMap); param.ApiPath = $"/repos/{owner}/{repositoryName}/commits/{commitId}"; // API 呼び出し Result <string, string> response = await this.SendGetRequestAsync(param); if (response.IsSuccess) { var result = JsonConvert.DeserializeObject <GetCommitModel>(response.Value); var commit = new CommitModel() { CommitId = result.sha, Comment = result.commit?.message, CommitAt = result.commit?.author?.date.ToLocalFormatedString(), CommitterName = result.commit?.author?.name }; return(Result <CommitModel, string> .CreateResult(commit)); } else { return(Result <CommitModel, string> .CreateErrorResult(response.Error)); } }
internal CommitedFileItemViewModel(CommitModel.CommitFileModel file, Action<CommitedFileItemViewModel> gotoAction) : this(gotoAction) { Name = System.IO.Path.GetFileName(file.Filename); RootPath = file.Filename.Substring(0, file.Filename.Length - Name.Length); CalculateSubtitle(file.Additions, file.Deletions, file.Changes); CalculateRef(file.ContentsUrl); }
protected virtual void GoToCommit(CommitModel x) { var repo = new RepositoryIdentifier(x.Repository.FullName); ShowViewModel <CommitViewModel>(new CommitViewModel.NavObject { Username = repo.Owner, Repository = repo.Name, Node = x.Hash }); }
/// <summary> /// 提交小程序代码 /// </summary> /// <param name="componentAccessToken">已授权用户的access_token</param> /// <param name="ext_json"></param> /// <returns></returns> public static OAuthAccessTokenResult Commit(string componentAccessToken, CommitModel ext_json) { string url = string.Format(_commitUrl, componentAccessToken); string dataJson = JsonConvert.SerializeObject(ext_json); string result = HttpHelper.DoPostJson(url, dataJson); OAuthAccessTokenResult model = GetResultModel <OAuthAccessTokenResult>(result); return(model); }
private bool ContainsSearchKeyword(CommitModel x) { try { return(x.Commit.Message.ContainsKeyword(SearchKeyword) || x.GenerateCommiterName().ContainsKeyword(SearchKeyword)); } catch { return(false); } }
private bool ContainsSearchKeyword(CommitModel x) { try { return x.Commit.Message.ContainsKeyword(SearchKeyword) || GenerateCommiterName(x).ContainsKeyword(SearchKeyword); } catch { return false; } }
public CommitElement(CommitModel model, Action action) { _model = model; _action = action; _avatar = new GitHubAvatar(_model.GenerateGravatarUrl()); _name = _model.GenerateCommiterName(); var msg = _model?.Commit?.Message ?? string.Empty; var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); _description = firstLine > 0 ? msg.Substring(0, firstLine) : msg; }
private void MenuUndoFile_Click(object sender, RoutedEventArgs e) { var selected = ListChangedItems.SelectedItem as RepositoryStatusItem; if (selected == null) { return; } CommitModel.GitHelper.UndoChanges(selected.FullPath); CommitModel.GetRepositoryChanges(); }
static void Main(string[] args) { do { Console.WriteLine("*** GitHub Manager ***"); string user = GetUserFromConsole(); string repository = GetRepositoryFromConsole(); var api = new CommitApi(); string result = api.GetResponse(user, repository); try { JArray resultArray = JArray.Parse(result); foreach (JObject commit in resultArray) { IBuilder builder = new CommitBuilder(commit); Director director = new Director(builder); var commitJson = builder.Build(); string commitConsoleLine = GetOneCommitLine(repository, commitJson); Commit commitToDatabase = new Commit { User = user, Repository = repository, Sha = commitJson["sha"], Message = commitJson["message"], Committer = commitJson["committerName"] }; try { CommitModel model = new CommitModel(); model.SaveToDatabase(commitToDatabase); } catch (Exception) { Console.WriteLine("Error 002: Database write error."); } Console.WriteLine(commitConsoleLine); } } catch (Exception) { Console.WriteLine("Error 001: Bad request. Try Again."); } }while (true); }
protected override void GoToCommit(CommitModel x) { if (_pullRequest?.Source?.Repository?.FullName == null) { DisplayAlert("Unable to locate the source repository for this pull request. It may have been deleted!"); } else { var repo = new RepositoryIdentifier(_pullRequest.Source.Repository.FullName); ShowViewModel <CommitViewModel>(new CommitViewModel.NavObject { Username = repo.Owner, Repository = repo.Name, Node = x.Hash }); } }
private void ButtonPull_Click(object sender, RoutedEventArgs e) { if (CommitModel.PullChanges()) { // refresh the file model CommitModel.GetRepositoryChanges(); // Refresh the folder browser Git status icons if (AppModel.WindowLayout.IsLeftSidebarVisible) { Dispatcher.InvokeAsync(() => AppModel.Window.FolderBrowser.UpdateGitStatus(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } ShowStatus("Changes have been pulled from the remote origin.", mmApp.Configuration.StatusMessageTimeout); } }
private static string GenerateCommiterName(CommitModel x) { if (x.Commit.Author != null && !string.IsNullOrEmpty(x.Commit.Author.Name)) { return(x.Commit.Author.Name); } if (x.Commit.Committer != null && !string.IsNullOrEmpty(x.Commit.Committer.Name)) { return(x.Commit.Committer.Name); } if (x.Author != null) { return(x.Author.Login); } return(x.Committer != null ? x.Committer.Login : "******"); }
internal CommitItemViewModel(CommitModel commit, Action<CommitItemViewModel> action) { var msg = commit.With(x => x.Commit).With(x => x.Message, () => string.Empty); var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); var description = firstLine > 0 ? msg.Substring(0, firstLine) : msg; _description = new Lazy<string>(() => Emojis.FindAndReplace(description)); var time = DateTimeOffset.MinValue; if (commit.Commit.Committer != null) time = commit.Commit.Committer.Date; Time = time.UtcDateTime.Humanize(); Name = commit.GenerateCommiterName(); Avatar = new GitHubAvatar(commit.GenerateGravatarUrl()); Commit = commit; GoToCommand = ReactiveCommand.Create().WithSubscription(_ => action(this)); }
private async void ButtonCommit_Click(object sender, RoutedEventArgs e) { if (await CommitModel.CommitChangesToRepository()) { if (string.IsNullOrEmpty(CommitModel.GitUsername)) { mmApp.Configuration.Git.GitName = CommitModel.GitUsername; } if (string.IsNullOrEmpty(CommitModel.GitEmail)) { mmApp.Configuration.Git.GitEmail = CommitModel.GitEmail; } if (AppModel.Configuration.Git.CloseAfterCommit) { Close(); AppModel.Window.ShowStatus("Files have been committed in the local repository.", mmApp.Configuration.StatusMessageTimeout, FontAwesomeIcon.CheckCircleOutline); } else { CommitModel.GetRepositoryChanges(); if (CommitModel.RepositoryStatusItems.Count < 1) { Close(); AppModel.Window.ShowStatus("Files have been committed and pushed to the remote.", mmApp.Configuration.StatusMessageTimeout); } else { ShowStatus("Files have been committed in the local repository.", mmApp.Configuration.StatusMessageTimeout, FontAwesomeIcon.CheckCircleOutline); } } if (AppModel.WindowLayout.IsLeftSidebarVisible) { await Dispatcher.InvokeAsync(() => AppModel.Window.FolderBrowser.UpdateGitStatus(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } mmApp.Configuration.Git.GitCommitBehavior = GitCommitBehaviors.Commit; } }
internal CommitItemViewModel(CommitModel commit, Action <CommitItemViewModel> action) { var msg = commit.Commit.Message ?? string.Empty; var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); Description = firstLine > 0 ? msg.Substring(0, firstLine) : msg; Time = DateTimeOffset.MinValue; if (commit.Commit.Committer != null) { Time = commit.Commit.Committer.Date; } Name = commit.GenerateCommiterName(); Avatar = new GitHubAvatar(commit.GenerateGravatarUrl()); Commit = commit; GoToCommand = ReactiveCommand.Create().WithSubscription(_ => action(this)); }
private void GitCommitDialog_Loaded(object sender, RoutedEventArgs e) { CommitModel.GitHelper.OpenRepository(CommitModel.Filename); CommitModel.Repository = CommitModel.GitHelper.Repository; // Check if a remote exists and disable push if not CommitModel.Remote = CommitModel.GitHelper.Repository.Network.Remotes?.FirstOrDefault()?.Name; if (CommitModel.Remote == null) { ButtonCommitAndPush.IsEnabled = false; ButtonOpenRemote.IsEnabled = false; AppModel.Configuration.Git.GitCommitBehavior = GitCommitBehaviors.Commit; } // get the main branch CommitModel.Branch = CommitModel.GitHelper.Repository?.Head?.FriendlyName; string defaultText = null; if (AppModel.Configuration.Git.GitCommitBehavior == GitCommitBehaviors.CommitAndPush) { ButtonCommitAndPush.IsDefault = true; ButtonCommitAndPush.FontWeight = FontWeight.FromOpenTypeWeight(600); defaultText = "commit and push"; var panel = ButtonCommitAndPush.Parent as ToolBar; // move to first position panel.Items.Remove(ButtonCommitAndPush); panel.Items.Insert(0, ButtonCommitAndPush); } else { ButtonCommit.IsDefault = true; ButtonCommit.FontWeight = FontWeight.FromOpenTypeWeight(600); defaultText = "commit"; } CommitModel.GetRepositoryChanges(); DataContext = CommitModel; StatusBar.ShowStatus($"Press Ctrl-Enter to quickly {defaultText}.", 8000); TextCommitMessage.Focus(); }
private CommitItemViewModel CreateViewModel(CommitModel x) { var msg = x.Commit.Message ?? string.Empty; var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); var desc = firstLine > 0 ? msg.Substring(0, firstLine) : msg; string login = GenerateCommiterName(x); var date = DateTimeOffset.MinValue; if (x.Commit.Committer != null) date = x.Commit.Committer.Date; var avatar = default(string); try { avatar = CreateGravatarUrl(x.Commit.Author.Email); } catch {} return new CommitItemViewModel(login, avatar, desc, date, _ => {}); }
private void ButtonCommit_Click(object sender, RoutedEventArgs e) { if (CommitModel.CommitChangesToRepository()) { if (string.IsNullOrEmpty(mmApp.Configuration.GitName)) { mmApp.Configuration.GitName = CommitModel.GitUsername; mmApp.Configuration.GitEmail = CommitModel.GitEmail; } Close(); if (AppModel.WindowLayout.IsLeftSidebarVisible) { Dispatcher.InvokeAsync(() => AppModel.Window.FolderBrowser.UpdateGitStatus(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } mmApp.Configuration.GitCommitBehavior = GitCommitBehaviors.Commit; AppModel.Window.ShowStatus("Files have been committed in the local repository.", mmApp.Configuration.StatusMessageTimeout); } }
private async void ButtonPush_Click(object sender, RoutedEventArgs e) { StatusBar.ShowStatusProgress("Pushing changes to the remote origin..."); if (await CommitModel.PushChangesAsync()) { // refresh the file model CommitModel.GetRepositoryChanges(); // Refresh the folder browser Git status icons if (AppModel.WindowLayout.IsLeftSidebarVisible) { UpdateFolderBrowserGitStatus(); } StatusBar.ShowStatusSuccess("Changes pushed to the remote origin."); return; } StatusBar.ShowStatusError($"Failed to pull changes from the server: {CommitModel.GitHelper.ErrorMessage}"); }
private void ButtonPush_Click(object sender, RoutedEventArgs e) { ShowStatusProgress("Pushing changes to the remote origin..."); if (CommitModel.PushChanges()) { // refresh the file model CommitModel.GetRepositoryChanges(); // Refresh the folder browser Git status icons if (AppModel.WindowLayout.IsLeftSidebarVisible) { Dispatcher.InvokeAsync(() => AppModel.Window.FolderBrowser.UpdateGitStatus(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } ShowStatusSuccess("Changes pushed to the remote origin."); return; } ShowStatusError("Failed to pull changes from the server: " + CommitModel.GitHelper.ErrorMessage); }
private void ButtonCommitAndPush_Click(object sender, RoutedEventArgs e) { if (CommitModel.CommitChangesToRepository(true)) { if (string.IsNullOrEmpty(mmApp.Configuration.Git.GitName)) { mmApp.Configuration.Git.GitName = CommitModel.GitUsername; mmApp.Configuration.Git.GitEmail = CommitModel.GitEmail; } if (AppModel.Configuration.Git.CloseAfterCommit) { Close(); AppModel.Window.ShowStatus("Files have been committed and pushed to the remote.", mmApp.Configuration.StatusMessageTimeout); } else { // reload settings CommitModel.GetRepositoryChanges(); if (CommitModel.RepositoryStatusItems.Count < 1) { Close(); AppModel.Window.ShowStatus("Files have been committed and pushed to the remote.", mmApp.Configuration.StatusMessageTimeout); } else { ShowStatus("Files have been committed and pushed to the remote.", mmApp.Configuration.StatusMessageTimeout); } } if (AppModel.WindowLayout.IsLeftSidebarVisible) { Dispatcher.InvokeAsync(() => AppModel.Window.FolderBrowser.UpdateGitStatus(), System.Windows.Threading.DispatcherPriority.ApplicationIdle); } mmApp.Configuration.Git.GitCommitBehavior = GitCommitBehaviors.CommitAndPush; } }
private CommitItemViewModel CreateViewModel(CommitModel x) { var msg = x.Commit.Message ?? string.Empty; var firstLine = msg.IndexOf("\n", StringComparison.Ordinal); var desc = firstLine > 0 ? msg.Substring(0, firstLine) : msg; string login = GenerateCommiterName(x); var date = DateTimeOffset.MinValue; if (x.Commit.Committer != null) { date = x.Commit.Committer.Date; } var avatar = default(string); try { avatar = CreateGravatarUrl(x.Commit.Author.Email); } catch {} return(new CommitItemViewModel(login, avatar, desc, date, _ => {})); }
protected virtual void GoToCommit(CommitModel x) { var repo = new RepositoryIdentifier(x.Repository.FullName); ShowViewModel<CommitViewModel>(new CommitViewModel.NavObject { Username = repo.Owner, Repository = repo.Name, Node = x.Hash }); }
private void ButtonRefresh_Click(object sender, RoutedEventArgs e) { CommitModel.GetRepositoryChanges(); }
private static Action MakeCallback(WeakReference<CommitsViewModel> weakVm, CommitModel model) { return new Action(() => weakVm.Get()?.GoToChangesetCommand.Execute(model)); }
private static string GenerateCommiterName(CommitModel x) { if (x.Commit.Author != null && !string.IsNullOrEmpty(x.Commit.Author.Name)) return x.Commit.Author.Name; if (x.Commit.Committer != null && !string.IsNullOrEmpty(x.Commit.Committer.Name)) return x.Commit.Committer.Name; if (x.Author != null) return x.Author.Login; return x.Committer != null ? x.Committer.Login : "******"; }
private void ComboBranch_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (firstBranchLoad) { firstBranchLoad = false; return; } if (CommitModel.Branch.StartsWith("<Create ")) { var input = new InputBox() { HeaderText = "Create new Git Branch", DescriptionText = "Enter the name for a new branch on this Git repository.", Button1Text = "Create Branch", Button2Text = "Cancel", Image = "../../Assets/git.png", InputPlaceholderText = "enter a new branch name", ParentWindow = this }; string branchName = input.Show(); if (branchName == null || input.Cancelled) { firstBranchLoad = true; CommitModel.Branch = CommitModel.GitHelper.Repository?.Head?.FriendlyName; return; } var newBranch = CommitModel.GitHelper.Repository.CreateBranch(branchName); if (newBranch == null) { StatusBar.ShowStatusError(CommitModel.GitHelper.ErrorMessage); return; } CommitModel.Branch = newBranch.FriendlyName; CommitModel.OnPropertyChanged("LocalBranches"); } else { if (CommitModel.RepositoryStatusItems.Count > 0) { CommitModel.Branch = CommitModel.GitHelper.Repository?.Head?.FriendlyName; StatusBar.ShowStatusError( "Can't change branches when there are pending changes on the current branch."); return; } if (MessageBox.Show("You're about to change your branch to:\r\n\r\n" + this.CommitModel.Branch + "\r\n\r\n" + "Are you sure you want to change branches?", "Change Branch", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) != MessageBoxResult.Yes) { return; } } if (!CommitModel.GitHelper.Checkout(CommitModel.Branch, CommitModel.Filename)) { CommitModel.Branch = CommitModel.GitHelper.Repository?.Head?.FriendlyName; StatusBar.ShowStatusError(CommitModel.GitHelper.ErrorMessage); } }
public void Render(CommitModel commitModel) { var headerSection = new Section(HeaderView) { _split }; var detailSection = new Section(); Root.Reset(headerSection, detailSection); var user = "******"; if (commitModel.Commit.Author != null) { user = commitModel.Commit.Author.Name; } if (commitModel.Commit.Committer != null) { user = commitModel.Commit.Committer.Name; } detailSection.Add(new MultilinedElement(user, commitModel.Commit.Message) { CaptionColor = Theme.CurrentTheme.MainTextColor, ValueColor = Theme.CurrentTheme.MainTextColor, BackgroundColor = UIColor.White }); if (ViewModel.ShowRepository) { var repo = new StyledStringElement(ViewModel.RepositoryName) { Accessory = MonoTouch.UIKit.UITableViewCellAccessory.DisclosureIndicator, Lines = 1, Font = StyledStringElement.DefaultDetailFont, TextColor = StyledStringElement.DefaultDetailColor, Image = Images.Repo }; repo.Tapped += () => ViewModel.GoToRepositoryCommand.Execute(null); detailSection.Add(repo); } var paths = commitModel.Files.GroupBy(y => { var filename = "/" + y.Filename; return(filename.Substring(0, filename.LastIndexOf("/", System.StringComparison.Ordinal) + 1)); }).OrderBy(y => y.Key); foreach (var p in paths) { var fileSection = new Section(p.Key); foreach (var x in p) { var y = x; var file = x.Filename.Substring(x.Filename.LastIndexOf('/') + 1); var sse = new ChangesetElement(file, x.Status, x.Additions, x.Deletions); sse.Tapped += () => ViewModel.GoToFileCommand.Execute(y); fileSection.Add(sse); } Root.Add(fileSection); } // // var fileSection = new Section(); // commitModel.Files.ForEach(x => { // var file = x.Filename.Substring(x.Filename.LastIndexOf('/') + 1); // var sse = new ChangesetElement(file, x.Status, x.Additions, x.Deletions); // sse.Tapped += () => ViewModel.GoToFileCommand.Execute(x); // fileSection.Add(sse); // }); // if (fileSection.Elements.Count > 0) // root.Add(fileSection); // var commentSection = new Section(); foreach (var comment in ViewModel.Comments) { //The path should be empty to indicate it's a comment on the entire commit, not a specific file if (!string.IsNullOrEmpty(comment.Path)) { continue; } commentSection.Add(new CommentElement { Name = comment.User.Login, Time = comment.CreatedAt.ToDaysAgo(), String = comment.Body, Image = Images.Anonymous, ImageUri = new Uri(comment.User.AvatarUrl), BackgroundColor = UIColor.White, }); } if (commentSection.Count > 0) { Root.Add(commentSection); } var addComment = new StyledStringElement("Add Comment") { Image = Images.Pencil }; addComment.Tapped += AddCommentTapped; Root.Add(new Section { addComment }); }
public void Render(CommitModel commitModel) { var headerSection = new Section(HeaderView) { _split }; var detailSection = new Section(); Root.Reset(headerSection, detailSection); var user = "******"; if (commitModel.Commit.Author != null) { user = commitModel.Commit.Author.Name; } if (commitModel.Commit.Committer != null) { user = commitModel.Commit.Committer.Name; } detailSection.Add(new MultilinedElement(user, commitModel.Commit.Message) { CaptionColor = Theme.CurrentTheme.MainTextColor, ValueColor = Theme.CurrentTheme.MainTextColor, BackgroundColor = UIColor.White }); if (ViewModel.ShowRepository) { var repo = new StyledStringElement(ViewModel.RepositoryName) { Accessory = MonoTouch.UIKit.UITableViewCellAccessory.DisclosureIndicator, Lines = 1, Font = StyledStringElement.DefaultDetailFont, TextColor = StyledStringElement.DefaultDetailColor, Image = Images.Repo }; repo.Tapped += () => ViewModel.GoToRepositoryCommand.Execute(null); detailSection.Add(repo); } var paths = commitModel.Files.GroupBy(y => { var filename = "/" + y.Filename; return(filename.Substring(0, filename.LastIndexOf("/", System.StringComparison.Ordinal) + 1)); }).OrderBy(y => y.Key); foreach (var p in paths) { var fileSection = new Section(p.Key); foreach (var x in p) { var y = x; var file = x.Filename.Substring(x.Filename.LastIndexOf('/') + 1); var sse = new ChangesetElement(file, x.Status, x.Additions, x.Deletions); sse.Tapped += () => ViewModel.GoToFileCommand.Execute(y); fileSection.Add(sse); } Root.Add(fileSection); } Root.Add(_commentSection); var addComment = new StyledStringElement("Add Comment") { Image = Images.Pencil }; addComment.Tapped += () => ViewModel.GoToCommentCommand.ExecuteIfCan(); Root.Add(new Section { addComment }); }
/// <summary> /// 上传小程序代码 /// </summary> /// <param name="appid"></param> /// <param name="mc_id"></param> /// <param name="mc_key"></param> /// <param name="typeid"></param> /// <returns></returns> public ActionResult Commit(string appid, string mc_id, string mc_key, int areacode) { try { //if (string.IsNullOrEmpty(appid)) //{ // return Json(new { code = -1, msg = "appid 不能为空" }); //} //if (string.IsNullOrEmpty(mc_id)) //{ // return Json(new { code = -1, msg = "mc_id 不能为空" }); //} //if (string.IsNullOrEmpty(mc_key)) //{ // return Json(new { code = -1, msg = "mc_key 不能为空" }); //} //if (areacode<=0) //{ // return Json(new { code = -1, msg = "areacode不能小于0" }); //} //var model = new PayCenterSettingBLL().GetModel($"Appid='{appid}'"); //if (model != null) //{ // return Json(new { code = -1, msg = "不能重复添加" }); //} var com_appid = "wx9cb1d8be83da075b"; var amodel = OpenAuthorizerInfoBLL.SingleModel.GetModel("authorizer_appid='" + com_appid + "'"); if (amodel != null) { var data = new { extEnable = true, extAppid = amodel.authorizer_appid, ext = new { areaCode = 110228, appid = amodel.authorizer_appid, appsr = "2de3680a7314ac1254c98294d1eabf64" }, window = new { navigationBarTitleText = "Q逗" } }; CommitModel model = new CommitModel(); model.user_version = "v1.0.0"; model.user_desc = "提供给同城用户的移动端经营管理工具,可以实现帖子添加、编辑、删除、置顶、刷新等管理功能"; model.template_id = 0; model.ext_json = JsonConvert.SerializeObject(data); var dd = XcxApis.XcxApis_Commit(amodel.authorizer_access_token, model); return(Json(new { code = 1, msg = dd })); } return(Json(new { code = -1, msg = "还未授权" })); } catch (Exception ex) { return(Json(new { code = 0, msg = "操作异常,msg=" + ex.Message })); } }
public static void Push(HttpListenerRequest request, HttpListenerResponse response) { var projectName = ""; try { using (var reader = new BinaryReader(request.InputStream)) { using (var writer = new BinaryWriter(response.OutputStream)) { try { var authority = ProjectAuthority.FromJson(Encoding.UTF8.GetString( reader.ReadBytes(reader.ReadInt32()) )); projectName = authority.ProjectName; // validate project name, password and check permisions from clientData if (!Authorization.HasAuthority(authority.AccessToken, projectName)) { writer.Write("Failed - project not found!"); return; } // request project lock if (ProjectLock.TryLock(projectName, ProjectLock.LockMode.Upload) != ProjectLock.LockMode.None) { writer.Write("Failed - project is locked!"); return; } // read commit var commitData = reader.ReadBytes(reader.ReadInt32()); var commit = Commit.FromJson(Encoding.UTF8.GetString(commitData)); var hasFile = reader.ReadBoolean(); if (hasFile) { Console.WriteLine("Receiving file..."); try { // read data file using (var fs = File.Create("temp_recv.zip")) { try { int read; var buffer = new byte[64 * 1024]; while ((read = reader.Read(buffer, 0, buffer.Length)) > 0) { fs.Write(buffer, 0, read); } } catch { // user lost connection or closed the client // before the whole data file arrived Console.WriteLine("User '" + authority.Username + "' canceled commit upload."); ProjectLock.Unlock(projectName); return; } } } catch { // user lost connection or closed the client // before the whole data file arrived Console.WriteLine("User '" + authority.Username + "' commit upload failed."); ProjectLock.Unlock(projectName); return; } } // --- from now - this part CAN'T fail, if so, the whole project may be incorrect after this! var projectDir = "data/" + projectName; // make commited files backup commit.Backup(projectDir); int commitId; try { // downloaded // now apply changes commit.Apply(projectDir, "temp_recv.zip", hasFile); // add commit to projects database var projectCollection = ServerCore.Database.GetCollection <CommitModel>(projectName); commitId = (int)projectCollection.Count(FilterDefinition <CommitModel> .Empty) + 1; // build commit var commitModel = new CommitModel { CommitId = commitId, CommitDescription = commit.Description, Files = new CommitModel.FileDiff[commit.Files.Length] }; for (var i = 0; i < commit.Files.Length; i++) { var file = commit.Files[i]; commitModel.Files[i] = new CommitModel.FileDiff { Name = file.FileName, Version = file.Version, Operation = (int)file.DiffType }; } // insert projectCollection.InsertOne(commitModel); // delete zip file if exists if (hasFile) { File.Delete("temp_recv.zip"); } } catch (Exception ex) { Console.WriteLine("Failed to apply commit from user '" + authority.Username + "'"); writer.Write("#RESTORE Failed - error when updating project! Error: " + ex); // restore backup commit.RestoreBackup(projectDir); // UNLOCK ProjectLock.Unlock(projectName); return; } // ok, we are out of the danger zone. // return message writer.Write("Done!"); writer.Write(commitId); // clean backups commit.CleanBackups(projectDir); Console.WriteLine("User '" + authority.Username + "' pushed changes!"); } catch (Exception ex) { writer.Write("Failed - invalid protocol/connection error! Error: " + ex); Console.WriteLine("PUSH failed"); ProjectLock.Unlock(projectName); } } } } catch { // this shouldn't be possible, // but anyway handle exceptions here Console.WriteLine("PUSH failed"); ProjectLock.Unlock(projectName); } Console.WriteLine("Push done"); ProjectLock.Unlock(projectName); }
private CommitModel ToCommitModel(Commit commit, string referenceName, bool isTree = true, string detailFilter = null, Tree compareWith = null) { if (commit == null) { return(null); } var model = new CommitModel { ReferenceName = referenceName, Sha = commit.Sha, CommitMessageShort = commit.MessageShort.RepetitionIfEmpty(UnknowString), CommitMessage = commit.Message.RepetitionIfEmpty(UnknowString), Author = commit.Author, Committer = commit.Committer, Parents = commit.Parents.Select(e => e.Sha).ToArray(), }; if (detailFilter != null) { if (detailFilter != "" && isTree) { detailFilter = detailFilter + "/"; } var firstTree = compareWith != null ? commit.Tree : commit.Parents.Any() ? commit.Parents.First().Tree : null; if (compareWith == null) { compareWith = commit.Tree; } var compareOptions = new LibGit2Sharp.CompareOptions { Similarity = SimilarityOptions.Renames, }; var paths = detailFilter == "" ? null : new[] { detailFilter }; var changes = _repository.Diff.Compare <TreeChanges>(firstTree, compareWith, paths, compareOptions: compareOptions); var patches = _repository.Diff.Compare <Patch>(firstTree, compareWith, paths, compareOptions: compareOptions); model.Changes = (from s in changes where (s.Path.Replace('\\', '/') + '/').StartsWith(detailFilter) orderby s.Path let patch = patches[s.Path] select new CommitChangeModel { //Name = s.Name, OldPath = s.OldPath.Replace('\\', '/'), Path = s.Path.Replace('\\', '/'), ChangeKind = s.Status, LinesAdded = patch.LinesAdded, LinesDeleted = patch.LinesDeleted, Patch = patch.Patch, }) .ToArray(); } return(model); }