Correctly handle cancel if rebasing haven't started yet
[TortoiseGit.git] / src / TortoiseProc / RebaseDlg.cpp
blobd18b9e6b4e4df8cde81791de785b20dbaa9d91fe
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2019 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // RebaseDlg.cpp : implementation file
23 #include "stdafx.h"
24 #include "TortoiseProc.h"
25 #include "RebaseDlg.h"
26 #include "AppUtils.h"
27 #include "LoglistUtils.h"
28 #include "MessageBox.h"
29 #include "UnicodeUtils.h"
30 #include "BrowseRefsDlg.h"
31 #include "ProgressDlg.h"
32 #include "SmartHandle.h"
33 #include "../TGitCache/CacheInterface.h"
34 #include "Settings/Settings.h"
35 #include "MassiveGitTask.h"
36 #include "CommitDlg.h"
37 #include "StringUtils.h"
38 #include "Hooks.h"
39 #include "LogDlg.h"
41 // CRebaseDlg dialog
43 IMPLEMENT_DYNAMIC(CRebaseDlg, CResizableStandAloneDialog)
45 CRebaseDlg::CRebaseDlg(CWnd* pParent /*=nullptr*/)
46 : CResizableStandAloneDialog(CRebaseDlg::IDD, pParent)
47 , m_bAddCherryPickedFrom(FALSE)
48 , m_bStatusWarning(false)
49 , m_bAutoSkipFailedCommit(FALSE)
50 , m_bFinishedRebase(false)
51 , m_bStashed(false)
52 , m_bSplitCommit(FALSE)
53 , m_bPreserveMerges(FALSE)
54 , m_bRebaseAutoStart(false)
55 , m_bRebaseAutoEnd(false)
56 , m_RebaseStage(CHOOSE_BRANCH)
57 , m_CurrentRebaseIndex(-1)
58 , m_bThreadRunning(FALSE)
59 , m_IsCherryPick(FALSE)
60 , m_bForce(BST_UNCHECKED)
61 , m_IsFastForward(FALSE)
62 , m_iSquashdate((int)CRegDWORD(L"Software\\TortoiseGit\\SquashDate", 0))
63 , m_bAbort(FALSE)
64 , m_CurrentCommitEmpty(false)
68 CRebaseDlg::~CRebaseDlg()
72 void CRebaseDlg::DoDataExchange(CDataExchange* pDX)
74 CDialog::DoDataExchange(pDX);
75 DDX_Control(pDX, IDC_REBASE_PROGRESS, m_ProgressBar);
76 DDX_Control(pDX, IDC_STATUS_STATIC, m_CtrlStatusText);
77 DDX_Control(pDX, IDC_REBASE_SPLIT, m_wndSplitter);
78 DDX_Control(pDX,IDC_COMMIT_LIST,m_CommitList);
79 DDX_Control(pDX,IDC_REBASE_COMBOXEX_BRANCH, this->m_BranchCtrl);
80 DDX_Control(pDX,IDC_REBASE_COMBOXEX_UPSTREAM, this->m_UpstreamCtrl);
81 DDX_Check(pDX, IDC_REBASE_CHECK_FORCE,m_bForce);
82 DDX_Check(pDX, IDC_REBASE_CHECK_PRESERVEMERGES, m_bPreserveMerges);
83 DDX_Check(pDX, IDC_CHECK_CHERRYPICKED_FROM, m_bAddCherryPickedFrom);
84 DDX_Control(pDX,IDC_REBASE_POST_BUTTON,m_PostButton);
85 DDX_Control(pDX, IDC_SPLITALLOPTIONS, m_SplitAllOptions);
86 DDX_Check(pDX, IDC_REBASE_SPLIT_COMMIT, m_bSplitCommit);
90 BEGIN_MESSAGE_MAP(CRebaseDlg, CResizableStandAloneDialog)
91 ON_BN_CLICKED(IDC_REBASE_SPLIT, &CRebaseDlg::OnBnClickedRebaseSplit)
92 ON_BN_CLICKED(IDC_REBASE_CONTINUE,OnBnClickedContinue)
93 ON_BN_CLICKED(IDC_REBASE_ABORT, OnBnClickedAbort)
94 ON_WM_SIZE()
95 ON_WM_THEMECHANGED()
96 ON_WM_SYSCOLORCHANGE()
97 ON_CBN_SELCHANGE(IDC_REBASE_COMBOXEX_BRANCH, &CRebaseDlg::OnCbnSelchangeBranch)
98 ON_CBN_SELCHANGE(IDC_REBASE_COMBOXEX_UPSTREAM, &CRebaseDlg::OnCbnSelchangeUpstream)
99 ON_MESSAGE(MSG_REBASE_UPDATE_UI, OnRebaseUpdateUI)
100 ON_REGISTERED_MESSAGE(CGitStatusListCtrl::GITSLNM_NEEDSREFRESH, OnGitStatusListCtrlNeedsRefresh)
101 ON_BN_CLICKED(IDC_BUTTON_REVERSE, OnBnClickedButtonReverse)
102 ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CRebaseDlg::OnBnClickedButtonBrowse)
103 ON_BN_CLICKED(IDC_REBASE_CHECK_FORCE, &CRebaseDlg::OnBnClickedRebaseCheckForce)
104 ON_BN_CLICKED(IDC_REBASE_CHECK_PRESERVEMERGES, &CRebaseDlg::OnBnClickedRebaseCheckForce)
105 ON_BN_CLICKED(IDC_CHECK_CHERRYPICKED_FROM, &CRebaseDlg::OnBnClickedCheckCherryPickedFrom)
106 ON_BN_CLICKED(IDC_REBASE_POST_BUTTON, &CRebaseDlg::OnBnClickedRebasePostButton)
107 ON_BN_CLICKED(IDC_BUTTON_UP, &CRebaseDlg::OnBnClickedButtonUp)
108 ON_BN_CLICKED(IDC_BUTTON_DOWN, &CRebaseDlg::OnBnClickedButtonDown)
109 ON_REGISTERED_MESSAGE(TaskBarButtonCreated, OnTaskbarBtnCreated)
110 ON_NOTIFY(LVN_ITEMCHANGED, IDC_COMMIT_LIST, OnLvnItemchangedLoglist)
111 ON_REGISTERED_MESSAGE(CGitLogListBase::m_RebaseActionMessage, OnRebaseActionMessage)
112 ON_WM_CTLCOLOR()
113 ON_BN_CLICKED(IDC_SPLITALLOPTIONS, &CRebaseDlg::OnBnClickedSplitAllOptions)
114 ON_BN_CLICKED(IDC_REBASE_SPLIT_COMMIT, &CRebaseDlg::OnBnClickedRebaseSplitCommit)
115 ON_BN_CLICKED(IDC_BUTTON_ONTO, &CRebaseDlg::OnBnClickedButtonOnto)
116 ON_BN_CLICKED(IDHELP, OnHelp)
117 ON_BN_CLICKED(IDC_BUTTON_ADD, &CRebaseDlg::OnBnClickedButtonAdd)
118 ON_MESSAGE(MSG_COMMITS_REORDERED, OnCommitsReordered)
119 END_MESSAGE_MAP()
121 void CRebaseDlg::CleanUpRebaseActiveFolder()
123 if (m_IsCherryPick)
124 return;
125 CString adminDir;
126 if (GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
128 CString dir(adminDir + L"tgitrebase.active");
129 ::DeleteFile(dir + L"\\head-name");
130 ::DeleteFile(dir + L"\\onto");
131 ::RemoveDirectory(dir);
135 void CRebaseDlg::AddRebaseAnchor()
137 AdjustControlSize(IDC_CHECK_CHERRYPICKED_FROM);
138 AdjustControlSize(IDC_REBASE_SPLIT_COMMIT);
139 AdjustControlSize(IDC_REBASE_CHECK_FORCE);
140 AdjustControlSize(IDC_REBASE_CHECK_PRESERVEMERGES);
142 AddAnchor(IDC_REBASE_TAB,TOP_LEFT,BOTTOM_RIGHT);
143 AddAnchor(IDC_COMMIT_LIST,TOP_LEFT, TOP_RIGHT);
144 AddAnchor(IDC_REBASE_SPLIT,TOP_LEFT, TOP_RIGHT);
145 AddAnchor(IDC_STATUS_STATIC, BOTTOM_LEFT,BOTTOM_RIGHT);
146 AddAnchor(IDC_REBASE_CONTINUE,BOTTOM_RIGHT);
147 AddAnchor(IDC_REBASE_ABORT, BOTTOM_RIGHT);
148 AddAnchor(IDC_REBASE_PROGRESS,BOTTOM_LEFT, BOTTOM_RIGHT);
149 AddAnchor(IDC_SPLITALLOPTIONS, TOP_LEFT);
150 AddAnchor(IDC_BUTTON_UP, TOP_LEFT);
151 AddAnchor(IDC_BUTTON_DOWN, TOP_LEFT);
152 AddAnchor(IDC_BUTTON_ADD, TOP_LEFT);
153 AddAnchor(IDC_REBASE_COMBOXEX_UPSTREAM, TOP_CENTER, TOP_RIGHT);
154 AddAnchor(IDC_REBASE_COMBOXEX_BRANCH, TOP_LEFT, TOP_CENTER);
155 AddAnchor(IDC_BUTTON_REVERSE, TOP_CENTER);
156 AddAnchor(IDC_BUTTON_BROWSE, TOP_RIGHT);
157 AddAnchor(IDC_BUTTON_ONTO, TOP_RIGHT);
158 AddAnchor(IDC_REBASE_STATIC_UPSTREAM, TOP_CENTER);
159 AddAnchor(IDC_REBASE_STATIC_BRANCH,TOP_LEFT);
160 AddAnchor(IDHELP, BOTTOM_RIGHT);
161 AddAnchor(IDC_REBASE_CHECK_FORCE, TOP_CENTER, TOP_RIGHT);
162 AddAnchor(IDC_REBASE_CHECK_PRESERVEMERGES, TOP_LEFT, TOP_CENTER);
163 AddAnchor(IDC_CHECK_CHERRYPICKED_FROM, TOP_RIGHT);
164 AddAnchor(IDC_REBASE_SPLIT_COMMIT, BOTTOM_RIGHT);
165 AddAnchor(IDC_REBASE_POST_BUTTON,BOTTOM_LEFT);
167 this->AddOthersToAnchor();
170 BOOL CRebaseDlg::OnInitDialog()
172 CResizableStandAloneDialog::OnInitDialog();
173 CAppUtils::MarkWindowAsUnpinnable(m_hWnd);
175 // Let the TaskbarButtonCreated message through the UIPI filter. If we don't
176 // do this, Explorer would be unable to send that message to our window if we
177 // were running elevated. It's OK to make the call all the time, since if we're
178 // not elevated, this is a no-op.
179 CHANGEFILTERSTRUCT cfs = { sizeof(CHANGEFILTERSTRUCT) };
180 typedef BOOL STDAPICALLTYPE ChangeWindowMessageFilterExDFN(HWND hWnd, UINT message, DWORD action, PCHANGEFILTERSTRUCT pChangeFilterStruct);
181 CAutoLibrary hUser = AtlLoadSystemLibraryUsingFullPath(L"user32.dll");
182 if (hUser)
184 ChangeWindowMessageFilterExDFN *pfnChangeWindowMessageFilterEx = (ChangeWindowMessageFilterExDFN*)GetProcAddress(hUser, "ChangeWindowMessageFilterEx");
185 if (pfnChangeWindowMessageFilterEx)
187 pfnChangeWindowMessageFilterEx(m_hWnd, TaskBarButtonCreated, MSGFLT_ALLOW, &cfs);
190 m_pTaskbarList.Release();
191 if (FAILED(m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList)))
192 m_pTaskbarList = nullptr;
194 CRect rectDummy;
195 //IDC_REBASE_DUMY_TAB
197 GetClientRect(m_DlgOrigRect);
198 m_CommitList.GetClientRect(m_CommitListOrigRect);
200 CWnd *pwnd=this->GetDlgItem(IDC_REBASE_DUMY_TAB);
201 pwnd->GetWindowRect(&rectDummy);
202 this->ScreenToClient(rectDummy);
204 if (!m_ctrlTabCtrl.Create(CMFCTabCtrl::STYLE_FLAT, rectDummy, this, IDC_REBASE_TAB))
206 TRACE0("Failed to create output tab window\n");
207 return FALSE; // fail to create
209 m_ctrlTabCtrl.SetResizeMode(CMFCTabCtrl::RESIZE_NO);
210 // Create output panes:
211 //const DWORD dwStyle = LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL;
212 DWORD dwStyle =LVS_REPORT | LVS_SHOWSELALWAYS | LVS_ALIGNLEFT | WS_BORDER | WS_TABSTOP | WS_CHILD | WS_VISIBLE;
214 if (! this->m_FileListCtrl.Create(dwStyle,rectDummy,&this->m_ctrlTabCtrl,0) )
216 TRACE0("Failed to create output windows\n");
217 return FALSE; // fail to create
219 m_FileListCtrl.m_hwndLogicalParent = this;
221 if (!m_LogMessageCtrl.Create(L"Scintilla", L"source", 0, rectDummy, &m_ctrlTabCtrl, 0, 0))
223 TRACE0("Failed to create log message control");
224 return FALSE;
226 m_ProjectProperties.ReadProps();
227 m_LogMessageCtrl.Init(m_ProjectProperties);
228 m_LogMessageCtrl.SetFont(CAppUtils::GetLogFontName(), CAppUtils::GetLogFontSize());
229 m_LogMessageCtrl.Call(SCI_SETREADONLY, TRUE);
231 dwStyle = LBS_NOINTEGRALHEIGHT | WS_CHILD | WS_VISIBLE | WS_HSCROLL | WS_VSCROLL;
233 if (!m_wndOutputRebase.Create(L"Scintilla", L"source", 0, rectDummy, &m_ctrlTabCtrl, 0, 0))
235 TRACE0("Failed to create output windows\n");
236 return -1; // fail to create
238 m_wndOutputRebase.Init(-1);
239 m_wndOutputRebase.SetFont(CAppUtils::GetLogFontName(), CAppUtils::GetLogFontSize());
240 m_wndOutputRebase.Call(SCI_SETREADONLY, TRUE);
242 m_tooltips.AddTool(IDC_REBASE_CHECK_FORCE,IDS_REBASE_FORCE_TT);
243 m_tooltips.AddTool(IDC_REBASE_ABORT, IDS_REBASE_ABORT_TT);
244 m_tooltips.AddTool(IDC_REBASE_CHECK_PRESERVEMERGES, IDS_REBASE_PRESERVEMERGES_TT);
247 CString temp;
248 temp.LoadString(IDS_PROC_REBASE_SELECTALL_PICK);
249 m_SplitAllOptions.AddEntry(temp);
250 temp.LoadString(IDS_PROC_REBASE_SELECTALL_SQUASH);
251 m_SplitAllOptions.AddEntry(temp);
252 temp.LoadString(IDS_PROC_REBASE_SELECTALL_EDIT);
253 m_SplitAllOptions.AddEntry(temp);
254 temp.LoadString(IDS_PROC_REBASE_UNSELECTED_SKIP);
255 m_SplitAllOptions.AddEntry(temp);
256 temp.LoadString(IDS_PROC_REBASE_UNSELECTED_SQUASH);
257 m_SplitAllOptions.AddEntry(temp);
258 temp.LoadString(IDS_PROC_REBASE_UNSELECTED_EDIT);
259 m_SplitAllOptions.AddEntry(temp);
262 m_FileListCtrl.Init(GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD | GITSLC_COLDEL, L"RebaseDlg", (GITSLC_POPALL ^ (GITSLC_POPCOMMIT | GITSLC_POPRESTORE)), false, true, GITSLC_COLEXT | GITSLC_COLSTATUS | GITSLC_COLADD| GITSLC_COLDEL);
264 m_ctrlTabCtrl.AddTab(&m_FileListCtrl, CString(MAKEINTRESOURCE(IDS_PROC_REVISIONFILES)));
265 m_ctrlTabCtrl.AddTab(&m_LogMessageCtrl, CString(MAKEINTRESOURCE(IDS_PROC_COMMITMESSAGE)), 1);
266 AddRebaseAnchor();
268 CString sWindowTitle;
269 GetWindowText(sWindowTitle);
270 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, sWindowTitle);
272 EnableSaveRestore(L"RebaseDlg");
274 DWORD yPos = CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\ResizableState\\RebaseDlgSizer");
275 RECT rcDlg, rcLogMsg, rcFileList;
276 GetClientRect(&rcDlg);
277 m_CommitList.GetWindowRect(&rcLogMsg);
278 ScreenToClient(&rcLogMsg);
279 this->m_ctrlTabCtrl.GetWindowRect(&rcFileList);
280 ScreenToClient(&rcFileList);
281 if (yPos)
283 RECT rectSplitter;
284 m_wndSplitter.GetWindowRect(&rectSplitter);
285 ScreenToClient(&rectSplitter);
286 int delta = yPos - rectSplitter.top;
287 if ((rcLogMsg.bottom + delta > rcLogMsg.top)&&(rcLogMsg.bottom + delta < rcFileList.bottom - 30))
289 m_wndSplitter.SetWindowPos(nullptr, 0, yPos, 0, 0, SWP_NOSIZE);
290 DoSize(delta);
294 if (this->m_RebaseStage == CHOOSE_BRANCH && !m_IsCherryPick)
295 this->LoadBranchInfo();
296 else
298 this->m_BranchCtrl.EnableWindow(FALSE);
299 this->m_UpstreamCtrl.EnableWindow(FALSE);
300 GetDlgItem(IDC_BUTTON_REVERSE)->EnableWindow(FALSE);
303 m_CommitList.m_ColumnRegKey = L"Rebase";
304 m_CommitList.m_IsIDReplaceAction = TRUE;
305 // m_CommitList.m_IsOldFirst = TRUE;
306 m_CommitList.m_IsRebaseReplaceGraph = TRUE;
307 m_CommitList.m_bNoHightlightHead = TRUE;
308 m_CommitList.m_bIsCherryPick = !!m_IsCherryPick;
310 m_CommitList.InsertGitColumn();
312 this->SetControlEnable();
314 if(m_IsCherryPick)
316 this->m_BranchCtrl.SetCurSel(-1);
317 this->m_BranchCtrl.EnableWindow(FALSE);
318 GetDlgItem(IDC_REBASE_CHECK_FORCE)->ShowWindow(SW_HIDE);
319 GetDlgItem(IDC_REBASE_CHECK_PRESERVEMERGES)->ShowWindow(SW_HIDE);
320 GetDlgItem(IDC_BUTTON_BROWSE)->EnableWindow(FALSE);
321 GetDlgItem(IDC_BUTTON_REVERSE)->EnableWindow(FALSE);
322 GetDlgItem(IDC_BUTTON_ONTO)->EnableWindow(FALSE);
323 this->m_UpstreamCtrl.AddString(L"HEAD");
324 this->m_UpstreamCtrl.EnableWindow(FALSE);
325 CAppUtils::SetWindowTitle(m_hWnd, g_Git.m_CurrentDir, CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_CHERRYPICK)));
326 // fill shown list
327 for (DWORD i = 0; i < m_CommitList.m_logEntries.size(); ++i)
328 m_CommitList.m_arShownList.SafeAdd(&m_CommitList.m_logEntries.GetGitRevAt(i));
329 m_CommitList.SetItemCountEx((int)m_CommitList.m_arShownList.size());
331 else
333 ((CButton*)GetDlgItem(IDC_BUTTON_ONTO))->SetCheck(m_Onto.IsEmpty() ? BST_UNCHECKED : BST_CHECKED);
334 GetDlgItem(IDC_CHECK_CHERRYPICKED_FROM)->ShowWindow(SW_HIDE);
335 int iconWidth = GetSystemMetrics(SM_CXSMICON);
336 int iconHeight = GetSystemMetrics(SM_CYSMICON);
337 ((CButton*)GetDlgItem(IDC_BUTTON_REVERSE))->SetIcon(CCommonAppUtils::LoadIconEx(IDI_SWITCHLEFTRIGHT, iconWidth, iconHeight));
338 SetContinueButtonText();
339 m_CommitList.DeleteAllItems();
340 FetchLogList();
343 m_CommitList.m_ContextMenuMask &= ~(m_CommitList.GetContextMenuBit(CGitLogListBase::ID_CHERRY_PICK)|
344 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_SWITCHTOREV)|
345 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_RESET)|
346 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REVERTREV)|
347 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_MERGEREV) |
348 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REBASE_TO_VERSION)|
349 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REVERTTOREV)|
350 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_COMBINE_COMMIT));
352 if(m_CommitList.m_IsOldFirst)
353 this->m_CurrentRebaseIndex = -1;
354 else
355 this->m_CurrentRebaseIndex = (int)m_CommitList.m_logEntries.size();
357 if (GetDlgItem(IDC_REBASE_CONTINUE)->IsWindowEnabled() && m_bRebaseAutoStart)
358 this->PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_CONTINUE, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_CONTINUE)->GetSafeHwnd());
360 return TRUE;
362 // CRebaseDlg message handlers
364 HBRUSH CRebaseDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
366 if (pWnd->GetDlgCtrlID() == IDC_STATUS_STATIC && nCtlColor == CTLCOLOR_STATIC && m_bStatusWarning)
368 pDC->SetBkColor(RGB(255, 0, 0));
369 pDC->SetTextColor(RGB(255, 255, 255));
370 return CreateSolidBrush(RGB(255, 0, 0));
373 return CResizableStandAloneDialog::OnCtlColor(pDC, pWnd, nCtlColor);
376 void CRebaseDlg::SetAllRebaseAction(int action)
378 for (size_t i = 0; i < this->m_CommitList.m_logEntries.size(); ++i)
380 if (action == CGitLogListBase::LOGACTIONS_REBASE_SQUASH && (i == this->m_CommitList.m_logEntries.size() - 1 || (!m_IsCherryPick && m_CommitList.m_logEntries.GetGitRevAt(i).ParentsCount() != 1)))
381 continue;
382 m_CommitList.m_logEntries.GetGitRevAt(i).GetRebaseAction() = action;
384 m_CommitList.Invalidate();
387 void CRebaseDlg::OnBnClickedRebaseSplit()
389 this->UpdateData();
392 LRESULT CRebaseDlg::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
394 switch (message) {
395 case WM_NOTIFY:
396 if (wParam == IDC_REBASE_SPLIT)
398 SPC_NMHDR* pHdr = (SPC_NMHDR*) lParam;
399 DoSize(pHdr->delta);
401 break;
404 return __super::DefWindowProc(message, wParam, lParam);
407 void CRebaseDlg::DoSize(int delta)
409 this->RemoveAllAnchors();
411 auto hdwp = BeginDeferWindowPos(9);
412 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_COMMIT_LIST), 0, 0, 0, delta);
413 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_REBASE_TAB), 0, delta, 0, 0);
414 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_SPLITALLOPTIONS), 0, delta, 0, delta);
415 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_BUTTON_UP), 0, delta, 0, delta);
416 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_BUTTON_DOWN), 0, delta, 0, delta);
417 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_BUTTON_ADD), 0, delta, 0, delta);
418 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_REBASE_CHECK_FORCE), 0, delta, 0, delta);
419 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_REBASE_CHECK_PRESERVEMERGES), 0, delta, 0, delta);
420 hdwp = CSplitterControl::ChangeRect(hdwp, GetDlgItem(IDC_CHECK_CHERRYPICKED_FROM), 0, delta, 0, delta);
421 EndDeferWindowPos(hdwp);
423 this->AddRebaseAnchor();
424 // adjust the minimum size of the dialog to prevent the resizing from
425 // moving the list control too far down.
426 CRect rcLogMsg;
427 m_CommitList.GetClientRect(rcLogMsg);
428 SetMinTrackSize(CSize(m_DlgOrigRect.Width(), m_DlgOrigRect.Height()-m_CommitListOrigRect.Height()+rcLogMsg.Height()));
430 SetSplitterRange();
431 // m_CommitList.Invalidate();
433 // GetDlgItem(IDC_LOGMESSAGE)->Invalidate();
435 this->m_ctrlTabCtrl.Invalidate();
436 this->m_CommitList.Invalidate();
437 this->m_FileListCtrl.Invalidate();
438 this->m_LogMessageCtrl.Invalidate();
439 m_SplitAllOptions.Invalidate();
440 GetDlgItem(IDC_REBASE_CHECK_FORCE)->Invalidate();
441 GetDlgItem(IDC_REBASE_CHECK_PRESERVEMERGES)->Invalidate();
442 GetDlgItem(IDC_CHECK_CHERRYPICKED_FROM)->Invalidate();
443 GetDlgItem(IDC_BUTTON_UP)->Invalidate();
444 GetDlgItem(IDC_BUTTON_DOWN)->Invalidate();
445 GetDlgItem(IDC_BUTTON_ADD)->Invalidate();
448 void CRebaseDlg::SetSplitterRange()
450 if ((m_CommitList)&&(m_ctrlTabCtrl))
452 CRect rcTop;
453 m_CommitList.GetWindowRect(rcTop);
454 ScreenToClient(rcTop);
455 CRect rcMiddle;
456 m_ctrlTabCtrl.GetWindowRect(rcMiddle);
457 ScreenToClient(rcMiddle);
458 if (rcMiddle.Height() && rcMiddle.Width())
459 m_wndSplitter.SetRange(rcTop.top+60, rcMiddle.bottom-80);
463 void CRebaseDlg::OnSize(UINT nType,int cx, int cy)
465 // first, let the resizing take place
466 __super::OnSize(nType, cx, cy);
468 //set range
469 SetSplitterRange();
472 void CRebaseDlg::SaveSplitterPos()
474 if (!IsIconic())
476 CRegDWORD regPos = CRegDWORD(L"Software\\TortoiseGit\\TortoiseProc\\ResizableState\\RebaseDlgSizer");
477 RECT rectSplitter;
478 m_wndSplitter.GetWindowRect(&rectSplitter);
479 ScreenToClient(&rectSplitter);
480 regPos = rectSplitter.top;
484 void CRebaseDlg::LoadBranchInfo()
486 m_BranchCtrl.SetMaxHistoryItems(0x7FFFFFFF);
487 m_UpstreamCtrl.SetMaxHistoryItems(0x7FFFFFFF);
489 STRING_VECTOR list;
490 list.clear();
491 int current = -1;
492 g_Git.GetBranchList(list,&current,CGit::BRANCH_ALL);
493 m_BranchCtrl.SetList(list);
494 if (current >= 0)
495 m_BranchCtrl.SetCurSel(current);
496 else
497 m_BranchCtrl.AddString(g_Git.GetCurrentBranch(true));
498 list.clear();
499 g_Git.GetBranchList(list, nullptr, CGit::BRANCH_ALL_F);
500 g_Git.GetTagList(list);
501 m_UpstreamCtrl.SetList(list);
503 AddBranchToolTips(m_BranchCtrl);
505 if(!m_Upstream.IsEmpty())
506 m_UpstreamCtrl.AddString(m_Upstream);
507 else
509 //Select pull-remote from current branch
510 CString pullRemote, pullBranch;
511 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
513 CString defaultUpstream;
514 defaultUpstream.Format(L"remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
515 int found = m_UpstreamCtrl.FindStringExact(0, defaultUpstream);
516 if(found >= 0)
517 m_UpstreamCtrl.SetCurSel(found);
518 else
519 m_UpstreamCtrl.SetCurSel(-1);
521 AddBranchToolTips(m_UpstreamCtrl);
524 void CRebaseDlg::OnCbnSelchangeBranch()
526 FetchLogList();
529 void CRebaseDlg::OnCbnSelchangeUpstream()
531 FetchLogList();
534 void CRebaseDlg::FetchLogList()
536 CGitHash base,hash,upstream;
537 m_IsFastForward=FALSE;
539 if (m_BranchCtrl.GetString().IsEmpty())
541 m_CommitList.ShowText(CString(MAKEINTRESOURCE(IDS_SELECTBRANCH)));
542 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(false);
543 return;
546 if (g_Git.GetHash(hash, m_BranchCtrl.GetString()))
548 m_CommitList.ShowText(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_BranchCtrl.GetString() + L"\"."));
549 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(false);
550 return;
553 if (m_UpstreamCtrl.GetString().IsEmpty())
555 m_CommitList.ShowText(CString(MAKEINTRESOURCE(IDS_SELECTUPSTREAM)));
556 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(false);
557 return;
560 if (g_Git.GetHash(upstream, m_UpstreamCtrl.GetString()))
562 m_CommitList.ShowText(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_UpstreamCtrl.GetString() + L"\"."));
563 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(false);
564 return;
567 if (hash == upstream)
569 m_CommitList.Clear();
570 CString text;
571 text.FormatMessage(IDS_REBASE_EQUAL_FMT, (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)this->m_UpstreamCtrl.GetString());
573 m_CommitList.ShowText(text);
574 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(false);
575 if (m_bRebaseAutoStart)
576 PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_ABORT, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_ABORT)->GetSafeHwnd());
577 return;
580 if (g_Git.IsFastForward(m_BranchCtrl.GetString(), m_UpstreamCtrl.GetString(), &base) && m_Onto.IsEmpty())
582 this->m_IsFastForward=TRUE;
584 m_CommitList.Clear();
585 CString text;
586 text.FormatMessage(IDS_REBASE_FASTFORWARD_FMT, (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)this->m_UpstreamCtrl.GetString(),
587 (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)this->m_UpstreamCtrl.GetString());
589 m_CommitList.ShowText(text);
590 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(true);
591 SetContinueButtonText();
593 return ;
596 if (!m_bForce && m_Onto.IsEmpty())
598 if (base == upstream)
600 m_CommitList.Clear();
601 CString text;
602 text.Format(IDS_REBASE_UPTODATE_FMT, (LPCTSTR)m_BranchCtrl.GetString());
603 m_CommitList.ShowText(text);
604 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(FALSE);
605 SetContinueButtonText();
606 if (m_bRebaseAutoStart)
607 PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_ABORT, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_ABORT)->GetSafeHwnd());
608 return;
612 m_CommitList.Clear();
613 CString refFrom = g_Git.FixBranchName(m_UpstreamCtrl.GetString());
614 CString refTo = g_Git.FixBranchName(m_BranchCtrl.GetString());
615 CString range;
616 range.Format(L"%s..%s", (LPCTSTR)refFrom, (LPCTSTR)refTo);
617 this->m_CommitList.FillGitLog(nullptr, &range, (m_bPreserveMerges ? 0 : CGit::LOG_INFO_NO_MERGE) | CGit::LOG_ORDER_TOPOORDER);
619 if( m_CommitList.GetItemCount() == 0 )
620 m_CommitList.ShowText(CString(MAKEINTRESOURCE(IDS_PROC_NOTHINGTOREBASE)));
622 m_rewrittenCommitsMap.clear();
623 if (m_bPreserveMerges)
625 CGitHash head;
626 if (g_Git.GetHash(head, L"HEAD"))
628 AddLogString(CString(MAKEINTRESOURCE(IDS_PROC_NOHEAD)));
629 return;
631 CGitHash upstreamHash;
632 if (g_Git.GetHash(upstreamHash, m_Onto.IsEmpty() ? m_UpstreamCtrl.GetString() : m_Onto))
634 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + (m_Onto.IsEmpty() ? m_UpstreamCtrl.GetString() : m_Onto) + L"\"."), L"TortoiseGit", MB_ICONERROR);
635 return;
637 CString mergecmd;
638 mergecmd.Format(L"git merge-base --all %s %s", (LPCTSTR)head.ToString(), (LPCTSTR)upstreamHash.ToString());
639 g_Git.Run(mergecmd, [&](const CStringA& line)
641 CGitHash hash;
642 hash.ConvertFromStrA(line);
643 if (hash.IsEmpty())
644 return;
645 m_rewrittenCommitsMap[hash] = upstreamHash;
648 std::vector<size_t> toDrop;
649 for (size_t i = m_CommitList.m_arShownList.size(); i-- > 0;)
651 bool preserve = false;
652 GitRevLoglist* pRev = m_CommitList.m_arShownList.SafeGetAt(i);
653 for (const auto& parent : pRev->m_ParentHash)
655 const auto rewrittenParent = m_rewrittenCommitsMap.find(parent);
656 if (rewrittenParent != m_rewrittenCommitsMap.cend())
658 preserve = true;
659 break;
662 if (preserve)
663 m_rewrittenCommitsMap[pRev->m_CommitHash] = CGitHash();
664 else
665 toDrop.push_back(i);
668 // Drop already included commits
669 std::vector<CGitHash> nonCherryPicked;
670 CString cherryCmd;
671 cherryCmd.Format(L"git rev-list \"%s...%s\" --left-right --cherry-pick", (LPCTSTR)refFrom, (LPCTSTR)refTo);
672 g_Git.Run(cherryCmd, [&](const CStringA& line)
674 if (line.GetLength() < 2)
675 return;
676 if (line[0] != '>')
677 return;
678 CString hash = CUnicodeUtils::GetUnicode(line.Mid(1));
679 hash.Trim();
680 nonCherryPicked.emplace_back(hash);
682 for (size_t i = m_CommitList.m_arShownList.size(); i-- > 0;)
684 GitRevLoglist* pRev = m_CommitList.m_arShownList.SafeGetAt(i);
685 pRev->GetRebaseAction() = CGitLogListBase::LOGACTIONS_REBASE_PICK;
686 if (m_rewrittenCommitsMap.find(pRev->m_CommitHash) != m_rewrittenCommitsMap.cend() && std::find(nonCherryPicked.cbegin(), nonCherryPicked.cend(), pRev->m_CommitHash) == nonCherryPicked.cend())
688 m_droppedCommitsMap[pRev->m_CommitHash].clear();
689 m_droppedCommitsMap[pRev->m_CommitHash].push_back(pRev->m_ParentHash[0]);
690 toDrop.push_back(i);
691 m_rewrittenCommitsMap.erase(pRev->m_CommitHash);
694 std::sort(toDrop.begin(), toDrop.end());
695 toDrop.erase(unique(toDrop.begin(), toDrop.end()), toDrop.end());
696 for (auto it = toDrop.crbegin(); it != toDrop.crend(); ++it)
698 m_CommitList.m_arShownList.SafeRemoveAt(*it);
699 m_CommitList.m_logEntries.erase(m_CommitList.m_logEntries.begin() + *it);
701 m_CommitList.SetItemCountEx((int)m_CommitList.m_logEntries.size());
704 #if 0
705 if(m_CommitList.m_logEntries[m_CommitList.m_logEntries.size()-1].m_ParentHash.size() >=0 )
707 if(upstream == m_CommitList.m_logEntries[m_CommitList.m_logEntries.size()-1].m_ParentHash[0])
709 m_CommitList.Clear();
710 m_CommitList.ShowText(L"Nothing Rebase");
713 #endif
715 m_tooltips.Pop();
716 AddBranchToolTips(m_BranchCtrl);
717 AddBranchToolTips(m_UpstreamCtrl);
719 bool bHasSKip = false;
720 if (!m_bPreserveMerges)
722 // Default all actions to 'pick'
723 std::unordered_map<CGitHash, size_t> revIxMap;
724 for (size_t i = 0; i < m_CommitList.m_logEntries.size(); ++i)
726 GitRevLoglist& rev = m_CommitList.m_logEntries.GetGitRevAt(i);
727 rev.GetRebaseAction() = CGitLogListBase::LOGACTIONS_REBASE_PICK;
728 revIxMap[rev.m_CommitHash] = i;
731 // Default to skip when already in upstream
732 if (!m_Onto.IsEmpty())
733 refFrom = g_Git.FixBranchName(m_Onto);
734 CString cherryCmd;
735 cherryCmd.Format(L"git.exe cherry \"%s\" \"%s\"", (LPCTSTR)refFrom, (LPCTSTR)refTo);
736 g_Git.Run(cherryCmd, [&](const CStringA& line)
738 if (line.GetLength() < 2)
739 return;
740 if (line[0] != '-')
741 return; // Don't skip (only skip commits starting with a '-')
742 CString hash = CUnicodeUtils::GetUnicode(line.Mid(1));
743 hash.Trim();
744 auto itIx = revIxMap.find(CGitHash(hash));
745 if (itIx == revIxMap.end())
746 return; // Not found?? Should not occur...
748 // Found. Skip it.
749 m_CommitList.m_logEntries.GetGitRevAt(itIx->second).GetRebaseAction() = CGitLogListBase::LOGACTIONS_REBASE_SKIP;
750 bHasSKip = true;
753 m_CommitList.Invalidate();
754 if (bHasSKip)
756 m_CtrlStatusText.SetWindowText(CString(MAKEINTRESOURCE(IDS_REBASE_AUTOSKIPPED)));
757 m_bStatusWarning = true;
759 else
761 m_CtrlStatusText.SetWindowText(m_sStatusText);
762 m_bStatusWarning = false;
764 m_CtrlStatusText.Invalidate();
766 if(m_CommitList.m_IsOldFirst)
767 this->m_CurrentRebaseIndex = -1;
768 else
769 this->m_CurrentRebaseIndex = (int)m_CommitList.m_logEntries.size();
771 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(m_bPreserveMerges || m_CommitList.GetItemCount());
772 SetContinueButtonText();
775 void CRebaseDlg::AddBranchToolTips(CHistoryCombo& pBranch)
777 pBranch.DisableTooltip();
779 CString text = pBranch.GetString();
781 if (text.IsEmpty())
782 return;
784 GitRev rev;
785 if (rev.GetCommit(text + L"^{}"))
787 MessageBox(L"Failed to get commit.\n" + rev.GetLastErr(), L"TortoiseGit", MB_ICONERROR);
788 return;
791 CString tooltip;
792 tooltip.Format(L"%s: %s\n%s: %s <%s>\n%s: %s\n%s:\n%s\n%s",
793 (LPCTSTR)CString(MAKEINTRESOURCE(IDS_LOG_REVISION)),
794 (LPCTSTR)rev.m_CommitHash.ToString(),
795 (LPCTSTR)CString(MAKEINTRESOURCE(IDS_LOG_AUTHOR)),
796 (LPCTSTR)rev.GetAuthorName(),
797 (LPCTSTR)rev.GetAuthorEmail(),
798 (LPCTSTR)CString(MAKEINTRESOURCE(IDS_LOG_DATE)),
799 (LPCTSTR)CLoglistUtils::FormatDateAndTime(rev.GetAuthorDate(), DATE_LONGDATE),
800 (LPCTSTR)CString(MAKEINTRESOURCE(IDS_LOG_MESSAGE)),
801 (LPCTSTR)rev.GetSubject(),
802 (LPCTSTR)rev.GetBody());
804 if (tooltip.GetLength() > 8000)
806 tooltip.Truncate(8000);
807 tooltip += L"...";
810 m_tooltips.AddTool(pBranch.GetComboBoxCtrl(), tooltip);
813 BOOL CRebaseDlg::PreTranslateMessage(MSG*pMsg)
815 if (pMsg->message == WM_KEYDOWN)
817 switch (pMsg->wParam)
819 case ' ':
820 if (LogListHasFocus(pMsg->hwnd)
821 && LogListHasMenuItem(CGitLogListBase::ID_REBASE_PICK)
822 && LogListHasMenuItem(CGitLogListBase::ID_REBASE_SQUASH)
823 && LogListHasMenuItem(CGitLogListBase::ID_REBASE_EDIT)
824 && LogListHasMenuItem(CGitLogListBase::ID_REBASE_SKIP))
826 m_CommitList.ShiftSelectedRebaseAction();
827 return TRUE;
829 break;
830 case 'P':
831 if (LogListHasFocus(pMsg->hwnd) && LogListHasMenuItem(CGitLogListBase::ID_REBASE_PICK))
833 m_CommitList.SetSelectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_PICK);
834 return TRUE;
836 break;
837 case 'S':
838 if (LogListHasFocus(pMsg->hwnd) && LogListHasMenuItem(CGitLogListBase::ID_REBASE_SKIP))
840 m_CommitList.SetSelectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_SKIP);
841 return TRUE;
843 break;
844 case 'Q':
845 if (LogListHasFocus(pMsg->hwnd) && LogListHasMenuItem(CGitLogListBase::ID_REBASE_SQUASH))
847 m_CommitList.SetSelectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_SQUASH);
848 return TRUE;
850 break;
851 case 'E':
852 if (LogListHasFocus(pMsg->hwnd) && LogListHasMenuItem(CGitLogListBase::ID_REBASE_EDIT))
854 m_CommitList.SetSelectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_EDIT);
855 return TRUE;
857 break;
858 case 'U':
859 if (LogListHasFocus(pMsg->hwnd) && GetDlgItem(IDC_BUTTON_UP)->IsWindowEnabled() == TRUE)
861 OnBnClickedButtonUp();
862 return TRUE;
864 break;
865 case 'D':
866 if (LogListHasFocus(pMsg->hwnd) && GetDlgItem(IDC_BUTTON_DOWN)->IsWindowEnabled() == TRUE)
868 OnBnClickedButtonDown();
869 return TRUE;
871 break;
872 case 'A':
873 if(LogListHasFocus(pMsg->hwnd) && GetAsyncKeyState(VK_CONTROL) & 0x8000)
875 // select all entries
876 for (int i = 0; i < m_CommitList.GetItemCount(); ++i)
877 m_CommitList.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
878 return TRUE;
880 break;
881 case VK_F5:
883 Refresh();
884 return TRUE;
886 break;
887 case VK_RETURN:
889 if (GetAsyncKeyState(VK_CONTROL) & 0x8000)
891 if (GetDlgItem(IDC_REBASE_CONTINUE)->IsWindowEnabled())
892 GetDlgItem(IDC_REBASE_CONTINUE)->SetFocus();
893 else if (GetDlgItem(IDC_REBASE_ABORT)->IsWindowEnabled())
894 GetDlgItem(IDC_REBASE_ABORT)->SetFocus();
895 else
896 GetDlgItem(IDHELP)->SetFocus();
897 return TRUE;
900 break;
901 /* Avoid TAB control destroy but dialog exist*/
902 case VK_ESCAPE:
903 case VK_CANCEL:
905 TCHAR buff[128] = { 0 };
906 ::GetClassName(pMsg->hwnd,buff,128);
909 /* Use MSFTEDIT_CLASS http://msdn.microsoft.com/en-us/library/bb531344.aspx */
910 if (_wcsnicmp(buff, MSFTEDIT_CLASS, 128) == 0 || //Unicode and MFC 2012 and later
911 _wcsnicmp(buff, RICHEDIT_CLASS, 128) == 0 || //ANSI or MFC 2010
912 _wcsnicmp(buff, L"Scintilla", 128) == 0 ||
913 _wcsnicmp(buff, L"SysListView32", 128) == 0 ||
914 ::GetParent(pMsg->hwnd) == this->m_ctrlTabCtrl.m_hWnd)
916 this->PostMessage(WM_KEYDOWN,VK_ESCAPE,0);
917 return TRUE;
922 else if (pMsg->message == WM_NEXTDLGCTL)
924 HWND hwnd = GetFocus()->GetSafeHwnd();
925 if (hwnd == m_LogMessageCtrl.GetSafeHwnd() || hwnd == m_wndOutputRebase.GetSafeHwnd())
927 if (GetDlgItem(IDC_REBASE_CONTINUE)->IsWindowEnabled())
928 GetDlgItem(IDC_REBASE_CONTINUE)->SetFocus();
929 else if (GetDlgItem(IDC_REBASE_ABORT)->IsWindowEnabled())
930 GetDlgItem(IDC_REBASE_ABORT)->SetFocus();
931 else
932 GetDlgItem(IDHELP)->SetFocus();
933 return TRUE;
936 return CResizableStandAloneDialog::PreTranslateMessage(pMsg);
939 bool CRebaseDlg::LogListHasFocus(HWND hwnd)
941 TCHAR buff[128] = { 0 };
942 ::GetClassName(hwnd, buff, 128);
944 if (_wcsnicmp(buff, L"SysListView32", 128) == 0)
945 return true;
946 return false;
949 bool CRebaseDlg::LogListHasMenuItem(int i)
951 return (m_CommitList.m_ContextMenuMask & m_CommitList.GetContextMenuBit(i)) != 0;
954 int CRebaseDlg::CheckRebaseCondition()
956 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
958 if( !g_Git.CheckCleanWorkTree() )
960 if ((!m_IsCherryPick && g_Git.GetConfigValueBool(L"rebase.autostash")) || CMessageBox::Show(GetSafeHwnd(), IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
962 CString out;
963 CString cmd = L"git.exe stash";
964 this->AddLogString(cmd);
965 if (g_Git.Run(cmd, &out, CP_UTF8))
967 MessageBox(out, L"TortoiseGit", MB_OK | MB_ICONERROR);
968 return -1;
970 m_bStashed = true;
972 else
973 return -1;
975 //Todo Check $REBASE_ROOT
976 //Todo Check $DOTEST
978 if (!CAppUtils::CheckUserData(GetSafeHwnd()))
979 return -1;
981 if (!m_IsCherryPick)
983 CString error;
984 DWORD exitcode = 0xFFFFFFFF;
985 CHooks::Instance().SetProjectProperties(g_Git.m_CurrentDir, m_ProjectProperties);
986 if (CHooks::Instance().PreRebase(GetSafeHwnd(), g_Git.m_CurrentDir, m_UpstreamCtrl.GetString(), m_BranchCtrl.GetString(), exitcode, error))
988 if (exitcode)
990 CString sErrorMsg;
991 sErrorMsg.Format(IDS_HOOK_ERRORMSG, (LPCWSTR)error);
992 CTaskDialog taskdlg(sErrorMsg, CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK2)), L"TortoiseGit", 0, TDF_ENABLE_HYPERLINKS | TDF_USE_COMMAND_LINKS | TDF_ALLOW_DIALOG_CANCELLATION | TDF_POSITION_RELATIVE_TO_WINDOW | TDF_SIZE_TO_CONTENT);
993 taskdlg.AddCommandControl(101, CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK3)));
994 taskdlg.AddCommandControl(102, CString(MAKEINTRESOURCE(IDS_HOOKFAILED_TASK4)));
995 taskdlg.SetDefaultCommandControl(101);
996 taskdlg.SetMainIcon(TD_ERROR_ICON);
997 if (taskdlg.DoModal(GetSafeHwnd()) != 102)
998 return -1;
1003 return 0;
1006 void CRebaseDlg::CheckRestoreStash()
1008 bool autoStash = !m_IsCherryPick && g_Git.GetConfigValueBool(L"rebase.autostash");
1009 if (m_bStashed && (autoStash || CMessageBox::Show(GetSafeHwnd(), IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) == IDYES))
1010 CAppUtils::StashPop(GetSafeHwnd(), autoStash ? 0 : 1);
1011 m_bStashed = false;
1014 int CRebaseDlg::StartRebase()
1016 CString cmd,out;
1017 m_OrigHEADBranch = g_Git.GetCurrentBranch(true);
1019 m_OrigHEADHash.Empty();
1020 if (g_Git.GetHash(m_OrigHEADHash, L"HEAD"))
1022 AddLogString(CString(MAKEINTRESOURCE(IDS_PROC_NOHEAD)));
1023 return -1;
1025 //Todo
1026 //git symbolic-ref HEAD > "$DOTEST"/head-name 2> /dev/null ||
1027 // echo "detached HEAD" > "$DOTEST"/head-name
1029 cmd.Format(L"git.exe update-ref ORIG_HEAD %s", (LPCTSTR)m_OrigHEADHash.ToString());
1030 if(g_Git.Run(cmd,&out,CP_UTF8))
1032 AddLogString(L"update ORIG_HEAD Fail");
1033 return -1;
1036 m_OrigUpstreamHash.Empty();
1037 if (g_Git.GetHash(m_OrigUpstreamHash, (m_IsCherryPick || m_Onto.IsEmpty()) ? m_UpstreamCtrl.GetString() : m_Onto))
1039 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + ((m_IsCherryPick || m_Onto.IsEmpty()) ? m_UpstreamCtrl.GetString() : m_Onto) + L"\"."), L"TortoiseGit", MB_ICONERROR);
1040 return -1;
1043 if( !this->m_IsCherryPick )
1045 if (g_Git.m_IsUseLibGit2)
1047 CAutoRepository repo(g_Git.GetGitRepository());
1048 CAutoReflog reflog;
1049 git_reflog_read(reflog.GetPointer(), repo, "HEAD");
1050 CAutoSignature signature;
1051 if (git_signature_default(signature.GetPointer(), repo) < 0)
1052 return -1;
1054 git_reflog_append(reflog, m_OrigHEADHash, signature, "rebase: start (" + CUnicodeUtils::GetUTF8(m_OrigHEADBranch) + " on " + CUnicodeUtils::GetUTF8(m_OrigUpstreamHash.ToString()) + ")");
1055 git_reflog_write(reflog);
1058 cmd.Format(L"git.exe checkout -f %s --", (LPCTSTR)m_OrigUpstreamHash.ToString());
1059 this->AddLogString(cmd);
1060 if (RunGitCmdRetryOrAbort(cmd))
1061 return -1;
1064 CString log;
1065 if( !this->m_IsCherryPick )
1067 if (g_Git.GetHash(m_OrigBranchHash, m_BranchCtrl.GetString()))
1069 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_BranchCtrl.GetString() + L"\"."), L"TortoiseGit", MB_ICONERROR);
1070 return -1;
1072 log.Format(L"%s\r\n", (LPCTSTR)CString(MAKEINTRESOURCE(IDS_PROC_REBASE_STARTREBASE)));
1074 else
1075 log.Format(L"%s\r\n", (LPCTSTR)CString(MAKEINTRESOURCE(IDS_PROC_REBASE_STARTCHERRYPICK)));
1077 this->AddLogString(log);
1078 return 0;
1080 int CRebaseDlg::VerifyNoConflict()
1082 int hasConflicts = g_Git.HasWorkingTreeConflicts();
1083 if (hasConflicts < 0)
1085 AddLogString(g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS));
1086 return -1;
1088 if (hasConflicts)
1090 CMessageBox::Show(GetSafeHwnd(), IDS_PROGRS_CONFLICTSOCCURRED, IDS_APPNAME, MB_OK | MB_ICONEXCLAMATION);
1091 auto locker(m_FileListCtrl.AcquireReadLock());
1092 auto pos = m_FileListCtrl.GetFirstSelectedItemPosition();
1093 while (pos)
1094 m_FileListCtrl.SetItemState(m_FileListCtrl.GetNextSelectedItem(pos), 0, LVIS_SELECTED);
1095 int nListItems = m_FileListCtrl.GetItemCount();
1096 for (int i = 0; i < nListItems; ++i)
1098 auto entry = m_FileListCtrl.GetListEntry(i);
1099 if (entry->m_Action & CTGitPath::LOGACTIONS_UNMERGED)
1101 m_FileListCtrl.EnsureVisible(i, FALSE);
1102 m_FileListCtrl.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
1103 m_FileListCtrl.SetFocus();
1104 return -1;
1107 return -1;
1109 CleanUpRebaseActiveFolder();
1110 return 0;
1113 int CRebaseDlg::FinishRebase()
1115 if (m_bFinishedRebase)
1116 return 0;
1118 m_bFinishedRebase = true;
1119 if(this->m_IsCherryPick) //cherry pick mode no "branch", working at upstream branch
1121 m_sStatusText.LoadString(IDS_DONE);
1122 m_CtrlStatusText.SetWindowText(m_sStatusText);
1123 m_bStatusWarning = false;
1124 m_CtrlStatusText.Invalidate();
1125 return 0;
1128 RewriteNotes();
1130 CGitHash head;
1131 if (g_Git.GetHash(head, L"HEAD"))
1133 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1134 return -1;
1137 m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1139 if (g_Git.IsLocalBranch(m_BranchCtrl.GetString()))
1141 CString cmd;
1142 cmd.Format(L"git.exe checkout -f -B %s %s --", (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)head.ToString());
1143 AddLogString(cmd);
1144 if (RunGitCmdRetryOrAbort(cmd))
1145 return -1;
1148 CString cmd;
1149 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)head.ToString());
1150 AddLogString(cmd);
1151 if (RunGitCmdRetryOrAbort(cmd))
1152 return -1;
1154 if (g_Git.m_IsUseLibGit2)
1156 CAutoRepository repo(g_Git.GetGitRepository());
1157 CAutoReflog reflog;
1158 git_reflog_read(reflog.GetPointer(), repo, "HEAD");
1159 CAutoSignature signature;
1160 git_signature_default(signature.GetPointer(), repo);
1161 git_reflog_append(reflog, m_OrigHEADHash, signature, "rebase: finished");
1162 git_reflog_write(reflog);
1165 while (m_ctrlTabCtrl.GetTabsNum() > 1)
1166 m_ctrlTabCtrl.RemoveTab(0);
1167 m_CtrlStatusText.SetWindowText(CString(MAKEINTRESOURCE(IDS_PROC_REBASEFINISHED)));
1168 m_sStatusText.LoadString(IDS_PROC_REBASEFINISHED);
1169 m_bStatusWarning = false;
1170 m_CtrlStatusText.Invalidate();
1172 m_bRebaseAutoEnd = m_bRebaseAutoStart;
1174 return 0;
1177 void CRebaseDlg::RewriteNotes()
1179 CString rewrites;
1180 for (const auto& entry : m_rewrittenCommitsMap)
1182 if (entry.second.IsEmpty())
1183 continue;
1184 rewrites += entry.first.ToString();
1185 rewrites += L' ';
1186 rewrites += entry.second.ToString();
1187 rewrites += L'\n';
1189 if (rewrites.IsEmpty())
1190 return;
1191 CString tmpfile = GetTempFile();
1192 tmpfile.Replace(L'\\', L'/');
1193 if (!CStringUtils::WriteStringToTextFile(tmpfile, rewrites))
1194 return;
1195 SCOPE_EXIT{ ::DeleteFile(tmpfile); };
1196 CString pipefile = GetTempFile();
1197 pipefile.Replace(L'\\', L'/');
1198 CString pipecmd;
1199 pipecmd.Format(L"git notes copy --for-rewrite=rebase < %s", (LPCTSTR)tmpfile);
1200 if (!CStringUtils::WriteStringToTextFile(pipefile, pipecmd))
1201 return;
1202 SCOPE_EXIT{ ::DeleteFile(pipefile); };
1203 CString out;
1204 g_Git.Run(L"bash.exe " + pipefile, &out, CP_UTF8);
1207 void CRebaseDlg::OnBnClickedContinue()
1209 if( m_RebaseStage == REBASE_DONE)
1211 OnOK();
1212 CleanUpRebaseActiveFolder();
1213 CheckRestoreStash();
1214 SaveSplitterPos();
1215 return;
1218 if (m_RebaseStage == CHOOSE_BRANCH || m_RebaseStage == CHOOSE_COMMIT_PICK_MODE)
1220 if (CAppUtils::IsTGitRebaseActive(GetSafeHwnd()))
1221 return;
1222 if (CheckRebaseCondition())
1223 return;
1226 m_bAbort = FALSE;
1227 if( this->m_IsFastForward )
1229 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(FALSE);
1230 CString cmd,out;
1231 if (g_Git.GetHash(m_OrigBranchHash, m_BranchCtrl.GetString()))
1233 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_BranchCtrl.GetString() + L"\"."), L"TortoiseGit", MB_ICONERROR);
1234 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1235 return;
1237 if (g_Git.GetHash(m_OrigUpstreamHash, m_UpstreamCtrl.GetString()))
1239 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_UpstreamCtrl.GetString() + L"\"."), L"TortoiseGit", MB_ICONERROR);
1240 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1241 return;
1244 if(!g_Git.IsFastForward(this->m_BranchCtrl.GetString(),this->m_UpstreamCtrl.GetString()))
1246 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1247 AddLogString(L"No fast forward possible.\r\nMaybe repository changed");
1248 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1249 return;
1252 if (g_Git.IsLocalBranch(m_BranchCtrl.GetString()))
1254 cmd.Format(L"git.exe checkout --no-track -f -B %s %s --", (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)m_UpstreamCtrl.GetString());
1255 AddLogString(cmd);
1256 if (RunGitCmdRetryOrAbort(cmd))
1258 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1259 return;
1261 AddLogString(out);
1262 out.Empty();
1264 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)g_Git.FixBranchName(this->m_UpstreamCtrl.GetString()));
1265 CString log;
1266 log.Format(IDS_PROC_REBASE_FFTO, (LPCTSTR)m_UpstreamCtrl.GetString());
1267 this->AddLogString(log);
1269 AddLogString(cmd);
1270 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1271 if (RunGitCmdRetryOrAbort(cmd))
1273 GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1274 return;
1276 AddLogString(out);
1277 AddLogString(CString(MAKEINTRESOURCE(IDS_DONE)));
1278 m_RebaseStage = REBASE_DONE;
1279 UpdateCurrentStatus();
1281 if (m_bRebaseAutoStart)
1282 this->PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_CONTINUE, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_CONTINUE)->GetSafeHwnd());
1284 return;
1287 if( m_RebaseStage == CHOOSE_BRANCH|| m_RebaseStage == CHOOSE_COMMIT_PICK_MODE )
1289 m_RebaseStage = REBASE_START;
1290 m_FileListCtrl.Clear();
1291 m_FileListCtrl.SetHasCheckboxes(false);
1292 m_FileListCtrl.m_CurrentVersion.Empty();
1293 m_ctrlTabCtrl.SetTabLabel(REBASE_TAB_CONFLICT, CString(MAKEINTRESOURCE(IDS_PROC_CONFLICTFILES)));
1294 m_ctrlTabCtrl.AddTab(&m_wndOutputRebase, CString(MAKEINTRESOURCE(IDS_LOG)), 2);
1295 m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1298 if( m_RebaseStage == REBASE_FINISH )
1300 if(FinishRebase())
1301 return ;
1303 SaveSplitterPos();
1304 OnOK();
1307 if( m_RebaseStage == REBASE_SQUASH_CONFLICT)
1309 if(VerifyNoConflict())
1310 return;
1311 if (CAppUtils::MessageContainsConflictHints(GetSafeHwnd(), m_LogMessageCtrl.GetText()))
1312 return;
1313 GitRevLoglist* curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1314 if(this->CheckNextCommitIsSquash())
1315 {//next commit is not squash;
1316 m_RebaseStage = REBASE_SQUASH_EDIT;
1317 this->OnRebaseUpdateUI(0,0);
1318 this->UpdateCurrentStatus();
1319 return ;
1321 m_RebaseStage=REBASE_CONTINUE;
1322 curRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
1323 m_forRewrite.push_back(curRev->m_CommitHash);
1324 this->UpdateCurrentStatus();
1327 if( m_RebaseStage == REBASE_CONFLICT )
1329 if(VerifyNoConflict())
1330 return;
1332 if (CAppUtils::MessageContainsConflictHints(GetSafeHwnd(), m_LogMessageCtrl.GetText()))
1333 return;
1335 m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1337 GitRevLoglist* curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1338 // ***************************************************
1339 // ATTENTION: Similar code in CommitDlg.cpp!!!
1340 // ***************************************************
1341 CMassiveGitTask mgtReAddAfterCommit(L"add --ignore-errors -f");
1342 CMassiveGitTask mgtReDelAfterCommit(L"rm --cached --ignore-unmatch");
1343 CMassiveGitTask mgtAdd(L"add -f");
1344 CMassiveGitTask mgtUpdateIndexForceRemove(L"update-index --force-remove");
1345 CMassiveGitTask mgtUpdateIndex(L"update-index");
1346 CMassiveGitTask mgtRm(L"rm --ignore-unmatch");
1347 CMassiveGitTask mgtRmFCache(L"rm -f --cache");
1348 CMassiveGitTask mgtReset(L"reset", TRUE, true);
1349 auto locker(m_FileListCtrl.AcquireReadLock());
1350 for (int i = 0; i < m_FileListCtrl.GetItemCount(); i++)
1352 auto entry = m_FileListCtrl.GetListEntry(i);
1353 if (entry->m_Checked)
1355 if ((entry->m_Action & CTGitPath::LOGACTIONS_UNVER) || (entry->IsDirectory() && !(entry->m_Action & CTGitPath::LOGACTIONS_DELETED)))
1356 mgtAdd.AddFile(entry->GetGitPathString());
1357 else if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED)
1358 mgtUpdateIndexForceRemove.AddFile(entry->GetGitPathString());
1359 else
1360 mgtUpdateIndex.AddFile(entry->GetGitPathString());
1362 if ((entry->m_Action & CTGitPath::LOGACTIONS_REPLACED) && !entry->GetGitOldPathString().IsEmpty())
1363 mgtRm.AddFile(entry->GetGitOldPathString());
1365 else
1367 if (entry->m_Action & CTGitPath::LOGACTIONS_ADDED || entry->m_Action & CTGitPath::LOGACTIONS_REPLACED)
1369 mgtRmFCache.AddFile(entry->GetGitPathString());
1370 mgtReAddAfterCommit.AddFile(*entry);
1372 if (entry->m_Action & CTGitPath::LOGACTIONS_REPLACED && !entry->GetGitOldPathString().IsEmpty())
1374 mgtReset.AddFile(entry->GetGitOldPathString());
1375 mgtReDelAfterCommit.AddFile(entry->GetGitOldPathString());
1378 else if(!(entry->m_Action & CTGitPath::LOGACTIONS_UNVER))
1380 mgtReset.AddFile(entry->GetGitPathString());
1381 if (entry->m_Action & CTGitPath::LOGACTIONS_DELETED && !(entry->m_Action & CTGitPath::LOGACTIONS_MISSING))
1382 mgtReDelAfterCommit.AddFile(entry->GetGitPathString());
1387 BOOL cancel = FALSE;
1388 bool successful = true;
1389 successful = successful && mgtAdd.Execute(cancel);
1390 successful = successful && mgtUpdateIndexForceRemove.Execute(cancel);
1391 successful = successful && mgtUpdateIndex.Execute(cancel);
1392 successful = successful && mgtRm.Execute(cancel);
1393 successful = successful && mgtRmFCache.Execute(cancel);
1394 successful = successful && mgtReset.Execute(cancel);
1396 if (!successful)
1398 AddLogString(L"An error occurred while updating the index.");
1399 return;
1402 CString allowempty;
1403 bool skipCurrent = false;
1404 if (!m_CurrentCommitEmpty)
1406 if (g_Git.IsResultingCommitBecomeEmpty() == TRUE)
1408 if (CheckNextCommitIsSquash() == 0)
1410 allowempty = L"--allow-empty ";
1411 m_CurrentCommitEmpty = false;
1413 else
1415 int choose = CMessageBox::ShowCheck(GetSafeHwnd(), IDS_CHERRYPICK_EMPTY, IDS_APPNAME, 1, IDI_QUESTION, IDS_COMMIT_COMMIT, IDS_SKIPBUTTON, IDS_MSGBOX_CANCEL, nullptr, 0);
1416 if (choose == 2)
1417 skipCurrent = true;
1418 else if (choose == 1)
1420 allowempty = L"--allow-empty ";
1421 m_CurrentCommitEmpty = true;
1423 else
1424 return;
1429 CString out;
1430 CString cmd;
1431 cmd.Format(L"git.exe commit %s--allow-empty-message -C %s", (LPCTSTR)allowempty, (LPCTSTR)curRev->m_CommitHash.ToString());
1433 AddLogString(cmd);
1435 if (!skipCurrent && g_Git.Run(cmd, &out, CP_UTF8))
1437 AddLogString(out);
1438 CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1439 return;
1442 AddLogString(out);
1444 // update commit message if needed
1445 CString str = m_LogMessageCtrl.GetText().Trim();
1446 if (!skipCurrent && str != (curRev->GetSubject() + L'\n' + curRev->GetBody()).Trim())
1448 if (str.IsEmpty())
1450 CMessageBox::Show(GetSafeHwnd(), IDS_PROC_COMMITMESSAGE_EMPTY,IDS_APPNAME, MB_OK | MB_ICONERROR);
1451 return;
1453 CString tempfile = ::GetTempFile();
1454 SCOPE_EXIT{ ::DeleteFile(tempfile); };
1455 if (CAppUtils::SaveCommitUnicodeFile(tempfile, str))
1457 CMessageBox::Show(GetSafeHwnd(), L"Could not save commit message", L"TortoiseGit", MB_OK | MB_ICONERROR);
1458 return;
1461 out.Empty();
1462 cmd.Format(L"git.exe commit --amend -F \"%s\"", (LPCTSTR)tempfile);
1463 AddLogString(cmd);
1465 if (g_Git.Run(cmd, &out, CP_UTF8))
1467 AddLogString(out);
1468 if (!g_Git.CheckCleanWorkTree())
1470 CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1471 return;
1473 CString retry;
1474 retry.LoadString(IDS_MSGBOX_RETRY);
1475 CString ignore;
1476 ignore.LoadString(IDS_MSGBOX_IGNORE);
1477 if (CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", 1, IDI_ERROR, retry, ignore) == 1)
1478 return;
1481 AddLogString(out);
1484 if (((DWORD)CRegStdDWORD(L"Software\\TortoiseGit\\ReaddUnselectedAddedFilesAfterCommit", TRUE)) == TRUE)
1486 BOOL cancel2 = FALSE;
1487 mgtReAddAfterCommit.Execute(cancel2);
1488 mgtReDelAfterCommit.Execute(cancel2);
1491 if (curRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_EDIT)
1493 m_RebaseStage=REBASE_EDIT;
1494 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_MESSAGE);
1495 this->UpdateCurrentStatus();
1496 return;
1498 else
1500 m_RebaseStage=REBASE_CONTINUE;
1501 curRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
1502 this->UpdateCurrentStatus();
1504 if (CheckNextCommitIsSquash() == 0) // remember commit msg after edit if next commit if squash
1505 ResetParentForSquash(str);
1506 else
1508 m_SquashMessage.Empty();
1509 CGitHash head;
1510 if (g_Git.GetHash(head, L"HEAD"))
1512 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1513 return;
1515 m_rewrittenCommitsMap[curRev->m_CommitHash] = head;
1520 if ((m_RebaseStage == REBASE_EDIT || m_RebaseStage == REBASE_CONTINUE || m_bSplitCommit || m_RebaseStage == REBASE_SQUASH_EDIT) && CheckNextCommitIsSquash() && (m_bSplitCommit || !g_Git.CheckCleanWorkTree(true)))
1522 if (!m_bSplitCommit && CMessageBox::Show(GetSafeHwnd(), IDS_PROC_REBASE_CONTINUE_NOTCLEAN, IDS_APPNAME, 1, IDI_ERROR, IDS_MSGBOX_OK, IDS_ABORTBUTTON) == 2)
1523 return;
1524 BOOL isFirst = TRUE;
1527 CCommitDlg dlg;
1528 if (isFirst)
1529 dlg.m_sLogMessage = m_LogMessageCtrl.GetText();
1530 dlg.m_bWholeProject = true;
1531 dlg.m_bSelectFilesForCommit = true;
1532 dlg.m_bCommitAmend = isFirst && (m_RebaseStage != REBASE_SQUASH_EDIT); // do not amend on squash_edit stage, we need a normal commit there
1533 if (isFirst && m_RebaseStage == REBASE_SQUASH_EDIT)
1535 if (m_iSquashdate != 2)
1536 dlg.SetTime(m_SquashFirstMetaData.time);
1537 dlg.SetAuthor(m_SquashFirstMetaData.GetAuthor());
1539 CTGitPathList gpl;
1540 gpl.AddPath(CTGitPath());
1541 dlg.m_pathList = gpl;
1542 dlg.m_bAmendDiffToLastCommit = !m_bSplitCommit;
1543 dlg.m_bNoPostActions = true;
1544 if (dlg.m_bCommitAmend)
1545 dlg.m_AmendStr = dlg.m_sLogMessage;
1546 dlg.m_bWarnDetachedHead = false;
1548 if (dlg.DoModal() != IDOK)
1549 return;
1551 isFirst = !m_bSplitCommit; // only select amend on second+ runs if not in split commit mode
1553 m_SquashMessage.Empty();
1554 m_CurrentCommitEmpty = dlg.m_bCommitMessageOnly;
1555 } while (!g_Git.CheckCleanWorkTree() || (m_bSplitCommit && CMessageBox::Show(GetSafeHwnd(), IDS_REBASE_ADDANOTHERCOMMIT, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) == IDYES));
1557 m_bSplitCommit = FALSE;
1558 UpdateData(FALSE);
1560 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1561 m_RebaseStage = REBASE_CONTINUE;
1562 GitRevLoglist* curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1563 CGitHash head;
1564 if (g_Git.GetHash(head, L"HEAD"))
1566 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1567 return;
1569 m_rewrittenCommitsMap[curRev->m_CommitHash] = head;
1570 for (const auto& hash : m_forRewrite)
1571 m_rewrittenCommitsMap[hash] = head;
1572 m_forRewrite.clear();
1573 curRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
1574 this->UpdateCurrentStatus();
1577 if( m_RebaseStage == REBASE_EDIT || m_RebaseStage == REBASE_SQUASH_EDIT )
1579 CString str;
1580 GitRevLoglist* curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1582 str=this->m_LogMessageCtrl.GetText();
1583 if(str.Trim().IsEmpty())
1585 CMessageBox::Show(GetSafeHwnd(), IDS_PROC_COMMITMESSAGE_EMPTY,IDS_APPNAME, MB_OK | MB_ICONERROR);
1586 return;
1589 CString tempfile=::GetTempFile();
1590 SCOPE_EXIT{ ::DeleteFile(tempfile); };
1591 if (CAppUtils::SaveCommitUnicodeFile(tempfile, str))
1593 CMessageBox::Show(GetSafeHwnd(), L"Could not save commit message", L"TortoiseGit", MB_OK | MB_ICONERROR);
1594 return;
1597 CString out, cmd, options;
1598 bool skipCurrent = false;
1599 if (m_CurrentCommitEmpty)
1600 options = L"--allow-empty ";
1601 else if (g_Git.IsResultingCommitBecomeEmpty(m_RebaseStage != REBASE_SQUASH_EDIT) == TRUE)
1603 int choose = CMessageBox::ShowCheck(GetSafeHwnd(), IDS_CHERRYPICK_EMPTY, IDS_APPNAME, 1, IDI_QUESTION, IDS_COMMIT_COMMIT, IDS_SKIPBUTTON, IDS_MSGBOX_CANCEL, nullptr, 0);
1604 if (choose == 2)
1605 skipCurrent = true;
1606 else if (choose == 1)
1608 options = L"--allow-empty ";
1609 m_CurrentCommitEmpty = true;
1611 else
1612 return;
1615 if (m_RebaseStage == REBASE_SQUASH_EDIT)
1616 cmd.Format(L"git.exe commit %s%s-F \"%s\"", (LPCTSTR)options, (LPCTSTR)m_SquashFirstMetaData.GetAsParam(m_iSquashdate == 2), (LPCTSTR)tempfile);
1617 else
1618 cmd.Format(L"git.exe commit --amend %s-F \"%s\"", (LPCTSTR)options, (LPCTSTR)tempfile);
1620 if (!skipCurrent && g_Git.Run(cmd, &out, CP_UTF8))
1622 if (!g_Git.CheckCleanWorkTree())
1624 CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1625 return;
1628 CString retry;
1629 retry.LoadString(IDS_MSGBOX_RETRY);
1630 CString ignore;
1631 ignore.LoadString(IDS_MSGBOX_IGNORE);
1632 if (CMessageBox::Show(GetSafeHwnd(), out, L"TortoiseGit", 1, IDI_ERROR, retry, ignore) == 1)
1633 return;
1636 AddLogString(out);
1637 if (CheckNextCommitIsSquash() == 0 && m_RebaseStage != REBASE_SQUASH_EDIT) // remember commit msg after edit if next commit if squash; but don't do this if ...->squash(reset here)->pick->squash
1639 ResetParentForSquash(str);
1641 else
1642 m_SquashMessage.Empty();
1643 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1644 m_RebaseStage=REBASE_CONTINUE;
1645 CGitHash head;
1646 if (g_Git.GetHash(head, L"HEAD"))
1648 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
1649 return;
1651 m_rewrittenCommitsMap[curRev->m_CommitHash] = head; // we had a reset to parent, so this is not the correct hash
1652 for (const auto& hash : m_forRewrite)
1653 m_rewrittenCommitsMap[hash] = head;
1654 m_forRewrite.clear();
1655 curRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
1656 this->UpdateCurrentStatus();
1660 InterlockedExchange(&m_bThreadRunning, TRUE);
1661 SetControlEnable();
1663 if (!AfxBeginThread(RebaseThreadEntry, this))
1665 InterlockedExchange(&m_bThreadRunning, FALSE);
1666 CMessageBox::Show(GetSafeHwnd(), L"Create Rebase Thread Fail", L"TortoiseGit", MB_OK | MB_ICONERROR);
1667 SetControlEnable();
1671 void CRebaseDlg::ResetParentForSquash(const CString& commitMessage)
1673 m_SquashMessage = commitMessage;
1674 // reset parent so that we can do "git cherry-pick --no-commit" w/o introducing an unwanted commit
1675 CString cmd = L"git.exe reset --soft HEAD~1";
1676 m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
1677 if (RunGitCmdRetryOrAbort(cmd))
1678 return;
1681 int CRebaseDlg::CheckNextCommitIsSquash()
1683 int index;
1684 if(m_CommitList.m_IsOldFirst)
1685 index=m_CurrentRebaseIndex+1;
1686 else
1687 index=m_CurrentRebaseIndex-1;
1689 GitRevLoglist* curRev;
1692 if(index<0)
1693 return -1;
1694 if(index>= m_CommitList.GetItemCount())
1695 return -1;
1697 curRev = m_CommitList.m_arShownList.SafeGetAt(index);
1699 if (curRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
1700 return 0;
1701 if (curRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_SKIP)
1703 if(m_CommitList.m_IsOldFirst)
1704 ++index;
1705 else
1706 --index;
1708 else
1709 return -1;
1711 } while(curRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_SKIP);
1713 return -1;
1716 int CRebaseDlg::GoNext()
1718 if(m_CommitList.m_IsOldFirst)
1719 ++m_CurrentRebaseIndex;
1720 else
1721 --m_CurrentRebaseIndex;
1722 return 0;
1725 void CRebaseDlg::SetContinueButtonText()
1727 CString Text;
1728 switch(this->m_RebaseStage)
1730 case CHOOSE_BRANCH:
1731 case CHOOSE_COMMIT_PICK_MODE:
1732 if(this->m_IsFastForward)
1733 Text.LoadString(IDS_PROC_STARTREBASEFFBUTTON);
1734 else
1735 Text.LoadString(IDS_PROC_STARTREBASEBUTTON);
1736 break;
1738 case REBASE_START:
1739 case REBASE_ERROR:
1740 case REBASE_CONTINUE:
1741 case REBASE_SQUASH_CONFLICT:
1742 Text.LoadString(IDS_CONTINUEBUTTON);
1743 break;
1745 case REBASE_CONFLICT:
1746 Text.LoadString(IDS_COMMITBUTTON);
1747 break;
1748 case REBASE_EDIT:
1749 Text.LoadString(IDS_AMENDBUTTON);
1750 break;
1752 case REBASE_SQUASH_EDIT:
1753 Text.LoadString(IDS_COMMITBUTTON);
1754 break;
1756 case REBASE_ABORT:
1757 case REBASE_FINISH:
1758 Text.LoadString(IDS_FINISHBUTTON);
1759 break;
1761 case REBASE_DONE:
1762 Text.LoadString(IDS_DONE);
1763 break;
1765 this->GetDlgItem(IDC_REBASE_CONTINUE)->SetWindowText(Text);
1768 void CRebaseDlg::SetControlEnable()
1770 switch(this->m_RebaseStage)
1772 case CHOOSE_BRANCH:
1773 case CHOOSE_COMMIT_PICK_MODE:
1775 this->GetDlgItem(IDC_SPLITALLOPTIONS)->EnableWindow(TRUE);
1776 this->GetDlgItem(IDC_BUTTON_UP)->EnableWindow(TRUE);
1777 this->GetDlgItem(IDC_BUTTON_DOWN)->EnableWindow(TRUE);
1778 this->GetDlgItem(IDC_BUTTON_ADD)->EnableWindow(!m_bPreserveMerges);
1779 m_CommitList.EnableDragnDrop(true);
1781 if(!m_IsCherryPick)
1783 this->GetDlgItem(IDC_REBASE_COMBOXEX_BRANCH)->EnableWindow(TRUE);
1784 this->GetDlgItem(IDC_REBASE_COMBOXEX_UPSTREAM)->EnableWindow(TRUE);
1785 this->GetDlgItem(IDC_BUTTON_REVERSE)->EnableWindow(TRUE);
1786 this->GetDlgItem(IDC_REBASE_CHECK_FORCE)->EnableWindow(TRUE);
1787 this->GetDlgItem(IDC_REBASE_CHECK_PRESERVEMERGES)->EnableWindow(TRUE);
1789 this->m_CommitList.m_ContextMenuMask |= m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REBASE_PICK)|
1790 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REBASE_SQUASH)|
1791 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REBASE_EDIT)|
1792 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_REBASE_SKIP)|
1793 m_CommitList.GetContextMenuBit(CGitLogListBase::ID_LOG);
1794 break;
1796 case REBASE_START:
1797 case REBASE_CONTINUE:
1798 case REBASE_ABORT:
1799 case REBASE_ERROR:
1800 case REBASE_FINISH:
1801 case REBASE_CONFLICT:
1802 case REBASE_EDIT:
1803 case REBASE_SQUASH_CONFLICT:
1804 case REBASE_DONE:
1805 this->GetDlgItem(IDC_SPLITALLOPTIONS)->EnableWindow(FALSE);
1806 this->GetDlgItem(IDC_REBASE_COMBOXEX_BRANCH)->EnableWindow(FALSE);
1807 this->GetDlgItem(IDC_REBASE_COMBOXEX_UPSTREAM)->EnableWindow(FALSE);
1808 this->GetDlgItem(IDC_BUTTON_REVERSE)->EnableWindow(FALSE);
1809 this->GetDlgItem(IDC_REBASE_CHECK_FORCE)->EnableWindow(FALSE);
1810 this->GetDlgItem(IDC_REBASE_CHECK_PRESERVEMERGES)->EnableWindow(FALSE);
1811 this->GetDlgItem(IDC_BUTTON_UP)->EnableWindow(FALSE);
1812 this->GetDlgItem(IDC_BUTTON_DOWN)->EnableWindow(FALSE);
1813 m_CommitList.EnableDragnDrop(false);
1814 this->GetDlgItem(IDC_BUTTON_ADD)->EnableWindow(FALSE);
1816 if( m_RebaseStage == REBASE_DONE && (this->m_PostButtonTexts.GetCount() != 0) )
1818 this->GetDlgItem(IDC_STATUS_STATIC)->ShowWindow(SW_HIDE);
1819 this->GetDlgItem(IDC_REBASE_POST_BUTTON)->ShowWindow(SW_SHOWNORMAL);
1820 this->m_PostButton.RemoveAll();
1821 this->m_PostButton.AddEntries(m_PostButtonTexts);
1822 //this->GetDlgItem(IDC_REBASE_POST_BUTTON)->SetWindowText(this->m_PostButtonText);
1824 break;
1827 GetDlgItem(IDC_REBASE_SPLIT_COMMIT)->ShowWindow((m_RebaseStage == REBASE_EDIT || m_RebaseStage == REBASE_SQUASH_EDIT) ? SW_SHOW : SW_HIDE);
1829 if(m_bThreadRunning)
1831 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(FALSE);
1834 else if (m_RebaseStage != REBASE_ERROR)
1836 this->GetDlgItem(IDC_REBASE_CONTINUE)->EnableWindow(TRUE);
1840 void CRebaseDlg::UpdateProgress()
1842 int index;
1843 CRect rect;
1845 if(m_CommitList.m_IsOldFirst)
1846 index = m_CurrentRebaseIndex+1;
1847 else
1848 index = m_CommitList.GetItemCount()-m_CurrentRebaseIndex;
1850 int finishedCommits = index - 1; // introduced an variable which shows the number handled revisions for the progress bars
1851 if (m_RebaseStage == REBASE_FINISH || finishedCommits == -1)
1852 finishedCommits = index;
1854 m_ProgressBar.SetRange32(0, m_CommitList.GetItemCount());
1855 m_ProgressBar.SetPos(finishedCommits);
1856 if (m_pTaskbarList)
1858 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NORMAL);
1859 m_pTaskbarList->SetProgressValue(m_hWnd, finishedCommits, m_CommitList.GetItemCount());
1862 if(m_CurrentRebaseIndex>=0 && m_CurrentRebaseIndex< m_CommitList.GetItemCount())
1864 CString text;
1865 text.FormatMessage(IDS_PROC_REBASING_PROGRESS, index, m_CommitList.GetItemCount());
1866 m_sStatusText = text;
1867 m_CtrlStatusText.SetWindowText(text);
1868 m_bStatusWarning = false;
1869 m_CtrlStatusText.Invalidate();
1872 GitRevLoglist* prevRev = nullptr, *curRev = nullptr;
1874 if (m_CurrentRebaseIndex >= 0 && m_CurrentRebaseIndex < (int)m_CommitList.m_arShownList.size())
1875 curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1877 for (int i = 0; i < (int)m_CommitList.m_arShownList.size(); ++i)
1879 prevRev = m_CommitList.m_arShownList.SafeGetAt(i);
1880 if (prevRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_CURRENT)
1882 prevRev->GetRebaseAction() &= ~CGitLogListBase::LOGACTIONS_REBASE_CURRENT;
1883 m_CommitList.GetItemRect(i,&rect,LVIR_BOUNDS);
1884 m_CommitList.InvalidateRect(rect);
1888 if(curRev)
1890 curRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_CURRENT;
1891 m_CommitList.GetItemRect(m_CurrentRebaseIndex,&rect,LVIR_BOUNDS);
1892 m_CommitList.InvalidateRect(rect);
1894 m_CommitList.EnsureVisible(m_CurrentRebaseIndex,FALSE);
1897 void CRebaseDlg::UpdateCurrentStatus()
1899 SetContinueButtonText();
1900 SetControlEnable();
1901 UpdateProgress();
1902 if (m_RebaseStage == REBASE_DONE)
1903 GetDlgItem(IDC_REBASE_CONTINUE)->SetFocus();
1906 void CRebaseDlg::AddLogString(const CString& str)
1908 this->m_wndOutputRebase.SendMessage(SCI_SETREADONLY, FALSE);
1909 CStringA sTextA = m_wndOutputRebase.StringForControl(str);//CUnicodeUtils::GetUTF8(str);
1910 this->m_wndOutputRebase.SendMessage(SCI_DOCUMENTEND);
1911 this->m_wndOutputRebase.SendMessage(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)sTextA);
1912 this->m_wndOutputRebase.SendMessage(SCI_REPLACESEL, 0, (LPARAM)(LPCSTR)"\n");
1913 this->m_wndOutputRebase.SendMessage(SCI_SETREADONLY, TRUE);
1916 int CRebaseDlg::GetCurrentCommitID()
1918 if(m_CommitList.m_IsOldFirst)
1919 return this->m_CurrentRebaseIndex+1;
1920 else
1921 return m_CommitList.GetItemCount()-m_CurrentRebaseIndex;
1924 int CRebaseDlg::IsCommitEmpty(const CGitHash& hash)
1926 CString cmd, tree, ptree;
1927 cmd.Format(L"git.exe rev-parse -q --verify %s^{tree}", (LPCTSTR)hash.ToString());
1928 if (g_Git.Run(cmd, &tree, CP_UTF8))
1930 AddLogString(cmd);
1931 AddLogString(tree);
1932 return -1;
1934 cmd.Format(L"git.exe rev-parse -q --verify %s^^{tree}", (LPCTSTR)hash.ToString());
1935 if (g_Git.Run(cmd, &ptree, CP_UTF8))
1936 ptree = L"4b825dc642cb6eb9a060e54bf8d69288fbee4904"; // empty tree
1937 return tree == ptree;
1940 static CString GetCommitTitle(const CGitHash& parentHash)
1942 CString str;
1943 GitRev rev;
1944 if (rev.GetCommit(parentHash.ToString()) == 0)
1946 CString commitTitle = rev.GetSubject();
1947 if (commitTitle.GetLength() > 20)
1949 commitTitle.Truncate(20);
1950 commitTitle += L"...";
1952 str.AppendFormat(L"\n%s (%s)", (LPCTSTR)commitTitle, (LPCTSTR)parentHash.ToString().Left(g_Git.GetShortHASHLength()));
1954 else
1955 str.AppendFormat(L"\n(%s)", (LPCTSTR)parentHash.ToString().Left(g_Git.GetShortHASHLength()));
1956 return str;
1959 int CRebaseDlg::DoRebase()
1961 CString cmd,out;
1962 if(m_CurrentRebaseIndex <0)
1963 return 0;
1964 if(m_CurrentRebaseIndex >= m_CommitList.GetItemCount() )
1965 return 0;
1967 GitRevLoglist* pRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
1968 int mode = pRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_MODE_MASK;
1969 CString nocommit;
1971 if (mode == CGitLogListBase::LOGACTIONS_REBASE_SKIP)
1973 pRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
1974 return 0;
1977 bool nextCommitIsSquash = (CheckNextCommitIsSquash() == 0);
1978 if (nextCommitIsSquash || mode != CGitLogListBase::LOGACTIONS_REBASE_PICK)
1979 { // next commit is squash or not pick
1980 if (!this->m_SquashMessage.IsEmpty())
1981 this->m_SquashMessage += L"\n\n";
1982 this->m_SquashMessage += pRev->GetSubject();
1983 this->m_SquashMessage += L'\n';
1984 this->m_SquashMessage += pRev->GetBody().TrimRight();
1985 if (m_bAddCherryPickedFrom)
1987 if (!pRev->GetBody().IsEmpty())
1988 m_SquashMessage += L'\n';
1989 m_SquashMessage += L"(cherry picked from commit ";
1990 m_SquashMessage += pRev->m_CommitHash.ToString();
1991 m_SquashMessage += L')';
1994 else
1996 this->m_SquashMessage.Empty();
1997 m_SquashFirstMetaData.Empty();
2000 if (nextCommitIsSquash && mode != CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2001 m_SquashFirstMetaData = SquashFirstMetaData(pRev);
2003 if ((nextCommitIsSquash && mode != CGitLogListBase::LOGACTIONS_REBASE_EDIT) || mode == CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2004 { // next or this commit is squash (don't do this on edit->squash sequence)
2005 nocommit = L" --no-commit ";
2006 if (m_iSquashdate == 1)
2007 m_SquashFirstMetaData.UpdateDate(pRev);
2010 CString log;
2011 log.Format(L"%s %d: %s", (LPCTSTR)CGitLogListBase::GetRebaseActionName(mode), GetCurrentCommitID(), (LPCTSTR)pRev->m_CommitHash.ToString());
2012 AddLogString(log);
2013 AddLogString(pRev->GetSubject());
2014 if (pRev->GetSubject().IsEmpty())
2016 CMessageBox::Show(m_hWnd, IDS_PROC_REBASE_EMPTYCOMMITMSG, IDS_APPNAME, MB_OK | MB_ICONEXCLAMATION);
2017 mode = CGitLogListBase::LOGACTIONS_REBASE_EDIT;
2020 CString cherryPickedFrom;
2021 if (m_bAddCherryPickedFrom)
2022 cherryPickedFrom = L"-x ";
2023 else if (!m_IsCherryPick && nocommit.IsEmpty())
2024 cherryPickedFrom = L"--ff "; // for issue #1833: "If the current HEAD is the same as the parent of the cherry-picked commit, then a fast forward to this commit will be performed."
2026 int isEmpty = IsCommitEmpty(pRev->m_CommitHash);
2027 if (isEmpty == 1)
2029 cherryPickedFrom += L"--allow-empty ";
2030 if (mode != CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2031 m_CurrentCommitEmpty = true;
2033 else if (isEmpty < 0)
2034 return -1;
2035 else
2036 m_CurrentCommitEmpty = false;
2038 if (m_IsCherryPick && pRev->m_ParentHash.size() > 1)
2040 CString msg;
2041 msg.FormatMessage(IDS_CHERRYPICK_MERGECOMMIT, (LPCTSTR)pRev->m_CommitHash.ToString(), (LPCTSTR)pRev->GetSubject());
2042 CString parent1;
2043 parent1.Format(IDS_PARENT, 1);
2044 parent1 += GetCommitTitle(pRev->m_ParentHash.at(0));
2045 CString parent2;
2046 parent2.Format(IDS_PARENT, 2);
2047 parent2 += GetCommitTitle(pRev->m_ParentHash.at(1));
2048 CString cancel;
2049 cancel.LoadString(IDS_MSGBOX_CANCEL);
2050 auto ret = CMessageBox::Show(m_hWnd, msg, L"TortoiseGit", 3, IDI_QUESTION, parent1, parent2, cancel);
2051 if (ret == 3)
2052 return - 1;
2054 cherryPickedFrom.AppendFormat(L"-m %d ", ret);
2057 while (true)
2059 cmd.Format(L"git.exe cherry-pick %s%s %s", (LPCTSTR)cherryPickedFrom, (LPCTSTR)nocommit, (LPCTSTR)pRev->m_CommitHash.ToString());
2060 if (m_bPreserveMerges)
2062 bool parentRewritten = false;
2063 CGitHash currentHeadHash;
2064 if (g_Git.GetHash(currentHeadHash, L"HEAD"))
2066 m_RebaseStage = REBASE_ERROR;
2067 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2068 return -1;
2070 if (!m_currentCommits.empty())
2072 for (const auto& commit : m_currentCommits)
2073 m_rewrittenCommitsMap[commit] = currentHeadHash;
2074 m_currentCommits.clear();
2076 m_currentCommits.push_back(pRev->m_CommitHash);
2077 GIT_REV_LIST possibleParents = pRev->m_ParentHash;
2078 GIT_REV_LIST newParents;
2079 for (auto it = possibleParents.cbegin(); it != possibleParents.cend(); it = possibleParents.begin())
2081 CGitHash parent = *it;
2082 possibleParents.erase(it);
2084 const auto rewrittenParent = m_rewrittenCommitsMap.find(parent);
2085 if (rewrittenParent == m_rewrittenCommitsMap.cend())
2087 auto droppedCommitParents = m_droppedCommitsMap.find(parent);
2088 if (droppedCommitParents != m_droppedCommitsMap.cend())
2090 parentRewritten = true;
2091 for (auto droppedIt = droppedCommitParents->second.crbegin(); droppedIt != droppedCommitParents->second.crend(); ++droppedIt)
2092 possibleParents.insert(possibleParents.begin(), *droppedIt);
2093 continue;
2096 newParents.push_back(parent);
2097 continue;
2100 if (rewrittenParent->second.IsEmpty() && parent == pRev->m_ParentHash[0] && pRev->ParentsCount() > 1)
2102 m_RebaseStage = REBASE_ERROR;
2103 AddLogString(L"");
2104 AddLogString(L"Unrecoverable error: Merge commit parent missing.");
2105 return -1;
2108 CGitHash newParent = rewrittenParent->second;
2109 if (newParent.IsEmpty()) // use current HEAD as fallback
2110 newParent = currentHeadHash;
2112 if (newParent != parent)
2113 parentRewritten = true;
2115 if (std::find(newParents.begin(), newParents.end(), newParent) == newParents.end())
2116 newParents.push_back(newParent);
2118 if (pRev->ParentsCount() > 1)
2120 if (mode == CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2122 m_RebaseStage = REBASE_ERROR;
2123 AddLogString(L"Cannot squash merge commit on rebase.");
2124 return -1;
2126 if (!parentRewritten && nocommit.IsEmpty())
2127 cmd.Format(L"git.exe reset --hard %s", (LPCTSTR)pRev->m_CommitHash.ToString());
2128 else
2130 CString parentString;
2131 for (const auto& parent : newParents)
2132 parentString += L' ' + parent.ToString();
2133 cmd.Format(L"git.exe checkout %s", (LPCTSTR)newParents[0].ToString());
2134 if (RunGitCmdRetryOrAbort(cmd))
2136 m_RebaseStage = REBASE_ERROR;
2137 return -1;
2139 cmd.Format(L"git.exe merge --no-ff%s %s", (LPCTSTR)nocommit, (LPCTSTR)parentString);
2140 if (nocommit.IsEmpty())
2142 if (g_Git.Run(cmd, &out, CP_UTF8))
2144 AddLogString(cmd);
2145 AddLogString(out);
2146 int hasConflicts = g_Git.HasWorkingTreeConflicts();
2147 if (hasConflicts > 0)
2149 m_RebaseStage = REBASE_CONFLICT;
2150 return -1;
2152 else if (hasConflicts < 0)
2153 AddLogString(g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS));
2154 AddLogString(L"An unrecoverable error occurred.");
2155 m_RebaseStage = REBASE_ERROR;
2156 return -1;
2158 CGitHash newHeadHash;
2159 if (g_Git.GetHash(newHeadHash, L"HEAD"))
2161 m_RebaseStage = REBASE_ERROR;
2162 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2163 return -1;
2165 // do nothing if already up2date
2166 if (currentHeadHash != newHeadHash)
2167 cmd.Format(L"git.exe commit --amend -C %s", (LPCTSTR)pRev->m_CommitHash.ToString());
2171 else
2173 if (mode != CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2175 cmd.Format(L"git.exe checkout %s", (LPCTSTR)newParents[0].ToString());
2176 if (RunGitCmdRetryOrAbort(cmd))
2178 m_RebaseStage = REBASE_ERROR;
2179 return -1;
2182 cmd.Format(L"git.exe cherry-pick %s%s %s", (LPCTSTR)cherryPickedFrom, (LPCTSTR)nocommit, (LPCTSTR)pRev->m_CommitHash.ToString());
2186 if(g_Git.Run(cmd,&out,CP_UTF8))
2188 AddLogString(out);
2189 int hasConflicts = g_Git.HasWorkingTreeConflicts();
2190 if (hasConflicts < 0)
2192 AddLogString(g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS));
2193 return -1;
2195 if (!hasConflicts)
2197 if (out.Find(L"commit --allow-empty") > 0)
2199 int choose = CMessageBox::ShowCheck(GetSafeHwnd(), IDS_CHERRYPICK_EMPTY, IDS_APPNAME, 1, IDI_QUESTION, IDS_COMMIT_COMMIT, IDS_SKIPBUTTON, IDS_MSGBOX_CANCEL, nullptr, 0);
2200 if (choose != 1)
2202 if (choose == 2 && !RunGitCmdRetryOrAbort(L"git.exe reset --hard"))
2204 pRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
2205 m_CommitList.Invalidate();
2206 return 0;
2209 m_RebaseStage = REBASE_ERROR;
2210 AddLogString(L"An unrecoverable error occurred.");
2211 return -1;
2214 cmd.Format(L"git.exe commit --allow-empty -C %s", (LPCTSTR)pRev->m_CommitHash.ToString());
2215 out.Empty();
2216 g_Git.Run(cmd, &out, CP_UTF8);
2217 m_CurrentCommitEmpty = true;
2219 else if (mode == CGitLogListBase::LOGACTIONS_REBASE_PICK)
2221 if (m_pTaskbarList)
2222 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
2223 int choose = -1;
2224 if (!m_bAutoSkipFailedCommit)
2226 choose = CMessageBox::ShowCheck(GetSafeHwnd(), IDS_CHERRYPICKFAILEDSKIP, IDS_APPNAME, 1, IDI_QUESTION, IDS_SKIPBUTTON, IDS_MSGBOX_RETRY, IDS_MSGBOX_CANCEL, nullptr, IDS_DO_SAME_FOR_REST, &m_bAutoSkipFailedCommit);
2227 if (choose == 2)
2229 m_bAutoSkipFailedCommit = FALSE;
2230 continue; // retry cherry pick
2233 if (m_bAutoSkipFailedCommit || choose == 1)
2235 if (!RunGitCmdRetryOrAbort(L"git.exe reset --hard"))
2237 pRev->GetRebaseAction() = CGitLogListBase::LOGACTIONS_REBASE_SKIP;
2238 m_CommitList.Invalidate();
2239 return 0;
2243 m_RebaseStage = REBASE_ERROR;
2244 AddLogString(L"An unrecoverable error occurred.");
2245 return -1;
2247 else if (mode == CGitLogListBase::LOGACTIONS_REBASE_EDIT)
2249 this->m_RebaseStage = REBASE_EDIT ;
2250 return -1; // Edit return -1 to stop rebase.
2252 // Squash Case
2253 else if (CheckNextCommitIsSquash())
2254 { // no squash
2255 // let user edit last commmit message
2256 this->m_RebaseStage = REBASE_SQUASH_EDIT;
2257 return -1;
2260 else
2262 if (m_pTaskbarList)
2263 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
2264 if (mode == CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2265 m_RebaseStage = REBASE_SQUASH_CONFLICT;
2266 else
2267 m_RebaseStage = REBASE_CONFLICT;
2268 return -1;
2272 AddLogString(out);
2273 if (mode == CGitLogListBase::LOGACTIONS_REBASE_PICK)
2275 if (nocommit.IsEmpty())
2277 CGitHash head;
2278 if (g_Git.GetHash(head, L"HEAD"))
2280 MessageBox(g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2281 m_RebaseStage = REBASE_ERROR;
2282 return -1;
2284 m_rewrittenCommitsMap[pRev->m_CommitHash] = head;
2286 else
2287 m_forRewrite.push_back(pRev->m_CommitHash);
2288 pRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
2289 return 0;
2291 if (mode == CGitLogListBase::LOGACTIONS_REBASE_EDIT)
2293 this->m_RebaseStage = REBASE_EDIT;
2294 return -1; // Edit return -1 to stop rebase.
2297 // Squash Case
2298 if (CheckNextCommitIsSquash())
2299 { // no squash
2300 // let user edit last commmit message
2301 this->m_RebaseStage = REBASE_SQUASH_EDIT;
2302 return -1;
2304 else if (mode == CGitLogListBase::LOGACTIONS_REBASE_SQUASH)
2306 pRev->GetRebaseAction() |= CGitLogListBase::LOGACTIONS_REBASE_DONE;
2307 m_forRewrite.push_back(pRev->m_CommitHash);
2310 return 0;
2314 BOOL CRebaseDlg::IsEnd()
2316 if(m_CommitList.m_IsOldFirst)
2317 return m_CurrentRebaseIndex>= this->m_CommitList.GetItemCount();
2318 else
2319 return m_CurrentRebaseIndex<0;
2322 int CRebaseDlg::RebaseThread()
2324 CBlockCacheForPath cacheBlock(g_Git.m_CurrentDir);
2326 int ret=0;
2327 while (!m_bAbort)
2329 if( m_RebaseStage == REBASE_START )
2331 if( this->StartRebase() )
2333 ret = -1;
2334 break;
2336 m_RebaseStage = REBASE_CONTINUE;
2338 else if( m_RebaseStage == REBASE_CONTINUE )
2340 this->GoNext();
2341 SendMessage(MSG_REBASE_UPDATE_UI);
2342 if(IsEnd())
2344 ret = 0;
2345 m_RebaseStage = REBASE_FINISH;
2347 else
2349 ret = DoRebase();
2350 if( ret )
2351 break;
2354 else if( m_RebaseStage == REBASE_FINISH )
2356 SendMessage(MSG_REBASE_UPDATE_UI);
2357 m_RebaseStage = REBASE_DONE;
2358 break;
2360 else
2361 break;
2362 this->PostMessage(MSG_REBASE_UPDATE_UI);
2365 InterlockedExchange(&m_bThreadRunning, FALSE);
2366 this->PostMessage(MSG_REBASE_UPDATE_UI);
2367 if (m_bAbort)
2368 PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_ABORT, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_ABORT)->GetSafeHwnd());
2369 return ret;
2372 void CRebaseDlg::ListConflictFile(bool noStoreScrollPosition)
2374 if (!noStoreScrollPosition)
2375 m_FileListCtrl.StoreScrollPos();
2376 this->m_FileListCtrl.Clear();
2377 m_FileListCtrl.SetHasCheckboxes(true);
2379 if (!m_IsCherryPick)
2381 CString adminDir;
2382 if (GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
2384 CString dir(adminDir + L"tgitrebase.active");
2385 ::CreateDirectory(dir, nullptr);
2386 CStringUtils::WriteStringToTextFile(dir + L"\\head-name", m_BranchCtrl.GetString());
2387 CStringUtils::WriteStringToTextFile(dir + L"\\onto", m_Onto.IsEmpty() ? m_UpstreamCtrl.GetString() : m_Onto);
2391 this->m_FileListCtrl.GetStatus(nullptr, true);
2392 m_FileListCtrl.Show(CTGitPath::LOGACTIONS_UNMERGED | CTGitPath::LOGACTIONS_MODIFIED | CTGitPath::LOGACTIONS_ADDED | CTGitPath::LOGACTIONS_DELETED | CTGitPath::LOGACTIONS_REPLACED, CTGitPath::LOGACTIONS_UNMERGED);
2394 m_FileListCtrl.Check(GITSLC_SHOWFILES);
2395 bool hasSubmoduleChange = false;
2396 auto locker(m_FileListCtrl.AcquireReadLock());
2397 for (int i = 0; i < m_FileListCtrl.GetItemCount(); i++)
2399 auto entry = m_FileListCtrl.GetListEntry(i);
2400 if (entry->IsDirectory())
2402 hasSubmoduleChange = true;
2403 break;
2407 if (hasSubmoduleChange)
2409 m_CtrlStatusText.SetWindowText(m_sStatusText + L", " + CString(MAKEINTRESOURCE(IDS_CARE_SUBMODULE_CHANGES)));
2410 m_bStatusWarning = true;
2411 m_CtrlStatusText.Invalidate();
2413 else
2415 m_CtrlStatusText.SetWindowText(m_sStatusText);
2416 m_bStatusWarning = false;
2417 m_CtrlStatusText.Invalidate();
2421 LRESULT CRebaseDlg::OnRebaseUpdateUI(WPARAM,LPARAM)
2423 if (m_RebaseStage == REBASE_FINISH)
2425 FinishRebase();
2426 return 0;
2428 UpdateCurrentStatus();
2430 if (m_RebaseStage == REBASE_DONE && m_bRebaseAutoEnd)
2432 m_bRebaseAutoEnd = false;
2433 this->PostMessage(WM_COMMAND, MAKELONG(IDC_REBASE_CONTINUE, BN_CLICKED), (LPARAM)GetDlgItem(IDC_REBASE_CONTINUE)->GetSafeHwnd());
2436 if (m_RebaseStage == REBASE_DONE && m_pTaskbarList)
2437 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS); // do not show progress on taskbar any more to show we finished
2438 if(m_CurrentRebaseIndex <0)
2439 return 0;
2440 if(m_CurrentRebaseIndex >= m_CommitList.GetItemCount() )
2441 return 0;
2442 GitRev* curRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
2444 switch(m_RebaseStage)
2446 case REBASE_CONFLICT:
2447 case REBASE_SQUASH_CONFLICT:
2449 ListConflictFile(true);
2450 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_CONFLICT);
2451 if (m_pTaskbarList)
2452 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_ERROR);
2453 this->m_LogMessageCtrl.Call(SCI_SETREADONLY, FALSE);
2454 CString logMessage;
2455 if (m_IsCherryPick)
2457 CString dotGitPath;
2458 GitAdminDir::GetWorktreeAdminDirPath(g_Git.m_CurrentDir, dotGitPath);
2459 // vanilla git also re-uses MERGE_MSG on conflict (listing all conflicted files)
2460 // and it's also needed for cherry-pick in order to get cherry-picked-from included on conflicts
2461 CGit::LoadTextFile(dotGitPath + L"MERGE_MSG", logMessage);
2463 if (logMessage.IsEmpty())
2464 logMessage = curRev->GetSubject() + L'\n' + curRev->GetBody();
2465 this->m_LogMessageCtrl.SetText(logMessage);
2466 break;
2468 case REBASE_EDIT:
2469 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_MESSAGE);
2470 if (m_pTaskbarList)
2471 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_PAUSED);
2472 this->m_LogMessageCtrl.Call(SCI_SETREADONLY, FALSE);
2473 if (m_bAddCherryPickedFrom)
2475 // Since the new commit is done and the HEAD points to it,
2476 // just using the new body modified by git self.
2477 GitRev headRevision;
2478 if (headRevision.GetCommit(L"HEAD"))
2479 MessageBox(headRevision.GetLastErr(), L"TortoiseGit", MB_ICONERROR);
2481 m_LogMessageCtrl.SetText(headRevision.GetSubject() + L'\n' + headRevision.GetBody());
2483 else
2484 m_LogMessageCtrl.SetText(curRev->GetSubject() + L'\n' + curRev->GetBody());
2485 break;
2486 case REBASE_SQUASH_EDIT:
2487 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_MESSAGE);
2488 this->m_LogMessageCtrl.Call(SCI_SETREADONLY, FALSE);
2489 this->m_LogMessageCtrl.SetText(this->m_SquashMessage);
2490 if (m_pTaskbarList)
2491 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_PAUSED);
2492 break;
2493 default:
2494 this->m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
2496 return 0;
2499 void CRebaseDlg::OnCancel()
2501 OnBnClickedAbort();
2504 void CRebaseDlg::OnBnClickedAbort()
2506 if (m_bThreadRunning)
2508 if (CMessageBox::Show(GetSafeHwnd(), IDS_PROC_REBASE_ABORT, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) != IDYES)
2509 return;
2510 m_bAbort = TRUE;
2511 return;
2514 if (m_pTaskbarList)
2515 m_pTaskbarList->SetProgressState(m_hWnd, TBPF_NOPROGRESS);
2517 m_tooltips.Pop();
2519 SaveSplitterPos();
2521 if(m_OrigUpstreamHash.IsEmpty())
2523 __super::OnCancel();
2524 return;
2527 if(m_RebaseStage == CHOOSE_BRANCH || m_RebaseStage== CHOOSE_COMMIT_PICK_MODE)
2529 __super::OnCancel();
2530 goto end;
2533 if (!m_bAbort && CMessageBox::Show(GetSafeHwnd(), IDS_PROC_REBASE_ABORT, IDS_APPNAME, MB_YESNO | MB_ICONQUESTION) != IDYES)
2534 return;
2536 m_ctrlTabCtrl.SetActiveTab(REBASE_TAB_LOG);
2538 if (g_Git.m_IsUseLibGit2 && !m_IsCherryPick)
2540 CAutoRepository repo(g_Git.GetGitRepository());
2541 CAutoReflog reflog;
2542 git_reflog_read(reflog.GetPointer(), repo, "HEAD");
2543 CAutoSignature signature;
2544 git_signature_default(signature.GetPointer(), repo);
2545 git_reflog_append(reflog, m_OrigHEADHash, signature, "rebase: begin aborting...");
2546 git_reflog_write(reflog);
2549 if(this->m_IsFastForward)
2551 CString cmd;
2552 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)this->m_OrigBranchHash.ToString());
2553 RunGitCmdRetryOrAbort(cmd);
2554 __super::OnCancel();
2555 goto end;
2558 if (m_IsCherryPick) // there are not "branch" at cherry pick mode
2560 CString cmd;
2561 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)m_OrigUpstreamHash.ToString());
2562 RunGitCmdRetryOrAbort(cmd);
2563 __super::OnCancel();
2564 goto end;
2567 if (m_OrigHEADBranch == m_BranchCtrl.GetString())
2569 CString cmd, out;
2570 if (g_Git.IsLocalBranch(m_OrigHEADBranch))
2571 cmd.Format(L"git.exe checkout -f -B %s %s --", (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)m_OrigBranchHash.ToString());
2572 else
2573 cmd.Format(L"git.exe checkout -f %s --", (LPCTSTR)m_OrigBranchHash.ToString());
2574 if (g_Git.Run(cmd, &out, CP_UTF8))
2576 AddLogString(out);
2577 ::MessageBox(m_hWnd, L"Unrecoverable error on cleanup:\n" + out, L"TortoiseGit", MB_ICONERROR);
2578 __super::OnCancel();
2579 goto end;
2582 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)m_OrigBranchHash.ToString());
2583 RunGitCmdRetryOrAbort(cmd);
2585 else
2587 CString cmd, out;
2588 if (m_OrigHEADBranch != g_Git.GetCurrentBranch(true))
2590 if (g_Git.IsLocalBranch(m_OrigHEADBranch))
2591 cmd.Format(L"git.exe checkout -f -B %s %s --", (LPCTSTR)m_OrigHEADBranch, (LPCTSTR)m_OrigHEADHash.ToString());
2592 else
2593 cmd.Format(L"git.exe checkout -f %s --", (LPCTSTR)m_OrigHEADHash.ToString());
2594 if (g_Git.Run(cmd, &out, CP_UTF8))
2596 AddLogString(out);
2597 ::MessageBox(m_hWnd, L"Unrecoverable error on cleanup:\n" + out, L"TortoiseGit", MB_ICONERROR);
2598 // continue to restore moved branch
2602 cmd.Format(L"git.exe reset --hard %s --", (LPCTSTR)m_OrigHEADHash.ToString());
2603 RunGitCmdRetryOrAbort(cmd);
2605 // restore moved branch
2606 if (g_Git.IsLocalBranch(m_BranchCtrl.GetString()))
2608 cmd.Format(L"git.exe branch -f %s %s --", (LPCTSTR)m_BranchCtrl.GetString(), (LPCTSTR)m_OrigBranchHash.ToString());
2609 if (g_Git.Run(cmd, &out, CP_UTF8))
2611 AddLogString(out);
2612 ::MessageBox(m_hWnd, L"Unrecoverable error on cleanup:\n" + out, L"TortoiseGit", MB_ICONERROR);
2613 __super::OnCancel();
2614 goto end;
2618 if (g_Git.m_IsUseLibGit2)
2620 CAutoRepository repo(g_Git.GetGitRepository());
2621 CAutoReflog reflog;
2622 git_reflog_read(reflog.GetPointer(), repo, "HEAD");
2623 CAutoSignature signature;
2624 git_signature_default(signature.GetPointer(), repo);
2625 git_reflog_append(reflog, m_OrigHEADHash, signature, "rebase: aborted");
2626 git_reflog_write(reflog);
2628 __super::OnCancel();
2629 end:
2630 CleanUpRebaseActiveFolder();
2631 CheckRestoreStash();
2634 void CRebaseDlg::OnBnClickedButtonReverse()
2636 CString temp = m_BranchCtrl.GetString();
2637 m_BranchCtrl.AddString(m_UpstreamCtrl.GetString());
2638 m_UpstreamCtrl.AddString(temp);
2639 OnCbnSelchangeUpstream();
2642 void CRebaseDlg::OnBnClickedButtonBrowse()
2644 if (CBrowseRefsDlg::PickRefForCombo(m_UpstreamCtrl))
2645 OnCbnSelchangeUpstream();
2648 void CRebaseDlg::OnBnClickedRebaseCheckForce()
2650 this->UpdateData();
2651 GetDlgItem(IDC_BUTTON_ADD)->EnableWindow(!m_bPreserveMerges);
2652 this->FetchLogList();
2655 void CRebaseDlg::OnBnClickedRebasePostButton()
2657 this->m_Upstream=this->m_UpstreamCtrl.GetString();
2658 this->m_Branch=this->m_BranchCtrl.GetString();
2660 this->EndDialog((int)(IDC_REBASE_POST_BUTTON+this->m_PostButton.GetCurrentEntry()));
2663 LRESULT CRebaseDlg::OnGitStatusListCtrlNeedsRefresh(WPARAM, LPARAM)
2665 Refresh();
2666 return 0;
2669 void CRebaseDlg::Refresh()
2671 if (m_RebaseStage == REBASE_CONFLICT || m_RebaseStage == REBASE_SQUASH_CONFLICT)
2673 ListConflictFile(false);
2674 return;
2677 if(this->m_IsCherryPick)
2678 return ;
2680 if(this->m_RebaseStage == CHOOSE_BRANCH )
2682 this->UpdateData();
2683 this->FetchLogList();
2687 void CRebaseDlg::OnBnClickedButtonUp()
2689 POSITION pos;
2690 pos = m_CommitList.GetFirstSelectedItemPosition();
2692 bool moveToTop = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
2693 // do nothing if the first selected item is the first item in the list
2694 if (!moveToTop && m_CommitList.GetNextSelectedItem(pos) == 0)
2695 return;
2697 pos = m_CommitList.GetFirstSelectedItemPosition();
2699 int count = 0;
2700 bool changed = false;
2701 while(pos)
2703 int index=m_CommitList.GetNextSelectedItem(pos);
2704 count = moveToTop ? count : (index - 1);
2705 while (index > count)
2707 std::swap(m_CommitList.m_logEntries[index], m_CommitList.m_logEntries[index - 1]);
2708 std::swap(m_CommitList.m_arShownList[index], m_CommitList.m_arShownList[index - 1]);
2709 m_CommitList.SetItemState(index - 1, LVIS_SELECTED, LVIS_SELECTED);
2710 m_CommitList.SetItemState(index, 0, LVIS_SELECTED);
2711 changed = true;
2712 index--;
2714 count++;
2716 if (changed)
2718 pos = m_CommitList.GetFirstSelectedItemPosition();
2719 m_CommitList.EnsureVisible(m_CommitList.GetNextSelectedItem(pos), false);
2720 m_CommitList.Invalidate();
2721 m_CommitList.SetFocus();
2725 void CRebaseDlg::OnBnClickedButtonDown()
2727 if (m_CommitList.GetSelectedCount() == 0)
2728 return;
2730 bool moveToBottom = !!(GetAsyncKeyState(VK_SHIFT) & 0x8000);
2731 POSITION pos;
2732 pos = m_CommitList.GetFirstSelectedItemPosition();
2733 bool changed = false;
2734 // use an array to store all selected item indexes; the user won't select too much items
2735 auto indexes = std::make_unique<int[]>(m_CommitList.GetSelectedCount());
2736 int i = 0;
2737 while(pos)
2738 indexes[i++] = m_CommitList.GetNextSelectedItem(pos);
2739 // don't move any item if the last selected item is the last item in the m_CommitList
2740 // (that would change the order of the selected items)
2741 if (!moveToBottom && indexes[m_CommitList.GetSelectedCount() - 1] >= m_CommitList.GetItemCount() - 1)
2742 return;
2743 int count = m_CommitList.GetItemCount() - 1;
2744 // iterate over the indexes backwards in order to correctly move multiselected items
2745 for (i = m_CommitList.GetSelectedCount() - 1; i >= 0; i--)
2747 int index = indexes[i];
2748 count = moveToBottom ? count : (index + 1);
2749 while (index < count)
2751 std::swap(m_CommitList.m_logEntries[index], m_CommitList.m_logEntries[index + 1]);
2752 std::swap(m_CommitList.m_arShownList[index], m_CommitList.m_arShownList[index + 1]);
2753 m_CommitList.SetItemState(index, 0, LVIS_SELECTED);
2754 m_CommitList.SetItemState(index + 1, LVIS_SELECTED, LVIS_SELECTED);
2755 changed = true;
2756 index++;
2758 count--;
2760 m_CommitList.EnsureVisible(indexes[m_CommitList.GetSelectedCount() - 1] + 1, false);
2761 if (changed)
2763 m_CommitList.Invalidate();
2764 m_CommitList.SetFocus();
2768 LRESULT CRebaseDlg::OnCommitsReordered(WPARAM wParam, LPARAM /*lParam*/)
2770 POSITION pos = m_CommitList.GetFirstSelectedItemPosition();
2771 int first = m_CommitList.GetNextSelectedItem(pos);
2772 int last = first;
2773 while (pos)
2774 last = m_CommitList.GetNextSelectedItem(pos);
2775 ++last;
2777 for (int i = first; i < last; ++i)
2778 m_CommitList.SetItemState(i, 0, LVIS_SELECTED);
2780 int dest = (int)wParam;
2781 if (dest > first)
2783 std::rotate(m_CommitList.m_logEntries.begin() + first, m_CommitList.m_logEntries.begin() + last, m_CommitList.m_logEntries.begin() + dest);
2784 std::rotate(m_CommitList.m_arShownList.begin() + first, m_CommitList.m_arShownList.begin() + last, m_CommitList.m_arShownList.begin() + dest);
2785 for (int i = first + dest - last; i < dest; ++i)
2786 m_CommitList.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2788 else
2790 std::rotate(m_CommitList.m_logEntries.begin() + dest, m_CommitList.m_logEntries.begin() + first, m_CommitList.m_logEntries.begin() + last);
2791 std::rotate(m_CommitList.m_arShownList.begin() + dest, m_CommitList.m_arShownList.begin() + first, m_CommitList.m_arShownList.begin() + last);
2792 for (int i = dest; i < dest + (last - first); ++i)
2793 m_CommitList.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
2796 m_CommitList.Invalidate();
2798 return 0;
2801 LRESULT CRebaseDlg::OnTaskbarBtnCreated(WPARAM wParam, LPARAM lParam)
2803 m_pTaskbarList.Release();
2804 m_pTaskbarList.CoCreateInstance(CLSID_TaskbarList);
2805 return __super::OnTaskbarButtonCreated(wParam, lParam);
2808 void CRebaseDlg::OnLvnItemchangedLoglist(NMHDR *pNMHDR, LRESULT *pResult)
2810 LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
2811 *pResult = 0;
2812 if(m_CommitList.m_bNoDispUpdates)
2813 return;
2814 if (pNMLV->iItem >= 0)
2816 this->m_CommitList.m_nSearchIndex = pNMLV->iItem;
2817 if (pNMLV->iSubItem != 0)
2818 return;
2819 if (pNMLV->iItem == (int)m_CommitList.m_arShownList.size())
2821 // remove the selected state
2822 if (pNMLV->uChanged & LVIF_STATE)
2824 m_CommitList.SetItemState(pNMLV->iItem, 0, LVIS_SELECTED);
2825 FillLogMessageCtrl();
2827 return;
2829 if (pNMLV->uChanged & LVIF_STATE)
2830 FillLogMessageCtrl();
2832 else
2833 FillLogMessageCtrl();
2836 void CRebaseDlg::FillLogMessageCtrl()
2838 int selCount = m_CommitList.GetSelectedCount();
2839 if (selCount == 1 && (m_RebaseStage == CHOOSE_BRANCH || m_RebaseStage == CHOOSE_COMMIT_PICK_MODE))
2841 POSITION pos = m_CommitList.GetFirstSelectedItemPosition();
2842 int selIndex = m_CommitList.GetNextSelectedItem(pos);
2843 GitRevLoglist* pLogEntry = m_CommitList.m_arShownList.SafeGetAt(selIndex);
2844 m_FileListCtrl.UpdateWithGitPathList(pLogEntry->GetFiles(&m_CommitList));
2845 m_FileListCtrl.m_CurrentVersion = pLogEntry->m_CommitHash.ToString();
2846 m_FileListCtrl.Show(GITSLC_SHOWVERSIONED);
2847 m_LogMessageCtrl.Call(SCI_SETREADONLY, FALSE);
2848 m_LogMessageCtrl.SetText(pLogEntry->GetSubject() + L'\n' + pLogEntry->GetBody());
2849 m_LogMessageCtrl.Call(SCI_SETREADONLY, TRUE);
2852 void CRebaseDlg::OnBnClickedCheckCherryPickedFrom()
2854 UpdateData();
2857 LRESULT CRebaseDlg::OnRebaseActionMessage(WPARAM, LPARAM)
2859 if (m_RebaseStage == REBASE_ERROR || m_RebaseStage == REBASE_CONFLICT)
2861 GitRevLoglist* pRev = m_CommitList.m_arShownList.SafeGetAt(m_CurrentRebaseIndex);
2862 int mode = pRev->GetRebaseAction() & CGitLogListBase::LOGACTIONS_REBASE_MODE_MASK;
2863 if (mode == CGitLogListBase::LOGACTIONS_REBASE_SKIP)
2865 if (!RunGitCmdRetryOrAbort(L"git.exe reset --hard"))
2867 m_FileListCtrl.Clear();
2868 m_RebaseStage = REBASE_CONTINUE;
2869 UpdateCurrentStatus();
2873 return 0;
2877 void CRebaseDlg::OnBnClickedSplitAllOptions()
2879 switch (m_SplitAllOptions.GetCurrentEntry())
2881 case 0:
2882 SetAllRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_PICK);
2883 break;
2884 case 1:
2885 SetAllRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_SQUASH);
2886 break;
2887 case 2:
2888 SetAllRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_EDIT);
2889 break;
2890 case 3:
2891 m_CommitList.SetUnselectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_SKIP);
2892 break;
2893 case 4:
2894 m_CommitList.SetUnselectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_SQUASH);
2895 break;
2896 case 5:
2897 m_CommitList.SetUnselectedRebaseAction(CGitLogListBase::LOGACTIONS_REBASE_EDIT);
2898 break;
2899 default:
2900 ATLASSERT(false);
2904 void CRebaseDlg::OnBnClickedRebaseSplitCommit()
2906 UpdateData();
2909 static bool GetCompareHash(const CString& ref, const CGitHash& hash)
2911 CGitHash refHash;
2912 if (g_Git.GetHash(refHash, ref))
2913 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get hash of \"" + ref + L"\"."), L"TortoiseGit", MB_ICONERROR);
2914 return refHash.IsEmpty() || (hash == refHash);
2917 void CRebaseDlg::OnBnClickedButtonOnto()
2919 m_Onto = CBrowseRefsDlg::PickRef(false, m_Onto);
2920 if (!m_Onto.IsEmpty())
2922 // make sure that the user did not select upstream, selected branch or HEAD
2923 CGitHash hash;
2924 if (g_Git.GetHash(hash, m_Onto))
2926 MessageBox(g_Git.GetGitLastErr(L"Could not get hash of \"" + m_BranchCtrl.GetString() + L"\"."), L"TortoiseGit", MB_ICONERROR);
2927 m_Onto.Empty();
2928 ((CButton*)GetDlgItem(IDC_BUTTON_ONTO))->SetCheck(m_Onto.IsEmpty() ? BST_UNCHECKED : BST_CHECKED);
2929 return;
2931 if (GetCompareHash(L"HEAD", hash) || GetCompareHash(m_UpstreamCtrl.GetString(), hash) || GetCompareHash(m_BranchCtrl.GetString(), hash))
2932 m_Onto.Empty();
2934 if (m_Onto.IsEmpty())
2935 m_tooltips.DelTool(IDC_BUTTON_ONTO);
2936 else
2937 m_tooltips.AddTool(IDC_BUTTON_ONTO, m_Onto);
2938 ((CButton*)GetDlgItem(IDC_BUTTON_ONTO))->SetCheck(m_Onto.IsEmpty() ? BST_UNCHECKED : BST_CHECKED);
2939 FetchLogList();
2942 void CRebaseDlg::OnHelp()
2944 HtmlHelp(0x20000 + (m_IsCherryPick ? IDD_REBASECHERRYPICK : IDD_REBASE));
2947 int CRebaseDlg::RunGitCmdRetryOrAbort(const CString& cmd)
2949 while (true)
2951 CString out;
2952 if (g_Git.Run(cmd, &out, CP_UTF8))
2954 AddLogString(cmd);
2955 AddLogString(CString(MAKEINTRESOURCE(IDS_FAIL)));
2956 AddLogString(out);
2957 CString msg;
2958 msg.Format(L"\"%s\" failed.\n%s", (LPCTSTR)cmd, (LPCTSTR)out);
2959 if (CMessageBox::Show(GetSafeHwnd(), msg, L"TortoiseGit", 1, IDI_ERROR, CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)), CString(MAKEINTRESOURCE(IDS_MSGBOX_ABORT))) != 1)
2960 return -1;
2962 else
2963 return 0;
2967 LRESULT CRebaseDlg::OnThemeChanged()
2969 CMFCVisualManager::GetInstance()->DestroyInstance();
2970 return 0;
2973 void CRebaseDlg::OnSysColorChange()
2975 __super::OnSysColorChange();
2976 m_LogMessageCtrl.SetColors(true);
2977 m_LogMessageCtrl.SetFont(CAppUtils::GetLogFontName(), CAppUtils::GetLogFontSize());
2978 m_wndOutputRebase.SetColors(true);
2979 m_wndOutputRebase.SetFont(CAppUtils::GetLogFontName(), CAppUtils::GetLogFontSize());
2982 void CRebaseDlg::OnBnClickedButtonAdd()
2984 CLogDlg dlg;
2985 // tell the dialog to use mode for selecting revisions
2986 dlg.SetSelect(true);
2987 // allow multi-select
2988 dlg.SingleSelection(false);
2989 if (dlg.DoModal() != IDOK || dlg.GetSelectedHash().empty())
2990 return;
2992 auto selectedHashes = dlg.GetSelectedHash();
2993 for (auto it = selectedHashes.crbegin(); it != selectedHashes.crend(); ++it)
2995 GitRevLoglist* pRev = m_CommitList.m_logEntries.m_pLogCache->GetCacheData(*it);
2996 if (pRev->GetCommit(it->ToString()))
2997 return;
2998 if (pRev->GetParentFromHash(pRev->m_CommitHash))
2999 return;
3000 pRev->GetRebaseAction() = CGitLogListBase::LOGACTIONS_REBASE_PICK;
3001 if (m_CommitList.m_IsOldFirst)
3003 m_CommitList.m_logEntries.push_back(pRev->m_CommitHash);
3004 m_CommitList.m_arShownList.SafeAdd(pRev);
3006 else
3008 m_CommitList.m_logEntries.insert(m_CommitList.m_logEntries.cbegin(), pRev->m_CommitHash);
3009 m_CommitList.m_arShownList.SafeAddFront(pRev);
3012 m_CommitList.SetItemCountEx((int)m_CommitList.m_logEntries.size());
3013 m_CommitList.Invalidate();
3015 if (m_CommitList.m_IsOldFirst)
3016 m_CurrentRebaseIndex = -1;
3017 else
3018 m_CurrentRebaseIndex = (int)m_CommitList.m_logEntries.size();