PageRenderTime 67ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/GitUI/CommandsDialogs/FormCommit.cs

https://github.com/qgppl/gitextensions
C# | 2542 lines | 2079 code | 406 blank | 57 comment | 361 complexity | e1288041fa82567c97d9465bfe8cf52a MD5 | raw file
Possible License(s): GPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Diagnostics;
  5. using System.Drawing;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Text.RegularExpressions;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using System.Windows.Forms;
  13. using GitCommands;
  14. using GitCommands.Config;
  15. using GitCommands.Utils;
  16. using GitUI.AutoCompletion;
  17. using GitUI.CommandsDialogs.CommitDialog;
  18. using GitUI.HelperDialogs;
  19. using GitUI.Hotkey;
  20. using GitUI.Script;
  21. using PatchApply;
  22. using ResourceManager;
  23. using Timer = System.Windows.Forms.Timer;
  24. namespace GitUI.CommandsDialogs
  25. {
  26. public sealed partial class FormCommit : GitModuleForm //, IHotkeyable
  27. {
  28. #region Translation
  29. private readonly TranslationString _amendCommit =
  30. new TranslationString("You are about to rewrite history." + Environment.NewLine +
  31. "Only use amend if the commit is not published yet!" + Environment.NewLine +
  32. Environment.NewLine + "Do you want to continue?");
  33. private readonly TranslationString _amendCommitCaption = new TranslationString("Amend commit");
  34. private readonly TranslationString _deleteFailed = new TranslationString("Delete file failed");
  35. private readonly TranslationString _deleteSelectedFiles =
  36. new TranslationString("Are you sure you want delete the selected file(s)?");
  37. private readonly TranslationString _deleteSelectedFilesCaption = new TranslationString("Delete");
  38. private readonly TranslationString _deleteUntrackedFiles =
  39. new TranslationString("Are you sure you want to delete all untracked files?");
  40. private readonly TranslationString _deleteUntrackedFilesCaption =
  41. new TranslationString("Delete untracked files.");
  42. private readonly TranslationString _enterCommitMessage = new TranslationString("Please enter commit message");
  43. private readonly TranslationString _enterCommitMessageCaption = new TranslationString("Commit message");
  44. private readonly TranslationString _commitMessageDisabled = new TranslationString("Commit Message is requested during commit");
  45. private readonly TranslationString _enterCommitMessageHint = new TranslationString("Enter commit message");
  46. private readonly TranslationString _mergeConflicts =
  47. new TranslationString("There are unresolved mergeconflicts, solve mergeconflicts before committing.");
  48. private readonly TranslationString _mergeConflictsCaption = new TranslationString("Merge conflicts");
  49. private readonly TranslationString _noFilesStagedAndNothingToCommit =
  50. new TranslationString("There are no files staged for this commit.");
  51. private readonly TranslationString _noFilesStagedButSuggestToCommitAllUnstaged =
  52. new TranslationString("There are no files staged for this commit. Stage and commit all unstaged files?");
  53. private readonly TranslationString _noFilesStagedAndConfirmAnEmptyMergeCommit =
  54. new TranslationString("There are no files staged for this commit.\nAre you sure you want to commit?");
  55. private readonly TranslationString _noStagedChanges = new TranslationString("There are no staged changes");
  56. private readonly TranslationString _noUnstagedChanges = new TranslationString("There are no unstaged changes");
  57. private readonly TranslationString _notOnBranchMainInstruction = new TranslationString("You are not working on a branch");
  58. private readonly TranslationString _notOnBranch =
  59. new TranslationString("This commit will be unreferenced when switching to another branch and can be lost." +
  60. Environment.NewLine + "" + Environment.NewLine + "Do you want to continue?");
  61. private readonly TranslationString _notOnBranchButtons = new TranslationString("Checkout branch|Create branch|Continue");
  62. private readonly TranslationString _notOnBranchCaption = new TranslationString("Not on a branch");
  63. private readonly TranslationString _onlyStageChunkOfSingleFileError =
  64. new TranslationString("You can only use this option when selecting a single file");
  65. private readonly TranslationString _resetChangesCaption = new TranslationString("Reset changes");
  66. private readonly TranslationString _resetSelectedChangesText =
  67. new TranslationString("Are you sure you want to reset all selected files?");
  68. private readonly TranslationString _resetStageChunkOfFileCaption = new TranslationString("Unstage chunk of file");
  69. private readonly TranslationString _stageDetails = new TranslationString("Stage Details");
  70. private readonly TranslationString _stageFiles = new TranslationString("Stage {0} files");
  71. private readonly TranslationString _selectOnlyOneFile = new TranslationString("You must have only one file selected.");
  72. private readonly TranslationString _selectOnlyOneFileCaption = new TranslationString("Error");
  73. private readonly TranslationString _stageSelectedLines = new TranslationString("Stage selected line(s)");
  74. private readonly TranslationString _unstageSelectedLines = new TranslationString("Unstage selected line(s)");
  75. private readonly TranslationString _resetSelectedLines = new TranslationString("Reset selected line(s)");
  76. private readonly TranslationString _resetSelectedLinesConfirmation = new TranslationString("Are you sure you want to reset the changes to the selected lines?");
  77. private readonly TranslationString _formTitle = new TranslationString("Commit to {0} ({1})");
  78. private readonly TranslationString _selectionFilterToolTip = new TranslationString("Enter a regular expression to select unstaged files.");
  79. private readonly TranslationString _selectionFilterErrorToolTip = new TranslationString("Error {0}");
  80. private readonly TranslationString _commitMsgFirstLineInvalid = new TranslationString("First line of commit message contains too many characters."
  81. + Environment.NewLine + "Do you want to continue?");
  82. private readonly TranslationString _commitMsgLineInvalid = new TranslationString("The following line of commit message contains too many characters:"
  83. + Environment.NewLine + Environment.NewLine + "{0}" + Environment.NewLine + Environment.NewLine + "Do you want to continue?");
  84. private readonly TranslationString _commitMsgSecondLineNotEmpty = new TranslationString("Second line of commit message is not empty." + Environment.NewLine + "Do you want to continue?");
  85. private readonly TranslationString _commitMsgRegExNotMatched = new TranslationString("Commit message does not match RegEx." + Environment.NewLine + "Do you want to continue?");
  86. private readonly TranslationString _commitValidationCaption = new TranslationString("Commit validation");
  87. private readonly TranslationString _commitTemplateSettings = new TranslationString("Settings");
  88. private readonly TranslationString _commitAuthorInfo = new TranslationString("Author");
  89. private readonly TranslationString _commitCommitterInfo = new TranslationString("Committer");
  90. private readonly TranslationString _commitCommitterToolTip = new TranslationString("Click to change committer information.");
  91. #endregion
  92. private FileStatusList _currentFilesList;
  93. private bool _skipUpdate;
  94. private readonly TaskScheduler _taskScheduler;
  95. private GitItemStatus _currentItem;
  96. private bool _currentItemStaged;
  97. private readonly CommitKind _commitKind;
  98. private readonly GitRevision _editedCommit;
  99. private readonly ToolStripMenuItem _stageSelectedLinesToolStripMenuItem;
  100. private readonly ToolStripMenuItem _resetSelectedLinesToolStripMenuItem;
  101. private string _commitTemplate;
  102. private bool IsMergeCommit { get; set; }
  103. private bool _shouldRescanChanges = true;
  104. private bool _shouldReloadCommitTemplates = true;
  105. private readonly AsyncLoader _unstagedLoader;
  106. private readonly bool _useFormCommitMessage;
  107. private CancellationTokenSource _interactiveAddBashCloseWaitCts = new CancellationTokenSource();
  108. private string _userName = "";
  109. private string _userEmail = "";
  110. /// <summary>
  111. /// For VS designer
  112. /// </summary>
  113. private FormCommit()
  114. : this(null)
  115. {
  116. }
  117. public FormCommit(GitUICommands aCommands)
  118. : this(aCommands, CommitKind.Normal, null)
  119. { }
  120. public FormCommit(GitUICommands aCommands, CommitKind commitKind, GitRevision editedCommit)
  121. : base(true, aCommands)
  122. {
  123. _taskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  124. _unstagedLoader = new AsyncLoader(_taskScheduler);
  125. _useFormCommitMessage = AppSettings.UseFormCommitMessage;
  126. InitializeComponent();
  127. Message.TextChanged += Message_TextChanged;
  128. Message.TextAssigned += Message_TextAssigned;
  129. if (Module != null)
  130. Message.AddAutoCompleteProvider(new CommitAutoCompleteProvider(Module));
  131. Loading.Image = Properties.Resources.loadingpanel;
  132. Translate();
  133. SolveMergeconflicts.Font = new Font(SystemFonts.MessageBoxFont, FontStyle.Bold);
  134. SelectedDiff.ExtraDiffArgumentsChanged += SelectedDiffExtraDiffArgumentsChanged;
  135. if (IsUICommandsInitialized)
  136. StageInSuperproject.Visible = Module.SuperprojectModule != null;
  137. StageInSuperproject.Checked = AppSettings.StageInSuperprojectAfterCommit;
  138. closeDialogAfterEachCommitToolStripMenuItem.Checked = AppSettings.CloseCommitDialogAfterCommit;
  139. closeDialogAfterAllFilesCommittedToolStripMenuItem.Checked = AppSettings.CloseCommitDialogAfterLastCommit;
  140. refreshDialogOnFormFocusToolStripMenuItem.Checked = AppSettings.RefreshCommitDialogOnFormFocus;
  141. Unstaged.SetNoFilesText(_noUnstagedChanges.Text);
  142. Unstaged.FilterVisible = true;
  143. Staged.SetNoFilesText(_noStagedChanges.Text);
  144. Message.Enabled = _useFormCommitMessage;
  145. commitMessageToolStripMenuItem.Enabled = _useFormCommitMessage;
  146. commitTemplatesToolStripMenuItem.Enabled = _useFormCommitMessage;
  147. Message.WatermarkText = _useFormCommitMessage
  148. ? _enterCommitMessageHint.Text
  149. : _commitMessageDisabled.Text;
  150. _commitKind = commitKind;
  151. _editedCommit = editedCommit;
  152. HotkeysEnabled = true;
  153. Hotkeys = HotkeySettingsManager.LoadHotkeys(HotkeySettingsName);
  154. SelectedDiff.AddContextMenuSeparator();
  155. _stageSelectedLinesToolStripMenuItem = SelectedDiff.AddContextMenuEntry(_stageSelectedLines.Text, StageSelectedLinesToolStripMenuItemClick);
  156. _stageSelectedLinesToolStripMenuItem.ShortcutKeyDisplayString = GetShortcutKeys((int)Commands.StageSelectedFile).ToShortcutKeyDisplayString();
  157. _resetSelectedLinesToolStripMenuItem = SelectedDiff.AddContextMenuEntry(_resetSelectedLines.Text, ResetSelectedLinesToolStripMenuItemClick);
  158. _resetSelectedLinesToolStripMenuItem.ShortcutKeyDisplayString = GetShortcutKeys((int)Commands.ResetSelectedFiles).ToShortcutKeyDisplayString();
  159. _resetSelectedLinesToolStripMenuItem.Image = Reset.Image;
  160. resetChanges.ShortcutKeyDisplayString = _resetSelectedLinesToolStripMenuItem.ShortcutKeyDisplayString;
  161. stagedResetChanges.ShortcutKeyDisplayString = _resetSelectedLinesToolStripMenuItem.ShortcutKeyDisplayString;
  162. deleteFileToolStripMenuItem.ShortcutKeyDisplayString = GetShortcutKeys((int)Commands.DeleteSelectedFiles).ToShortcutKeyDisplayString();
  163. viewFileHistoryToolStripItem.ShortcutKeyDisplayString = GetShortcutKeys((int)Commands.ShowHistory).ToShortcutKeyDisplayString();
  164. toolStripMenuItem6.ShortcutKeyDisplayString = GetShortcutKeys((int)Commands.ShowHistory).ToShortcutKeyDisplayString();
  165. commitAuthorStatus.ToolTipText = _commitCommitterToolTip.Text;
  166. toolAuthor.Control.PreviewKeyDown += ToolAuthor_PreviewKeyDown;
  167. }
  168. void ToolAuthor_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
  169. {
  170. if (e.Alt)
  171. e.IsInputKey = true;
  172. }
  173. private void FormCommit_Load(object sender, EventArgs e)
  174. {
  175. if (AppSettings.CommitDialogSplitter != -1)
  176. splitMain.SplitterDistance = AppSettings.CommitDialogSplitter;
  177. if (AppSettings.CommitDialogRightSplitter != -1)
  178. splitRight.SplitterDistance = AppSettings.CommitDialogRightSplitter;
  179. Reset.Visible = AppSettings.ShowResetAllChanges;
  180. ResetUnStaged.Visible = AppSettings.ShowResetUnstagedChanges;
  181. CommitAndPush.Visible = AppSettings.ShowCommitAndPush;
  182. AdjustCommitButtonPanelHeight();
  183. }
  184. private void AdjustCommitButtonPanelHeight()
  185. {
  186. splitRight.Panel2MinSize = Math.Max(splitRight.Panel2MinSize, flowCommitButtons.PreferredSize.Height);
  187. splitRight.SplitterDistance = Math.Min(splitRight.SplitterDistance, splitRight.Height - splitRight.Panel2MinSize);
  188. }
  189. private void FormCommitFormClosing(object sender, FormClosingEventArgs e)
  190. {
  191. Message.CancelAutoComplete();
  192. // Do not remember commit message of fixup or squash commits, since they have
  193. // a special meaning, and can be dangerous if used inappropriately.
  194. if (CommitKind.Normal == _commitKind)
  195. GitCommands.CommitHelper.SetCommitMessage(Module, Message.Text);
  196. AppSettings.CommitDialogSplitter = splitMain.SplitterDistance;
  197. AppSettings.CommitDialogRightSplitter = splitRight.SplitterDistance;
  198. }
  199. void SelectedDiff_ContextMenuOpening(object sender, System.ComponentModel.CancelEventArgs e)
  200. {
  201. _stageSelectedLinesToolStripMenuItem.Enabled = SelectedDiff.HasAnyPatches() || _currentItem != null && _currentItem.IsNew;
  202. _resetSelectedLinesToolStripMenuItem.Enabled = _stageSelectedLinesToolStripMenuItem.Enabled;
  203. }
  204. #region Hotkey commands
  205. public const string HotkeySettingsName = "Commit";
  206. internal enum Commands
  207. {
  208. AddToGitIgnore,
  209. DeleteSelectedFiles,
  210. FocusUnstagedFiles,
  211. FocusSelectedDiff,
  212. FocusStagedFiles,
  213. FocusCommitMessage,
  214. ResetSelectedFiles,
  215. StageSelectedFile,
  216. UnStageSelectedFile,
  217. ShowHistory,
  218. ToggleSelectionFilter
  219. }
  220. private bool AddToGitIgnore()
  221. {
  222. if (Unstaged.Focused)
  223. {
  224. AddFileTogitignoreToolStripMenuItemClick(this, null);
  225. return true;
  226. }
  227. return false;
  228. }
  229. private bool DeleteSelectedFiles()
  230. {
  231. if (Unstaged.Focused)
  232. {
  233. DeleteFileToolStripMenuItemClick(this, null);
  234. return true;
  235. }
  236. return false;
  237. }
  238. private bool FocusStagedFiles()
  239. {
  240. Staged.Focus();
  241. return true;
  242. }
  243. private bool FocusUnstagedFiles()
  244. {
  245. Unstaged.Focus();
  246. return true;
  247. }
  248. private bool FocusSelectedDiff()
  249. {
  250. SelectedDiff.Focus();
  251. return true;
  252. }
  253. private bool FocusCommitMessage()
  254. {
  255. Message.Focus();
  256. return true;
  257. }
  258. private bool ResetSelectedFiles()
  259. {
  260. if (Unstaged.Focused || Staged.Focused)
  261. {
  262. ResetSoftClick(this, null);
  263. return true;
  264. }
  265. else if (SelectedDiff.ContainsFocus && _resetSelectedLinesToolStripMenuItem.Enabled)
  266. {
  267. ResetSelectedLinesToolStripMenuItemClick(this, null);
  268. return true;
  269. }
  270. return false;
  271. }
  272. private bool StageSelectedFile()
  273. {
  274. if (Unstaged.Focused)
  275. {
  276. StageClick(this, null);
  277. return true;
  278. }
  279. else if (SelectedDiff.ContainsFocus && !_currentItemStaged && _stageSelectedLinesToolStripMenuItem.Enabled)
  280. {
  281. StageSelectedLinesToolStripMenuItemClick(this, null);
  282. return true;
  283. }
  284. return false;
  285. }
  286. private bool UnStageSelectedFile()
  287. {
  288. if (Staged.Focused)
  289. {
  290. UnstageFilesClick(this, null);
  291. return true;
  292. }
  293. else if (SelectedDiff.ContainsFocus && _currentItemStaged && _stageSelectedLinesToolStripMenuItem.Enabled)
  294. {
  295. StageSelectedLinesToolStripMenuItemClick(this, null);
  296. return true;
  297. }
  298. return false;
  299. }
  300. private bool StartFileHistoryDialog()
  301. {
  302. if (Staged.Focused || Unstaged.Focused)
  303. {
  304. if (_currentFilesList.SelectedItem != null)
  305. {
  306. if ((!_currentFilesList.SelectedItem.IsNew) && (!_currentFilesList.SelectedItem.IsRenamed))
  307. {
  308. UICommands.StartFileHistoryDialog(this, _currentFilesList.SelectedItem.Name, null);
  309. }
  310. }
  311. return true;
  312. }
  313. return false;
  314. }
  315. private bool ToggleSelectionFilter()
  316. {
  317. selectionFilterToolStripMenuItem.Checked = !selectionFilterToolStripMenuItem.Checked;
  318. toolbarSelectionFilter.Visible = selectionFilterToolStripMenuItem.Checked;
  319. return true;
  320. }
  321. protected override bool ExecuteCommand(int cmd)
  322. {
  323. switch ((Commands)cmd)
  324. {
  325. case Commands.AddToGitIgnore: return AddToGitIgnore();
  326. case Commands.DeleteSelectedFiles: return DeleteSelectedFiles();
  327. case Commands.FocusStagedFiles: return FocusStagedFiles();
  328. case Commands.FocusUnstagedFiles: return FocusUnstagedFiles();
  329. case Commands.FocusSelectedDiff: return FocusSelectedDiff();
  330. case Commands.FocusCommitMessage: return FocusCommitMessage();
  331. case Commands.ResetSelectedFiles: return ResetSelectedFiles();
  332. case Commands.StageSelectedFile: return StageSelectedFile();
  333. case Commands.UnStageSelectedFile: return UnStageSelectedFile();
  334. case Commands.ShowHistory: return StartFileHistoryDialog();
  335. case Commands.ToggleSelectionFilter: return ToggleSelectionFilter();
  336. default: return base.ExecuteCommand(cmd);
  337. }
  338. }
  339. #endregion
  340. public void ShowDialogWhenChanges()
  341. {
  342. ShowDialogWhenChanges(null);
  343. }
  344. private void ComputeUnstagedFiles(Action<IList<GitItemStatus>> onComputed, bool DoAsync)
  345. {
  346. Func<IList<GitItemStatus>> getAllChangedFilesWithSubmodulesStatus = () => Module.GetAllChangedFilesWithSubmodulesStatus(
  347. !showIgnoredFilesToolStripMenuItem.Checked,
  348. !showAssumeUnchangedFilesToolStripMenuItem.Checked,
  349. showUntrackedFilesToolStripMenuItem.Checked ? UntrackedFilesMode.Default : UntrackedFilesMode.No);
  350. if (DoAsync)
  351. _unstagedLoader.Load(getAllChangedFilesWithSubmodulesStatus, onComputed);
  352. else
  353. {
  354. _unstagedLoader.Cancel();
  355. onComputed(getAllChangedFilesWithSubmodulesStatus());
  356. }
  357. }
  358. public void ShowDialogWhenChanges(IWin32Window owner)
  359. {
  360. ComputeUnstagedFiles((allChangedFiles) =>
  361. {
  362. if (allChangedFiles.Count > 0)
  363. {
  364. LoadUnstagedOutput(allChangedFiles);
  365. Initialize(false);
  366. ShowDialog(owner);
  367. }
  368. else
  369. Close();
  370. #if !__MonoCS__ // animated GIFs are not supported in Mono/Linux
  371. //trying to properly dispose loading image issue #1037
  372. Loading.Image.Dispose();
  373. #endif
  374. }, false
  375. );
  376. }
  377. private bool _selectedDiffReloaded = true;
  378. private void StageSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
  379. {
  380. //to prevent multiple clicks
  381. if (!_selectedDiffReloaded)
  382. return;
  383. Debug.Assert(_currentItem != null);
  384. // Prepare git command
  385. string args = "apply --cached --whitespace=nowarn";
  386. if (_currentItemStaged) //staged
  387. args += " --reverse";
  388. byte[] patch;
  389. if (!_currentItemStaged && _currentItem.IsNew)
  390. patch = PatchManager.GetSelectedLinesAsNewPatch(Module, _currentItem.Name,
  391. SelectedDiff.GetText(), SelectedDiff.GetSelectionPosition(),
  392. SelectedDiff.GetSelectionLength(), SelectedDiff.Encoding, false, SelectedDiff.FilePreabmle);
  393. else
  394. patch = PatchManager.GetSelectedLinesAsPatch(Module, SelectedDiff.GetText(),
  395. SelectedDiff.GetSelectionPosition(), SelectedDiff.GetSelectionLength(),
  396. _currentItemStaged, SelectedDiff.Encoding, _currentItem.IsNew);
  397. if (patch != null && patch.Length > 0)
  398. {
  399. string output = Module.RunGitCmd(args, null, patch);
  400. ProcessApplyOutput(output, patch);
  401. }
  402. }
  403. private void ProcessApplyOutput(string output, byte[] patch)
  404. {
  405. if (!string.IsNullOrEmpty(output))
  406. {
  407. MessageBox.Show(this, output + "\n\n" + SelectedDiff.Encoding.GetString(patch));
  408. }
  409. if (_currentItemStaged)
  410. Staged.StoreNextIndexToSelect();
  411. else
  412. Unstaged.StoreNextIndexToSelect();
  413. ScheduleGoToLine();
  414. _selectedDiffReloaded = false;
  415. RescanChanges();
  416. }
  417. private void ScheduleGoToLine()
  418. {
  419. int selectedDifflineToSelect = SelectedDiff.GetText().Substring(0, SelectedDiff.GetSelectionPosition()).Count(c => c == '\n');
  420. int scrollPosition = SelectedDiff.ScrollPos;
  421. string selectedFileName = _currentItem.Name;
  422. Action stageAreaLoaded = null;
  423. stageAreaLoaded = () =>
  424. {
  425. EventHandler textLoaded = null;
  426. textLoaded = (a, b) =>
  427. {
  428. if (_currentItem != null && _currentItem.Name.Equals(selectedFileName))
  429. {
  430. SelectedDiff.GoToLine(selectedDifflineToSelect);
  431. SelectedDiff.ScrollPos = scrollPosition;
  432. }
  433. SelectedDiff.TextLoaded -= textLoaded;
  434. _selectedDiffReloaded = true;
  435. };
  436. SelectedDiff.TextLoaded += textLoaded;
  437. OnStageAreaLoaded -= stageAreaLoaded;
  438. };
  439. OnStageAreaLoaded += stageAreaLoaded;
  440. }
  441. private void ResetSelectedLinesToolStripMenuItemClick(object sender, EventArgs e)
  442. {
  443. //to prevent multiple clicks
  444. if (!_selectedDiffReloaded)
  445. return;
  446. if (MessageBox.Show(this, _resetSelectedLinesConfirmation.Text, _resetChangesCaption.Text,
  447. MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
  448. return;
  449. Debug.Assert(_currentItem != null);
  450. // Prepare git command
  451. string args = "apply --whitespace=nowarn";
  452. if (_currentItemStaged) //staged
  453. args += " --reverse --index";
  454. byte[] patch;
  455. if (_currentItemStaged)
  456. patch = PatchManager.GetSelectedLinesAsPatch(Module, SelectedDiff.GetText(),
  457. SelectedDiff.GetSelectionPosition(), SelectedDiff.GetSelectionLength(),
  458. _currentItemStaged, SelectedDiff.Encoding, _currentItem.IsNew);
  459. else if (_currentItem.IsNew)
  460. patch = PatchManager.GetSelectedLinesAsNewPatch(Module, _currentItem.Name,
  461. SelectedDiff.GetText(), SelectedDiff.GetSelectionPosition(), SelectedDiff.GetSelectionLength(),
  462. SelectedDiff.Encoding, true, SelectedDiff.FilePreabmle);
  463. else
  464. patch = PatchManager.GetResetUnstagedLinesAsPatch(Module, SelectedDiff.GetText(),
  465. SelectedDiff.GetSelectionPosition(), SelectedDiff.GetSelectionLength(),
  466. _currentItemStaged, SelectedDiff.Encoding);
  467. if (patch != null && patch.Length > 0)
  468. {
  469. string output = Module.RunGitCmd(args, null, patch);
  470. if (EnvUtils.RunningOnWindows())
  471. {
  472. //remove file mode warnings on windows
  473. Regex regEx = new Regex("warning: .*has type .* expected .*", RegexOptions.Compiled);
  474. output = output.RemoveLines(regEx.IsMatch);
  475. }
  476. ProcessApplyOutput(output, patch);
  477. }
  478. }
  479. private void EnableStageButtons(bool enable)
  480. {
  481. toolUnstageItem.Enabled = enable;
  482. toolUnstageAllItem.Enabled = enable;
  483. toolStageItem.Enabled = enable;
  484. toolStageAllItem.Enabled = enable;
  485. workingToolStripMenuItem.Enabled = enable;
  486. ResetUnStaged.Enabled = Unstaged.AllItems.Any();
  487. }
  488. private bool _initialized;
  489. private void Initialize(bool loadUnstaged)
  490. {
  491. _initialized = true;
  492. Task.Factory.StartNew(() => string.Format(_formTitle.Text, Module.GetSelectedBranch(),
  493. Module.WorkingDir))
  494. .ContinueWith(task => Text = task.Result, _taskScheduler);
  495. Cursor.Current = Cursors.WaitCursor;
  496. if (loadUnstaged)
  497. {
  498. Loading.Visible = true;
  499. LoadingStaged.Visible = true;
  500. Commit.Enabled = false;
  501. CommitAndPush.Enabled = false;
  502. Amend.Enabled = false;
  503. Reset.Enabled = false;
  504. ResetUnStaged.Enabled = false;
  505. EnableStageButtons(false);
  506. ComputeUnstagedFiles(LoadUnstagedOutput, true);
  507. }
  508. UpdateMergeHead();
  509. Message.TextBoxFont = AppSettings.CommitFont;
  510. // Check if commit.template is used
  511. string fileName = Module.GetEffectivePathSetting("commit.template");
  512. if (!string.IsNullOrEmpty(fileName))
  513. {
  514. using (var commitReader = new StreamReader(fileName))
  515. {
  516. _commitTemplate = commitReader.ReadToEnd().Replace("\r", "");
  517. }
  518. Message.Text = _commitTemplate;
  519. }
  520. Cursor.Current = Cursors.Default;
  521. }
  522. private void Initialize()
  523. {
  524. Initialize(true);
  525. }
  526. private void UpdateMergeHead()
  527. {
  528. var mergeHead = Module.RevParse("MERGE_HEAD");
  529. IsMergeCommit = Regex.IsMatch(mergeHead, GitRevision.Sha1HashPattern);
  530. }
  531. private void InitializedStaged()
  532. {
  533. Cursor.Current = Cursors.WaitCursor;
  534. SolveMergeconflicts.Visible = Module.InTheMiddleOfConflictedMerge();
  535. Staged.GitItemStatuses = Module.GetStagedFilesWithSubmodulesStatus();
  536. Cursor.Current = Cursors.Default;
  537. }
  538. private event Action OnStageAreaLoaded;
  539. private bool _loadUnstagedOutputFirstTime = true;
  540. /// <summary>
  541. /// Loads the unstaged output.
  542. /// This method is passed in to the SetTextCallBack delegate
  543. /// to set the Text property of textBox1.
  544. /// </summary>
  545. private void LoadUnstagedOutput(IList<GitItemStatus> allChangedFiles)
  546. {
  547. var lastSelection = new List<GitItemStatus>();
  548. if (_currentFilesList != null)
  549. lastSelection = _currentSelection;
  550. var unStagedFiles = new List<GitItemStatus>();
  551. var stagedFiles = new List<GitItemStatus>();
  552. foreach (var fileStatus in allChangedFiles)
  553. {
  554. if (fileStatus.IsStaged)
  555. stagedFiles.Add(fileStatus);
  556. else
  557. unStagedFiles.Add(fileStatus);
  558. }
  559. Unstaged.GitItemStatuses = unStagedFiles;
  560. Staged.GitItemStatuses = stagedFiles;
  561. Loading.Visible = false;
  562. LoadingStaged.Visible = false;
  563. Commit.Enabled = true;
  564. CommitAndPush.Enabled = true;
  565. Amend.Enabled = true;
  566. Reset.Enabled = DoChangesExist();
  567. EnableStageButtons(true);
  568. workingToolStripMenuItem.Enabled = true;
  569. var inTheMiddleOfConflictedMerge = Module.InTheMiddleOfConflictedMerge();
  570. SolveMergeconflicts.Visible = inTheMiddleOfConflictedMerge;
  571. if (Staged.IsEmpty)
  572. {
  573. _currentFilesList = Unstaged;
  574. if (Staged.ContainsFocus)
  575. Unstaged.Focus();
  576. }
  577. else if (Unstaged.IsEmpty)
  578. {
  579. _currentFilesList = Staged;
  580. if (Unstaged.ContainsFocus)
  581. Staged.Focus();
  582. }
  583. RestoreSelectedFiles(unStagedFiles, stagedFiles, lastSelection);
  584. if (OnStageAreaLoaded != null)
  585. OnStageAreaLoaded();
  586. if (_loadUnstagedOutputFirstTime)
  587. {
  588. var fc = this.FindFocusedControl();
  589. if (fc == this.Ok)
  590. {
  591. if (Unstaged.GitItemStatuses.Any())
  592. Unstaged.Focus();
  593. else if (Staged.GitItemStatuses.Any())
  594. Message.Focus();
  595. else
  596. Amend.Focus();
  597. }
  598. _loadUnstagedOutputFirstTime = false;
  599. }
  600. }
  601. private void SelectStoredNextIndex()
  602. {
  603. Unstaged.SelectStoredNextIndex(0);
  604. if (Unstaged.GitItemStatuses.Any())
  605. {
  606. Staged.SelectStoredNextIndex();
  607. }
  608. else
  609. {
  610. Staged.SelectStoredNextIndex(0);
  611. }
  612. }
  613. private void RestoreSelectedFiles(IList<GitItemStatus> unStagedFiles, IList<GitItemStatus> stagedFiles, IList<GitItemStatus> lastSelection)
  614. {
  615. if (_currentFilesList == null || _currentFilesList.IsEmpty)
  616. {
  617. SelectStoredNextIndex();
  618. return;
  619. }
  620. var newItems = _currentFilesList == Staged ? stagedFiles : unStagedFiles;
  621. var names = lastSelection.ToHashSet(x => x.Name);
  622. var newSelection = newItems.Where(x => names.Contains(x.Name)).ToList();
  623. if (newSelection.Any())
  624. _currentFilesList.SelectedItems = newSelection;
  625. else
  626. SelectStoredNextIndex();
  627. }
  628. /// <summary>Returns if there are any changes at all, staged or unstaged.</summary>
  629. private bool DoChangesExist()
  630. {
  631. return Unstaged.AllItems.Any() || Staged.AllItems.Any();
  632. }
  633. private void ShowChanges(GitItemStatus item, bool staged)
  634. {
  635. _currentItem = item;
  636. _currentItemStaged = staged;
  637. if (item == null)
  638. return;
  639. long length = GetItemLength(item.Name);
  640. if (length < 5 * 1024 * 1024) // 5Mb
  641. SetSelectedDiff(item, staged);
  642. else
  643. {
  644. SelectedDiff.Clear();
  645. SelectedDiff.Refresh();
  646. llShowPreview.Show();
  647. }
  648. _stageSelectedLinesToolStripMenuItem.Text = staged ? _unstageSelectedLines.Text : _stageSelectedLines.Text;
  649. _stageSelectedLinesToolStripMenuItem.Image = staged ? toolUnstageItem.Image : toolStageItem.Image;
  650. _stageSelectedLinesToolStripMenuItem.ShortcutKeyDisplayString =
  651. GetShortcutKeys((int)(staged ? Commands.UnStageSelectedFile : Commands.StageSelectedFile)).ToShortcutKeyDisplayString();
  652. }
  653. private long GetItemLength(string fileName)
  654. {
  655. long length = -1;
  656. string path = fileName;
  657. if (!File.Exists(fileName))
  658. path = Path.Combine(Module.WorkingDir, fileName);
  659. if (File.Exists(path))
  660. {
  661. FileInfo fi = new FileInfo(path);
  662. length = fi.Length;
  663. }
  664. return length;
  665. }
  666. private void llShowPreview_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  667. {
  668. llShowPreview.Hide();
  669. SetSelectedDiff(_currentItem, _currentItemStaged);
  670. }
  671. private void SetSelectedDiff(GitItemStatus item, bool staged)
  672. {
  673. if (item.Name.EndsWith(".png"))
  674. {
  675. SelectedDiff.ViewFile(item.Name);
  676. }
  677. else if (item.IsTracked)
  678. {
  679. SelectedDiff.ViewCurrentChanges(item, staged);
  680. }
  681. else
  682. {
  683. SelectedDiff.ViewFile(item.Name);
  684. }
  685. }
  686. private List<GitItemStatus> _currentSelection;
  687. private void ClearDiffViewIfNoFilesLeft()
  688. {
  689. llShowPreview.Hide();
  690. if (Staged.IsEmpty && Unstaged.IsEmpty)
  691. SelectedDiff.Clear();
  692. }
  693. private void CommitClick(object sender, EventArgs e)
  694. {
  695. ExecuteCommitCommand();
  696. }
  697. private void CheckForStagedAndCommit(bool amend, bool push)
  698. {
  699. if (amend)
  700. {
  701. // This is an amend commit. Confirm the user understands the implications. We don't want to prompt for an empty
  702. // commit, because amend may be used just to change the commit message or timestamp.
  703. if (!AppSettings.DontConfirmAmend)
  704. if (MessageBox.Show(this, _amendCommit.Text, _amendCommitCaption.Text, MessageBoxButtons.YesNo) != DialogResult.Yes)
  705. return;
  706. }
  707. else if (Staged.IsEmpty)
  708. {
  709. if (IsMergeCommit)
  710. {
  711. // it is a merge commit, so user can commit just for merging two branches even the changeset is empty,
  712. // but also user may forget to add files, so only ask for confirmation that user really wants to commit an empty changeset
  713. if (MessageBox.Show(this, _noFilesStagedAndConfirmAnEmptyMergeCommit.Text, _noStagedChanges.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
  714. return;
  715. }
  716. else
  717. {
  718. if (Unstaged.IsEmpty)
  719. {
  720. MessageBox.Show(this, _noFilesStagedAndNothingToCommit.Text, _noStagedChanges.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  721. return;
  722. }
  723. // there are no staged files, but there are unstaged files. Most probably user forgot to stage them.
  724. if (MessageBox.Show(this, _noFilesStagedButSuggestToCommitAllUnstaged.Text, _noStagedChanges.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
  725. return;
  726. StageAllAccordingToFilter();
  727. // if staging failed (i.e. line endings conflict), user already got error message, don't try to commit empty changeset.
  728. if (Staged.IsEmpty)
  729. return;
  730. }
  731. }
  732. DoCommit(amend, push);
  733. }
  734. private void DoCommit(bool amend, bool push)
  735. {
  736. if (Module.InTheMiddleOfConflictedMerge())
  737. {
  738. MessageBox.Show(this, _mergeConflicts.Text, _mergeConflictsCaption.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
  739. return;
  740. }
  741. if (_useFormCommitMessage && (string.IsNullOrEmpty(Message.Text) || Message.Text == _commitTemplate))
  742. {
  743. MessageBox.Show(this, _enterCommitMessage.Text, _enterCommitMessageCaption.Text, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
  744. return;
  745. }
  746. if (_useFormCommitMessage && !ValidCommitMessage())
  747. return;
  748. if (Module.IsDetachedHead() && !Module.InTheMiddleOfRebase())
  749. {
  750. int idx = PSTaskDialog.cTaskDialog.ShowCommandBox(this,
  751. _notOnBranchCaption.Text,
  752. _notOnBranchMainInstruction.Text,
  753. _notOnBranch.Text,
  754. _notOnBranchButtons.Text,
  755. true);
  756. switch (idx)
  757. {
  758. case 0:
  759. string revision = _editedCommit != null ? _editedCommit.Guid : "";
  760. if (!UICommands.StartCheckoutBranch(this, new[] {revision}))
  761. return;
  762. break;
  763. case 1:
  764. if (!UICommands.StartCreateBranchDialog(this, _editedCommit))
  765. return;
  766. break;
  767. case -1:
  768. return;
  769. }
  770. }
  771. try
  772. {
  773. if (_useFormCommitMessage)
  774. {
  775. SetCommitMessageFromTextBox(Message.Text);
  776. }
  777. ScriptManager.RunEventScripts(this, ScriptEvent.BeforeCommit);
  778. var errorOccurred = !FormProcess.ShowDialog(this, Module.CommitCmd(amend, signOffToolStripMenuItem.Checked, toolAuthor.Text, _useFormCommitMessage, noVerifyToolStripMenuItem.Checked));
  779. UICommands.RepoChangedNotifier.Notify();
  780. if (errorOccurred)
  781. return;
  782. Amend.Checked = false;
  783. noVerifyToolStripMenuItem.Checked = false;
  784. ScriptManager.RunEventScripts(this, ScriptEvent.AfterCommit);
  785. Message.Text = string.Empty;
  786. CommitHelper.SetCommitMessage(Module, string.Empty);
  787. bool pushCompleted = true;
  788. if (push)
  789. {
  790. UICommands.StartPushDialog(this, true, out pushCompleted);
  791. }
  792. if (pushCompleted && Module.SuperprojectModule != null && AppSettings.StageInSuperprojectAfterCommit)
  793. Module.SuperprojectModule.StageFile(Module.SubmodulePath);
  794. if (AppSettings.CloseCommitDialogAfterCommit)
  795. {
  796. Close();
  797. return;
  798. }
  799. if (Unstaged.GitItemStatuses.Any())
  800. {
  801. InitializedStaged();
  802. return;
  803. }
  804. if (AppSettings.CloseCommitDialogAfterLastCommit)
  805. Close();
  806. else
  807. InitializedStaged();
  808. }
  809. catch (Exception e)
  810. {
  811. MessageBox.Show(this, string.Format("Exception: {0}", e.Message));
  812. }
  813. }
  814. private bool ValidCommitMessage()
  815. {
  816. if (AppSettings.CommitValidationMaxCntCharsFirstLine > 0)
  817. {
  818. var firstLine = Message.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries)[0];
  819. if (firstLine.Length > AppSettings.CommitValidationMaxCntCharsFirstLine)
  820. {
  821. if (DialogResult.No == MessageBox.Show(this, _commitMsgFirstLineInvalid.Text, _commitValidationCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
  822. return false;
  823. }
  824. }
  825. if (AppSettings.CommitValidationMaxCntCharsPerLine > 0)
  826. {
  827. var lines = Message.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
  828. foreach (var line in lines)
  829. {
  830. if (line.Length > AppSettings.CommitValidationMaxCntCharsPerLine)
  831. {
  832. if (DialogResult.No == MessageBox.Show(this, String.Format(_commitMsgLineInvalid.Text, line), _commitValidationCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
  833. return false;
  834. }
  835. }
  836. }
  837. if (AppSettings.CommitValidationSecondLineMustBeEmpty)
  838. {
  839. var lines = Message.Text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
  840. if (lines.Length > 2)
  841. {
  842. if (lines[1].Length != 0)
  843. {
  844. if (DialogResult.No == MessageBox.Show(this, _commitMsgSecondLineNotEmpty.Text, _commitValidationCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
  845. return false;
  846. }
  847. }
  848. }
  849. if (!AppSettings.CommitValidationRegEx.IsNullOrEmpty())
  850. {
  851. try
  852. {
  853. if (!Regex.IsMatch(Message.Text, AppSettings.CommitValidationRegEx))
  854. {
  855. if (DialogResult.No == MessageBox.Show(this, _commitMsgRegExNotMatched.Text, _commitValidationCaption.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk))
  856. return false;
  857. }
  858. }
  859. catch
  860. {
  861. }
  862. }
  863. return true;
  864. }
  865. private void RescanChanges()
  866. {
  867. if (_shouldRescanChanges)
  868. {
  869. toolRefreshItem.Enabled = false;
  870. Initialize();
  871. toolRefreshItem.Enabled = true;
  872. }
  873. }
  874. private void UnstageFilesClick(object sender, EventArgs e)
  875. {
  876. if (_currentFilesList != Staged)
  877. return;
  878. Unstage();
  879. }
  880. void Staged_DoubleClick(object sender, EventArgs e)
  881. {
  882. _currentFilesList = Staged;
  883. Unstage();
  884. }
  885. private void UnstageAllToolStripMenuItemClick(object sender, EventArgs e)
  886. {
  887. var lastSelection = new List<GitItemStatus>();
  888. if (_currentFilesList != null)
  889. lastSelection = _currentSelection;
  890. Action stageAreaLoaded = null;
  891. stageAreaLoaded = () =>
  892. {
  893. _currentFilesList = Unstaged;
  894. RestoreSelectedFiles(Unstaged.GitItemStatuses, Staged.GitItemStatuses, lastSelection);
  895. Unstaged.Focus();
  896. OnStageAreaLoaded -= stageAreaLoaded;
  897. };
  898. OnStageAreaLoaded += stageAreaLoaded;
  899. Module.ResetMixed("HEAD");
  900. Initialize();
  901. }
  902. private void UnstagedSelectionChanged(object sender, EventArgs e)
  903. {
  904. if (_currentFilesList != Unstaged || _skipUpdate)
  905. return;
  906. ClearDiffViewIfNoFilesLeft();
  907. Unstaged.ContextMenuStrip = null;
  908. if (!Unstaged.SelectedItems.Any())
  909. return;
  910. Staged.ClearSelected();
  911. _currentSelection = Unstaged.SelectedItems.ToList();
  912. GitItemStatus item = _currentSelection.FirstOrDefault();
  913. ShowChanges(item, false);
  914. if (!item.IsSubmodule)
  915. Unstaged.ContextMenuStrip = UnstagedFileContext;
  916. else
  917. Unstaged.ContextMenuStrip = UnstagedSubmoduleContext;
  918. }
  919. private void Unstaged_Enter(object sender, EventArgs e)
  920. {
  921. if (_currentFilesList != Unstaged)
  922. {
  923. _currentFilesList = Unstaged;
  924. _skipUpdate = false;
  925. UnstagedSelectionChanged(Unstaged, null);
  926. }
  927. }
  928. private void Unstage()
  929. {
  930. if (Staged.GitItemStatuses.Count() > 10 && Staged.SelectedItems.Count() == Staged.GitItemStatuses.Count())
  931. {
  932. UnstageAllToolStripMenuItemClick(null, null);
  933. return;
  934. }
  935. Cursor.Current = Cursors.WaitCursor;
  936. EnableStageButtons(false);
  937. try
  938. {
  939. var lastSelection = new List<GitItemStatus>();
  940. if (_currentFilesList != null)
  941. lastSelection = _currentSelection;
  942. toolStripProgressBar1.Visible = true;
  943. toolStripProgressBar1.Maximum = Staged.SelectedItems.Count() * 2;
  944. toolStripProgressBar1.Value = 0;
  945. Staged.StoreNextIndexToSelect();
  946. var files = new List<GitItemStatus>();
  947. var allFiles = new List<GitItemStatus>();
  948. foreach (var item in Staged.SelectedItems)
  949. {
  950. toolStripProgressBar1.Value = Math.Min(toolStripProgressBar1.Maximum - 1, toolStripProgressBar1.Value + 1);
  951. if (!item.IsNew)
  952. {
  953. toolStripProgressBar1.Value = Math.Min(toolStripProgressBar1.Maximum - 1, toolStripProgressBar1.Value + 1);
  954. Module.UnstageFileToRemove(item.Name);
  955. if (item.IsRenamed)
  956. Module.UnstageFileToRemove(item.OldName);
  957. }
  958. else
  959. {
  960. files.Add(item);
  961. }
  962. allFiles.Add(item);
  963. }
  964. Module.UnstageFiles(files);
  965. _skipUpdate = true;
  966. InitializedStaged();
  967. var stagedFiles = Staged.GitItemStatuses.ToList();
  968. var unStagedFiles = Unstaged.GitItemStatuses.ToList();
  969. foreach (var item in allFiles)
  970. {
  971. var item1 = item;
  972. if (stagedFiles.Exists(i => i.Name == item1.Name))
  973. continue;
  974. var item2 = item;
  975. if (unStagedFiles.Exists(i => i.Name == item2.Name))
  976. continue;
  977. if (item.IsNew && !item.IsChanged && !item.IsDeleted)
  978. item.IsTracked = false;
  979. else
  980. item.IsTracked = true;
  981. if (item.IsRenamed)
  982. {
  983. var clone = new GitItemStatus
  984. {
  985. Name = item.OldName,
  986. IsDeleted = true,
  987. IsTracked = true,
  988. IsStaged = false
  989. };
  990. unStagedFiles.Add(clone);
  991. item.IsRenamed = false;
  992. item.IsNew = true;
  993. item.IsTracked = false;
  994. item.OldName = string.Empty;
  995. }
  996. item.IsStaged = false;
  997. unStagedFiles.Add(item);
  998. }
  999. Staged.GitItemStatuses = stagedFiles;
  1000. Unstaged.GitItemStatuses = unStagedFiles;
  1001. _skipUpdate = false;
  1002. Staged.SelectStoredNextIndex();
  1003. toolStripProgressBar1.Value = toolStripProgressBar1.Maximum;
  1004. toolStripProgressBar1.Visible = false;
  1005. if (Staged.IsEmpty)
  1006. {
  1007. _currentFilesList = Unstaged;
  1008. RestoreSelectedFiles(Unstaged.GitItemStatuses, Staged.GitItemStatuses, lastSelection);
  1009. Unstaged.Focus();
  1010. }
  1011. }
  1012. catch (Exception ex)
  1013. {
  1014. Trace.WriteLine(ex.Message);
  1015. }
  1016. EnableStageButtons(true);
  1017. Cursor.Current = Cursors.Default;
  1018. if (AppSettings.RevisionGraphShowWorkingDirChanges)
  1019. UICommands.RepoChangedNotifier.Notify();
  1020. }
  1021. private void StageClick(object sender, EventArgs e)
  1022. {
  1023. if (_currentFilesList != Unstaged)
  1024. return;
  1025. Stage(Unstaged.SelectedItems.ToList());
  1026. if (U

Large files files are truncated, but you can click here to view the full file