Fixed issue #3141: bisect: add good/bad continue options to progress dialog
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobba359bf8ecb1ee05c5644a362a21dfc7c75ef81b
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - TortoiseGit
4 // Copyright (C) 2003-2011, 2013-2014 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 #include "MessageBox.h"
25 #include "registry.h"
26 #include "TGitPath.h"
27 #include "Git.h"
28 #include "UnicodeUtils.h"
29 #include "ExportDlg.h"
30 #include "ProgressDlg.h"
31 #include "GitAdminDir.h"
32 #include "ProgressDlg.h"
33 #include "BrowseFolder.h"
34 #include "DirFileEnum.h"
35 #include "CreateBranchTagDlg.h"
36 #include "GitSwitchDlg.h"
37 #include "ResetDlg.h"
38 #include "DeleteConflictDlg.h"
39 #include "SendMailDlg.h"
40 #include "GitProgressDlg.h"
41 #include "PushDlg.h"
42 #include "CommitDlg.h"
43 #include "MergeDlg.h"
44 #include "MergeAbortDlg.h"
45 #include "Hooks.h"
46 #include "../Settings/Settings.h"
47 #include "InputDlg.h"
48 #include "SVNDCommitDlg.h"
49 #include "requestpulldlg.h"
50 #include "PullFetchDlg.h"
51 #include "RebaseDlg.h"
52 #include "PropKey.h"
53 #include "StashSave.h"
54 #include "IgnoreDlg.h"
55 #include "FormatMessageWrapper.h"
56 #include "SmartHandle.h"
57 #include "BisectStartDlg.h"
58 #include "SysProgressDlg.h"
59 #include "UserPassword.h"
60 #include "SendmailPatch.h"
61 #include "Globals.h"
62 #include "ProgressCommands/ResetProgressCommand.h"
63 #include "ProgressCommands/FetchProgressCommand.h"
64 #include "ProgressCommands/SendMailProgressCommand.h"
65 #include "CertificateValidationHelper.h"
66 #include "CheckCertificateDlg.h"
67 #include "SubmoduleResolveConflictDlg.h"
68 #include "GitDiff.h"
69 #include "../TGitCache/CacheInterface.h"
71 static struct last_accepted_cert {
72 BYTE* data;
73 size_t len;
75 last_accepted_cert()
76 : data(nullptr)
77 , len(0)
80 ~last_accepted_cert()
82 free(data);
84 boolean cmp(git_cert_x509* cert)
86 return len > 0 && len == cert->len && memcmp(data, cert->data, len) == 0;
88 void set(git_cert_x509* cert)
90 free(data);
91 len = cert->len;
92 if (len == 0)
94 data = nullptr;
95 return;
97 data = new BYTE[len];
98 memcpy(data, cert->data, len);
100 } last_accepted_cert;
102 static bool DoFetch(const CString& url, const bool fetchAllRemotes, const bool loadPuttyAgent, const int prune, const bool bDepth, const int nDepth, const int fetchTags, const CString& remoteBranch, int runRebase, const bool rebasePreserveMerges);
104 bool CAppUtils::StashSave(const CString& msg, bool showPull, bool pullShowPush, bool showMerge, const CString& mergeRev)
106 if (!CheckUserData())
107 return false;
109 CStashSaveDlg dlg;
110 dlg.m_sMessage = msg;
111 if (dlg.DoModal() == IDOK)
113 CString cmd = L"git.exe stash push";
114 if (!CAppUtils::IsGitVersionNewerOrEqual(2, 14))
115 cmd = L"git.exe stash save";
117 if (dlg.m_bIncludeUntracked)
118 cmd += L" --include-untracked";
119 else if (dlg.m_bAll)
120 cmd += L" --all";
122 if (!dlg.m_sMessage.IsEmpty())
124 CString message = dlg.m_sMessage;
125 message.Replace(L"\"", L"\"\"");
126 if (CAppUtils::IsGitVersionNewerOrEqual(2, 14))
127 cmd += L" -m \"" + message + L'"';
128 else
129 cmd += L" -- \"" + message + L'"';
132 CProgressDlg progress;
133 progress.m_GitCmd = cmd;
134 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
136 if (status)
137 return;
139 if (showPull)
140 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(pullShowPush, true); });
141 if (showMerge)
142 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ CAppUtils::Merge(&mergeRev, true); });
143 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, [] { CAppUtils::StashPop(); });
145 return (progress.DoModal() == IDOK);
147 return false;
150 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
152 CString cmd = L"git.exe stash apply ";
153 if (CStringUtils::StartsWith(ref, L"refs/"))
154 ref = ref.Mid(5);
155 if (CStringUtils::StartsWith(ref, L"stash{"))
156 ref = L"stash@" + ref.Mid(5);
157 cmd += ref;
159 CSysProgressDlg sysProgressDlg;
160 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
161 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
162 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
163 sysProgressDlg.SetShowProgressBar(false);
164 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
165 sysProgressDlg.ShowModeless((HWND)nullptr, true);
167 CString out;
168 int ret = g_Git.Run(cmd, &out, CP_UTF8);
170 sysProgressDlg.Stop();
172 bool hasConflicts = (out.Find(L"CONFLICT") >= 0);
173 if (ret && !(ret == 1 && hasConflicts))
174 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + L'\n' + out, L"TortoiseGit", MB_OK | MB_ICONERROR);
175 else
177 CString message;
178 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
179 if (hasConflicts)
180 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
181 if (showChanges)
183 if (CMessageBox::Show(nullptr, message + L'\n' + CString(MAKEINTRESOURCE(IDS_SEECHANGES)), L"TortoiseGit", MB_YESNO | MB_ICONINFORMATION) == IDYES)
185 cmd.Format(L"/command:repostatus /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
186 CAppUtils::RunTortoiseGitProc(cmd);
188 return true;
190 else
192 MessageBox(nullptr, message ,L"TortoiseGit", MB_OK | MB_ICONINFORMATION);
193 return true;
196 return false;
199 bool CAppUtils::StashPop(int showChanges /* = 1 */)
201 CString cmd = L"git.exe stash pop";
203 CSysProgressDlg sysProgressDlg;
204 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
205 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
206 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
207 sysProgressDlg.SetShowProgressBar(false);
208 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
209 sysProgressDlg.ShowModeless((HWND)nullptr, true);
211 CString out;
212 int ret = g_Git.Run(cmd, &out, CP_UTF8);
214 sysProgressDlg.Stop();
216 bool hasConflicts = (out.Find(L"CONFLICT") >= 0);
217 if (ret && !(ret == 1 && hasConflicts))
218 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + L'\n' + out, L"TortoiseGit", MB_OK | MB_ICONERROR);
219 else
221 CString message;
222 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
223 if (hasConflicts)
224 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
225 if (showChanges == 1 || (showChanges == 0 && hasConflicts))
227 if (CMessageBox::ShowCheck(nullptr, message + L'\n' + CString(MAKEINTRESOURCE(IDS_SEECHANGES)), L"TortoiseGit", MB_YESNO | (hasConflicts ? MB_ICONEXCLAMATION : MB_ICONINFORMATION), hasConflicts ? L"StashPopShowConflictChanges" : L"StashPopShowChanges") == IDYES)
229 cmd.Format(L"/command:repostatus /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
230 CAppUtils::RunTortoiseGitProc(cmd);
232 return true;
234 else if (showChanges > 1)
236 MessageBox(nullptr, message, L"TortoiseGit", MB_OK | MB_ICONINFORMATION);
237 return true;
239 else if (showChanges == 0)
240 return true;
242 return false;
245 BOOL CAppUtils::StartExtMerge(bool bAlternative,
246 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
247 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
248 HWND resolveMsgHwnd, bool bDeleteBaseTheirsMineOnClose)
250 CRegString regCom = CRegString(L"Software\\TortoiseGit\\Merge");
251 CString ext = mergedfile.GetFileExtension();
252 CString com = regCom;
253 bool bInternal = false;
255 if (!ext.IsEmpty())
257 // is there an extension specific merge tool?
258 CRegString mergetool(L"Software\\TortoiseGit\\MergeTools\\" + ext.MakeLower());
259 if (!CString(mergetool).IsEmpty())
260 com = mergetool;
262 // is there a filename specific merge tool?
263 CRegString mergetool(L"Software\\TortoiseGit\\MergeTools\\." + mergedfile.GetFilename().MakeLower());
264 if (!CString(mergetool).IsEmpty())
265 com = mergetool;
267 if (bAlternative && !com.IsEmpty())
269 if (CStringUtils::StartsWith(com, L"#"))
270 com.Delete(0);
271 else
272 com.Empty();
275 if (com.IsEmpty() || CStringUtils::StartsWith(com, L"#"))
277 // Maybe we should use TortoiseIDiff?
278 if ((ext == L".jpg") || (ext == L".jpeg") ||
279 (ext == L".bmp") || (ext == L".gif") ||
280 (ext == L".png") || (ext == L".ico") ||
281 (ext == L".tif") || (ext == L".tiff") ||
282 (ext == L".dib") || (ext == L".emf") ||
283 (ext == L".cur"))
285 com = CPathUtils::GetAppDirectory() + L"TortoiseGitIDiff.exe";
286 com = L'"' + com + L'"';
287 com = com + L" /base:%base /theirs:%theirs /mine:%mine /result:%merged";
288 com = com + L" /basetitle:%bname /theirstitle:%tname /minetitle:%yname";
289 if (resolveMsgHwnd)
290 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
292 else
294 // use TortoiseGitMerge
295 bInternal = true;
296 com = CPathUtils::GetAppDirectory() + L"TortoiseGitMerge.exe";
297 com = L'"' + com + L'"';
298 com = com + L" /base:%base /theirs:%theirs /mine:%mine /merged:%merged";
299 com = com + L" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname";
300 com += L" /saverequired";
301 if (resolveMsgHwnd)
302 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
303 if (bDeleteBaseTheirsMineOnClose)
304 com += L" /deletebasetheirsmineonclose";
306 if (!g_sGroupingUUID.IsEmpty())
308 com += L" /groupuuid:\"";
309 com += g_sGroupingUUID;
310 com += L'"';
313 // check if the params are set. If not, just add the files to the command line
314 if ((com.Find(L"%merged") < 0) && (com.Find(L"%base") < 0) && (com.Find(L"%theirs") < 0) && (com.Find(L"%mine") < 0))
316 com += L" \"" + basefile.GetWinPathString() + L'"';
317 com += L" \"" + theirfile.GetWinPathString() + L'"';
318 com += L" \"" + yourfile.GetWinPathString() + L'"';
319 com += L" \"" + mergedfile.GetWinPathString() + L'"';
321 if (basefile.IsEmpty())
323 com.Replace(L"/base:%base", L"");
324 com.Replace(L"%base", L"");
326 else
327 com.Replace(L"%base", L'"' + basefile.GetWinPathString() + L'"');
328 if (theirfile.IsEmpty())
330 com.Replace(L"/theirs:%theirs", L"");
331 com.Replace(L"%theirs", L"");
333 else
334 com.Replace(L"%theirs", L'"' + theirfile.GetWinPathString() + L'"');
335 if (yourfile.IsEmpty())
337 com.Replace(L"/mine:%mine", L"");
338 com.Replace(L"%mine", L"");
340 else
341 com.Replace(L"%mine", L'"' + yourfile.GetWinPathString() + L'"');
342 if (mergedfile.IsEmpty())
344 com.Replace(L"/merged:%merged", L"");
345 com.Replace(L"%merged", L"");
347 else
348 com.Replace(L"%merged", L'"' + mergedfile.GetWinPathString() + L'"');
349 if (basename.IsEmpty())
351 if (basefile.IsEmpty())
353 com.Replace(L"/basename:%bname", L"");
354 com.Replace(L"%bname", L"");
356 else
357 com.Replace(L"%bname", L'"' + basefile.GetUIFileOrDirectoryName() + L'"');
359 else
360 com.Replace(L"%bname", L'"' + basename + L'"');
361 if (theirname.IsEmpty())
363 if (theirfile.IsEmpty())
365 com.Replace(L"/theirsname:%tname", L"");
366 com.Replace(L"%tname", L"");
368 else
369 com.Replace(L"%tname", L'"' + theirfile.GetUIFileOrDirectoryName() + L'"');
371 else
372 com.Replace(L"%tname", L'"' + theirname + L'"');
373 if (yourname.IsEmpty())
375 if (yourfile.IsEmpty())
377 com.Replace(L"/minename:%yname", L"");
378 com.Replace(L"%yname", L"");
380 else
381 com.Replace(L"%yname", L'"' + yourfile.GetUIFileOrDirectoryName() + L'"');
383 else
384 com.Replace(L"%yname", L'"' + yourname + L'"');
385 if (mergedname.IsEmpty())
387 if (mergedfile.IsEmpty())
389 com.Replace(L"/mergedname:%mname", L"");
390 com.Replace(L"%mname", L"");
392 else
393 com.Replace(L"%mname", L'"' + mergedfile.GetUIFileOrDirectoryName() + L'"');
395 else
396 com.Replace(L"%mname", L'"' + mergedname + L'"');
398 com.Replace(L"%wtroot", L'"' + g_Git.m_CurrentDir + L'"');
400 if ((bReadOnly)&&(bInternal))
401 com += L" /readonly";
403 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
405 return FALSE;
408 return TRUE;
411 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
413 CString viewer;
414 // use TortoiseGitMerge
415 viewer = CPathUtils::GetAppDirectory();
416 viewer += L"TortoiseGitMerge.exe";
418 viewer = L'"' + viewer + L'"';
419 viewer = viewer + L" /diff:\"" + patchfile.GetWinPathString() + L'"';
420 viewer = viewer + L" /patchpath:\"" + dir.GetWinPathString() + L'"';
421 if (bReversed)
422 viewer += L" /reversedpatch";
423 if (!sOriginalDescription.IsEmpty())
424 viewer = viewer + L" /patchoriginal:\"" + sOriginalDescription + L'"';
425 if (!sPatchedDescription.IsEmpty())
426 viewer = viewer + L" /patchpatched:\"" + sPatchedDescription + L'"';
427 if (!g_sGroupingUUID.IsEmpty())
429 viewer += L" /groupuuid:\"";
430 viewer += g_sGroupingUUID;
431 viewer += L'"';
433 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
434 return FALSE;
435 return TRUE;
438 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
440 CString difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + file2.GetFilename().MakeLower());
441 if (!difftool.IsEmpty())
442 return difftool;
443 difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + file1.GetFilename().MakeLower());
444 if (!difftool.IsEmpty())
445 return difftool;
447 // Is there an extension specific diff tool?
448 CString ext = file2.GetFileExtension().MakeLower();
449 if (!ext.IsEmpty())
451 difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + ext);
452 if (!difftool.IsEmpty())
453 return difftool;
454 // Maybe we should use TortoiseIDiff?
455 if ((ext == L".jpg") || (ext == L".jpeg") ||
456 (ext == L".bmp") || (ext == L".gif") ||
457 (ext == L".png") || (ext == L".ico") ||
458 (ext == L".tif") || (ext == L".tiff") ||
459 (ext == L".dib") || (ext == L".emf") ||
460 (ext == L".cur"))
462 return
463 L'"' + CPathUtils::GetAppDirectory() + L"TortoiseGitIDiff.exe" + L'"' +
464 L" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname" +
465 L" /groupuuid:\"" + g_sGroupingUUID + L'"';
469 // Finally, pick a generic external diff tool
470 difftool = CRegString(L"Software\\TortoiseGit\\Diff");
471 return difftool;
474 bool CAppUtils::StartExtDiff(
475 const CString& file1, const CString& file2,
476 const CString& sName1, const CString& sName2,
477 const CString& originalFile1, const CString& originalFile2,
478 const CString& hash1, const CString& hash2,
479 const DiffFlags& flags, int jumpToLine)
481 CString viewer;
483 CRegDWORD blamediff(L"Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge", FALSE);
484 if (!flags.bBlame || !(DWORD)blamediff)
486 viewer = PickDiffTool(file1, file2);
487 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
488 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
489 if (flags.bAlternativeTool)
491 // Invert external vs. internal diff tool selection.
492 if (bCommentedOut)
493 viewer.Delete(0); // uncomment
494 else
495 viewer.Empty();
497 else if (bCommentedOut)
498 viewer.Empty();
501 bool bInternal = viewer.IsEmpty();
502 if (bInternal)
504 viewer =
505 L'"' + CPathUtils::GetAppDirectory() + L"TortoiseGitMerge.exe" + L'"' +
506 L" /base:%base /mine:%mine /basename:%bname /minename:%yname" +
507 L" /basereflectedname:%bpath /minereflectedname:%ypath";
508 if (!g_sGroupingUUID.IsEmpty())
510 viewer += L" /groupuuid:\"";
511 viewer += g_sGroupingUUID;
512 viewer += L'"';
514 if (flags.bBlame)
515 viewer += L" /blame";
517 // check if the params are set. If not, just add the files to the command line
518 if ((viewer.Find(L"%base") < 0) && (viewer.Find(L"%mine") < 0))
520 viewer += L" \"" + file1 + L'"';
521 viewer += L" \"" + file2 + L'"';
523 if (viewer.Find(L"%base") >= 0)
524 viewer.Replace(L"%base", L'"' + file1 + L'"');
525 if (viewer.Find(L"%mine") >= 0)
526 viewer.Replace(L"%mine", L'"' + file2 + L'"');
528 if (sName1.IsEmpty())
529 viewer.Replace(L"%bname", L'"' + file1 + L'"');
530 else
531 viewer.Replace(L"%bname", L'"' + sName1 + L'"');
533 if (sName2.IsEmpty())
534 viewer.Replace(L"%yname", L'"' + file2 + L'"');
535 else
536 viewer.Replace(L"%yname", L'"' + sName2 + L'"');
538 viewer.Replace(L"%bpath", L'"' + originalFile1 + L'"');
539 viewer.Replace(L"%ypath", L'"' + originalFile2 + L'"');
541 viewer.Replace(L"%brev", L'"' + hash1 + L'"');
542 viewer.Replace(L"%yrev", L'"' + hash2 + L'"');
544 viewer.Replace(L"%wtroot", L'"' + g_Git.m_CurrentDir + L'"');
546 if (flags.bReadOnly && bInternal)
547 viewer += L" /readonly";
549 if (jumpToLine > 0)
550 viewer.AppendFormat(L" /line:%d", jumpToLine);
552 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
555 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait, bool bAlternativeTool)
557 CString viewer;
558 CRegString v = CRegString(L"Software\\TortoiseGit\\DiffViewer");
559 viewer = v;
561 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
562 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
563 if (bAlternativeTool)
565 // Invert external vs. internal diff tool selection.
566 if (bCommentedOut)
567 viewer.Delete(0); // uncomment
568 else
569 viewer.Empty();
571 else if (bCommentedOut)
572 viewer.Empty();
574 if (viewer.IsEmpty())
576 // use TortoiseGitUDiff
577 viewer = CPathUtils::GetAppDirectory();
578 viewer += L"TortoiseGitUDiff.exe";
579 // enquote the path to TortoiseGitUDiff
580 viewer = L'"' + viewer + L'"';
581 // add the params
582 viewer = viewer + L" /patchfile:%1 /title:\"%title\"";
583 if (!g_sGroupingUUID.IsEmpty())
585 viewer += L" /groupuuid:\"";
586 viewer += g_sGroupingUUID;
587 viewer += L'"';
590 if (viewer.Find(L"%1") >= 0)
592 if (viewer.Find(L"\"%1\"") >= 0)
593 viewer.Replace(L"%1", patchfile);
594 else
595 viewer.Replace(L"%1", L'"' + patchfile + L'"');
597 else
598 viewer += L" \"" + patchfile + L'"';
599 if (viewer.Find(L"%title") >= 0)
600 viewer.Replace(L"%title", title);
602 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
603 return FALSE;
604 return TRUE;
607 BOOL CAppUtils::StartTextViewer(CString file)
609 CString viewer;
610 CRegString txt = CRegString(L".txt\\", L"", FALSE, HKEY_CLASSES_ROOT);
611 viewer = txt;
612 viewer = viewer + L"\\Shell\\Open\\Command\\";
613 CRegString txtexe = CRegString(viewer, L"", FALSE, HKEY_CLASSES_ROOT);
614 viewer = txtexe;
616 DWORD len = ExpandEnvironmentStrings(viewer, nullptr, 0);
617 auto buf = std::make_unique<TCHAR[]>(len + 1);
618 ExpandEnvironmentStrings(viewer, buf.get(), len);
619 viewer = buf.get();
620 len = ExpandEnvironmentStrings(file, nullptr, 0);
621 auto buf2 = std::make_unique<TCHAR[]>(len + 1);
622 ExpandEnvironmentStrings(file, buf2.get(), len);
623 file = buf2.get();
624 file = L'"' + file + L'"';
625 if (viewer.IsEmpty())
626 return CAppUtils::ShowOpenWithDialog(file) ? TRUE : FALSE;
627 if (viewer.Find(L"\"%1\"") >= 0)
628 viewer.Replace(L"\"%1\"", file);
629 else if (viewer.Find(L"%1") >= 0)
630 viewer.Replace(L"%1", file);
631 else
632 viewer += L' ';
633 viewer += file;
635 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
636 return FALSE;
637 return TRUE;
640 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
642 DWORD length = 0;
643 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
644 if (!hFile)
645 return TRUE;
646 length = ::GetFileSize(hFile, nullptr);
647 if (length < 4)
648 return TRUE;
649 return FALSE;
652 CString CAppUtils::GetLogFontName()
654 return (CString)CRegString(L"Software\\TortoiseGit\\LogFontName", L"Consolas");
657 DWORD CAppUtils::GetLogFontSize()
659 return (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogFontSize", 9);
662 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
664 LOGFONT logFont;
665 HDC hScreenDC = ::GetDC(nullptr);
666 logFont.lfHeight = -MulDiv(GetLogFontSize(), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
667 ::ReleaseDC(nullptr, hScreenDC);
668 logFont.lfWidth = 0;
669 logFont.lfEscapement = 0;
670 logFont.lfOrientation = 0;
671 logFont.lfWeight = FW_NORMAL;
672 logFont.lfItalic = 0;
673 logFont.lfUnderline = 0;
674 logFont.lfStrikeOut = 0;
675 logFont.lfCharSet = DEFAULT_CHARSET;
676 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
677 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
678 logFont.lfQuality = DRAFT_QUALITY;
679 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
680 wcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)GetLogFontName());
681 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
684 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
686 CString key,remote;
687 CString cmd,out;
688 if (!pRemote)
689 remote = L"origin";
690 else
691 remote=*pRemote;
693 if (!keyfile)
695 cmd.Format(L"remote.%s.puttykeyfile", (LPCTSTR)remote);
696 key = g_Git.GetConfigValue(cmd);
698 else
699 key=*keyfile;
701 if(key.IsEmpty())
702 return false;
704 CString proc=CPathUtils::GetAppDirectory();
705 proc += L"pageant.exe \"";
706 proc += key;
707 proc += L'"';
709 CString tempfile = GetTempFile();
710 ::DeleteFile(tempfile);
712 proc += L" -c \"";
713 proc += CPathUtils::GetAppDirectory();
714 proc += L"tgittouch.exe\"";
715 proc += L" \"";
716 proc += tempfile;
717 proc += L'"';
719 CString appDir = CPathUtils::GetAppDirectory();
720 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
721 if(!b)
722 return b;
724 int i=0;
725 while(!::PathFileExists(tempfile))
727 Sleep(100);
728 ++i;
729 if(i>10*60*5)
730 break; //timeout 5 minutes
733 if( i== 10*60*5)
734 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
735 ::DeleteFile(tempfile);
736 return true;
739 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
741 CString editTool = CRegString(L"Software\\TortoiseGit\\AlternativeEditor");
742 if (editTool.IsEmpty() || CStringUtils::StartsWith(editTool, L"#"))
743 editTool = CPathUtils::GetAppDirectory() + L"notepad2.exe";
745 CString sCmd;
746 sCmd.Format(L"\"%s\" \"%s\"", (LPCTSTR)editTool, (LPCTSTR)filename);
748 LaunchApplication(sCmd, 0, false, nullptr, uac);
749 return true;
752 bool CAppUtils::LaunchRemoteSetting()
754 CTGitPath path(g_Git.m_CurrentDir);
755 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
756 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
757 dlg.SetTreeWidth(220);
758 dlg.m_DefaultPage = L"gitremote";
760 dlg.DoModal();
761 dlg.HandleRestart();
762 return true;
766 * Launch the external blame viewer
768 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile, const CString& Rev, const CString& sParams)
770 CString viewer = L'"' + CPathUtils::GetAppDirectory();
771 viewer += L"TortoiseGitBlame.exe";
772 viewer += L"\" \"" + sBlameFile + L'"';
773 //viewer += L" \"" + sLogFile + L'"';
774 //viewer += L" \"" + sOriginalFile + L'"';
775 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
776 viewer += L" /rev:" + Rev;
777 if (!g_sGroupingUUID.IsEmpty())
779 viewer += L" /groupuuid:\"";
780 viewer += g_sGroupingUUID;
781 viewer += L'"';
783 viewer += L' ' + sParams;
785 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
788 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
790 CString sText;
791 if (!pWnd)
792 return false;
793 bool bStyled = false;
794 pWnd->GetWindowText(sText);
795 // the rich edit control doesn't count the CR char!
796 // to be exact: CRLF is treated as one char.
797 sText.Remove(L'\r');
799 // style each line separately
800 int offset = 0;
801 int nNewlinePos;
804 nNewlinePos = sText.Find('\n', offset);
805 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
807 int start = 0;
808 int end = 0;
809 while (FindStyleChars(sLine, '*', start, end))
811 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
812 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
813 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
814 bStyled = true;
815 start = end;
817 start = 0;
818 end = 0;
819 while (FindStyleChars(sLine, '^', start, end))
821 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
822 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
823 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
824 bStyled = true;
825 start = end;
827 start = 0;
828 end = 0;
829 while (FindStyleChars(sLine, '_', start, end))
831 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
832 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
833 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
834 bStyled = true;
835 start = end;
837 offset = nNewlinePos+1;
838 } while(nNewlinePos>=0);
839 return bStyled;
842 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
844 int i=start;
845 int last = sText.GetLength() - 1;
846 bool bFoundMarker = false;
847 TCHAR c = i == 0 ? L'\0' : sText[i - 1];
848 TCHAR nextChar = i >= last ? L'\0' : sText[i + 1];
850 // find a starting marker
851 while (i < last)
853 TCHAR prevChar = c;
854 c = nextChar;
855 nextChar = sText[i + 1];
857 // IsCharAlphaNumeric can be somewhat expensive.
858 // Long lines of "*****" or "----" will be pre-emptied efficiently
859 // by the (c != nextChar) condition.
861 if ((c == stylechar) && (c != nextChar))
863 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
865 start = ++i;
866 bFoundMarker = true;
867 break;
870 ++i;
872 if (!bFoundMarker)
873 return false;
875 // find ending marker
876 // c == sText[i - 1]
878 bFoundMarker = false;
879 while (i <= last)
881 TCHAR prevChar = c;
882 c = sText[i];
883 if (c == stylechar)
885 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
887 end = i;
888 ++i;
889 bFoundMarker = true;
890 break;
893 ++i;
895 return bFoundMarker;
898 // from CSciEdit
899 namespace {
900 bool IsValidURLChar(wchar_t ch)
902 return iswalnum(ch) ||
903 ch == L'_' || ch == L'/' || ch == L';' || ch == L'?' || ch == L'&' || ch == L'=' ||
904 ch == L'%' || ch == L':' || ch == L'.' || ch == L'#' || ch == L'-' || ch == L'+' ||
905 ch == L'|' || ch == L'>' || ch == L'<' || ch == L'!' || ch == L'@' || ch == L'~';
908 bool IsUrlOrEmail(const CString& sText)
910 if (!PathIsURLW(sText))
912 auto atpos = sText.Find(L'@');
913 if (atpos <= 0)
914 return false;
915 if (sText.Find(L'.', atpos) <= atpos + 1) // a dot must follow after the @, but not directly after it
916 return false;
917 if (sText.Find(L':', atpos) < 0) // do not detect git@example.com:something as an email address
918 return true;
919 return false;
921 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" })
923 if (CStringUtils::StartsWith(sText, prefix) && sText.GetLength() != prefix.GetLength())
924 return true;
926 return false;
930 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
932 std::vector<CHARRANGE> positions = FindURLMatches(msg);
933 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
935 return positions.empty() ? FALSE : TRUE;
939 * implements URL searching with the same logic as CSciEdit::StyleURLs
941 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
943 std::vector<CHARRANGE> result;
945 int len = msg.GetLength();
946 int starturl = -1;
948 for (int i = 0; i <= msg.GetLength(); ++i)
950 if ((i < len) && IsValidURLChar(msg[i]))
952 if (starturl < 0)
953 starturl = i;
955 else
957 if (starturl >= 0)
959 bool strip = true;
960 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
962 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
963 ++starturl;
964 strip = false;
965 i = starturl;
966 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
967 ++i;
970 int skipTrailing = 0;
971 while (strip && i - skipTrailing - 1 > starturl && (msg[i - skipTrailing - 1] == '.' || msg[i - skipTrailing - 1] == '-' || msg[i - skipTrailing - 1] == '?' || msg[i - skipTrailing - 1] == ';' || msg[i - skipTrailing - 1] == ':' || msg[i - skipTrailing - 1] == '>' || msg[i - skipTrailing - 1] == '<' || msg[i - skipTrailing - 1] == '!'))
972 ++skipTrailing;
974 if (!IsUrlOrEmail(msg.Mid(starturl, i - starturl - skipTrailing)))
976 starturl = -1;
977 continue;
980 CHARRANGE range = { starturl, i - skipTrailing };
981 result.push_back(range);
983 starturl = -1;
987 return result;
990 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const CString& rev1,
991 const CTGitPath& /*url2*/, const CString& rev2,
992 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
993 bool bAlternateDiff /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
994 bool /* blame = false */,
995 bool bMerge,
996 bool bCombine,
997 bool bNoPrefix)
999 int diffContext = g_Git.GetConfigValueInt32(L"diff.context", -1);
1000 CString tempfile=GetTempFile();
1001 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext, bNoPrefix))
1003 MessageBox(hWnd, g_Git.GetGitLastErr(L"Could not get unified diff.", CGit::GIT_CMD_DIFF), L"TortoiseGit", MB_OK);
1004 return false;
1006 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1.IsEmpty() ? rev2 : rev1 + L':' + rev2, FALSE, bAlternateDiff);
1008 #if 0
1009 CString sCmd;
1010 sCmd.Format(L"%s /command:showcompare /unified",
1011 (LPCTSTR)(CPathUtils::GetAppDirectory()+L"TortoiseGitProc.exe"));
1012 sCmd += L" /url1:\"" + url1.GetGitPathString() + L'"';
1013 if (rev1.IsValid())
1014 sCmd += L" /revision1:" + rev1.ToString();
1015 sCmd += L" /url2:\"" + url2.GetGitPathString() + L'"';
1016 if (rev2.IsValid())
1017 sCmd += L" /revision2:" + rev2.ToString();
1018 if (peg.IsValid())
1019 sCmd += L" /pegrevision:" + peg.ToString();
1020 if (headpeg.IsValid())
1021 sCmd += L" /headpegrevision:" + headpeg.ToString();
1023 if (bAlternateDiff)
1024 sCmd += L" /alternatediff";
1026 if (bIgnoreAncestry)
1027 sCmd += L" /ignoreancestry";
1029 if (hWnd)
1031 sCmd += L" /hwnd:";
1032 TCHAR buf[30];
1033 swprintf_s(buf, 30, L"%p", (void*)hWnd);
1034 sCmd += buf;
1037 return CAppUtils::LaunchApplication(sCmd, 0, false);
1038 #endif
1039 return TRUE;
1042 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1044 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1045 scriptsdir += L"Diff-Scripts";
1046 CSimpleFileFind files(scriptsdir);
1047 while (files.FindNextFileNoDirectories())
1049 CString file = files.GetFilePath();
1050 CString filename = files.GetFileName();
1051 CString ext = file.Mid(file.ReverseFind('-') + 1);
1052 ext = L"." + ext.Left(ext.ReverseFind(L'.'));
1053 std::set<CString> extensions;
1054 extensions.insert(ext);
1055 CString kind;
1056 if (CStringUtils::EndsWithI(file, L"vbs"))
1057 kind = L" //E:vbscript";
1058 if (CStringUtils::EndsWithI(file, L"js"))
1059 kind = L" //E:javascript";
1060 // open the file, read the first line and find possible extensions
1061 // this script can handle
1064 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1065 CString extline;
1066 if (f.ReadString(extline))
1068 if ((extline.GetLength() > 15 ) &&
1069 (CStringUtils::StartsWith(extline, L"// extensions: ") ||
1070 CStringUtils::StartsWith(extline, L"' extensions: ")))
1072 if (extline[0] == '/')
1073 extline = extline.Mid(15);
1074 else
1075 extline = extline.Mid(14);
1076 CString sToken;
1077 int curPos = 0;
1078 sToken = extline.Tokenize(L";", curPos);
1079 while (!sToken.IsEmpty())
1081 if (!sToken.IsEmpty())
1083 if (sToken[0] != '.')
1084 sToken = L"." + sToken;
1085 extensions.insert(sToken);
1087 sToken = extline.Tokenize(L";", curPos);
1091 f.Close();
1093 catch (CFileException* e)
1095 e->Delete();
1098 for (const auto& extension : extensions)
1100 if (type.IsEmpty() || (type.Compare(L"Diff") == 0))
1102 if (CStringUtils::StartsWithI(filename, L"diff-"))
1104 CRegString diffreg = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + extension);
1105 CString diffregstring = diffreg;
1106 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1107 diffreg = L"wscript.exe \"" + file + L"\" %base %mine" + kind;
1110 if (type.IsEmpty() || (type.Compare(L"Merge") == 0))
1112 if (CStringUtils::StartsWithI(filename, L"merge-"))
1114 CRegString diffreg = CRegString(L"Software\\TortoiseGit\\MergeTools\\" + extension);
1115 CString diffregstring = diffreg;
1116 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1117 diffreg = L"wscript.exe \"" + file + L"\" %merged %theirs %mine %base" + kind;
1123 return true;
1126 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1128 // ask from where the export has to be done
1129 CExportDlg dlg;
1130 if(BashHash)
1131 dlg.m_initialRefName=*BashHash;
1132 if (orgPath)
1134 if (PathIsRelative(orgPath->GetWinPath()))
1135 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1136 else
1137 dlg.m_orgPath = *orgPath;
1140 if (dlg.DoModal() == IDOK)
1142 CString cmd;
1143 cmd.Format(L"git.exe archive --output=\"%s\" --format=zip --verbose %s --",
1144 (LPCTSTR)dlg.m_strFile, (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName));
1146 CProgressDlg pro;
1147 pro.m_GitCmd=cmd;
1148 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1150 if (status)
1151 return;
1152 postCmdList.emplace_back(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); });
1155 CGit git;
1156 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1158 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1159 pro.m_Git = &git;
1161 return (pro.DoModal() == IDOK);
1163 return false;
1166 bool CAppUtils::UpdateBranchDescription(const CString& branch, CString description)
1168 if (branch.IsEmpty())
1169 return false;
1171 CString key;
1172 key.Format(L"branch.%s.description", (LPCTSTR)branch);
1173 description.Remove(L'\r');
1174 description.Trim();
1175 if (description.IsEmpty())
1176 g_Git.UnsetConfigValue(key);
1177 else
1178 g_Git.SetConfigValue(key, description);
1180 return true;
1183 bool CAppUtils::CreateBranchTag(bool isTag /*true*/, const CString* commitHash /*nullptr*/, bool switchNewBranch /*false*/, LPCTSTR name /*nullptr*/)
1185 CCreateBranchTagDlg dlg;
1186 dlg.m_bIsTag = isTag;
1187 dlg.m_bSwitch = switchNewBranch;
1189 if (commitHash)
1190 dlg.m_initialRefName = *commitHash;
1192 if (name)
1193 dlg.m_BranchTagName = name;
1195 if(dlg.DoModal()==IDOK)
1197 CString cmd;
1198 CString force;
1199 CString track;
1200 if(dlg.m_bTrack == TRUE)
1201 track = L"--track";
1202 else if(dlg.m_bTrack == FALSE)
1203 track = L"--no-track";
1205 if(dlg.m_bForce)
1206 force = L"-f";
1208 if (isTag)
1210 CString sign;
1211 if(dlg.m_bSign)
1212 sign = L"-s";
1214 cmd.Format(L"git.exe tag %s %s %s %s",
1215 (LPCTSTR)force,
1216 (LPCTSTR)sign,
1217 (LPCTSTR)dlg.m_BranchTagName,
1218 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1221 if(!dlg.m_Message.Trim().IsEmpty())
1223 CString tempfile = ::GetTempFile();
1224 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1226 MessageBox(nullptr, L"Could not save tag message", L"TortoiseGit", MB_OK | MB_ICONERROR);
1227 return FALSE;
1229 cmd += L" -F " + tempfile;
1232 else
1234 cmd.Format(L"git.exe branch %s %s %s %s",
1235 (LPCTSTR)track,
1236 (LPCTSTR)force,
1237 (LPCTSTR)dlg.m_BranchTagName,
1238 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1241 CString out;
1242 if(g_Git.Run(cmd,&out,CP_UTF8))
1244 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1245 return FALSE;
1247 if (!isTag && dlg.m_bSwitch)
1249 // it is a new branch and the user has requested to switch to it
1250 PerformSwitch(dlg.m_BranchTagName);
1252 if (!isTag && !dlg.m_Message.IsEmpty())
1253 UpdateBranchDescription(dlg.m_BranchTagName, dlg.m_Message);
1255 return TRUE;
1257 return FALSE;
1260 bool CAppUtils::Switch(const CString& initialRefName)
1262 CGitSwitchDlg dlg;
1263 if(!initialRefName.IsEmpty())
1264 dlg.m_initialRefName = initialRefName;
1266 if (dlg.DoModal() == IDOK)
1268 CString branch;
1269 if (dlg.m_bBranch)
1270 branch = dlg.m_NewBranch;
1272 // if refs/heads/ is not stripped, checkout will detach HEAD
1273 // checkout prefers branches on name clashes (with tags)
1274 if (CStringUtils::StartsWith(dlg.m_VersionName, L"refs/heads/") && dlg.m_bBranchOverride != TRUE)
1275 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1277 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1279 return FALSE;
1282 bool CAppUtils::PerformSwitch(const CString& ref, bool bForce /* false */, const CString& sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1284 CString cmd;
1285 CString track;
1286 CString force;
1287 CString branch;
1288 CString merge;
1290 if(!sNewBranch.IsEmpty()){
1291 if (bBranchOverride)
1292 branch.Format(L"-B %s ", (LPCTSTR)sNewBranch);
1293 else
1294 branch.Format(L"-b %s ", (LPCTSTR)sNewBranch);
1295 if (bTrack == TRUE)
1296 track = L"--track ";
1297 else if (bTrack == FALSE)
1298 track = L"--no-track ";
1300 if (bForce)
1301 force = L"-f ";
1302 if (bMerge)
1303 merge = L"--merge ";
1305 cmd.Format(L"git.exe checkout %s%s%s%s%s --",
1306 (LPCTSTR)force,
1307 (LPCTSTR)track,
1308 (LPCTSTR)merge,
1309 (LPCTSTR)branch,
1310 (LPCTSTR)g_Git.FixBranchName(ref));
1312 CProgressDlg progress;
1313 progress.m_GitCmd = cmd;
1315 CString currentBranch;
1316 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1317 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1319 if (!status)
1321 CTGitPath gitPath = g_Git.m_CurrentDir;
1322 if (gitPath.HasSubmodules())
1324 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1326 CString sCmd;
1327 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1328 RunTortoiseGitProc(sCmd);
1331 if (hasBranch)
1332 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); });
1335 CString newBranch;
1336 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1337 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); });
1339 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []{
1340 CTGitPathList pathlist;
1341 CTGitPathList selectedlist;
1342 pathlist.AddPath(CTGitPath());
1343 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(L"Software\\TortoiseGit\\SelectFilesForCommit", TRUE));
1344 CString str;
1345 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1348 else
1350 if (bMerge && g_Git.HasWorkingTreeConflicts() > 0)
1352 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
1354 CString sCmd;
1355 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1356 CAppUtils::RunTortoiseGitProc(sCmd);
1359 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); });
1360 if (!bMerge)
1361 postCmdList.emplace_back(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); });
1364 progress.m_PostExecCallback = [&](DWORD& exitCode, CString& extraMsg)
1366 if (bMerge && !exitCode && g_Git.HasWorkingTreeConflicts() > 0)
1368 exitCode = 1; // Treat it as failure
1369 extraMsg = L"Has merge conflict";
1373 INT_PTR ret = progress.DoModal();
1375 return ret == IDOK;
1378 class CIgnoreFile : public CStdioFile
1380 public:
1381 STRING_VECTOR m_Items;
1382 CString m_eol;
1384 virtual BOOL ReadString(CString& rString)
1386 if (GetPosition() == 0)
1388 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1389 char buf[3] = { 0, 0, 0 };
1390 Read(buf, 3);
1391 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1392 SeekToBegin();
1395 CStringA strA;
1396 char lastChar = '\0';
1397 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1399 if (c == '\r')
1400 continue;
1401 if (c == '\n')
1403 m_eol = lastChar == L'\r' ? L"\r\n" : L"\n";
1404 break;
1406 strA.AppendChar(c);
1408 if (strA.IsEmpty())
1409 return FALSE;
1411 rString = CUnicodeUtils::GetUnicode(strA);
1412 return TRUE;
1415 void ResetState()
1417 m_Items.clear();
1418 m_eol.Empty();
1422 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1424 file.ResetState();
1425 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1427 MessageBox(nullptr, filename + L" Open Failure", L"TortoiseGit", MB_OK | MB_ICONERROR);
1428 return false;
1431 if (file.GetLength() > 0)
1433 CString fileText;
1434 while (file.ReadString(fileText))
1435 file.m_Items.push_back(fileText);
1436 file.Seek(file.GetLength() - 1, 0);
1437 char lastchar[1] = { 0 };
1438 file.Read(lastchar, 1);
1439 file.SeekToEnd();
1440 if (lastchar[0] != '\n')
1442 CStringA eol = CStringA(file.m_eol.IsEmpty() ? L"\n" : file.m_eol);
1443 file.Write(eol, eol.GetLength());
1446 else
1447 file.SeekToEnd();
1449 return true;
1452 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1454 CIgnoreDlg ignoreDlg;
1455 if (ignoreDlg.DoModal() == IDOK)
1457 CString ignorefile;
1458 ignorefile = g_Git.m_CurrentDir + L'\\';
1460 switch (ignoreDlg.m_IgnoreFile)
1462 case 0:
1463 ignorefile += L".gitignore";
1464 break;
1465 case 2:
1466 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1467 ignorefile += L"info";
1468 if (!PathFileExists(ignorefile))
1469 CreateDirectory(ignorefile, nullptr);
1470 ignorefile += L"\\exclude";
1471 break;
1474 CIgnoreFile file;
1477 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1478 return false;
1480 for (int i = 0; i < path.GetCount(); ++i)
1482 if (ignoreDlg.m_IgnoreFile == 1)
1484 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + L"\\.gitignore";
1485 if (!OpenIgnoreFile(file, ignorefile))
1486 return false;
1489 CString ignorePattern;
1490 if (ignoreDlg.m_IgnoreType == 0)
1492 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1493 ignorePattern += L'/' + path[i].GetContainingDirectory().GetGitPathString();
1495 ignorePattern += L'/';
1497 if (IsMask)
1498 ignorePattern += L'*' + path[i].GetFileExtension();
1499 else
1500 ignorePattern += path[i].GetFileOrDirectoryName();
1502 // escape [ and ] so that files get ignored correctly
1503 ignorePattern.Replace(L"[", L"\\[");
1504 ignorePattern.Replace(L"]", L"\\]");
1506 bool found = false;
1507 for (size_t j = 0; j < file.m_Items.size(); ++j)
1509 if (file.m_Items[j] == ignorePattern)
1511 found = true;
1512 break;
1515 if (!found)
1517 file.m_Items.push_back(ignorePattern);
1518 ignorePattern += file.m_eol.IsEmpty() ? L"\n" : file.m_eol;
1519 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1520 file.Write(ignorePatternA, ignorePatternA.GetLength());
1523 if (ignoreDlg.m_IgnoreFile == 1)
1524 file.Close();
1527 if (ignoreDlg.m_IgnoreFile != 1)
1528 file.Close();
1530 catch(...)
1532 file.Abort();
1533 return false;
1536 return true;
1538 return false;
1541 static bool Reset(const CString& resetTo, int resetType)
1543 CString cmd;
1544 CString type;
1545 switch (resetType)
1547 case 0:
1548 type = L"--soft";
1549 break;
1550 case 1:
1551 type = L"--mixed";
1552 break;
1553 case 2:
1554 type = L"--hard";
1555 break;
1556 case 3:
1558 CProgressDlg progress;
1559 progress.m_GitCmd = L"git.exe reset --merge";
1560 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1562 if (status)
1564 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [] { CAppUtils::MergeAbort(); });
1565 return;
1568 CTGitPath gitPath = g_Git.m_CurrentDir;
1569 if (gitPath.HasSubmodules() && resetType == 2)
1571 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1573 CString sCmd;
1574 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1575 CAppUtils::RunTortoiseGitProc(sCmd);
1579 return progress.DoModal() == IDOK;
1581 default:
1582 ATLASSERT(false);
1583 resetType = 1;
1584 type = L"--mixed";
1585 break;
1587 cmd.Format(L"git.exe reset %s %s --", (LPCTSTR)type, (LPCTSTR)resetTo);
1589 CProgressDlg progress;
1590 progress.m_GitCmd = cmd;
1592 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1594 if (status)
1596 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); });
1597 return;
1600 CTGitPath gitPath = g_Git.m_CurrentDir;
1601 if (gitPath.HasSubmodules() && resetType == 2)
1603 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1605 CString sCmd;
1606 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1607 CAppUtils::RunTortoiseGitProc(sCmd);
1611 if (gitPath.IsBisectActive())
1613 postCmdList.emplace_back(IDI_THUMB_UP, IDS_MENUBISECTGOOD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /good"); });
1614 postCmdList.emplace_back(IDI_THUMB_DOWN, IDS_MENUBISECTBAD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /bad"); });
1615 postCmdList.emplace_back(IDI_BISECT_RESET, IDS_MENUBISECTRESET, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /reset"); });
1619 INT_PTR ret;
1620 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1622 CGitProgressDlg gitdlg;
1623 ResetProgressCommand resetProgressCommand;
1624 gitdlg.SetCommand(&resetProgressCommand);
1625 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1626 resetProgressCommand.SetRevision(resetTo);
1627 resetProgressCommand.SetResetType(resetType);
1628 ret = gitdlg.DoModal();
1630 else
1631 ret = progress.DoModal();
1633 return ret == IDOK;
1636 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1638 CResetDlg dlg;
1639 dlg.m_ResetType=type;
1640 dlg.m_ResetToVersion=*CommitHash;
1641 dlg.m_initialRefName = *CommitHash;
1642 if (dlg.DoModal() == IDOK)
1643 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1645 return false;
1648 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1650 if(mode == FALSE)
1652 descript.LoadString(IDS_SVNACTION_DELETE);
1653 return;
1655 if(base)
1657 descript.LoadString(IDS_SVNACTION_MODIFIED);
1658 return;
1660 descript.LoadString(IDS_PROC_CREATED);
1663 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1665 ::DeleteFile(CAppUtils::GetMergeTempFile(L"LOCAL", path));
1666 ::DeleteFile(CAppUtils::GetMergeTempFile(L"REMOTE", path));
1667 ::DeleteFile(CAppUtils::GetMergeTempFile(L"BASE", path));
1669 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1671 return g_Git.CombinePath(merge.GetWinPathString() + L'.' + type + merge.GetFileExtension());;
1674 static bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, bool& isFile1, CString& hash2, bool& isFile2, CString& hash3, bool& isFile3)
1676 size_t pos = 0;
1677 CString one;
1678 CString part;
1680 while (pos < out.size())
1682 one.Empty();
1684 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1685 int tabstart = 0;
1686 one.Tokenize(L"\t", tabstart);
1688 tabstart = 0;
1689 part = one.Tokenize(L" ", tabstart); //Tag
1690 CString mode = one.Tokenize(L" ", tabstart); //Mode
1691 part = one.Tokenize(L" ", tabstart); //Hash
1692 CString hash = part;
1693 part = one.Tokenize(L"\t", tabstart); //Stage
1694 int stage = _wtol(part);
1695 if (stage == 1)
1697 hash1 = hash;
1698 isFile1 = _wtol(mode) != 160000;
1700 else if (stage == 2)
1702 hash2 = hash;
1703 isFile2 = _wtol(mode) != 160000;
1705 else if (stage == 3)
1707 hash3 = hash;
1708 isFile3 = _wtol(mode) != 160000;
1709 return true;
1712 pos = out.findNextString(pos);
1715 return false;
1718 void CAppUtils::GetConflictTitles(CString* baseText, CString& mineText, CString& theirsText, bool rebaseActive)
1720 if (baseText)
1721 baseText->LoadString(IDS_PROC_DIFF_BASE);
1722 if (rebaseActive)
1724 CString adminDir;
1725 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir);
1726 mineText = L"Branch being rebased onto";
1727 if (!CStringUtils::ReadStringFromTextFile(adminDir + L"tgitrebase.active\\onto", mineText))
1729 CGitHash hash;
1730 if (!g_Git.GetHash(hash, L"rebase-apply/onto"))
1731 g_Git.GuessRefForHash(mineText, hash);
1733 theirsText = L"Branch being rebased";
1734 if (!CStringUtils::ReadStringFromTextFile(adminDir + L"tgitrebase.active\\head-name", theirsText))
1736 if (CStringUtils::ReadStringFromTextFile(adminDir + L"rebase-apply/head-name", theirsText))
1737 theirsText = CGit::StripRefName(theirsText);
1739 return;
1742 static const struct {
1743 const wchar_t* headref;
1744 bool guessRef;
1745 UINT theirstext;
1746 } infotexts[] = { { L"MERGE_HEAD", true, IDS_CONFLICT_INFOTEXT }, { L"CHERRY_PICK_HEAD", false, IDS_CONFLICT_INFOTEXT }, { L"REVERT_HEAD", false, IDS_CONFLICT_REVERT } };
1747 mineText = L"HEAD";
1748 theirsText.LoadString(IDS_CONFLICT_REFTOBEMERGED);
1749 for (const auto& infotext : infotexts)
1751 CGitHash hash;
1752 if (!g_Git.GetHash(hash, infotext.headref))
1754 CString guessedRef;
1755 if (!infotext.guessRef)
1756 guessedRef = hash.ToString();
1757 else
1758 g_Git.GuessRefForHash(guessedRef, hash);
1759 theirsText.FormatMessage(infotext.theirstext, infotext.headref, (LPCTSTR)guessedRef);
1760 break;
1765 bool CAppUtils::ConflictEdit(CTGitPath& path, bool bAlternativeTool /*= false*/, bool isRebase /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1767 CTGitPath merge=path;
1768 CTGitPath directory = merge.GetDirectory();
1770 BYTE_VECTOR vector;
1772 CString cmd;
1773 cmd.Format(L"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
1775 if (g_Git.Run(cmd, &vector))
1776 return FALSE;
1778 CString baseTitle, mineTitle, theirsTitle;
1779 GetConflictTitles(&baseTitle, mineTitle, theirsTitle, isRebase);
1781 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1782 bool baseIsFile = true, localIsFile = true, remoteIsFile = true;
1783 if (ParseHashesFromLsFile(vector, realBaseHash, baseIsFile, localHash, localIsFile, remoteHash, remoteIsFile))
1784 baseHash = realBaseHash;
1786 if (!baseIsFile || !localIsFile || !remoteIsFile)
1788 if (merge.HasAdminDir())
1790 CGit subgit;
1791 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1792 CGitHash hash;
1793 subgit.GetHash(hash, L"HEAD");
1794 baseHash = hash;
1797 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1798 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1800 bool baseOK = false, mineOK = false, theirsOK = false;
1801 CString baseSubject, mineSubject, theirsSubject;
1802 if (merge.HasAdminDir())
1804 CGit subgit;
1805 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1806 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1807 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1809 else if (baseHash == GIT_REV_ZERO && localHash == GIT_REV_ZERO && remoteHash != GIT_REV_ZERO) // merge conflict with no submodule, but submodule in merged revision (not initialized)
1811 changeTypeMine = CGitDiff::Identical;
1812 changeTypeTheirs = CGitDiff::NewSubmodule;
1813 baseSubject.LoadString(IDS_CONFLICT_NOSUBMODULE);
1814 mineSubject = baseSubject;
1815 theirsSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1817 else if (baseHash.IsEmpty() && localHash != GIT_REV_ZERO && remoteHash == GIT_REV_ZERO) // merge conflict with no submodule initialized, but submodule exists in base and folder with no submodule is merged
1819 baseHash = localHash;
1820 baseSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1821 mineSubject = baseSubject;
1822 theirsSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1823 changeTypeMine = CGitDiff::Identical;
1824 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1826 else if (baseHash != GIT_REV_ZERO && localHash != GIT_REV_ZERO && remoteHash != GIT_REV_ZERO) // base has submodule, mine has submodule and theirs also, but not initialized
1828 baseSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1829 mineSubject = baseSubject;
1830 theirsSubject = baseSubject;
1831 if (baseHash == localHash)
1832 changeTypeMine = CGitDiff::Identical;
1834 else if (baseHash == GIT_REV_ZERO && localHash != GIT_REV_ZERO && remoteHash != GIT_REV_ZERO)
1836 baseOK = true;
1837 mineSubject = baseSubject;
1838 if (remoteIsFile)
1840 theirsSubject.LoadString(IDS_CONFLICT_NOTASUBMODULE);
1841 changeTypeMine = CGitDiff::NewSubmodule;
1843 else
1844 theirsSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1845 if (localIsFile)
1847 mineSubject.LoadString(IDS_CONFLICT_NOTASUBMODULE);
1848 changeTypeTheirs = CGitDiff::NewSubmodule;
1850 else
1851 mineSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1853 else if (baseHash != GIT_REV_ZERO && (localHash == GIT_REV_ZERO || remoteHash == GIT_REV_ZERO))
1855 baseSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1856 if (localHash == GIT_REV_ZERO)
1858 mineSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1859 changeTypeMine = CGitDiff::DeleteSubmodule;
1861 else
1863 mineSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1864 if (localHash == baseHash)
1865 changeTypeMine = CGitDiff::Identical;
1867 if (remoteHash == GIT_REV_ZERO)
1869 theirsSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1870 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1872 else
1874 theirsSubject.LoadString(IDS_CONFLICT_SUBMODULENOTINITIALIZED);
1875 if (remoteHash == baseHash)
1876 changeTypeTheirs = CGitDiff::Identical;
1879 else
1880 return FALSE;
1882 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1883 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), isRebase, baseTitle, mineTitle, theirsTitle, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1884 resolveSubmoduleConflictDialog.DoModal();
1885 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1887 static UINT WM_REVERTMSG = RegisterWindowMessage(L"GITSLNM_NEEDSREFRESH");
1888 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1891 return TRUE;
1894 CTGitPathList list;
1895 if (list.ParserFromLsFile(vector))
1897 MessageBox(nullptr, L"Parse ls-files failed!", L"TortoiseGit", MB_OK | MB_ICONERROR);
1898 return FALSE;
1901 if (list.IsEmpty())
1902 return FALSE;
1904 CTGitPath theirs;
1905 CTGitPath mine;
1906 CTGitPath base;
1908 if (isRebase)
1910 mine.SetFromGit(GetMergeTempFile(L"REMOTE", merge));
1911 theirs.SetFromGit(GetMergeTempFile(L"LOCAL", merge));
1913 else
1915 mine.SetFromGit(GetMergeTempFile(L"LOCAL", merge));
1916 theirs.SetFromGit(GetMergeTempFile(L"REMOTE", merge));
1918 base.SetFromGit(GetMergeTempFile(L"BASE",merge));
1920 CString format = L"git.exe checkout-index --temp --stage=%d -- \"%s\"";
1921 CFile tempfile;
1922 //create a empty file, incase stage is not three
1923 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1924 tempfile.Close();
1925 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1926 tempfile.Close();
1927 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1928 tempfile.Close();
1930 bool b_base=false, b_local=false, b_remote=false;
1932 for (int i = 0; i< list.GetCount(); ++i)
1934 CString outfile;
1935 cmd.Empty();
1936 outfile.Empty();
1938 if( list[i].m_Stage == 1)
1940 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1941 b_base = true;
1942 outfile = base.GetWinPathString();
1945 if( list[i].m_Stage == 2 )
1947 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1948 b_local = true;
1949 outfile = mine.GetWinPathString();
1952 if( list[i].m_Stage == 3 )
1954 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1955 b_remote = true;
1956 outfile = theirs.GetWinPathString();
1958 CString output, err;
1959 if(!outfile.IsEmpty())
1960 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1962 CString file;
1963 int start =0 ;
1964 file = output.Tokenize(L"\t", start);
1965 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1967 else
1968 CMessageBox::Show(nullptr, output + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
1971 if(b_local && b_remote )
1973 merge.SetFromWin(g_Git.CombinePath(merge));
1974 if (isRebase)
1975 return !!CAppUtils::StartExtMerge(bAlternativeTool, base, mine, theirs, merge, baseTitle, mineTitle, theirsTitle, CString(), false, resolveMsgHwnd, true);
1977 return !!CAppUtils::StartExtMerge(bAlternativeTool, base, theirs, mine, merge, baseTitle, theirsTitle, mineTitle, CString(), false, resolveMsgHwnd, true);
1979 else
1981 ::DeleteFile(mine.GetWinPathString());
1982 ::DeleteFile(theirs.GetWinPathString());
1983 if (!b_base)
1984 ::DeleteFile(base.GetWinPathString());
1986 SCOPE_EXIT{
1987 if (b_base)
1988 ::DeleteFile(base.GetWinPathString());
1991 CDeleteConflictDlg dlg;
1992 if (!isRebase)
1994 DescribeConflictFile(b_local, b_base, dlg.m_LocalStatus);
1995 DescribeConflictFile(b_remote, b_base, dlg.m_RemoteStatus);
1996 dlg.m_LocalHash = mineTitle;
1997 dlg.m_RemoteHash = theirsTitle;
1998 dlg.m_bDiffMine = b_local;
2000 else
2002 DescribeConflictFile(b_local, b_base, dlg.m_RemoteStatus);
2003 DescribeConflictFile(b_remote, b_base, dlg.m_LocalStatus);
2004 dlg.m_LocalHash = theirsTitle;
2005 dlg.m_RemoteHash = mineTitle;
2006 dlg.m_bDiffMine = !b_local;
2008 dlg.m_bShowModifiedButton = b_base;
2009 dlg.m_File = merge;
2010 dlg.m_FileBaseVersion = base;
2011 if(dlg.DoModal() == IDOK)
2013 CString out;
2014 if(dlg.m_bIsDelete)
2015 cmd.Format(L"git.exe rm -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
2016 else
2017 cmd.Format(L"git.exe add -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
2019 if (g_Git.Run(cmd, &out, CP_UTF8))
2021 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
2022 return FALSE;
2024 if (!dlg.m_bIsDelete)
2026 path.m_Action |= CTGitPath::LOGACTIONS_ADDED;
2027 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
2029 return TRUE;
2031 return FALSE;
2035 bool CAppUtils::IsSSHPutty()
2037 CString sshclient = g_Git.m_Environment.GetEnv(L"GIT_SSH");
2038 sshclient=sshclient.MakeLower();
2039 return sshclient.Find(L"plink", 0) >= 0;
2042 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2044 if (!OpenClipboard(nullptr))
2045 return CString();
2047 CString sClipboardText;
2048 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2049 if (hglb)
2051 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2052 sClipboardText = CString(lpstr);
2053 GlobalUnlock(hglb);
2055 hglb = GetClipboardData(CF_UNICODETEXT);
2056 if (hglb)
2058 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2059 sClipboardText = lpstr;
2060 GlobalUnlock(hglb);
2062 CloseClipboard();
2064 if(!sClipboardText.IsEmpty())
2066 if (sClipboardText[0] == L'"' && sClipboardText[sClipboardText.GetLength() - 1] == L'"')
2067 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2069 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ssh://", L"git@" })
2071 if (CStringUtils::StartsWith(sClipboardText, prefix) && sClipboardText.GetLength() != prefix.GetLength())
2072 return sClipboardText;
2075 if(sClipboardText.GetLength()>=2)
2076 if (sClipboardText[1] == L':')
2077 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2078 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2079 return sClipboardText;
2081 // trim prefixes like "git clone "
2082 if (!skipGitPrefix.IsEmpty() && CStringUtils::StartsWith(sClipboardText, skipGitPrefix))
2084 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2085 int spacePos = -1;
2086 while (paramsCount >= 0)
2088 --paramsCount;
2089 spacePos = sClipboardText.Find(L' ', spacePos + 1);
2090 if (spacePos == -1)
2091 break;
2093 if (spacePos > 0 && paramsCount < 0)
2094 sClipboardText.Truncate(spacePos);
2095 return sClipboardText;
2099 return CString();
2102 CString CAppUtils::ChooseRepository(const CString* path)
2104 CBrowseFolder browseFolder;
2105 CRegString regLastResopitory = CRegString(L"Software\\TortoiseGit\\TortoiseProc\\LastRepo", L"");
2107 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2108 CString strCloneDirectory;
2109 if(path)
2110 strCloneDirectory=*path;
2111 else
2112 strCloneDirectory = regLastResopitory;
2114 CString title;
2115 title.LoadString(IDS_CHOOSE_REPOSITORY);
2117 browseFolder.SetInfo(title);
2119 if (browseFolder.Show(nullptr, strCloneDirectory) == CBrowseFolder::OK)
2121 regLastResopitory = strCloneDirectory;
2122 return strCloneDirectory;
2124 else
2125 return CString();
2128 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2130 CSendMailDlg dlg;
2132 dlg.m_PathList = list;
2134 if(dlg.DoModal()==IDOK)
2136 if (dlg.m_PathList.IsEmpty())
2137 return FALSE;
2139 CGitProgressDlg progDlg;
2140 if (bIsMainWnd)
2141 theApp.m_pMainWnd = &progDlg;
2142 SendMailProgressCommand sendMailProgressCommand;
2143 progDlg.SetCommand(&sendMailProgressCommand);
2145 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2146 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2148 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2149 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2151 progDlg.DoModal();
2153 return true;
2155 return false;
2158 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2160 CTGitPathList list;
2161 CString log=formatpatchoutput;
2162 int start=log.Find(cmd);
2163 if(start >=0)
2164 log.Tokenize(L"\n", start);
2165 else
2166 start = 0;
2168 while(start>=0)
2170 CString one = log.Tokenize(L"\n", start);
2171 one=one.Trim();
2172 if (one.IsEmpty() || CStringUtils::StartsWith(one, CString(MAKEINTRESOURCE(IDS_SUCCESS))))
2173 continue;
2174 one.Replace(L'/', L'\\');
2175 CTGitPath path;
2176 path.SetFromWin(one);
2177 list.AddPath(path);
2179 if (!list.IsEmpty())
2180 return SendPatchMail(list, bIsMainWnd);
2181 else
2183 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2184 return true;
2189 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2191 CString output;
2192 output = pGit->GetConfigValue(L"i18n.logOutputEncoding");
2193 if(output.IsEmpty())
2194 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(L"i18n.commitencoding"));
2195 else
2196 return CUnicodeUtils::GetCPCode(output);
2199 bool CAppUtils::MessageContainsConflictHints(HWND hWnd, const CString& message)
2201 bool stripComments = (CRegDWORD(L"Software\\TortoiseGit\\StripCommentedLines", FALSE) == TRUE);
2202 if (stripComments)
2203 return false;
2204 CString cleanupMode = g_Git.GetConfigValue(L"core.cleanup", L"default");
2205 if (cleanupMode == L"verbatim" || cleanupMode == L"whitespace" || cleanupMode == L"scissors")
2206 return false;
2207 TCHAR commentChar = L'#';
2208 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2209 if (!commentCharValue.IsEmpty())
2210 commentChar = commentCharValue[0];
2212 CString conflictsHint;
2213 conflictsHint.Format(L"\n%c Conflicts:\n%c\t", commentChar, commentChar);
2215 if (message.Find(conflictsHint) <= 0)
2216 return false;
2218 BOOL dontaskagainchecked = FALSE;
2219 if (CMessageBox::ShowCheck(hWnd, IDS_CONFLICT_HINT_IN_COMMIT_MESSAGE, IDS_APPNAME, 2, IDI_QUESTION, IDS_IGNOREBUTTON, IDS_ABORTBUTTON, 0, L"CommitMessageContainsConflictHint", IDS_MSGBOX_DONOTSHOWAGAIN, &dontaskagainchecked) == 2)
2221 if (dontaskagainchecked)
2222 CMessageBox::RemoveRegistryKey(L"CommitMessageContainsConflictHint");
2223 return true;
2225 return false;
2228 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2232 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2233 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(L"i18n.commitencoding"));
2235 bool stripComments = (CRegDWORD(L"Software\\TortoiseGit\\StripCommentedLines", FALSE) == TRUE);
2236 TCHAR commentChar = L'#';
2237 if (stripComments)
2239 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2240 if (!commentCharValue.IsEmpty())
2241 commentChar = commentCharValue[0];
2244 bool sanitize = (CRegDWORD(L"Software\\TortoiseGit\\SanitizeCommitMsg", TRUE) == TRUE);
2245 if (sanitize)
2246 message.Trim(L" \r\n");
2248 int len = message.GetLength();
2249 int start = 0;
2250 int emptyLineCnt = 0;
2251 while (start >= 0 && start < len)
2253 int oldStart = start;
2254 start = message.Find(L'\n', oldStart);
2255 CString line = message.Mid(oldStart);
2256 if (start != -1)
2258 line.Truncate(start - oldStart);
2259 ++start; // move forward so we don't find the same char again
2261 if (stripComments && (!line.IsEmpty() && line.GetAt(0) == commentChar) || (start < 0 && line.IsEmpty()))
2262 continue;
2263 line.TrimRight(L" \r");
2264 if (sanitize)
2266 if (line.IsEmpty())
2268 ++emptyLineCnt;
2269 continue;
2271 if (emptyLineCnt) // squash multiple newlines
2272 file.Write("\n", 1);
2273 emptyLineCnt = 0;
2275 CStringA lineA = CUnicodeUtils::GetMulti(line + L'\n', cp);
2276 file.Write((LPCSTR)lineA, lineA.GetLength());
2278 file.Close();
2279 return 0;
2281 catch (CFileException *e)
2283 e->Delete();
2284 return -1;
2288 bool DoPull(const CString& url, bool bAutoLoad, BOOL bFetchTags, bool bNoFF, bool bFFonly, bool bSquash, bool bNoCommit, int* nDepth, BOOL bPrune, const CString& remoteBranchName, bool showPush, bool showStashPop, bool bUnrelated)
2290 if (bAutoLoad)
2291 CAppUtils::LaunchPAgent(nullptr, &url);
2293 CGitHash hashOld;
2294 if (g_Git.GetHash(hashOld, L"HEAD"))
2296 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2297 return false;
2300 CString args;
2301 if (CRegDWORD(L"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE) == FALSE)
2302 args += L" --no-rebase";
2304 if (bFetchTags == BST_UNCHECKED)
2305 args += L" --no-tags";
2306 else if (bFetchTags == BST_CHECKED)
2307 args += L" --tags";
2309 if (bNoFF)
2310 args += L" --no-ff";
2312 if (bFFonly)
2313 args += L" --ff-only";
2315 if (bSquash)
2316 args += L" --squash";
2318 if (bNoCommit)
2319 args += L" --no-commit";
2321 if (nDepth)
2322 args.AppendFormat(L" --depth %d", *nDepth);
2324 if (bPrune == BST_CHECKED)
2325 args += L" --prune";
2326 else if (bPrune == BST_UNCHECKED)
2327 args += L" --no-prune";
2329 if (bUnrelated)
2330 args += L" --allow-unrelated-histories";
2332 CString cmd;
2333 cmd.Format(L"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR)args, (LPCTSTR)url, (LPCTSTR)remoteBranchName);
2334 CProgressDlg progress;
2335 progress.m_GitCmd = cmd;
2337 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2338 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2340 if (status)
2342 int hasConflicts = g_Git.HasWorkingTreeConflicts();
2343 if (hasConflicts < 0)
2344 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
2345 else if (hasConflicts)
2347 CMessageBox::ShowCheck(nullptr, IDS_NEED_TO_RESOLVE_CONFLICTS_HINT, IDS_APPNAME, MB_ICONINFORMATION, L"MergeConflictsNeedsCommit", IDS_MSGBOX_DONOTSHOWAGAIN);
2348 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2350 CString sCmd;
2351 sCmd.Format(L"/command:resolve /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2352 CAppUtils::RunTortoiseGitProc(sCmd);
2355 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
2357 CString sCmd;
2358 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2359 CAppUtils::RunTortoiseGitProc(sCmd);
2361 return;
2364 if (CAppUtils::IsGitVersionNewerOrEqual(2, 9))
2366 STRING_VECTOR remotes;
2367 g_Git.GetRemoteList(remotes);
2368 if (std::find(remotes.begin(), remotes.end(), url) != remotes.end())
2370 CString currentBranch;
2371 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2372 currentBranch.Empty();
2373 CString remoteRef = L"remotes/" + url + L"/" + remoteBranchName;
2374 if (!currentBranch.IsEmpty() && remoteBranchName.IsEmpty())
2376 CString pullRemote, pullBranch;
2377 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2378 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2379 remoteRef = L"remotes/" + pullRemote + L"/" + pullBranch;
2381 CGitHash common;
2382 g_Git.IsFastForward(L"HEAD", remoteRef, &common);
2383 if (common.IsEmpty())
2384 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoPull(url, bAutoLoad, bFetchTags, bNoFF, bFFonly, bSquash, bNoCommit, nDepth, bPrune, remoteBranchName, showPush, showStashPop, true); });
2388 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(); });
2389 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(L"", true); });
2390 return;
2393 if (showStashPop)
2394 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
2396 if (g_Git.GetHash(hashNew, L"HEAD"))
2397 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash after pulling."), L"TortoiseGit", MB_ICONERROR);
2398 else
2400 postCmdList.emplace_back(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2402 CString sCmd;
2403 sCmd.Format(L"/command:showcompare /path:\"%s\" /revision1:%s /revision2:%s", (LPCTSTR)g_Git.m_CurrentDir, (LPCTSTR)hashOld.ToString(), (LPCTSTR)hashNew.ToString());
2404 CAppUtils::RunTortoiseGitProc(sCmd);
2406 postCmdList.emplace_back(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2408 CString sCmd;
2409 sCmd.Format(L"/command:log /path:\"%s\" /range:%s", (LPCTSTR)g_Git.m_CurrentDir, (LPCTSTR)(hashOld.ToString() + L".." + hashNew.ToString()));
2410 CAppUtils::RunTortoiseGitProc(sCmd);
2414 if (showPush)
2415 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
2417 CTGitPath gitPath = g_Git.m_CurrentDir;
2418 if (gitPath.HasSubmodules())
2420 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2422 CString sCmd;
2423 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2424 CAppUtils::RunTortoiseGitProc(sCmd);
2429 INT_PTR ret = progress.DoModal();
2431 if (ret == IDOK && progress.m_GitStatus == 1 && progress.m_LogText.Find(L"CONFLICT") >= 0 && CMessageBox::Show(nullptr, IDS_SEECHANGES, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
2433 cmd.Format(L"/command:repostatus /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2434 CAppUtils::RunTortoiseGitProc(cmd);
2436 return true;
2439 return ret == IDOK;
2442 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2444 if (IsTGitRebaseActive())
2445 return false;
2447 CPullFetchDlg dlg;
2448 dlg.m_IsPull = TRUE;
2449 if (dlg.DoModal() == IDOK)
2451 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2452 if (dlg.m_bRebase)
2453 return DoFetch(dlg.m_RemoteURL,
2454 FALSE, // Fetch all remotes
2455 dlg.m_bAutoLoad == BST_CHECKED,
2456 dlg.m_bPrune,
2457 dlg.m_bDepth == BST_CHECKED,
2458 dlg.m_nDepth,
2459 dlg.m_bFetchTags,
2460 dlg.m_RemoteBranchName,
2461 dlg.m_bRebaseActivatedInConfigForPull ? 2 : 1, // Rebase after fetching
2462 dlg.m_bRebasePreserveMerges == TRUE); // Preserve merges on rebase
2464 return DoPull(dlg.m_RemoteURL, dlg.m_bAutoLoad == BST_CHECKED, dlg.m_bFetchTags, dlg.m_bNoFF == BST_CHECKED, dlg.m_bFFonly == BST_CHECKED, dlg.m_bSquash == BST_CHECKED, dlg.m_bNoCommit == BST_CHECKED, dlg.m_bDepth ? &dlg.m_nDepth : nullptr, dlg.m_bPrune, dlg.m_RemoteBranchName, showPush, showStashPop, false);
2467 return false;
2470 bool CAppUtils::RebaseAfterFetch(const CString& upstream, int rebase, bool preserveMerges)
2472 while (true)
2474 CRebaseDlg dlg;
2475 if (!upstream.IsEmpty())
2476 dlg.m_Upstream = upstream;
2477 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2478 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2479 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2480 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2481 dlg.m_bRebaseAutoStart = (rebase == 2);
2482 dlg.m_bPreserveMerges = preserveMerges;
2483 INT_PTR response = dlg.DoModal();
2484 if (response == IDOK)
2485 return true;
2486 else if (response == IDC_REBASE_POST_BUTTON)
2488 CString cmd = L"/command:log";
2489 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2490 CAppUtils::RunTortoiseGitProc(cmd);
2491 return true;
2493 else if (response == IDC_REBASE_POST_BUTTON + 1)
2494 return Push();
2495 else if (response == IDC_REBASE_POST_BUTTON + 2)
2497 CString cmd, out, err;
2498 cmd.Format(L"git.exe format-patch -o \"%s\" %s..%s",
2499 (LPCTSTR)g_Git.m_CurrentDir,
2500 (LPCTSTR)g_Git.FixBranchName(dlg.m_Upstream),
2501 (LPCTSTR)g_Git.FixBranchName(dlg.m_Branch));
2502 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2504 CMessageBox::Show(nullptr, out + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
2505 return false;
2507 CAppUtils::SendPatchMail(cmd, out);
2508 return true;
2510 else if (response == IDC_REBASE_POST_BUTTON + 3)
2511 continue;
2512 else if (response == IDCANCEL)
2513 return false;
2514 return false;
2518 static bool DoFetch(const CString& url, const bool fetchAllRemotes, const bool loadPuttyAgent, const int prune, const bool bDepth, const int nDepth, const int fetchTags, const CString& remoteBranch, int runRebase, const bool rebasePreserveMerges)
2520 if (loadPuttyAgent)
2522 if (fetchAllRemotes)
2524 STRING_VECTOR list;
2525 g_Git.GetRemoteList(list);
2527 for (const auto& remote : list)
2528 CAppUtils::LaunchPAgent(nullptr, &remote);
2530 else
2531 CAppUtils::LaunchPAgent(nullptr, &url);
2534 CString upstream = L"FETCH_HEAD";
2535 CGitHash oldUpstreamHash;
2536 if (runRebase)
2538 STRING_VECTOR list;
2539 g_Git.GetRemoteList(list);
2540 for (auto it = list.cbegin(); it != list.cend(); ++it)
2542 if (url == *it)
2544 upstream.Empty();
2545 if (remoteBranch.IsEmpty()) // pulldlg might clear remote branch if its the default tracked branch
2547 CString currentBranch;
2548 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2549 currentBranch.Empty();
2550 if (!currentBranch.IsEmpty() && remoteBranch.IsEmpty())
2552 CString pullRemote, pullBranch;
2553 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2554 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty() && pullRemote == url) // pullRemote == url is just another safety-check and should not be needed
2555 upstream = L"remotes/" + *it + L'/' + pullBranch;
2558 else
2559 upstream = L"remotes/" + *it + L'/' + remoteBranch;
2561 g_Git.GetHash(oldUpstreamHash, upstream);
2562 break;
2567 CString cmd, arg;
2568 arg = L" --progress";
2570 if (bDepth)
2571 arg.AppendFormat(L" --depth %d", nDepth);
2573 if (prune == TRUE)
2574 arg += L" --prune";
2575 else if (prune == FALSE)
2576 arg += L" --no-prune";
2578 if (fetchTags == 1)
2579 arg += L" --tags";
2580 else if (fetchTags == 0)
2581 arg += L" --no-tags";
2583 if (fetchAllRemotes)
2584 cmd.Format(L"git.exe fetch --all -v%s", (LPCTSTR)arg);
2585 else
2586 cmd.Format(L"git.exe fetch -v%s \"%s\" %s", (LPCTSTR)arg, (LPCTSTR)url, (LPCTSTR)remoteBranch);
2588 CProgressDlg progress;
2589 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2591 if (status)
2593 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase, rebasePreserveMerges); });
2594 if (fetchAllRemotes)
2595 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2597 CString cmd = L"/command:log";
2598 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2599 CAppUtils::RunTortoiseGitProc(cmd);
2601 return;
2604 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2606 CString cmd = L"/command:log";
2607 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2608 CAppUtils::RunTortoiseGitProc(cmd);
2611 postCmdList.emplace_back(IDI_REVERT, IDS_PROC_RESET, []
2613 CString pullRemote, pullBranch;
2614 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2615 CString defaultUpstream;
2616 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2617 defaultUpstream.Format(L"remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
2618 CAppUtils::GitReset(&defaultUpstream, 2);
2621 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); });
2623 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2624 postCmdList.emplace_back(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); });
2627 progress.m_GitCmd = cmd;
2629 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2631 CGitProgressDlg gitdlg;
2632 FetchProgressCommand fetchProgressCommand;
2633 if (!fetchAllRemotes)
2634 fetchProgressCommand.SetUrl(url);
2635 gitdlg.SetCommand(&fetchProgressCommand);
2636 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2637 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2638 fetchProgressCommand.SetPrune(prune == BST_CHECKED ? GIT_FETCH_PRUNE : prune == BST_INDETERMINATE ? GIT_FETCH_PRUNE_UNSPECIFIED : GIT_FETCH_NO_PRUNE);
2639 if (!fetchAllRemotes)
2640 fetchProgressCommand.SetRefSpec(remoteBranch);
2641 return gitdlg.DoModal() == IDOK;
2644 progress.m_PostExecCallback = [&](DWORD& exitCode, CString&)
2646 if (exitCode || !runRebase)
2647 return;
2649 CGitHash remoteBranchHash;
2650 g_Git.GetHash(remoteBranchHash, upstream);
2652 if (runRebase == 1)
2654 CGitHash headHash, commonAcestor;
2655 if (!g_Git.GetHash(headHash, L"HEAD") && (remoteBranchHash == headHash || (g_Git.IsFastForward(upstream, L"HEAD", &commonAcestor) && commonAcestor == remoteBranchHash)) && CMessageBox::ShowCheck(nullptr, IDS_REBASE_CURRENTBRANCHUPTODATE, IDS_APPNAME, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2, L"OpenRebaseRemoteBranchEqualsHEAD", IDS_MSGBOX_DONOTSHOWAGAIN) == IDNO)
2656 return;
2658 if (remoteBranchHash == oldUpstreamHash && !oldUpstreamHash.IsEmpty() && CMessageBox::ShowCheck(nullptr, IDS_REBASE_BRANCH_UNCHANGED, IDS_APPNAME, MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2, L"OpenRebaseRemoteBranchUnchanged", IDS_MSGBOX_DONOTSHOWAGAIN) == IDNO)
2659 return;
2662 if (runRebase == 1 && g_Git.IsFastForward(L"HEAD", upstream))
2664 UINT ret = CMessageBox::ShowCheck(nullptr, IDS_REBASE_BRANCH_FF, IDS_APPNAME, 2, IDI_QUESTION, IDS_MERGEBUTTON, IDS_REBASEBUTTON, IDS_ABORTBUTTON, L"OpenRebaseRemoteBranchFastForwards", IDS_MSGBOX_DONOTSHOWAGAIN);
2665 if (ret == 3)
2666 return;
2667 if (ret == 1)
2669 CProgressDlg mergeProgress;
2670 mergeProgress.m_GitCmd = L"git.exe merge --ff-only " + upstream;
2671 mergeProgress.m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
2672 mergeProgress.m_PostCmdCallback = [](DWORD status, PostCmdList& postCmdList)
2674 if (status && g_Git.HasWorkingTreeConflicts())
2676 // there are conflict files
2677 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2679 CString sCmd;
2680 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2681 CAppUtils::RunTortoiseGitProc(sCmd);
2685 mergeProgress.DoModal();
2686 return;
2690 CAppUtils::RebaseAfterFetch(upstream, runRebase, rebasePreserveMerges);
2693 return progress.DoModal() == IDOK;
2696 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2698 CPullFetchDlg dlg;
2699 dlg.m_PreSelectRemote = remoteName;
2700 dlg.m_IsPull=FALSE;
2701 dlg.m_bAllRemotes = allRemotes;
2703 if(dlg.DoModal()==IDOK)
2704 return DoFetch(dlg.m_RemoteURL, dlg.m_bAllRemotes == BST_CHECKED, dlg.m_bAutoLoad == BST_CHECKED, dlg.m_bPrune, dlg.m_bDepth == BST_CHECKED, dlg.m_nDepth, dlg.m_bFetchTags, dlg.m_RemoteBranchName, dlg.m_bRebase == BST_CHECKED ? 1 : 0, FALSE);
2706 return false;
2709 bool CAppUtils::DoPush(bool autoloadKey, bool pack, bool tags, bool allRemotes, bool allBranches, bool force, bool forceWithLease, const CString& localBranch, const CString& remote, const CString& remoteBranch, bool setUpstream, int recurseSubmodules)
2711 CString error;
2712 DWORD exitcode = 0xFFFFFFFF;
2713 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2715 if (exitcode)
2717 CString temp;
2718 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2719 MessageBox(nullptr, temp, L"TortoiseGit", MB_OK | MB_ICONERROR);
2720 return false;
2724 int iRecurseSubmodules = 0;
2725 if (IsGitVersionNewerOrEqual(2, 7))
2727 CString sRecurseSubmodules = g_Git.GetConfigValue(L"push.recurseSubmodules");
2728 if (sRecurseSubmodules == L"check")
2729 iRecurseSubmodules = 1;
2730 else if (sRecurseSubmodules == L"on-demand")
2731 iRecurseSubmodules = 2;
2734 CString arg;
2735 if (pack)
2736 arg += L"--thin ";
2737 if (tags && !allBranches)
2738 arg += L"--tags ";
2739 if (force)
2740 arg += L"--force ";
2741 if (forceWithLease)
2742 arg += L"--force-with-lease ";
2743 if (setUpstream)
2744 arg += L"--set-upstream ";
2745 if (recurseSubmodules == 0 && recurseSubmodules != iRecurseSubmodules)
2746 arg += L"--recurse-submodules=no ";
2747 if (recurseSubmodules == 1 && recurseSubmodules != iRecurseSubmodules)
2748 arg += L"--recurse-submodules=check ";
2749 if (recurseSubmodules == 2 && recurseSubmodules != iRecurseSubmodules)
2750 arg += L"--recurse-submodules=on-demand ";
2752 arg += L"--progress ";
2754 CProgressDlg progress;
2756 STRING_VECTOR remotesList;
2757 if (allRemotes)
2758 g_Git.GetRemoteList(remotesList);
2759 else
2760 remotesList.push_back(remote);
2762 for (unsigned int i = 0; i < remotesList.size(); ++i)
2764 if (autoloadKey)
2765 CAppUtils::LaunchPAgent(nullptr, &remotesList[i]);
2767 CString cmd;
2768 if (allBranches)
2770 cmd.Format(L"git.exe push --all %s\"%s\"",
2771 (LPCTSTR)arg,
2772 (LPCTSTR)remotesList[i]);
2774 if (tags)
2776 progress.m_GitCmdList.push_back(cmd);
2777 cmd.Format(L"git.exe push --tags %s\"%s\"", (LPCTSTR)arg, (LPCTSTR)remotesList[i]);
2780 else
2782 cmd.Format(L"git.exe push %s\"%s\" %s",
2783 (LPCTSTR)arg,
2784 (LPCTSTR)remotesList[i],
2785 (LPCTSTR)localBranch);
2786 if (!remoteBranch.IsEmpty())
2788 cmd += L":";
2789 cmd += remoteBranch;
2792 progress.m_GitCmdList.push_back(cmd);
2794 if (!allBranches && !!CRegDWORD(L"Software\\TortoiseGit\\ShowBranchRevisionNumber", FALSE))
2796 cmd.Format(L"git.exe rev-list --count --first-parent %s", (LPCTSTR)localBranch);
2797 progress.m_GitCmdList.push_back(cmd);
2801 CString superprojectRoot;
2802 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2803 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2805 // need to execute hooks as those might be needed by post action commands
2806 DWORD exitcode = 0xFFFFFFFF;
2807 CString error;
2808 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2810 if (exitcode)
2812 CString temp;
2813 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2814 MessageBox(nullptr, temp, L"TortoiseGit", MB_OK | MB_ICONERROR);
2818 if (status)
2820 bool rejected = progress.GetLogText().Find(L"! [rejected]") > 0;
2821 if (rejected)
2823 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, []{ Pull(true); });
2824 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(allRemotes ? L"" : remote, allRemotes); });
2826 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2827 return;
2830 postCmdList.emplace_back(IDS_PROC_REQUESTPULL, [&]{ RequestPull(remoteBranch); });
2831 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2832 postCmdList.emplace_back(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); });
2833 if (!superprojectRoot.IsEmpty())
2835 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2837 CString sCmd;
2838 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)superprojectRoot);
2839 RunTortoiseGitProc(sCmd);
2844 INT_PTR ret = progress.DoModal();
2845 return ret == IDOK;
2848 bool CAppUtils::Push(const CString& selectLocalBranch)
2850 CPushDlg dlg;
2851 dlg.m_BranchSourceName = selectLocalBranch;
2853 if (dlg.DoModal() == IDOK)
2854 return DoPush(!!dlg.m_bAutoLoad, !!dlg.m_bPack, !!dlg.m_bTags, !!dlg.m_bPushAllRemotes, !!dlg.m_bPushAllBranches, !!dlg.m_bForce, !!dlg.m_bForceWithLease, dlg.m_BranchSourceName, dlg.m_URL, dlg.m_BranchRemoteName, !!dlg.m_bSetUpstream, dlg.m_RecurseSubmodules);
2856 return FALSE;
2859 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2861 CRequestPullDlg dlg;
2862 dlg.m_RepositoryURL = repositoryUrl;
2863 dlg.m_EndRevision = endrevision;
2864 if (dlg.DoModal()==IDOK)
2866 CString cmd;
2867 cmd.Format(L"git.exe request-pull %s \"%s\" %s", (LPCTSTR)dlg.m_StartRevision, (LPCTSTR)dlg.m_RepositoryURL, (LPCTSTR)dlg.m_EndRevision);
2869 CSysProgressDlg sysProgressDlg;
2870 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2871 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2872 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2873 sysProgressDlg.SetShowProgressBar(false);
2874 sysProgressDlg.ShowModeless((HWND)nullptr, true);
2876 CString tempFileName = GetTempFile();
2877 CString err;
2878 DeleteFile(tempFileName);
2879 CreateDirectory(tempFileName, nullptr);
2880 tempFileName += L"\\pullrequest.txt";
2881 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2883 CString msg;
2884 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2885 MessageBox(nullptr, msg + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
2886 return false;
2889 if (sysProgressDlg.HasUserCancelled())
2891 CMessageBox::Show(nullptr, IDS_USERCANCELLED, IDS_APPNAME, MB_OK);
2892 ::DeleteFile(tempFileName);
2893 return false;
2896 sysProgressDlg.Stop();
2898 if (dlg.m_bSendMail)
2900 CSendMailDlg sendmaildlg;
2901 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2902 sendmaildlg.m_bCustomSubject = true;
2904 if (sendmaildlg.DoModal() == IDOK)
2906 if (sendmaildlg.m_PathList.IsEmpty())
2907 return FALSE;
2909 CGitProgressDlg progDlg;
2910 if (bIsMainWnd)
2911 theApp.m_pMainWnd = &progDlg;
2912 SendMailProgressCommand sendMailProgressCommand;
2913 progDlg.SetCommand(&sendMailProgressCommand);
2915 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2916 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2918 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2919 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2921 progDlg.DoModal();
2923 return true;
2925 return false;
2928 CAppUtils::LaunchAlternativeEditor(tempFileName);
2930 return true;
2933 void CAppUtils::RemoveTrailSlash(CString &path)
2935 if(path.IsEmpty())
2936 return ;
2938 // For URL, do not trim the slash just after the host name component.
2939 int index = path.Find(L"://");
2940 if (index >= 0)
2942 index += 4;
2943 index = path.Find(L'/', index);
2944 if (index == path.GetLength() - 1)
2945 return;
2948 while (path[path.GetLength() - 1] == L'\\' || path[path.GetLength() - 1] == L'/')
2950 path.Truncate(path.GetLength() - 1);
2951 if(path.IsEmpty())
2952 return;
2956 bool CAppUtils::CheckUserData()
2958 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2960 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO | MB_ICONERROR) == IDYES)
2962 CTGitPath path(g_Git.m_CurrentDir);
2963 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2964 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2965 dlg.SetTreeWidth(220);
2966 dlg.m_DefaultPage = L"gitconfig";
2968 dlg.DoModal();
2969 dlg.HandleRestart();
2972 else
2973 return false;
2976 return true;
2979 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
2980 CTGitPathList &pathList,
2981 CTGitPathList &selectedList,
2982 bool bSelectFilesForCommit)
2984 bool bFailed = true;
2986 if (!CheckUserData())
2987 return false;
2989 while (bFailed)
2991 bFailed = false;
2992 CCommitDlg dlg;
2993 dlg.m_sBugID = bugid;
2995 dlg.m_bWholeProject = bWholeProject;
2997 dlg.m_sLogMessage = sLogMsg;
2998 dlg.m_pathList = pathList;
2999 dlg.m_checkedPathList = selectedList;
3000 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
3001 if (dlg.DoModal() == IDOK)
3003 if (dlg.m_pathList.IsEmpty())
3004 return false;
3005 // if the user hasn't changed the list of selected items
3006 // we don't use that list. Because if we would use the list
3007 // of pre-checked items, the dialog would show different
3008 // checked items on the next startup: it would only try
3009 // to check the parent folder (which might not even show)
3010 // instead, we simply use an empty list and let the
3011 // default checking do its job.
3012 if (!dlg.m_pathList.IsEqual(pathList))
3013 selectedList = dlg.m_pathList;
3014 pathList = dlg.m_updatedPathList;
3015 sLogMsg = dlg.m_sLogMessage;
3016 bSelectFilesForCommit = true;
3018 switch (dlg.m_PostCmd)
3020 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3021 CAppUtils::SVNDCommit();
3022 break;
3023 case GIT_POSTCOMMIT_CMD_PUSH:
3024 CAppUtils::Push();
3025 break;
3026 case GIT_POSTCOMMIT_CMD_CREATETAG:
3027 CAppUtils::CreateBranchTag(TRUE);
3028 break;
3029 case GIT_POSTCOMMIT_CMD_PULL:
3030 CAppUtils::Pull(true);
3031 break;
3032 default:
3033 break;
3036 // CGitProgressDlg progDlg;
3037 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3038 // if (parser.HasVal(L"closeonend"))
3039 // progDlg.SetAutoClose(parser.GetLongVal(L"closeonend"));
3040 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3041 // progDlg.SetPathList(dlg.m_pathList);
3042 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3043 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3044 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3045 // progDlg.SetItemCount(dlg.m_itemsCount);
3046 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3047 // progDlg.DoModal();
3048 // CRegDWORD err = CRegDWORD(L"Software\\TortoiseGit\\ErrorOccurred", FALSE);
3049 // err = (DWORD)progDlg.DidErrorsOccur();
3050 // bFailed = progDlg.DidErrorsOccur();
3051 // bRet = progDlg.DidErrorsOccur();
3052 // CRegDWORD bFailRepeat = CRegDWORD(L"Software\\TortoiseGit\\CommitReopen", FALSE);
3053 // if (DWORD(bFailRepeat)==0)
3054 // bFailed = false; // do not repeat if the user chose not to in the settings.
3057 return true;
3060 BOOL CAppUtils::SVNDCommit()
3062 CSVNDCommitDlg dcommitdlg;
3063 CString gitSetting = g_Git.GetConfigValue(L"svn.rmdir");
3064 if (gitSetting.IsEmpty()) {
3065 if (dcommitdlg.DoModal() != IDOK)
3066 return false;
3067 else
3069 if (dcommitdlg.m_remember)
3071 if (dcommitdlg.m_rmdir)
3072 gitSetting = L"true";
3073 else
3074 gitSetting = L"false";
3075 if (g_Git.SetConfigValue(L"svn.rmdir", gitSetting))
3077 CString msg;
3078 msg.Format(IDS_PROC_SAVECONFIGFAILED, L"svn.rmdir", (LPCTSTR)gitSetting);
3079 MessageBox(nullptr, msg, L"TortoiseGit", MB_OK | MB_ICONERROR);
3085 BOOL IsStash = false;
3086 if(!g_Git.CheckCleanWorkTree())
3088 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3090 CSysProgressDlg sysProgressDlg;
3091 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3092 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3093 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3094 sysProgressDlg.SetShowProgressBar(false);
3095 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3096 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3098 CString out;
3099 if (g_Git.Run(L"git.exe stash", &out, CP_UTF8))
3101 sysProgressDlg.Stop();
3102 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3103 return false;
3105 sysProgressDlg.Stop();
3107 IsStash =true;
3109 else
3110 return false;
3113 CProgressDlg progress;
3114 if (dcommitdlg.m_rmdir)
3115 progress.m_GitCmd = L"git.exe svn dcommit --rmdir";
3116 else
3117 progress.m_GitCmd = L"git.exe svn dcommit";
3118 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3120 if( IsStash)
3122 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
3124 CSysProgressDlg sysProgressDlg;
3125 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3126 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3127 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3128 sysProgressDlg.SetShowProgressBar(false);
3129 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3130 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3132 CString out;
3133 if (g_Git.Run(L"git.exe stash pop", &out, CP_UTF8))
3135 sysProgressDlg.Stop();
3136 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3137 return false;
3139 sysProgressDlg.Stop();
3141 else
3142 return false;
3144 return TRUE;
3146 return FALSE;
3149 static bool DoMerge(bool noFF, bool ffOnly, bool squash, bool noCommit, const int* log, bool unrelated, const CString& mergeStrategy, const CString& strategyOption, const CString& strategyParam, const CString& logMessage, const CString& version, bool isBranch, bool showStashPop)
3151 CString args;
3152 if (noFF)
3153 args += L" --no-ff";
3154 else if (ffOnly)
3155 args += L" --ff-only";
3157 if (squash)
3158 args += L" --squash";
3160 if (noCommit)
3161 args += L" --no-commit";
3163 if (unrelated)
3164 args += L" --allow-unrelated-histories";
3166 if (log)
3167 args.AppendFormat(L" --log=%d", *log);
3169 if (!mergeStrategy.IsEmpty())
3171 args += L" --strategy=" + mergeStrategy;
3172 if (!strategyOption.IsEmpty())
3174 args += L" --strategy-option=" + strategyOption;
3175 if (!strategyParam.IsEmpty())
3176 args += L'=' + strategyParam;
3180 if (!logMessage.IsEmpty())
3182 CString logmsg = logMessage;
3183 logmsg.Replace(L"\\\"", L"\\\\\"");
3184 logmsg.Replace(L"\"", L"\\\"");
3185 args += L" -m \"" + logmsg + L"\"";
3188 CString mergeVersion = g_Git.FixBranchName(version);
3189 CString cmd;
3190 cmd.Format(L"git.exe merge%s %s", (LPCTSTR)args, (LPCTSTR)mergeVersion);
3192 CProgressDlg Prodlg;
3193 Prodlg.m_GitCmd = cmd;
3195 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3197 if (status)
3199 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3200 if (hasConflicts < 0)
3201 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
3202 else if (hasConflicts)
3204 // there are conflict files
3205 CMessageBox::ShowCheck(nullptr, IDS_NEED_TO_RESOLVE_CONFLICTS_HINT, IDS_APPNAME, MB_ICONINFORMATION, L"MergeConflictsNeedsCommit", IDS_MSGBOX_DONOTSHOWAGAIN);
3206 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3208 CString sCmd;
3209 sCmd.Format(L"/command:resolve /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3210 CAppUtils::RunTortoiseGitProc(sCmd);
3213 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3215 CString sCmd;
3216 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3217 CAppUtils::RunTortoiseGitProc(sCmd);
3221 if (CAppUtils::IsGitVersionNewerOrEqual(2, 9))
3223 CGitHash common;
3224 g_Git.IsFastForward(L"HEAD", mergeVersion, &common);
3225 if (common.IsEmpty())
3226 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoMerge(noFF, ffOnly, squash, noCommit, log, true, mergeStrategy, strategyOption, strategyParam, logMessage, version, isBranch, showStashPop); });
3229 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [=]{ CAppUtils::StashSave(L"", false, false, true, mergeVersion); });
3231 return;
3234 if (showStashPop)
3235 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
3237 if (noCommit || squash)
3239 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3241 CString sCmd;
3242 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3243 CAppUtils::RunTortoiseGitProc(sCmd);
3245 return;
3248 if (isBranch && !CStringUtils::StartsWith(version, L"remotes/")) // do not ask to remove remote branches
3250 postCmdList.emplace_back(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3252 CString msg;
3253 msg.Format(IDS_PROC_DELETEBRANCHTAG, (LPCTSTR)version);
3254 if (CMessageBox::Show(nullptr, msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3256 CString cmd, out;
3257 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)version);
3258 if (g_Git.Run(cmd, &out, CP_UTF8))
3259 MessageBox(nullptr, out, L"TortoiseGit", MB_OK);
3263 if (isBranch)
3264 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
3266 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3267 if (hasGitSVN)
3268 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ CAppUtils::SVNDCommit(); });
3271 Prodlg.DoModal();
3272 return !Prodlg.m_GitStatus;
3275 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3277 if (!CheckUserData())
3278 return FALSE;
3280 if (IsTGitRebaseActive())
3281 return FALSE;
3283 CMergeDlg dlg;
3284 if (commit)
3285 dlg.m_initialRefName = *commit;
3287 if (dlg.DoModal() == IDOK)
3288 return DoMerge(dlg.m_bNoFF == BST_CHECKED, dlg.m_bFFonly == BST_CHECKED, dlg.m_bSquash == BST_CHECKED, dlg.m_bNoCommit == BST_CHECKED, dlg.m_bLog ? &dlg.m_nLog : nullptr, false, dlg.m_MergeStrategy, dlg.m_StrategyOption, dlg.m_StrategyParam, dlg.m_strLogMesage, dlg.m_VersionName, dlg.m_bIsBranch, showStashPop);
3290 return FALSE;
3293 BOOL CAppUtils::MergeAbort()
3295 CMergeAbortDlg dlg;
3296 if (dlg.DoModal() == IDOK)
3297 return Reset(L"HEAD", (dlg.m_ResetType == 0) ? 3 : dlg.m_ResetType);
3299 return FALSE;
3302 void CAppUtils::EditNote(GitRevLoglist* rev, ProjectProperties* projectProperties)
3304 if (!CheckUserData())
3305 return;
3307 CInputDlg dlg;
3308 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3309 dlg.m_sInputText = rev->m_Notes;
3310 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3311 dlg.m_pProjectProperties = projectProperties;
3312 dlg.m_bUseLogWidth = true;
3313 if(dlg.DoModal() == IDOK)
3315 if (g_Git.SetGitNotes(rev->m_CommitHash, dlg.m_sInputText))
3317 CString err;
3318 err.LoadString(IDS_PROC_FAILEDSAVINGNOTES);
3319 MessageBox(nullptr, g_Git.GetLibGit2LastErr(err), L"TortoiseGit", MB_OK | MB_ICONERROR);
3320 return;
3323 if (g_Git.GetGitNotes(rev->m_CommitHash, rev->m_Notes))
3324 MessageBox(nullptr, g_Git.GetLibGit2LastErr(L"Could not load notes for commit " + rev->m_CommitHash.ToString() + L'.'), L"TortoiseGit", MB_OK | MB_ICONERROR);
3328 inline static int ConvertToVersionInt(int major, int minor, int patchlevel, int build)
3330 return (major << 24) + (minor << 16) + (patchlevel << 8) + build;
3333 inline bool CAppUtils::IsGitVersionNewerOrEqual(int major, int minor, int patchlevel, int build)
3335 auto ver = GetMsysgitVersion();
3336 return ver >= ConvertToVersionInt(major, minor, patchlevel, build);
3339 int CAppUtils::GetMsysgitVersion()
3341 if (g_Git.ms_LastMsysGitVersion)
3342 return g_Git.ms_LastMsysGitVersion;
3344 CString cmd;
3345 CString versiondebug;
3346 CString version;
3348 CRegDWORD regTime = CRegDWORD(L"Software\\TortoiseGit\\git_file_time");
3349 CRegDWORD regVersion = CRegDWORD(L"Software\\TortoiseGit\\git_cached_version");
3351 CString gitpath = CGit::ms_LastMsysGitDir + L"\\git.exe";
3353 __int64 time=0;
3354 if (!CGit::GetFileModifyTime(gitpath, &time))
3356 if ((DWORD)CGit::filetime_to_time_t(time) == regTime)
3358 g_Git.ms_LastMsysGitVersion = regVersion;
3359 return regVersion;
3363 CString err;
3364 int ver = g_Git.GetGitVersion(&versiondebug, &err);
3365 if (ver < 0)
3367 MessageBox(nullptr, L"git.exe not correctly set up (" + err + L")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\".", L"TortoiseGit", MB_OK | MB_ICONERROR);
3368 return -1;
3372 if (!ver)
3374 MessageBox(nullptr, L"Could not parse git.exe version number: \"" + versiondebug + L'"', L"TortoiseGit", MB_OK | MB_ICONERROR);
3375 return -1;
3379 regTime = time&0xFFFFFFFF;
3380 regVersion = ver;
3381 g_Git.ms_LastMsysGitVersion = ver;
3383 return ver;
3386 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3388 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3390 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(L"Shell32.dll");
3392 if (hShell.IsValid()) {
3393 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3394 if (pfnSHGPSFW) {
3395 IPropertyStore *pps;
3396 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3397 if (SUCCEEDED(hr)) {
3398 PROPVARIANT var;
3399 var.vt = VT_BOOL;
3400 var.boolVal = VARIANT_TRUE;
3401 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3402 pps->Release();
3408 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3410 ASSERT(dialogname.GetLength() < 70);
3411 ASSERT(urlorpath.GetLength() < MAX_PATH);
3412 WCHAR pathbuf[MAX_PATH] = {0};
3414 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3416 wcscat_s(pathbuf, L" - ");
3417 wcscat_s(pathbuf, dialogname);
3418 wcscat_s(pathbuf, L" - ");
3419 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3420 SetWindowText(hWnd, pathbuf);
3423 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3425 if (!g_Git.CheckCleanWorkTree())
3427 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3429 CSysProgressDlg sysProgressDlg;
3430 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3431 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3432 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3433 sysProgressDlg.SetShowProgressBar(false);
3434 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3435 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3437 CString out;
3438 if (g_Git.Run(L"git.exe stash", &out, CP_UTF8))
3440 sysProgressDlg.Stop();
3441 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3442 return false;
3444 sysProgressDlg.Stop();
3446 else
3447 return false;
3450 CBisectStartDlg bisectStartDlg;
3452 if (!lastGood.IsEmpty())
3453 bisectStartDlg.m_sLastGood = lastGood;
3454 if (!firstBad.IsEmpty())
3455 bisectStartDlg.m_sFirstBad = firstBad;
3457 if (bisectStartDlg.DoModal() == IDOK)
3459 CProgressDlg progress;
3460 if (bIsMainWnd)
3461 theApp.m_pMainWnd = &progress;
3462 progress.m_GitCmdList.push_back(L"git.exe bisect start");
3463 progress.m_GitCmdList.push_back(L"git.exe bisect good " + bisectStartDlg.m_LastGoodRevision);
3464 progress.m_GitCmdList.push_back(L"git.exe bisect bad " + bisectStartDlg.m_FirstBadRevision);
3466 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3468 if (status)
3469 return;
3471 CTGitPath path(g_Git.m_CurrentDir);
3472 if (path.HasSubmodules())
3474 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3476 CString sCmd;
3477 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3478 CAppUtils::RunTortoiseGitProc(sCmd);
3482 postCmdList.emplace_back(IDI_THUMB_UP, IDS_MENUBISECTGOOD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /good"); });
3483 postCmdList.emplace_back(IDI_THUMB_DOWN, IDS_MENUBISECTBAD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /bad"); });
3484 postCmdList.emplace_back(IDI_BISECT_RESET, IDS_MENUBISECTRESET, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /reset"); });
3487 INT_PTR ret = progress.DoModal();
3488 return ret == IDOK;
3491 return false;
3494 bool CAppUtils::BisectOperation(const CString& op, const CString& ref, bool bIsMainWnd)
3496 CString cmd = L"git.exe bisect " + op;
3498 if (!ref.IsEmpty())
3500 cmd += L' ';
3501 cmd += ref;
3504 CProgressDlg progress;
3505 if (bIsMainWnd)
3506 theApp.m_pMainWnd = &progress;
3507 progress.m_GitCmd = cmd;
3509 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3511 if (status)
3512 return;
3514 CTGitPath path = g_Git.m_CurrentDir;
3515 if (path.HasSubmodules())
3517 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3519 CString sCmd;
3520 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3521 CAppUtils::RunTortoiseGitProc(sCmd);
3525 postCmdList.emplace_back(IDI_THUMB_UP, IDS_MENUBISECTGOOD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /good"); });
3526 postCmdList.emplace_back(IDI_THUMB_DOWN, IDS_MENUBISECTBAD, [] { CAppUtils::RunTortoiseGitProc(L"/command:bisect /bad"); });
3527 if (op != L"reset")
3528 postCmdList.emplace_back(IDI_BISECT_RESET, IDS_MENUBISECTRESET, []{ CAppUtils::RunTortoiseGitProc(L"/command:bisect /reset"); });
3531 INT_PTR ret = progress.DoModal();
3532 return ret == IDOK;
3535 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3537 CUserPassword dlg;
3538 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3539 if (username_from_url)
3540 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3542 CStringA username, password;
3543 if (dlg.DoModal() == IDOK)
3545 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3546 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3547 return git_cred_userpass_plaintext_new(out, username, password);
3549 giterr_set_str(GITERR_NONE, "User cancelled.");
3550 return GIT_EUSER;
3553 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3555 if (base_cert->cert_type == GIT_CERT_X509)
3557 git_cert_x509* cert = (git_cert_x509*)base_cert;
3559 if (last_accepted_cert.cmp(cert))
3560 return 0;
3562 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3563 SCOPE_EXIT { CertFreeCertificateContext(pServerCert); };
3565 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3566 if (!verificationError)
3568 last_accepted_cert.set(cert);
3569 return 0;
3572 CString servernameInCert;
3573 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, CStrBuf(servernameInCert, 128), 128);
3575 CString issuer;
3576 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, CStrBuf(issuer, 128), 128);
3578 CCheckCertificateDlg dlg;
3579 dlg.cert = cert;
3580 dlg.m_sCertificateCN = servernameInCert;
3581 dlg.m_sCertificateIssuer = issuer;
3582 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3583 dlg.m_sError = CFormatMessageWrapper(verificationError);
3584 if (dlg.DoModal() == IDOK)
3586 last_accepted_cert.set(cert);
3587 return 0;
3590 return GIT_ECERTIFICATE;
3593 int CAppUtils::ExploreTo(HWND hwnd, CString path)
3595 if (PathFileExists(path))
3597 HRESULT ret = E_FAIL;
3598 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3599 if (pidl)
3601 ret = SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3602 ILFree(pidl);
3604 return SUCCEEDED(ret) ? 0 : -1;
3606 // if filepath does not exist any more, navigate to closest matching folder
3609 int pos = path.ReverseFind(L'\\');
3610 if (pos <= 3)
3611 break;
3612 path.Truncate(pos);
3613 } while (!PathFileExists(path));
3614 return (INT_PTR)ShellExecute(hwnd, L"explore", path, nullptr, nullptr, SW_SHOW) > 32 ? 0 : -1;
3617 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3619 bool b_local = false, b_remote = false;
3620 BYTE_VECTOR vector;
3622 CString cmd;
3623 cmd.Format(L"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3624 if (g_Git.Run(cmd, &vector))
3626 MessageBox(nullptr, L"git ls-files failed!", L"TortoiseGit", MB_OK);
3627 return -1;
3630 CTGitPathList list;
3631 if (list.ParserFromLsFile(vector))
3633 MessageBox(nullptr, L"Parse ls-files failed!", L"TortoiseGit", MB_OK);
3634 return -1;
3637 if (list.IsEmpty())
3638 return 0;
3639 for (int i = 0; i < list.GetCount(); ++i)
3641 if (list[i].m_Stage == 2)
3642 b_local = true;
3643 if (list[i].m_Stage == 3)
3644 b_remote = true;
3648 bool baseIsFile = true, localIsFile = true, remoteIsFile = true;
3649 CString baseHash, localHash, remoteHash;
3650 ParseHashesFromLsFile(vector, baseHash, baseIsFile, localHash, localIsFile, remoteHash, remoteIsFile);
3652 CBlockCacheForPath block(g_Git.m_CurrentDir);
3653 if ((resolveWith == RESOLVE_WITH_THEIRS && !b_remote) || (resolveWith == RESOLVE_WITH_MINE && !b_local))
3655 CString gitcmd, output; //retest with registered submodule!
3656 gitcmd.Format(L"git.exe rm -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3657 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3659 // a .git folder in a submodule which is not in .gitmodules cannot be deleted using "git rm"
3660 if (PathIsDirectory(path.GetGitPathString()) && !PathIsDirectoryEmpty(path.GetGitPathString()))
3662 CString message(output);
3663 output += L"\n\n";
3664 output.AppendFormat(IDS_PROC_DELETEBRANCHTAG, path.GetWinPath());
3665 CString deleteButton;
3666 deleteButton.LoadString(IDS_DELETEBUTTON);
3667 CString abortButton;
3668 abortButton.LoadString(IDS_ABORTBUTTON);
3669 if (CMessageBox::Show(nullptr, output, L"TortoiseGit", 2, IDI_QUESTION, deleteButton, abortButton) == 2)
3670 return -1;
3671 path.Delete(true, true);
3672 output.Empty();
3673 if (!g_Git.Run(gitcmd, &output, CP_UTF8))
3675 RemoveTempMergeFile(path);
3676 return 0;
3679 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3680 return -1;
3682 RemoveTempMergeFile(path);
3683 return 0;
3686 if (resolveWith == RESOLVE_WITH_THEIRS || resolveWith == RESOLVE_WITH_MINE)
3688 auto resolve = [&b_local, &b_remote](const CTGitPath& path, int stage, bool willBeFile, const CString& hash) -> int
3690 if (!willBeFile)
3692 if (!path.HasAdminDir()) // check if submodule is initialized
3694 CString gitcmd, output;
3695 if (!path.IsDirectory())
3697 gitcmd.Format(L"git.exe checkout-index -f --stage=%d -- \"%s\"", stage, (LPCTSTR)path.GetGitPathString());
3698 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3700 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3701 return -1;
3704 gitcmd.Format(L"git.exe update-index --replace --cacheinfo 0160000,%s,\"%s\"", (LPCTSTR)hash, (LPCTSTR)path.GetGitPathString());
3705 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3707 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3708 return -1;
3710 return 0;
3713 CGit subgit;
3714 subgit.m_CurrentDir = g_Git.CombinePath(path);
3715 CGitHash submoduleHead;
3716 if (subgit.GetHash(submoduleHead, L"HEAD"))
3718 MessageBox(nullptr, subgit.GetGitLastErr(L"Could not get HEAD hash of submodule, this should not happen!"), L"TortoiseGit", MB_ICONERROR);
3719 return -1;
3721 if (submoduleHead.ToString() != hash)
3723 CString origPath = g_Git.m_CurrentDir;
3724 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3725 if (!GitReset(&hash))
3727 g_Git.m_CurrentDir = origPath;
3728 return -1;
3730 g_Git.m_CurrentDir = origPath;
3733 else
3735 CString gitcmd, output;
3736 if (b_local && b_remote)
3737 gitcmd.Format(L"git.exe checkout-index -f --stage=%d -- \"%s\"", stage, (LPCTSTR)path.GetGitPathString());
3738 else
3739 gitcmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3740 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3742 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3743 return -1;
3746 return 0;
3748 int ret = -1;
3749 if (resolveWith == RESOLVE_WITH_THEIRS)
3750 ret = resolve(path, 3, remoteIsFile, remoteHash);
3751 else
3752 ret = resolve(path, 2, localIsFile, localHash);
3753 if (ret)
3754 return ret;
3757 if (PathFileExists(g_Git.CombinePath(path)) && (path.m_Action & CTGitPath::LOGACTIONS_UNMERGED))
3759 CString gitcmd, output;
3760 gitcmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3761 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3763 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3764 return -1;
3767 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3768 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
3771 RemoveTempMergeFile(path);
3772 return 0;
3775 bool CAppUtils::ShellOpen(const CString& file, HWND hwnd /*= nullptr */)
3777 if ((INT_PTR)ShellExecute(hwnd, nullptr, file, nullptr, nullptr, SW_SHOW) > HINSTANCE_ERROR)
3778 return true;
3780 return ShowOpenWithDialog(file, hwnd);
3783 bool CAppUtils::ShowOpenWithDialog(const CString& file, HWND hwnd /*= nullptr */)
3785 OPENASINFO oi = { 0 };
3786 oi.pcszFile = file;
3787 oi.oaifInFlags = OAIF_EXEC;
3788 return SUCCEEDED(SHOpenWithDialog(hwnd, &oi));
3791 bool CAppUtils::IsTGitRebaseActive()
3793 CString adminDir;
3794 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3795 return false;
3797 if (!PathIsDirectory(adminDir + L"tgitrebase.active"))
3798 return false;
3800 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_REMOVESTALEBUTTON, IDS_ABORTBUTTON) == 2)
3801 return true;
3803 RemoveDirectory(adminDir + L"tgitrebase.active");
3805 return false;
3808 bool CAppUtils::DeleteRef(CWnd* parent, const CString& ref)
3810 CString shortname;
3811 if (CGit::GetShortName(ref, shortname, L"refs/remotes/"))
3813 CString msg;
3814 msg.Format(IDS_PROC_DELETEREMOTEBRANCH, (LPCTSTR)ref);
3815 int result = CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), msg, L"TortoiseGit", 3, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_PROC_DELETEREMOTEBRANCH_LOCALREMOTE)), CString(MAKEINTRESOURCE(IDS_PROC_DELETEREMOTEBRANCH_LOCAL)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
3816 if (result == 1)
3818 CString remoteName = shortname.Left(shortname.Find(L'/'));
3819 shortname = shortname.Mid(shortname.Find(L'/') + 1);
3820 if (CAppUtils::IsSSHPutty())
3821 CAppUtils::LaunchPAgent(nullptr, &remoteName);
3823 CSysProgressDlg sysProgressDlg;
3824 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3825 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_DELETING_REMOTE_REFS)));
3826 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3827 sysProgressDlg.SetShowProgressBar(false);
3828 sysProgressDlg.ShowModal(parent, true);
3829 STRING_VECTOR list;
3830 list.push_back(L"refs/heads/" + shortname);
3831 if (g_Git.DeleteRemoteRefs(remoteName, list))
3832 CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), g_Git.GetGitLastErr(L"Could not delete remote ref.", CGit::GIT_CMD_PUSH), L"TortoiseGit", MB_OK | MB_ICONERROR);
3833 sysProgressDlg.Stop();
3834 return true;
3836 else if (result == 2)
3838 if (g_Git.DeleteRef(ref))
3840 CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), g_Git.GetGitLastErr(L"Could not delete reference.", CGit::GIT_CMD_DELETETAGBRANCH), L"TortoiseGit", MB_OK | MB_ICONERROR);
3841 return false;
3843 return true;
3845 return false;
3847 else if (CGit::GetShortName(ref, shortname, L"refs/stash"))
3849 CString err;
3850 std::vector<GitRevLoglist> stashList;
3851 size_t count = !GitRevLoglist::GetRefLog(ref, stashList, err) ? stashList.size() : 0;
3852 CString msg;
3853 msg.Format(IDS_PROC_DELETEALLSTASH, count);
3854 int choose = CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), msg, L"TortoiseGit", 3, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_DROPONESTASH)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON)));
3855 if (choose == 1)
3857 CString out;
3858 if (g_Git.Run(L"git.exe stash clear", &out, CP_UTF8))
3859 CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3860 return true;
3862 else if (choose == 2)
3864 CString out;
3865 if (g_Git.Run(L"git.exe stash drop refs/stash@{0}", &out, CP_UTF8))
3866 CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3867 return true;
3869 return false;
3872 CString msg;
3873 msg.Format(IDS_PROC_DELETEBRANCHTAG, (LPCTSTR)ref);
3874 // Check if branch is fully merged in HEAD
3875 if (CGit::GetShortName(ref, shortname, L"refs/heads/") && !g_Git.IsFastForward(ref, L"HEAD"))
3877 msg += L"\n\n";
3878 msg += CString(MAKEINTRESOURCE(IDS_PROC_BROWSEREFS_WARNINGUNMERGED));
3880 if (CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3882 if (g_Git.DeleteRef(ref))
3884 CMessageBox::Show(parent->GetSafeOwner()->GetSafeHwnd(), g_Git.GetGitLastErr(L"Could not delete reference.", CGit::GIT_CMD_DELETETAGBRANCH), L"TortoiseGit", MB_OK | MB_ICONERROR);
3885 return false;
3887 return true;
3889 return false;