Make more use of CStringUtils::StartsWith
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
bloba3b7b57aa51d937293720edcc3f078f5263dda92
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - 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 "MessageBox.h"
36 #include "GitStatus.h"
37 #include "CreateBranchTagDlg.h"
38 #include "GitSwitchDlg.h"
39 #include "ResetDlg.h"
40 #include "DeleteConflictDlg.h"
41 #include "ChangedDlg.h"
42 #include "SendMailDlg.h"
43 #include "GitProgressDlg.h"
44 #include "PushDlg.h"
45 #include "CommitDlg.h"
46 #include "MergeDlg.h"
47 #include "MergeAbortDlg.h"
48 #include "Hooks.h"
49 #include "..\Settings\Settings.h"
50 #include "InputDlg.h"
51 #include "SVNDCommitDlg.h"
52 #include "requestpulldlg.h"
53 #include "PullFetchDlg.h"
54 #include "FileDiffDlg.h"
55 #include "RebaseDlg.h"
56 #include "PropKey.h"
57 #include "StashSave.h"
58 #include "IgnoreDlg.h"
59 #include "FormatMessageWrapper.h"
60 #include "SmartHandle.h"
61 #include "BisectStartDlg.h"
62 #include "SysProgressDlg.h"
63 #include "UserPassword.h"
64 #include "SendmailPatch.h"
65 #include "Globals.h"
66 #include "ProgressCommands/ResetProgressCommand.h"
67 #include "ProgressCommands/FetchProgressCommand.h"
68 #include "ProgressCommands/SendMailProgressCommand.h"
69 #include "CertificateValidationHelper.h"
70 #include "CheckCertificateDlg.h"
71 #include "SubmoduleResolveConflictDlg.h"
72 #include "GitDiff.h"
73 #include "../TGitCache/CacheInterface.h"
75 static struct last_accepted_cert {
76 BYTE* data;
77 size_t len;
79 last_accepted_cert()
80 : data(nullptr)
81 , len(0)
84 ~last_accepted_cert()
86 free(data);
88 boolean cmp(git_cert_x509* cert)
90 return len > 0 && len == cert->len && memcmp(data, cert->data, len) == 0;
92 void set(git_cert_x509* cert)
94 free(data);
95 len = cert->len;
96 if (len == 0)
98 data = nullptr;
99 return;
101 data = new BYTE[len];
102 memcpy(data, cert->data, len);
104 } last_accepted_cert;
106 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);
108 bool CAppUtils::StashSave(const CString& msg, bool showPull, bool pullShowPush, bool showMerge, const CString& mergeRev)
110 CStashSaveDlg dlg;
111 dlg.m_sMessage = msg;
112 if (dlg.DoModal() == IDOK)
114 CString cmd;
115 cmd = _T("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(_T("\""), _T("\"\""));
126 cmd += _T(" -- \"") + message + _T("\"");
129 CProgressDlg progress;
130 progress.m_GitCmd = cmd;
131 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
133 if (status)
134 return;
136 if (showPull)
137 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(pullShowPush, true); });
138 if (showMerge)
139 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ CAppUtils::Merge(&mergeRev, true); });
141 return (progress.DoModal() == IDOK);
143 return false;
146 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
148 CString cmd,out;
149 cmd = _T("git.exe stash apply ");
150 if (CStringUtils::StartsWith(ref, L"refs/"))
151 ref = ref.Mid(5);
152 if (CStringUtils::StartsWith(ref, L"stash{"))
153 ref = _T("stash@") + ref.Mid(5);
154 cmd += ref;
156 CSysProgressDlg sysProgressDlg;
157 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
158 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
159 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
160 sysProgressDlg.SetShowProgressBar(false);
161 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
162 sysProgressDlg.ShowModeless((HWND)nullptr, true);
164 int ret = g_Git.Run(cmd, &out, CP_UTF8);
166 sysProgressDlg.Stop();
168 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
169 if (ret && !(ret == 1 && hasConflicts))
170 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
171 else
173 CString message;
174 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
175 if (hasConflicts)
176 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
177 if (showChanges)
179 if (CMessageBox::Show(nullptr, message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)), _T("TortoiseGit"), MB_YESNO | MB_ICONINFORMATION) == IDYES)
181 CChangedDlg dlg;
182 dlg.m_pathList.AddPath(CTGitPath());
183 dlg.DoModal();
185 return true;
187 else
189 CMessageBox::Show(nullptr, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
190 return true;
193 return false;
196 bool CAppUtils::StashPop(int showChanges /* = 1 */)
198 CString cmd,out;
199 cmd=_T("git.exe stash pop ");
201 CSysProgressDlg sysProgressDlg;
202 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
203 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
204 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
205 sysProgressDlg.SetShowProgressBar(false);
206 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
207 sysProgressDlg.ShowModeless((HWND)nullptr, true);
209 int ret = g_Git.Run(cmd, &out, CP_UTF8);
211 sysProgressDlg.Stop();
213 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
214 if (ret && !(ret == 1 && hasConflicts))
215 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
216 else
218 CString message;
219 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
220 if (hasConflicts)
221 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
222 if (showChanges == 1 || (showChanges == 0 && hasConflicts))
224 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)
226 CChangedDlg dlg;
227 dlg.m_pathList.AddPath(CTGitPath());
228 dlg.DoModal();
230 return true;
232 else if (showChanges > 1)
234 CMessageBox::Show(nullptr, message, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
235 return true;
237 else if (showChanges == 0)
238 return true;
240 return false;
243 BOOL CAppUtils::StartExtMerge(bool bAlternative,
244 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
245 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
246 HWND resolveMsgHwnd, bool bDeleteBaseTheirsMineOnClose)
248 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
249 CString ext = mergedfile.GetFileExtension();
250 CString com = regCom;
251 bool bInternal = false;
253 if (!ext.IsEmpty())
255 // is there an extension specific merge tool?
256 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
257 if (!CString(mergetool).IsEmpty())
258 com = mergetool;
260 // is there a filename specific merge tool?
261 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
262 if (!CString(mergetool).IsEmpty())
263 com = mergetool;
265 if (bAlternative && !com.IsEmpty())
267 if (CStringUtils::StartsWith(com, L"#"))
268 com.Delete(0);
269 else
270 com.Empty();
273 if (com.IsEmpty() || CStringUtils::StartsWith(com, L"#"))
275 // Maybe we should use TortoiseIDiff?
276 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
277 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
278 (ext == _T(".png")) || (ext == _T(".ico")) ||
279 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
280 (ext == _T(".dib")) || (ext == _T(".emf")) ||
281 (ext == _T(".cur")))
283 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
284 com = _T("\"") + com + _T("\"");
285 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
286 com = com + _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
287 if (resolveMsgHwnd)
288 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
290 else
292 // use TortoiseGitMerge
293 bInternal = true;
294 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
295 com = _T("\"") + com + _T("\"");
296 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
297 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
298 com += _T(" /saverequired");
299 if (resolveMsgHwnd)
300 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
301 if (bDeleteBaseTheirsMineOnClose)
302 com += _T(" /deletebasetheirsmineonclose");
304 if (!g_sGroupingUUID.IsEmpty())
306 com += L" /groupuuid:\"";
307 com += g_sGroupingUUID;
308 com += L"\"";
311 // check if the params are set. If not, just add the files to the command line
312 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
314 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
315 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
316 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
317 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
319 if (basefile.IsEmpty())
321 com.Replace(_T("/base:%base"), _T(""));
322 com.Replace(_T("%base"), _T(""));
324 else
325 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
326 if (theirfile.IsEmpty())
328 com.Replace(_T("/theirs:%theirs"), _T(""));
329 com.Replace(_T("%theirs"), _T(""));
331 else
332 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
333 if (yourfile.IsEmpty())
335 com.Replace(_T("/mine:%mine"), _T(""));
336 com.Replace(_T("%mine"), _T(""));
338 else
339 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
340 if (mergedfile.IsEmpty())
342 com.Replace(_T("/merged:%merged"), _T(""));
343 com.Replace(_T("%merged"), _T(""));
345 else
346 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
347 if (basename.IsEmpty())
349 if (basefile.IsEmpty())
351 com.Replace(_T("/basename:%bname"), _T(""));
352 com.Replace(_T("%bname"), _T(""));
354 else
355 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
357 else
358 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
359 if (theirname.IsEmpty())
361 if (theirfile.IsEmpty())
363 com.Replace(_T("/theirsname:%tname"), _T(""));
364 com.Replace(_T("%tname"), _T(""));
366 else
367 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
369 else
370 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
371 if (yourname.IsEmpty())
373 if (yourfile.IsEmpty())
375 com.Replace(_T("/minename:%yname"), _T(""));
376 com.Replace(_T("%yname"), _T(""));
378 else
379 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
381 else
382 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
383 if (mergedname.IsEmpty())
385 if (mergedfile.IsEmpty())
387 com.Replace(_T("/mergedname:%mname"), _T(""));
388 com.Replace(_T("%mname"), _T(""));
390 else
391 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
393 else
394 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
396 if ((bReadOnly)&&(bInternal))
397 com += _T(" /readonly");
399 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
401 return FALSE;
404 return TRUE;
407 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
409 CString viewer;
410 // use TortoiseGitMerge
411 viewer = CPathUtils::GetAppDirectory();
412 viewer += _T("TortoiseGitMerge.exe");
414 viewer = _T("\"") + viewer + _T("\"");
415 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
416 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
417 if (bReversed)
418 viewer += _T(" /reversedpatch");
419 if (!sOriginalDescription.IsEmpty())
420 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
421 if (!sPatchedDescription.IsEmpty())
422 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
423 if (!g_sGroupingUUID.IsEmpty())
425 viewer += L" /groupuuid:\"";
426 viewer += g_sGroupingUUID;
427 viewer += L"\"";
429 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
430 return FALSE;
431 return TRUE;
434 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
436 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file2.GetFilename().MakeLower());
437 if (!difftool.IsEmpty())
438 return difftool;
439 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file1.GetFilename().MakeLower());
440 if (!difftool.IsEmpty())
441 return difftool;
443 // Is there an extension specific diff tool?
444 CString ext = file2.GetFileExtension().MakeLower();
445 if (!ext.IsEmpty())
447 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
448 if (!difftool.IsEmpty())
449 return difftool;
450 // Maybe we should use TortoiseIDiff?
451 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
452 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
453 (ext == _T(".png")) || (ext == _T(".ico")) ||
454 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
455 (ext == _T(".dib")) || (ext == _T(".emf")) ||
456 (ext == _T(".cur")))
458 return
459 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
460 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
461 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
465 // Finally, pick a generic external diff tool
466 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
467 return difftool;
470 bool CAppUtils::StartExtDiff(
471 const CString& file1, const CString& file2,
472 const CString& sName1, const CString& sName2,
473 const CString& originalFile1, const CString& originalFile2,
474 const git_revnum_t& hash1, const git_revnum_t& hash2,
475 const DiffFlags& flags, int jumpToLine)
477 CString viewer;
479 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
480 if (!flags.bBlame || !(DWORD)blamediff)
482 viewer = PickDiffTool(file1, file2);
483 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
484 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
485 if (flags.bAlternativeTool)
487 // Invert external vs. internal diff tool selection.
488 if (bCommentedOut)
489 viewer.Delete(0); // uncomment
490 else
491 viewer.Empty();
493 else if (bCommentedOut)
494 viewer.Empty();
497 bool bInternal = viewer.IsEmpty();
498 if (bInternal)
500 viewer =
501 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
502 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
503 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
504 if (!g_sGroupingUUID.IsEmpty())
506 viewer += L" /groupuuid:\"";
507 viewer += g_sGroupingUUID;
508 viewer += L"\"";
510 if (flags.bBlame)
511 viewer += _T(" /blame");
513 // check if the params are set. If not, just add the files to the command line
514 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
516 viewer += _T(" \"")+file1+_T("\"");
517 viewer += _T(" \"")+file2+_T("\"");
519 if (viewer.Find(_T("%base")) >= 0)
520 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
521 if (viewer.Find(_T("%mine")) >= 0)
522 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
524 if (sName1.IsEmpty())
525 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
526 else
527 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
529 if (sName2.IsEmpty())
530 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
531 else
532 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
534 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
535 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
537 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
538 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
540 if (flags.bReadOnly && bInternal)
541 viewer += _T(" /readonly");
543 if (jumpToLine > 0)
544 viewer.AppendFormat(L" /line:%d", jumpToLine);
546 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
549 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait, bool bAlternativeTool)
551 CString viewer;
552 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
553 viewer = v;
555 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
556 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
557 if (bAlternativeTool)
559 // Invert external vs. internal diff tool selection.
560 if (bCommentedOut)
561 viewer.Delete(0); // uncomment
562 else
563 viewer.Empty();
565 else if (bCommentedOut)
566 viewer.Empty();
568 if (viewer.IsEmpty())
570 // use TortoiseGitUDiff
571 viewer = CPathUtils::GetAppDirectory();
572 viewer += _T("TortoiseGitUDiff.exe");
573 // enquote the path to TortoiseGitUDiff
574 viewer = _T("\"") + viewer + _T("\"");
575 // add the params
576 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
577 if (!g_sGroupingUUID.IsEmpty())
579 viewer += L" /groupuuid:\"";
580 viewer += g_sGroupingUUID;
581 viewer += L"\"";
584 if (viewer.Find(_T("%1"))>=0)
586 if (viewer.Find(_T("\"%1\"")) >= 0)
587 viewer.Replace(_T("%1"), patchfile);
588 else
589 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
591 else
592 viewer += _T(" \"") + patchfile + _T("\"");
593 if (viewer.Find(_T("%title")) >= 0)
594 viewer.Replace(_T("%title"), title);
596 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
597 return FALSE;
598 return TRUE;
601 BOOL CAppUtils::StartTextViewer(CString file)
603 CString viewer;
604 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
605 viewer = txt;
606 viewer = viewer + _T("\\Shell\\Open\\Command\\");
607 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
608 viewer = txtexe;
610 DWORD len = ExpandEnvironmentStrings(viewer, nullptr, 0);
611 auto buf = std::make_unique<TCHAR[]>(len + 1);
612 ExpandEnvironmentStrings(viewer, buf.get(), len);
613 viewer = buf.get();
614 len = ExpandEnvironmentStrings(file, nullptr, 0);
615 auto buf2 = std::make_unique<TCHAR[]>(len + 1);
616 ExpandEnvironmentStrings(file, buf2.get(), len);
617 file = buf2.get();
618 file = _T("\"")+file+_T("\"");
619 if (viewer.IsEmpty())
620 return CAppUtils::ShowOpenWithDialog(file) ? TRUE : FALSE;
621 if (viewer.Find(_T("\"%1\"")) >= 0)
622 viewer.Replace(_T("\"%1\""), file);
623 else if (viewer.Find(_T("%1")) >= 0)
624 viewer.Replace(_T("%1"), file);
625 else
626 viewer += _T(" ");
627 viewer += file;
629 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
630 return FALSE;
631 return TRUE;
634 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
636 DWORD length = 0;
637 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr);
638 if (!hFile)
639 return TRUE;
640 length = ::GetFileSize(hFile, nullptr);
641 if (length < 4)
642 return TRUE;
643 return FALSE;
646 CString CAppUtils::GetLogFontName()
648 return (CString)CRegString(L"Software\\TortoiseGit\\LogFontName", L"Consolas");
651 DWORD CAppUtils::GetLogFontSize()
653 return (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogFontSize", 9);
656 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
658 LOGFONT logFont;
659 HDC hScreenDC = ::GetDC(nullptr);
660 logFont.lfHeight = -MulDiv(GetLogFontSize(), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
661 ::ReleaseDC(nullptr, hScreenDC);
662 logFont.lfWidth = 0;
663 logFont.lfEscapement = 0;
664 logFont.lfOrientation = 0;
665 logFont.lfWeight = FW_NORMAL;
666 logFont.lfItalic = 0;
667 logFont.lfUnderline = 0;
668 logFont.lfStrikeOut = 0;
669 logFont.lfCharSet = DEFAULT_CHARSET;
670 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
671 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
672 logFont.lfQuality = DRAFT_QUALITY;
673 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
674 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)GetLogFontName());
675 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
678 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
680 CString key,remote;
681 CString cmd,out;
682 if (!pRemote)
683 remote=_T("origin");
684 else
685 remote=*pRemote;
687 if (!keyfile)
689 cmd.Format(_T("remote.%s.puttykeyfile"), (LPCTSTR)remote);
690 key = g_Git.GetConfigValue(cmd);
692 else
693 key=*keyfile;
695 if(key.IsEmpty())
696 return false;
698 CString proc=CPathUtils::GetAppDirectory();
699 proc += _T("pageant.exe \"");
700 proc += key;
701 proc += _T("\"");
703 CString tempfile = GetTempFile();
704 ::DeleteFile(tempfile);
706 proc += _T(" -c \"");
707 proc += CPathUtils::GetAppDirectory();
708 proc += _T("tgittouch.exe\"");
709 proc += _T(" \"");
710 proc += tempfile;
711 proc += _T("\"");
713 CString appDir = CPathUtils::GetAppDirectory();
714 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
715 if(!b)
716 return b;
718 int i=0;
719 while(!::PathFileExists(tempfile))
721 Sleep(100);
722 ++i;
723 if(i>10*60*5)
724 break; //timeout 5 minutes
727 if( i== 10*60*5)
728 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
729 ::DeleteFile(tempfile);
730 return true;
732 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
734 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
735 if (editTool.IsEmpty() || CStringUtils::StartsWith(editTool, L"#"))
736 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
738 CString sCmd;
739 sCmd.Format(_T("\"%s\" \"%s\""), (LPCTSTR)editTool, (LPCTSTR)filename);
741 LaunchApplication(sCmd, 0, false, nullptr, uac);
742 return true;
744 bool CAppUtils::LaunchRemoteSetting()
746 CTGitPath path(g_Git.m_CurrentDir);
747 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
748 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
749 dlg.SetTreeWidth(220);
750 dlg.m_DefaultPage = _T("gitremote");
752 dlg.DoModal();
753 dlg.HandleRestart();
754 return true;
757 * Launch the external blame viewer
759 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile, const CString& Rev, const CString& sParams)
761 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
762 viewer += _T("TortoiseGitBlame.exe");
763 viewer += _T("\" \"") + sBlameFile + _T("\"");
764 //viewer += _T(" \"") + sLogFile + _T("\"");
765 //viewer += _T(" \"") + sOriginalFile + _T("\"");
766 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
767 viewer += L" /rev:" + Rev;
768 if (!g_sGroupingUUID.IsEmpty())
770 viewer += L" /groupuuid:\"";
771 viewer += g_sGroupingUUID;
772 viewer += L"\"";
774 viewer += _T(" ")+sParams;
776 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
779 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
781 CString sText;
782 if (!pWnd)
783 return false;
784 bool bStyled = false;
785 pWnd->GetWindowText(sText);
786 // the rich edit control doesn't count the CR char!
787 // to be exact: CRLF is treated as one char.
788 sText.Remove(_T('\r'));
790 // style each line separately
791 int offset = 0;
792 int nNewlinePos;
795 nNewlinePos = sText.Find('\n', offset);
796 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
798 int start = 0;
799 int end = 0;
800 while (FindStyleChars(sLine, '*', start, end))
802 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
803 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
804 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
805 bStyled = true;
806 start = end;
808 start = 0;
809 end = 0;
810 while (FindStyleChars(sLine, '^', start, end))
812 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
813 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
814 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
815 bStyled = true;
816 start = end;
818 start = 0;
819 end = 0;
820 while (FindStyleChars(sLine, '_', start, end))
822 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
823 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
824 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
825 bStyled = true;
826 start = end;
828 offset = nNewlinePos+1;
829 } while(nNewlinePos>=0);
830 return bStyled;
833 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
835 int i=start;
836 int last = sText.GetLength() - 1;
837 bool bFoundMarker = false;
838 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
839 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
841 // find a starting marker
842 while (i < last)
844 TCHAR prevChar = c;
845 c = nextChar;
846 nextChar = sText[i + 1];
848 // IsCharAlphaNumeric can be somewhat expensive.
849 // Long lines of "*****" or "----" will be pre-empted efficiently
850 // by the (c != nextChar) condition.
852 if ((c == stylechar) && (c != nextChar))
854 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
856 start = ++i;
857 bFoundMarker = true;
858 break;
861 ++i;
863 if (!bFoundMarker)
864 return false;
866 // find ending marker
867 // c == sText[i - 1]
869 bFoundMarker = false;
870 while (i <= last)
872 TCHAR prevChar = c;
873 c = sText[i];
874 if (c == stylechar)
876 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
878 end = i;
879 ++i;
880 bFoundMarker = true;
881 break;
884 ++i;
886 return bFoundMarker;
889 // from CSciEdit
890 namespace {
891 bool IsValidURLChar(wchar_t ch)
893 return iswalnum(ch) ||
894 ch == L'_' || ch == L'/' || ch == L';' || ch == L'?' || ch == L'&' || ch == L'=' ||
895 ch == L'%' || ch == L':' || ch == L'.' || ch == L'#' || ch == L'-' || ch == L'+' ||
896 ch == L'|' || ch == L'>' || ch == L'<' || ch == L'!' || ch == L'@';
899 bool IsUrlOrEmail(const CString& sText)
901 if (!PathIsURLW(sText))
903 auto atpos = sText.Find(L'@');
904 if (atpos <= 0)
905 return false;
906 if (sText.ReverseFind(L'.') > atpos)
907 return true;
908 return false;
910 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" })
912 if (CStringUtils::StartsWith(sText, prefix) && sText.GetLength() != prefix.GetLength())
913 return true;
915 return false;
919 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
921 std::vector<CHARRANGE> positions = FindURLMatches(msg);
922 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
924 return positions.empty() ? FALSE : TRUE;
928 * implements URL searching with the same logic as CSciEdit::StyleURLs
930 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
932 std::vector<CHARRANGE> result;
934 int len = msg.GetLength();
935 int starturl = -1;
937 for (int i = 0; i <= msg.GetLength(); ++i)
939 if ((i < len) && IsValidURLChar(msg[i]))
941 if (starturl < 0)
942 starturl = i;
944 else
946 if (starturl >= 0)
948 bool strip = true;
949 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
951 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
952 ++starturl;
953 strip = false;
954 i = starturl;
955 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
956 ++i;
959 int skipTrailing = 0;
960 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] == '!'))
961 ++skipTrailing;
963 if (!IsUrlOrEmail(msg.Mid(starturl, i - starturl - skipTrailing)))
965 starturl = -1;
966 continue;
969 CHARRANGE range = { starturl, i - skipTrailing };
970 result.push_back(range);
972 starturl = -1;
976 return result;
979 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
980 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
981 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
982 bool bAlternateDiff /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
983 bool /* blame = false */,
984 bool bMerge,
985 bool bCombine,
986 bool bNoPrefix)
988 int diffContext = g_Git.GetConfigValueInt32(L"diff.context", -1);
989 CString tempfile=GetTempFile();
990 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext, bNoPrefix))
992 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
993 return false;
995 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + L":" + rev2, FALSE, bAlternateDiff);
997 #if 0
998 CString sCmd;
999 sCmd.Format(_T("%s /command:showcompare /unified"),
1000 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
1001 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1002 if (rev1.IsValid())
1003 sCmd += _T(" /revision1:") + rev1.ToString();
1004 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1005 if (rev2.IsValid())
1006 sCmd += _T(" /revision2:") + rev2.ToString();
1007 if (peg.IsValid())
1008 sCmd += _T(" /pegrevision:") + peg.ToString();
1009 if (headpeg.IsValid())
1010 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1012 if (bAlternateDiff)
1013 sCmd += _T(" /alternatediff");
1015 if (bIgnoreAncestry)
1016 sCmd += _T(" /ignoreancestry");
1018 if (hWnd)
1020 sCmd += _T(" /hwnd:");
1021 TCHAR buf[30];
1022 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
1023 sCmd += buf;
1026 return CAppUtils::LaunchApplication(sCmd, 0, false);
1027 #endif
1028 return TRUE;
1031 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1033 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1034 scriptsdir += _T("Diff-Scripts");
1035 CSimpleFileFind files(scriptsdir);
1036 while (files.FindNextFileNoDirectories())
1038 CString file = files.GetFilePath();
1039 CString filename = files.GetFileName();
1040 CString ext = file.Mid(file.ReverseFind('-') + 1);
1041 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
1042 std::set<CString> extensions;
1043 extensions.insert(ext);
1044 CString kind;
1045 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
1046 kind = _T(" //E:vbscript");
1047 if (file.Right(2).CompareNoCase(_T("js"))==0)
1048 kind = _T(" //E:javascript");
1049 // open the file, read the first line and find possible extensions
1050 // this script can handle
1053 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1054 CString extline;
1055 if (f.ReadString(extline))
1057 if ((extline.GetLength() > 15 ) &&
1058 (CStringUtils::StartsWith(extline, L"// extensions: ") ||
1059 CStringUtils::StartsWith(extline, L"' extensions: ")))
1061 if (extline[0] == '/')
1062 extline = extline.Mid(15);
1063 else
1064 extline = extline.Mid(14);
1065 CString sToken;
1066 int curPos = 0;
1067 sToken = extline.Tokenize(_T(";"), curPos);
1068 while (!sToken.IsEmpty())
1070 if (!sToken.IsEmpty())
1072 if (sToken[0] != '.')
1073 sToken = _T(".") + sToken;
1074 extensions.insert(sToken);
1076 sToken = extline.Tokenize(_T(";"), curPos);
1080 f.Close();
1082 catch (CFileException* e)
1084 e->Delete();
1087 for (const auto& extension : extensions)
1089 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1091 if (CStringUtils::StartsWithI(filename, L"diff-"))
1093 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension);
1094 CString diffregstring = diffreg;
1095 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1096 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1099 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1101 if (CStringUtils::StartsWithI(filename, L"merge-"))
1103 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension);
1104 CString diffregstring = diffreg;
1105 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1106 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1112 return true;
1115 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1117 // ask from where the export has to be done
1118 CExportDlg dlg;
1119 if(BashHash)
1120 dlg.m_initialRefName=*BashHash;
1121 if (orgPath)
1123 if (PathIsRelative(orgPath->GetWinPath()))
1124 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1125 else
1126 dlg.m_orgPath = *orgPath;
1129 if (dlg.DoModal() == IDOK)
1131 CString cmd;
1132 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1133 (LPCTSTR)dlg.m_strFile, (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName));
1135 CProgressDlg pro;
1136 pro.m_GitCmd=cmd;
1137 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1139 if (status)
1140 return;
1141 postCmdList.emplace_back(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); });
1144 CGit git;
1145 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1147 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1148 pro.m_Git = &git;
1150 return (pro.DoModal() == IDOK);
1152 return false;
1155 bool CAppUtils::UpdateBranchDescription(const CString& branch, CString description)
1157 if (branch.IsEmpty())
1158 return false;
1160 CString key;
1161 key.Format(L"branch.%s.description", (LPCTSTR)branch);
1162 description.Replace(L"\r", L"");
1163 description.Trim();
1164 if (description.IsEmpty())
1165 g_Git.UnsetConfigValue(key);
1166 else
1167 g_Git.SetConfigValue(key, description);
1169 return true;
1172 bool CAppUtils::CreateBranchTag(bool isTag /*true*/, const CString* commitHash /*nullptr*/, bool switchNewBranch /*false*/, LPCTSTR name /*nullptr*/)
1174 CCreateBranchTagDlg dlg;
1175 dlg.m_bIsTag = isTag;
1176 dlg.m_bSwitch = switchNewBranch;
1178 if (commitHash)
1179 dlg.m_initialRefName = *commitHash;
1181 if (name)
1182 dlg.m_BranchTagName = name;
1184 if(dlg.DoModal()==IDOK)
1186 CString cmd;
1187 CString force;
1188 CString track;
1189 if(dlg.m_bTrack == TRUE)
1190 track=_T(" --track ");
1191 else if(dlg.m_bTrack == FALSE)
1192 track=_T(" --no-track");
1194 if(dlg.m_bForce)
1195 force=_T(" -f ");
1197 if (isTag)
1199 CString sign;
1200 if(dlg.m_bSign)
1201 sign=_T("-s");
1203 cmd.Format(_T("git.exe tag %s %s %s %s"),
1204 (LPCTSTR)force,
1205 (LPCTSTR)sign,
1206 (LPCTSTR)dlg.m_BranchTagName,
1207 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1210 if(!dlg.m_Message.Trim().IsEmpty())
1212 CString tempfile = ::GetTempFile();
1213 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1215 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1216 return FALSE;
1218 cmd += _T(" -F ")+tempfile;
1221 else
1223 cmd.Format(_T("git.exe branch %s %s %s %s"),
1224 (LPCTSTR)track,
1225 (LPCTSTR)force,
1226 (LPCTSTR)dlg.m_BranchTagName,
1227 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1230 CString out;
1231 if(g_Git.Run(cmd,&out,CP_UTF8))
1233 CMessageBox::Show(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1234 return FALSE;
1236 if (!isTag && dlg.m_bSwitch)
1238 // it is a new branch and the user has requested to switch to it
1239 PerformSwitch(dlg.m_BranchTagName);
1241 if (!isTag && !dlg.m_Message.IsEmpty())
1242 UpdateBranchDescription(dlg.m_BranchTagName, dlg.m_Message);
1244 return TRUE;
1246 return FALSE;
1249 bool CAppUtils::Switch(const CString& initialRefName)
1251 CGitSwitchDlg dlg;
1252 if(!initialRefName.IsEmpty())
1253 dlg.m_initialRefName = initialRefName;
1255 if (dlg.DoModal() == IDOK)
1257 CString branch;
1258 if (dlg.m_bBranch)
1259 branch = dlg.m_NewBranch;
1261 // if refs/heads/ is not stripped, checkout will detach HEAD
1262 // checkout prefers branches on name clashes (with tags)
1263 if (CStringUtils::StartsWith(dlg.m_VersionName, L"refs/heads/") && dlg.m_bBranchOverride != TRUE)
1264 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1266 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1268 return FALSE;
1271 bool CAppUtils::PerformSwitch(const CString& ref, bool bForce /* false */, const CString& sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1273 CString cmd;
1274 CString track;
1275 CString force;
1276 CString branch;
1277 CString merge;
1279 if(!sNewBranch.IsEmpty()){
1280 if (bBranchOverride)
1281 branch.Format(_T("-B %s "), (LPCTSTR)sNewBranch);
1282 else
1283 branch.Format(_T("-b %s "), (LPCTSTR)sNewBranch);
1284 if (bTrack == TRUE)
1285 track = _T("--track ");
1286 else if (bTrack == FALSE)
1287 track = _T("--no-track ");
1289 if (bForce)
1290 force = _T("-f ");
1291 if (bMerge)
1292 merge = _T("--merge ");
1294 cmd.Format(_T("git.exe checkout %s%s%s%s%s --"),
1295 (LPCTSTR)force,
1296 (LPCTSTR)track,
1297 (LPCTSTR)merge,
1298 (LPCTSTR)branch,
1299 (LPCTSTR)g_Git.FixBranchName(ref));
1301 CProgressDlg progress;
1302 progress.m_GitCmd = cmd;
1304 CString currentBranch;
1305 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1306 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1308 if (!status)
1310 CTGitPath gitPath = g_Git.m_CurrentDir;
1311 if (gitPath.HasSubmodules())
1313 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1315 CString sCmd;
1316 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1317 RunTortoiseGitProc(sCmd);
1320 if (hasBranch)
1321 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); });
1324 CString newBranch;
1325 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1326 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); });
1328 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []{
1329 CTGitPathList pathlist;
1330 CTGitPathList selectedlist;
1331 pathlist.AddPath(CTGitPath());
1332 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
1333 CString str;
1334 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1337 else
1339 if (bMerge && g_Git.HasWorkingTreeConflicts() > 0)
1341 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
1343 CString sCmd;
1344 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1345 CAppUtils::RunTortoiseGitProc(sCmd);
1348 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); });
1349 if (!bMerge)
1350 postCmdList.emplace_back(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); });
1353 progress.m_PostExecCallback = [&](DWORD& exitCode, CString& extraMsg)
1355 if (bMerge && !exitCode && g_Git.HasWorkingTreeConflicts() > 0)
1357 exitCode = 1; // Treat it as failure
1358 extraMsg = _T("Has merge conflict");
1362 INT_PTR ret = progress.DoModal();
1364 return ret == IDOK;
1367 class CIgnoreFile : public CStdioFile
1369 public:
1370 STRING_VECTOR m_Items;
1371 CString m_eol;
1373 virtual BOOL ReadString(CString& rString)
1375 if (GetPosition() == 0)
1377 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1378 char buf[3] = { 0, 0, 0 };
1379 Read(buf, 3);
1380 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1381 SeekToBegin();
1384 CStringA strA;
1385 char lastChar = '\0';
1386 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1388 if (c == '\r')
1389 continue;
1390 if (c == '\n')
1392 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1393 break;
1395 strA.AppendChar(c);
1397 if (strA.IsEmpty())
1398 return FALSE;
1400 rString = CUnicodeUtils::GetUnicode(strA);
1401 return TRUE;
1404 void ResetState()
1406 m_Items.clear();
1407 m_eol.Empty();
1411 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1413 file.ResetState();
1414 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1416 CMessageBox::Show(nullptr, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1417 return false;
1420 if (file.GetLength() > 0)
1422 CString fileText;
1423 while (file.ReadString(fileText))
1424 file.m_Items.push_back(fileText);
1425 file.Seek(file.GetLength() - 1, 0);
1426 char lastchar[1] = { 0 };
1427 file.Read(lastchar, 1);
1428 file.SeekToEnd();
1429 if (lastchar[0] != '\n')
1431 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1432 file.Write(eol, eol.GetLength());
1435 else
1436 file.SeekToEnd();
1438 return true;
1441 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1443 CIgnoreDlg ignoreDlg;
1444 if (ignoreDlg.DoModal() == IDOK)
1446 CString ignorefile;
1447 ignorefile = g_Git.m_CurrentDir + _T("\\");
1449 switch (ignoreDlg.m_IgnoreFile)
1451 case 0:
1452 ignorefile += _T(".gitignore");
1453 break;
1454 case 2:
1455 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1456 ignorefile += _T("info");
1457 if (!PathFileExists(ignorefile))
1458 CreateDirectory(ignorefile, nullptr);
1459 ignorefile += _T("\\exclude");
1460 break;
1463 CIgnoreFile file;
1466 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1467 return false;
1469 for (int i = 0; i < path.GetCount(); ++i)
1471 if (ignoreDlg.m_IgnoreFile == 1)
1473 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1474 if (!OpenIgnoreFile(file, ignorefile))
1475 return false;
1478 CString ignorePattern;
1479 if (ignoreDlg.m_IgnoreType == 0)
1481 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1482 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1484 ignorePattern += _T("/");
1486 if (IsMask)
1487 ignorePattern += _T("*") + path[i].GetFileExtension();
1488 else
1489 ignorePattern += path[i].GetFileOrDirectoryName();
1491 // escape [ and ] so that files get ignored correctly
1492 ignorePattern.Replace(_T("["), _T("\\["));
1493 ignorePattern.Replace(_T("]"), _T("\\]"));
1495 bool found = false;
1496 for (size_t j = 0; j < file.m_Items.size(); ++j)
1498 if (file.m_Items[j] == ignorePattern)
1500 found = true;
1501 break;
1504 if (!found)
1506 file.m_Items.push_back(ignorePattern);
1507 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1508 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1509 file.Write(ignorePatternA, ignorePatternA.GetLength());
1512 if (ignoreDlg.m_IgnoreFile == 1)
1513 file.Close();
1516 if (ignoreDlg.m_IgnoreFile != 1)
1517 file.Close();
1519 catch(...)
1521 file.Abort();
1522 return false;
1525 return true;
1527 return false;
1530 static bool Reset(const CString& resetTo, int resetType)
1532 CString cmd;
1533 CString type;
1534 switch (resetType)
1536 case 0:
1537 type = _T("--soft");
1538 break;
1539 case 1:
1540 type = _T("--mixed");
1541 break;
1542 case 2:
1543 type = _T("--hard");
1544 break;
1545 default:
1546 resetType = 1;
1547 type = _T("--mixed");
1548 break;
1550 cmd.Format(_T("git.exe reset %s %s --"), (LPCTSTR)type, (LPCTSTR)resetTo);
1552 CProgressDlg progress;
1553 progress.m_GitCmd = cmd;
1555 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1557 if (status)
1559 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); });
1560 return;
1563 CTGitPath gitPath = g_Git.m_CurrentDir;
1564 if (gitPath.HasSubmodules() && resetType == 2)
1566 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1568 CString sCmd;
1569 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1570 CAppUtils::RunTortoiseGitProc(sCmd);
1575 INT_PTR ret;
1576 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1578 CGitProgressDlg gitdlg;
1579 ResetProgressCommand resetProgressCommand;
1580 gitdlg.SetCommand(&resetProgressCommand);
1581 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1582 resetProgressCommand.SetRevision(resetTo);
1583 resetProgressCommand.SetResetType(resetType);
1584 ret = gitdlg.DoModal();
1586 else
1587 ret = progress.DoModal();
1589 return ret == IDOK;
1592 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1594 CResetDlg dlg;
1595 dlg.m_ResetType=type;
1596 dlg.m_ResetToVersion=*CommitHash;
1597 dlg.m_initialRefName = *CommitHash;
1598 if (dlg.DoModal() == IDOK)
1599 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1601 return false;
1604 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1606 if(mode == FALSE)
1608 descript.LoadString(IDS_SVNACTION_DELETE);
1609 return;
1611 if(base)
1613 descript.LoadString(IDS_SVNACTION_MODIFIED);
1614 return;
1616 descript.LoadString(IDS_PROC_CREATED);
1619 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1621 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1622 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1623 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1625 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1627 CString file;
1628 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1630 return file;
1633 bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, CString& hash2, CString& hash3)
1635 size_t pos = 0;
1636 CString one;
1637 CString part;
1639 while (pos < out.size())
1641 one.Empty();
1643 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1644 int tabstart = 0;
1645 one.Tokenize(_T("\t"), tabstart);
1647 tabstart = 0;
1648 part = one.Tokenize(_T(" "), tabstart); //Tag
1649 part = one.Tokenize(_T(" "), tabstart); //Mode
1650 part = one.Tokenize(_T(" "), tabstart); //Hash
1651 CString hash = part;
1652 part = one.Tokenize(_T("\t"), tabstart); //Stage
1653 int stage = _ttol(part);
1654 if (stage == 1)
1655 hash1 = hash;
1656 else if (stage == 2)
1657 hash2 = hash;
1658 else if (stage == 3)
1660 hash3 = hash;
1661 return true;
1664 pos = out.findNextString(pos);
1667 return false;
1670 bool CAppUtils::ConflictEdit(const CTGitPath& path, bool bAlternativeTool /*= false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1672 bool bRet = false;
1674 CTGitPath merge=path;
1675 CTGitPath directory = merge.GetDirectory();
1677 // we have the conflicted file (%merged)
1678 // now look for the other required files
1679 //GitStatus stat;
1680 //stat.GetStatus(merge);
1681 //if (stat.status == nullptr)
1682 // return false;
1684 BYTE_VECTOR vector;
1686 CString cmd;
1687 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1689 if (g_Git.Run(cmd, &vector))
1690 return FALSE;
1692 if (merge.IsDirectory())
1694 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1695 if (merge.HasAdminDir()) {
1696 CGit subgit;
1697 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1698 CGitHash hash;
1699 subgit.GetHash(hash, _T("HEAD"));
1700 baseHash = hash;
1702 if (ParseHashesFromLsFile(vector, realBaseHash, localHash, remoteHash)) // in base no submodule, but in remote submodule
1703 baseHash = realBaseHash;
1705 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1706 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1708 bool baseOK = false, mineOK = false, theirsOK = false;
1709 CString baseSubject, mineSubject, theirsSubject;
1710 if (merge.HasAdminDir())
1712 CGit subgit;
1713 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1714 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1715 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1717 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)
1719 changeTypeMine = CGitDiff::Identical;
1720 changeTypeTheirs = CGitDiff::NewSubmodule;
1721 baseSubject = _T("no submodule");
1722 mineSubject = baseSubject;
1723 theirsSubject = _T("not initialized");
1725 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
1727 baseHash = localHash;
1728 baseSubject = _T("not initialized");
1729 mineSubject = baseSubject;
1730 theirsSubject = _T("not initialized");
1731 changeTypeMine = CGitDiff::Identical;
1732 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1734 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
1736 baseSubject = _T("not initialized");
1737 mineSubject = baseSubject;
1738 theirsSubject = baseSubject;
1739 if (baseHash == localHash)
1740 changeTypeMine = CGitDiff::Identical;
1742 else
1743 return FALSE;
1745 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1746 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), revertTheirMy, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1747 resolveSubmoduleConflictDialog.DoModal();
1748 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1750 static UINT WM_REVERTMSG = RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1751 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1754 return TRUE;
1757 CTGitPathList list;
1758 if (list.ParserFromLsFile(vector))
1760 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1761 return FALSE;
1764 if (list.IsEmpty())
1765 return FALSE;
1767 CTGitPath theirs;
1768 CTGitPath mine;
1769 CTGitPath base;
1771 if (revertTheirMy)
1773 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1774 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1776 else
1778 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1779 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1781 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1783 CString format;
1785 //format=_T("git.exe cat-file blob \":%d:%s\"");
1786 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1787 CFile tempfile;
1788 //create a empty file, incase stage is not three
1789 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1790 tempfile.Close();
1791 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1792 tempfile.Close();
1793 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1794 tempfile.Close();
1796 bool b_base=false, b_local=false, b_remote=false;
1798 for (int i = 0; i< list.GetCount(); ++i)
1800 CString outfile;
1801 cmd.Empty();
1802 outfile.Empty();
1804 if( list[i].m_Stage == 1)
1806 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1807 b_base = true;
1808 outfile = base.GetWinPathString();
1811 if( list[i].m_Stage == 2 )
1813 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1814 b_local = true;
1815 outfile = mine.GetWinPathString();
1818 if( list[i].m_Stage == 3 )
1820 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1821 b_remote = true;
1822 outfile = theirs.GetWinPathString();
1824 CString output, err;
1825 if(!outfile.IsEmpty())
1826 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1828 CString file;
1829 int start =0 ;
1830 file = output.Tokenize(_T("\t"), start);
1831 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1833 else
1834 CMessageBox::Show(nullptr, output + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1837 if(b_local && b_remote )
1839 merge.SetFromWin(g_Git.CombinePath(merge));
1840 if( revertTheirMy )
1841 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, mine, theirs, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1842 else
1843 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1845 else
1847 ::DeleteFile(mine.GetWinPathString());
1848 ::DeleteFile(theirs.GetWinPathString());
1849 ::DeleteFile(base.GetWinPathString());
1851 CDeleteConflictDlg dlg;
1852 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1853 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1854 CGitHash localHash, remoteHash;
1855 if (!g_Git.GetHash(localHash, _T("HEAD")))
1856 dlg.m_LocalHash = localHash.ToString();
1857 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1858 dlg.m_RemoteHash = remoteHash.ToString();
1859 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1860 dlg.m_RemoteHash = remoteHash.ToString();
1861 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1862 dlg.m_RemoteHash = remoteHash.ToString();
1863 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1864 dlg.m_RemoteHash = remoteHash.ToString();
1865 dlg.m_bShowModifiedButton=b_base;
1866 dlg.m_File=merge.GetGitPathString();
1867 if(dlg.DoModal() == IDOK)
1869 CString out;
1870 if(dlg.m_bIsDelete)
1871 cmd.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1872 else
1873 cmd.Format(_T("git.exe add -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1875 if (g_Git.Run(cmd, &out, CP_UTF8))
1877 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1878 return FALSE;
1880 return TRUE;
1882 else
1883 return FALSE;
1886 #if 0
1887 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1888 base, theirs, mine, merge);
1889 #endif
1890 #if 0
1891 if (stat.status->text_status == svn_wc_status_conflicted)
1893 // we have a text conflict, use our merge tool to resolve the conflict
1895 CTSVNPath theirs(directory);
1896 CTSVNPath mine(directory);
1897 CTSVNPath base(directory);
1898 bool bConflictData = false;
1900 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1902 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1903 bConflictData = true;
1905 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1907 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1908 bConflictData = true;
1910 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1912 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1913 bConflictData = true;
1915 else
1916 mine = merge;
1917 if (bConflictData)
1918 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1919 base, theirs, mine, merge);
1922 if (stat.status->prop_status == svn_wc_status_conflicted)
1924 // we have a property conflict
1925 CTSVNPath prej(directory);
1926 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1928 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1929 // there's a problem: the prej file contains a _description_ of the conflict, and
1930 // that description string might be translated. That means we have no way of parsing
1931 // the file to find out the conflicting values.
1932 // The only thing we can do: show a dialog with the conflict description, then
1933 // let the user either accept the existing property or open the property edit dialog
1934 // to manually change the properties and values. And a button to mark the conflict as
1935 // resolved.
1936 CEditPropConflictDlg dlg;
1937 dlg.SetPrejFile(prej);
1938 dlg.SetConflictedItem(merge);
1939 bRet = (dlg.DoModal() != IDCANCEL);
1943 if (stat.status->tree_conflict)
1945 // we have a tree conflict
1946 SVNInfo info;
1947 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1948 if (pInfoData)
1950 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1952 CTSVNPath theirs(directory);
1953 CTSVNPath mine(directory);
1954 CTSVNPath base(directory);
1955 bool bConflictData = false;
1957 if (pInfoData->treeconflict_theirfile)
1959 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1960 bConflictData = true;
1962 if (pInfoData->treeconflict_basefile)
1964 base.AppendPathString(pInfoData->treeconflict_basefile);
1965 bConflictData = true;
1967 if (pInfoData->treeconflict_myfile)
1969 mine.AppendPathString(pInfoData->treeconflict_myfile);
1970 bConflictData = true;
1972 else
1973 mine = merge;
1974 if (bConflictData)
1975 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1976 base, theirs, mine, merge);
1978 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1980 CString sConflictAction;
1981 CString sConflictReason;
1982 CString sResolveTheirs;
1983 CString sResolveMine;
1984 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1985 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1987 if (pInfoData->treeconflict_nodekind == svn_node_file)
1989 switch (pInfoData->treeconflict_operation)
1991 case svn_wc_operation_update:
1992 switch (pInfoData->treeconflict_action)
1994 case svn_wc_conflict_action_edit:
1995 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1996 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1997 break;
1998 case svn_wc_conflict_action_add:
1999 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
2000 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2001 break;
2002 case svn_wc_conflict_action_delete:
2003 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
2004 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2005 break;
2007 break;
2008 case svn_wc_operation_switch:
2009 switch (pInfoData->treeconflict_action)
2011 case svn_wc_conflict_action_edit:
2012 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
2013 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2014 break;
2015 case svn_wc_conflict_action_add:
2016 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
2017 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2018 break;
2019 case svn_wc_conflict_action_delete:
2020 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
2021 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2022 break;
2024 break;
2025 case svn_wc_operation_merge:
2026 switch (pInfoData->treeconflict_action)
2028 case svn_wc_conflict_action_edit:
2029 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
2030 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2031 break;
2032 case svn_wc_conflict_action_add:
2033 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
2034 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2035 break;
2036 case svn_wc_conflict_action_delete:
2037 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
2038 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2039 break;
2041 break;
2044 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
2046 switch (pInfoData->treeconflict_operation)
2048 case svn_wc_operation_update:
2049 switch (pInfoData->treeconflict_action)
2051 case svn_wc_conflict_action_edit:
2052 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
2053 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2054 break;
2055 case svn_wc_conflict_action_add:
2056 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
2057 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2058 break;
2059 case svn_wc_conflict_action_delete:
2060 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
2061 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2062 break;
2064 break;
2065 case svn_wc_operation_switch:
2066 switch (pInfoData->treeconflict_action)
2068 case svn_wc_conflict_action_edit:
2069 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
2070 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2071 break;
2072 case svn_wc_conflict_action_add:
2073 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
2074 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2075 break;
2076 case svn_wc_conflict_action_delete:
2077 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
2078 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2079 break;
2081 break;
2082 case svn_wc_operation_merge:
2083 switch (pInfoData->treeconflict_action)
2085 case svn_wc_conflict_action_edit:
2086 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
2087 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2088 break;
2089 case svn_wc_conflict_action_add:
2090 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
2091 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2092 break;
2093 case svn_wc_conflict_action_delete:
2094 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
2095 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2096 break;
2098 break;
2102 UINT uReasonID = 0;
2103 switch (pInfoData->treeconflict_reason)
2105 case svn_wc_conflict_reason_edited:
2106 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
2107 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2108 break;
2109 case svn_wc_conflict_reason_obstructed:
2110 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
2111 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2112 break;
2113 case svn_wc_conflict_reason_deleted:
2114 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
2115 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2116 break;
2117 case svn_wc_conflict_reason_added:
2118 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
2119 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2120 break;
2121 case svn_wc_conflict_reason_missing:
2122 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
2123 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2124 break;
2125 case svn_wc_conflict_reason_unversioned:
2126 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
2127 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2128 break;
2130 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
2132 CTreeConflictEditorDlg dlg;
2133 dlg.SetConflictInfoText(sConflictReason);
2134 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
2135 dlg.SetPath(treeConflictPath);
2136 INT_PTR dlgRet = dlg.DoModal();
2137 bRet = (dlgRet != IDCANCEL);
2141 #endif
2142 return bRet;
2145 bool CAppUtils::IsSSHPutty()
2147 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2148 sshclient=sshclient.MakeLower();
2149 return sshclient.Find(L"plink", 0) >= 0;
2152 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2154 if (!OpenClipboard(nullptr))
2155 return CString();
2157 CString sClipboardText;
2158 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2159 if (hglb)
2161 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2162 sClipboardText = CString(lpstr);
2163 GlobalUnlock(hglb);
2165 hglb = GetClipboardData(CF_UNICODETEXT);
2166 if (hglb)
2168 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2169 sClipboardText = lpstr;
2170 GlobalUnlock(hglb);
2172 CloseClipboard();
2174 if(!sClipboardText.IsEmpty())
2176 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2177 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2179 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ssh://", L"git@" })
2181 if (CStringUtils::StartsWith(sClipboardText, prefix) && sClipboardText.GetLength() != prefix.GetLength())
2182 return sClipboardText;
2185 if(sClipboardText.GetLength()>=2)
2186 if( sClipboardText[1] == _T(':') )
2187 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2188 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2189 return sClipboardText;
2191 // trim prefixes like "git clone "
2192 if (!skipGitPrefix.IsEmpty() && CStringUtils::StartsWith(sClipboardText, skipGitPrefix))
2194 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2195 int spacePos = -1;
2196 while (paramsCount >= 0)
2198 --paramsCount;
2199 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2200 if (spacePos == -1)
2201 break;
2203 if (spacePos > 0 && paramsCount < 0)
2204 sClipboardText.Truncate(spacePos);
2205 return sClipboardText;
2209 return CString();
2212 CString CAppUtils::ChooseRepository(const CString* path)
2214 CBrowseFolder browseFolder;
2215 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2217 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2218 CString strCloneDirectory;
2219 if(path)
2220 strCloneDirectory=*path;
2221 else
2222 strCloneDirectory = regLastResopitory;
2224 CString title;
2225 title.LoadString(IDS_CHOOSE_REPOSITORY);
2227 browseFolder.SetInfo(title);
2229 if (browseFolder.Show(nullptr, strCloneDirectory) == CBrowseFolder::OK)
2231 regLastResopitory = strCloneDirectory;
2232 return strCloneDirectory;
2234 else
2235 return CString();
2238 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2240 CSendMailDlg dlg;
2242 dlg.m_PathList = list;
2244 if(dlg.DoModal()==IDOK)
2246 if (dlg.m_PathList.IsEmpty())
2247 return FALSE;
2249 CGitProgressDlg progDlg;
2250 if (bIsMainWnd)
2251 theApp.m_pMainWnd = &progDlg;
2252 SendMailProgressCommand sendMailProgressCommand;
2253 progDlg.SetCommand(&sendMailProgressCommand);
2255 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2256 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2258 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2259 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2261 progDlg.DoModal();
2263 return true;
2265 return false;
2268 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2270 CTGitPathList list;
2271 CString log=formatpatchoutput;
2272 int start=log.Find(cmd);
2273 if(start >=0)
2274 CString one=log.Tokenize(_T("\n"),start);
2275 else
2276 start = 0;
2278 while(start>=0)
2280 CString one=log.Tokenize(_T("\n"),start);
2281 one=one.Trim();
2282 if (one.IsEmpty() || one.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS))) == 0)
2283 continue;
2284 one.Replace(_T('/'),_T('\\'));
2285 CTGitPath path;
2286 path.SetFromWin(one);
2287 list.AddPath(path);
2289 if (!list.IsEmpty())
2290 return SendPatchMail(list, bIsMainWnd);
2291 else
2293 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2294 return true;
2299 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2301 CString output;
2302 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2303 if(output.IsEmpty())
2304 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2305 else
2306 return CUnicodeUtils::GetCPCode(output);
2308 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2312 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2313 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2315 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2316 TCHAR commentChar = L'#';
2317 if (stripComments)
2319 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2320 if (!commentCharValue.IsEmpty())
2321 commentChar = commentCharValue[0];
2324 bool sanitize = (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE);
2325 if (sanitize)
2326 message.Trim(L" \r\n");
2328 int len = message.GetLength();
2329 int start = 0;
2330 int emptyLineCnt = 0;
2331 while (start >= 0 && start < len)
2333 int oldStart = start;
2334 start = message.Find(L"\n", oldStart);
2335 CString line = message.Mid(oldStart);
2336 if (start != -1)
2338 line.Truncate(start - oldStart);
2339 ++start; // move forward so we don't find the same char again
2341 if (stripComments && (!line.IsEmpty() && line.GetAt(0) == commentChar) || (start < 0 && line.IsEmpty()))
2342 continue;
2343 line.TrimRight(L" \r");
2344 if (sanitize)
2346 if (line.IsEmpty())
2348 ++emptyLineCnt;
2349 continue;
2351 if (emptyLineCnt) // squash multiple newlines
2352 file.Write("\n", 1);
2353 emptyLineCnt = 0;
2355 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2356 file.Write((LPCSTR)lineA, lineA.GetLength());
2358 file.Close();
2359 return 0;
2361 catch (CFileException *e)
2363 e->Delete();
2364 return -1;
2368 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)
2370 if (bAutoLoad)
2371 CAppUtils::LaunchPAgent(nullptr, &url);
2373 CGitHash hashOld;
2374 if (g_Git.GetHash(hashOld, L"HEAD"))
2376 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2377 return false;
2380 CString args;
2381 if (CRegDWORD(L"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE) == FALSE)
2382 args += L" --no-rebase";
2384 if (bFetchTags == BST_UNCHECKED)
2385 args += L" --no-tags";
2386 else if (bFetchTags == BST_CHECKED)
2387 args += L" --tags";
2389 if (bNoFF)
2390 args += L" --no-ff";
2392 if (bFFonly)
2393 args += L" --ff-only";
2395 if (bSquash)
2396 args += L" --squash";
2398 if (bNoCommit)
2399 args += L" --no-commit";
2401 if (nDepth)
2402 args.AppendFormat(L" --depth %d", *nDepth);
2404 if (bPrune == BST_CHECKED)
2405 args += L" --prune";
2406 else if (bPrune == BST_UNCHECKED)
2407 args += L" --no-prune";
2409 if (bUnrelated)
2410 args += L" --allow-unrelated-histories";
2412 CString cmd;
2413 cmd.Format(L"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR)args, (LPCTSTR)url, (LPCTSTR)remoteBranchName);
2414 CProgressDlg progress;
2415 progress.m_GitCmd = cmd;
2417 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2418 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2420 if (status)
2422 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2424 STRING_VECTOR remotes;
2425 g_Git.GetRemoteList(remotes);
2426 if (std::find(remotes.begin(), remotes.end(), url) != remotes.end())
2428 CString currentBranch;
2429 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2430 currentBranch.Empty();
2431 CString remoteRef = L"remotes/" + url + L"/" + remoteBranchName;
2432 if (!currentBranch.IsEmpty() && remoteBranchName.IsEmpty())
2434 CString pullRemote, pullBranch;
2435 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2436 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2437 remoteRef = L"remotes/" + pullRemote + L"/" + pullBranch;
2439 CGitHash common;
2440 g_Git.IsFastForward(L"HEAD", remoteRef, &common);
2441 if (common.IsEmpty())
2442 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoPull(url, bAutoLoad, bFetchTags, bNoFF, bFFonly, bSquash, bNoCommit, nDepth, bPrune, remoteBranchName, showPush, showStashPop, true); });
2446 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(); });
2447 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(L"", true); });
2448 return;
2451 if (showStashPop)
2452 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
2454 if (g_Git.GetHash(hashNew, L"HEAD"))
2455 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash after pulling."), L"TortoiseGit", MB_ICONERROR);
2456 else
2458 postCmdList.emplace_back(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2460 CFileDiffDlg dlg;
2461 dlg.SetDiff(nullptr, hashOld.ToString(), hashNew.ToString());
2462 dlg.DoModal();
2464 postCmdList.emplace_back(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2466 CLogDlg dlg;
2467 dlg.SetParams(CTGitPath(L""), CTGitPath(L""), L"", hashOld.ToString() + L".." + hashNew.ToString(), 0);
2468 dlg.DoModal();
2472 if (showPush)
2473 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
2475 CTGitPath gitPath = g_Git.m_CurrentDir;
2476 if (gitPath.HasSubmodules())
2478 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2480 CString sCmd;
2481 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2482 CAppUtils::RunTortoiseGitProc(sCmd);
2487 INT_PTR ret = progress.DoModal();
2489 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)
2491 CChangedDlg changeddlg;
2492 changeddlg.m_pathList.AddPath(CTGitPath());
2493 changeddlg.DoModal();
2495 return true;
2498 return ret == IDOK;
2501 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2503 if (IsTGitRebaseActive())
2504 return false;
2506 CPullFetchDlg dlg;
2507 dlg.m_IsPull = TRUE;
2508 if (dlg.DoModal() == IDOK)
2510 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2511 if (dlg.m_bRebase)
2512 return DoFetch(dlg.m_RemoteURL,
2513 FALSE, // Fetch all remotes
2514 dlg.m_bAutoLoad == BST_CHECKED,
2515 dlg.m_bPrune,
2516 dlg.m_bDepth == BST_CHECKED,
2517 dlg.m_nDepth,
2518 dlg.m_bFetchTags,
2519 dlg.m_RemoteBranchName,
2520 dlg.m_bRebaseActivatedInConfigForPull ? 2 : 1, // Rebase after fetching
2521 dlg.m_bRebasePreserveMerges == TRUE); // Preserve merges on rebase
2523 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);
2526 return false;
2529 bool CAppUtils::RebaseAfterFetch(const CString& upstream, int rebase, bool preserveMerges)
2531 while (true)
2533 CRebaseDlg dlg;
2534 if (!upstream.IsEmpty())
2535 dlg.m_Upstream = upstream;
2536 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2537 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2538 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2539 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2540 dlg.m_bRebaseAutoStart = (rebase == 2);
2541 dlg.m_bPreserveMerges = preserveMerges;
2542 INT_PTR response = dlg.DoModal();
2543 if (response == IDOK)
2544 return true;
2545 else if (response == IDC_REBASE_POST_BUTTON)
2547 CString cmd = _T("/command:log");
2548 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2549 CAppUtils::RunTortoiseGitProc(cmd);
2550 return true;
2552 else if (response == IDC_REBASE_POST_BUTTON + 1)
2553 return Push();
2554 else if (response == IDC_REBASE_POST_BUTTON + 2)
2556 CString cmd, out, err;
2557 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2558 (LPCTSTR)g_Git.m_CurrentDir,
2559 (LPCTSTR)g_Git.FixBranchName(dlg.m_Upstream),
2560 (LPCTSTR)g_Git.FixBranchName(dlg.m_Branch));
2561 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2563 CMessageBox::Show(nullptr, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2564 return false;
2566 CAppUtils::SendPatchMail(cmd, out);
2567 return true;
2569 else if (response == IDC_REBASE_POST_BUTTON + 3)
2570 continue;
2571 else if (response == IDCANCEL)
2572 return false;
2573 return false;
2577 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)
2579 if (loadPuttyAgent)
2581 if (fetchAllRemotes)
2583 STRING_VECTOR list;
2584 g_Git.GetRemoteList(list);
2586 for (const auto& remote : list)
2587 CAppUtils::LaunchPAgent(nullptr, &remote);
2589 else
2590 CAppUtils::LaunchPAgent(nullptr, &url);
2593 CString upstream = _T("FETCH_HEAD");
2594 CGitHash oldUpstreamHash;
2595 if (runRebase)
2597 STRING_VECTOR list;
2598 g_Git.GetRemoteList(list);
2599 for (auto it = list.cbegin(); it != list.cend(); ++it)
2601 if (url == *it)
2603 CString remote, trackedBranch;
2604 g_Git.GetRemoteTrackedBranchForHEAD(remote, trackedBranch);
2605 if (!remote.IsEmpty() && !trackedBranch.IsEmpty())
2607 upstream = L"remotes/" + remote + L"/" + trackedBranch;
2608 g_Git.GetHash(oldUpstreamHash, upstream);
2610 break;
2615 CString cmd, arg;
2616 arg = _T(" --progress");
2618 if (bDepth)
2619 arg.AppendFormat(_T(" --depth %d"), nDepth);
2621 if (prune == TRUE)
2622 arg += _T(" --prune");
2623 else if (prune == FALSE)
2624 arg += _T(" --no-prune");
2626 if (fetchTags == 1)
2627 arg += _T(" --tags");
2628 else if (fetchTags == 0)
2629 arg += _T(" --no-tags");
2631 if (fetchAllRemotes)
2632 cmd.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR)arg);
2633 else
2634 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR)arg, (LPCTSTR)url, (LPCTSTR)remoteBranch);
2636 CProgressDlg progress;
2637 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2639 if (status)
2641 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase, rebasePreserveMerges); });
2642 return;
2645 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2647 CString cmd = _T("/command:log");
2648 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2649 CAppUtils::RunTortoiseGitProc(cmd);
2652 postCmdList.emplace_back(IDI_REVERT, IDS_PROC_RESET, []
2654 CString pullRemote, pullBranch;
2655 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2656 CString defaultUpstream;
2657 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2658 defaultUpstream.Format(_T("remotes/%s/%s"), (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
2659 CAppUtils::GitReset(&defaultUpstream, 2);
2662 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); });
2664 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2665 postCmdList.emplace_back(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); });
2668 progress.m_GitCmd = cmd;
2670 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2672 CGitProgressDlg gitdlg;
2673 FetchProgressCommand fetchProgressCommand;
2674 if (!fetchAllRemotes)
2675 fetchProgressCommand.SetUrl(url);
2676 gitdlg.SetCommand(&fetchProgressCommand);
2677 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2678 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2679 if (!fetchAllRemotes)
2680 fetchProgressCommand.SetRefSpec(remoteBranch);
2681 return gitdlg.DoModal() == IDOK;
2684 progress.m_PostExecCallback = [&](DWORD& exitCode, CString&)
2686 if (exitCode || !runRebase)
2687 return;
2689 CGitHash remoteBranchHash;
2690 g_Git.GetHash(remoteBranchHash, upstream);
2691 if (runRebase == 1 && 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)
2692 return;
2694 if (runRebase == 1 && g_Git.IsFastForward(L"HEAD", upstream))
2696 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);
2697 if (ret == 3)
2698 return;
2699 if (ret == 1)
2701 CProgressDlg mergeProgress;
2702 mergeProgress.m_GitCmd = L"git.exe merge --ff-only " + upstream;
2703 mergeProgress.m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
2704 mergeProgress.m_PostCmdCallback = [](DWORD status, PostCmdList& postCmdList)
2706 if (status && g_Git.HasWorkingTreeConflicts())
2708 // there are conflict files
2709 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2711 CString sCmd;
2712 sCmd.Format(L"/command:commit /path:\"%s\"", g_Git.m_CurrentDir);
2713 CAppUtils::RunTortoiseGitProc(sCmd);
2717 mergeProgress.DoModal();
2718 return;
2722 CAppUtils::RebaseAfterFetch(upstream, runRebase, rebasePreserveMerges);
2725 return progress.DoModal() == IDOK;
2728 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2730 CPullFetchDlg dlg;
2731 dlg.m_PreSelectRemote = remoteName;
2732 dlg.m_IsPull=FALSE;
2733 dlg.m_bAllRemotes = allRemotes;
2735 if(dlg.DoModal()==IDOK)
2736 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);
2738 return false;
2741 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)
2743 CString error;
2744 DWORD exitcode = 0xFFFFFFFF;
2745 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2747 if (exitcode)
2749 CString temp;
2750 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2751 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2752 return false;
2756 int iRecurseSubmodules = 0;
2757 if (GetMsysgitVersion() >= 0x02070000)
2759 CString sRecurseSubmodules = g_Git.GetConfigValue(_T("push.recurseSubmodules"));
2760 if (sRecurseSubmodules == _T("check"))
2761 iRecurseSubmodules = 1;
2762 else if (sRecurseSubmodules == _T("on-demand"))
2763 iRecurseSubmodules = 2;
2766 CString arg;
2767 if (pack)
2768 arg += _T("--thin ");
2769 if (tags && !allBranches)
2770 arg += _T("--tags ");
2771 if (force)
2772 arg += _T("--force ");
2773 if (forceWithLease)
2774 arg += _T("--force-with-lease ");
2775 if (setUpstream)
2776 arg += _T("--set-upstream ");
2777 if (recurseSubmodules == 0 && recurseSubmodules != iRecurseSubmodules)
2778 arg += _T("--recurse-submodules=no ");
2779 if (recurseSubmodules == 1 && recurseSubmodules != iRecurseSubmodules)
2780 arg += _T("--recurse-submodules=check ");
2781 if (recurseSubmodules == 2 && recurseSubmodules != iRecurseSubmodules)
2782 arg += _T("--recurse-submodules=on-demand ");
2784 arg += _T("--progress ");
2786 CProgressDlg progress;
2788 STRING_VECTOR remotesList;
2789 if (allRemotes)
2790 g_Git.GetRemoteList(remotesList);
2791 else
2792 remotesList.push_back(remote);
2794 for (unsigned int i = 0; i < remotesList.size(); ++i)
2796 if (autoloadKey)
2797 CAppUtils::LaunchPAgent(nullptr, &remotesList[i]);
2799 CString cmd;
2800 if (allBranches)
2802 cmd.Format(_T("git.exe push --all %s\"%s\""),
2803 (LPCTSTR)arg,
2804 (LPCTSTR)remotesList[i]);
2806 if (tags)
2808 progress.m_GitCmdList.push_back(cmd);
2809 cmd.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR)arg, (LPCTSTR)remotesList[i]);
2812 else
2814 cmd.Format(_T("git.exe push %s\"%s\" %s"),
2815 (LPCTSTR)arg,
2816 (LPCTSTR)remotesList[i],
2817 (LPCTSTR)localBranch);
2818 if (!remoteBranch.IsEmpty())
2820 cmd += L":";
2821 cmd += remoteBranch;
2824 progress.m_GitCmdList.push_back(cmd);
2826 if (!allBranches && !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE))
2828 cmd.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR)localBranch);
2829 progress.m_GitCmdList.push_back(cmd);
2833 CString superprojectRoot;
2834 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2835 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2837 // need to execute hooks as those might be needed by post action commands
2838 DWORD exitcode = 0xFFFFFFFF;
2839 CString error;
2840 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2842 if (exitcode)
2844 CString temp;
2845 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2846 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2850 if (status)
2852 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2853 if (rejected)
2855 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, []{ Pull(true); });
2856 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(allRemotes ? _T("") : remote, allRemotes); });
2858 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2859 return;
2862 postCmdList.emplace_back(IDS_PROC_REQUESTPULL, [&]{ RequestPull(remoteBranch); });
2863 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2864 postCmdList.emplace_back(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); });
2865 if (!superprojectRoot.IsEmpty())
2867 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2869 CString sCmd;
2870 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)superprojectRoot);
2871 RunTortoiseGitProc(sCmd);
2876 INT_PTR ret = progress.DoModal();
2877 return ret == IDOK;
2880 bool CAppUtils::Push(const CString& selectLocalBranch)
2882 CPushDlg dlg;
2883 dlg.m_BranchSourceName = selectLocalBranch;
2885 if (dlg.DoModal() == IDOK)
2886 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);
2888 return FALSE;
2891 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2893 CRequestPullDlg dlg;
2894 dlg.m_RepositoryURL = repositoryUrl;
2895 dlg.m_EndRevision = endrevision;
2896 if (dlg.DoModal()==IDOK)
2898 CString cmd;
2899 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR)dlg.m_StartRevision, (LPCTSTR)dlg.m_RepositoryURL, (LPCTSTR)dlg.m_EndRevision);
2901 CSysProgressDlg sysProgressDlg;
2902 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2903 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2904 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2905 sysProgressDlg.SetShowProgressBar(false);
2906 sysProgressDlg.ShowModeless((HWND)nullptr, true);
2908 CString tempFileName = GetTempFile();
2909 CString err;
2910 DeleteFile(tempFileName);
2911 CreateDirectory(tempFileName, nullptr);
2912 tempFileName += _T("\\pullrequest.txt");
2913 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2915 CString msg;
2916 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2917 MessageBox(nullptr, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2918 return false;
2921 if (sysProgressDlg.HasUserCancelled())
2923 CMessageBox::Show(nullptr, IDS_USERCANCELLED, IDS_APPNAME, MB_OK);
2924 ::DeleteFile(tempFileName);
2925 return false;
2928 sysProgressDlg.Stop();
2930 if (dlg.m_bSendMail)
2932 CSendMailDlg sendmaildlg;
2933 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2934 sendmaildlg.m_bCustomSubject = true;
2936 if (sendmaildlg.DoModal() == IDOK)
2938 if (sendmaildlg.m_PathList.IsEmpty())
2939 return FALSE;
2941 CGitProgressDlg progDlg;
2942 if (bIsMainWnd)
2943 theApp.m_pMainWnd = &progDlg;
2944 SendMailProgressCommand sendMailProgressCommand;
2945 progDlg.SetCommand(&sendMailProgressCommand);
2947 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2948 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2950 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2951 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2953 progDlg.DoModal();
2955 return true;
2957 return false;
2960 CAppUtils::LaunchAlternativeEditor(tempFileName);
2962 return true;
2965 void CAppUtils::RemoveTrailSlash(CString &path)
2967 if(path.IsEmpty())
2968 return ;
2970 // For URL, do not trim the slash just after the host name component.
2971 int index = path.Find(_T("://"));
2972 if (index >= 0)
2974 index += 4;
2975 index = path.Find(_T('/'), index);
2976 if (index == path.GetLength() - 1)
2977 return;
2980 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2982 path.Truncate(path.GetLength() - 1);
2983 if(path.IsEmpty())
2984 return;
2988 bool CAppUtils::CheckUserData()
2990 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2992 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO | MB_ICONERROR) == IDYES)
2994 CTGitPath path(g_Git.m_CurrentDir);
2995 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2996 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2997 dlg.SetTreeWidth(220);
2998 dlg.m_DefaultPage = _T("gitconfig");
3000 dlg.DoModal();
3001 dlg.HandleRestart();
3004 else
3005 return false;
3008 return true;
3011 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
3012 CTGitPathList &pathList,
3013 CTGitPathList &selectedList,
3014 bool bSelectFilesForCommit)
3016 bool bFailed = true;
3018 if (!CheckUserData())
3019 return false;
3021 while (bFailed)
3023 bFailed = false;
3024 CCommitDlg dlg;
3025 dlg.m_sBugID = bugid;
3027 dlg.m_bWholeProject = bWholeProject;
3029 dlg.m_sLogMessage = sLogMsg;
3030 dlg.m_pathList = pathList;
3031 dlg.m_checkedPathList = selectedList;
3032 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
3033 if (dlg.DoModal() == IDOK)
3035 if (dlg.m_pathList.IsEmpty())
3036 return false;
3037 // if the user hasn't changed the list of selected items
3038 // we don't use that list. Because if we would use the list
3039 // of pre-checked items, the dialog would show different
3040 // checked items on the next startup: it would only try
3041 // to check the parent folder (which might not even show)
3042 // instead, we simply use an empty list and let the
3043 // default checking do its job.
3044 if (!dlg.m_pathList.IsEqual(pathList))
3045 selectedList = dlg.m_pathList;
3046 pathList = dlg.m_updatedPathList;
3047 sLogMsg = dlg.m_sLogMessage;
3048 bSelectFilesForCommit = true;
3050 switch (dlg.m_PostCmd)
3052 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3053 CAppUtils::SVNDCommit();
3054 break;
3055 case GIT_POSTCOMMIT_CMD_PUSH:
3056 CAppUtils::Push();
3057 break;
3058 case GIT_POSTCOMMIT_CMD_CREATETAG:
3059 CAppUtils::CreateBranchTag(TRUE);
3060 break;
3061 case GIT_POSTCOMMIT_CMD_PULL:
3062 CAppUtils::Pull(true);
3063 break;
3064 default:
3065 break;
3068 // CGitProgressDlg progDlg;
3069 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3070 // if (parser.HasVal(_T("closeonend")))
3071 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3072 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3073 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3074 // progDlg.SetPathList(dlg.m_pathList);
3075 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3076 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3077 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3078 // progDlg.SetItemCount(dlg.m_itemsCount);
3079 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3080 // progDlg.DoModal();
3081 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3082 // err = (DWORD)progDlg.DidErrorsOccur();
3083 // bFailed = progDlg.DidErrorsOccur();
3084 // bRet = progDlg.DidErrorsOccur();
3085 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3086 // if (DWORD(bFailRepeat)==0)
3087 // bFailed = false; // do not repeat if the user chose not to in the settings.
3090 return true;
3093 BOOL CAppUtils::SVNDCommit()
3095 CSVNDCommitDlg dcommitdlg;
3096 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
3097 if (gitSetting.IsEmpty()) {
3098 if (dcommitdlg.DoModal() != IDOK)
3099 return false;
3100 else
3102 if (dcommitdlg.m_remember)
3104 if (dcommitdlg.m_rmdir)
3105 gitSetting = _T("true");
3106 else
3107 gitSetting = _T("false");
3108 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
3110 CString msg;
3111 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
3112 CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3118 BOOL IsStash = false;
3119 if(!g_Git.CheckCleanWorkTree())
3121 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3123 CSysProgressDlg sysProgressDlg;
3124 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3125 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3126 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3127 sysProgressDlg.SetShowProgressBar(false);
3128 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3129 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3131 CString cmd,out;
3132 cmd=_T("git.exe stash");
3133 if (g_Git.Run(cmd, &out, CP_UTF8))
3135 sysProgressDlg.Stop();
3136 MessageBox(nullptr, out,_T("TortoiseGit"), MB_OK | MB_ICONERROR);
3137 return false;
3139 sysProgressDlg.Stop();
3141 IsStash =true;
3143 else
3144 return false;
3147 CProgressDlg progress;
3148 if (dcommitdlg.m_rmdir)
3149 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
3150 else
3151 progress.m_GitCmd=_T("git.exe svn dcommit");
3152 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3154 if( IsStash)
3156 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
3158 CSysProgressDlg sysProgressDlg;
3159 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3160 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3161 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3162 sysProgressDlg.SetShowProgressBar(false);
3163 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3164 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3166 CString cmd,out;
3167 cmd=_T("git.exe stash pop");
3168 if (g_Git.Run(cmd, &out, CP_UTF8))
3170 sysProgressDlg.Stop();
3171 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3172 return false;
3174 sysProgressDlg.Stop();
3176 else
3177 return false;
3179 return TRUE;
3181 return FALSE;
3184 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)
3186 CString args;
3187 if (noFF)
3188 args += L" --no-ff";
3189 else if (ffOnly)
3190 args += L" --ff-only";
3192 if (squash)
3193 args += L" --squash";
3195 if (noCommit)
3196 args += L" --no-commit";
3198 if (unrelated)
3199 args += L" --allow-unrelated-histories";
3201 if (log)
3202 args.AppendFormat(L" --log=%d", *log);
3204 if (!mergeStrategy.IsEmpty())
3206 args += L" --strategy=" + mergeStrategy;
3207 if (!strategyOption.IsEmpty())
3209 args += L" --strategy-option=" + strategyOption;
3210 if (!strategyParam.IsEmpty())
3211 args += L'=' + strategyParam;
3215 if (!logMessage.IsEmpty())
3217 CString logmsg = logMessage;
3218 logmsg.Replace(L"\\\"", L"\\\\\"");
3219 logmsg.Replace(L"\"", L"\\\"");
3220 args += L" -m \"" + logmsg + L"\"";
3223 CString mergeVersion = g_Git.FixBranchName(version);
3224 CString cmd;
3225 cmd.Format(L"git.exe merge%s %s", (LPCTSTR)args, (LPCTSTR)mergeVersion);
3227 CProgressDlg Prodlg;
3228 Prodlg.m_GitCmd = cmd;
3230 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3232 if (status)
3234 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3235 if (hasConflicts < 0)
3236 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
3237 else if (hasConflicts)
3239 // there are conflict files
3241 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3243 CString sCmd;
3244 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3245 CAppUtils::RunTortoiseGitProc(sCmd);
3249 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3251 CGitHash common;
3252 g_Git.IsFastForward(L"HEAD", mergeVersion, &common);
3253 if (common.IsEmpty())
3254 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoMerge(noFF, ffOnly, squash, noCommit, log, true, mergeStrategy, strategyOption, strategyParam, logMessage, version, isBranch, showStashPop); });
3257 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [=]{ CAppUtils::StashSave(L"", false, false, true, mergeVersion); });
3259 return;
3262 if (showStashPop)
3263 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
3265 if (noCommit)
3267 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3269 CString sCmd;
3270 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3271 CAppUtils::RunTortoiseGitProc(sCmd);
3273 return;
3276 if (isBranch && !CStringUtils::StartsWith(version, L"remotes/")) // do not ask to remove remote branches
3278 postCmdList.emplace_back(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3280 CString msg;
3281 msg.Format(IDS_PROC_DELETEBRANCHTAG, version);
3282 if (CMessageBox::Show(nullptr, msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3284 CString cmd, out;
3285 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)version);
3286 if (g_Git.Run(cmd, &out, CP_UTF8))
3287 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3291 if (isBranch)
3292 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
3294 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3295 if (hasGitSVN)
3296 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ CAppUtils::SVNDCommit(); });
3299 Prodlg.DoModal();
3300 return !Prodlg.m_GitStatus;
3303 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3305 if (!CheckUserData())
3306 return FALSE;
3308 if (IsTGitRebaseActive())
3309 return FALSE;
3311 CMergeDlg dlg;
3312 if (commit)
3313 dlg.m_initialRefName = *commit;
3315 if (dlg.DoModal() == IDOK)
3316 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);
3318 return FALSE;
3321 BOOL CAppUtils::MergeAbort()
3323 CMergeAbortDlg dlg;
3324 if (dlg.DoModal() == IDOK)
3325 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3327 return FALSE;
3330 void CAppUtils::EditNote(GitRevLoglist* rev)
3332 if (!CheckUserData())
3333 return;
3335 CInputDlg dlg;
3336 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3337 dlg.m_sInputText = rev->m_Notes;
3338 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3339 //dlg.m_pProjectProperties = &m_ProjectProperties;
3340 dlg.m_bUseLogWidth = true;
3341 if(dlg.DoModal() == IDOK)
3343 CString cmd,output;
3344 cmd=_T("notes add -f -F \"");
3346 CString tempfile=::GetTempFile();
3347 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3349 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3350 return;
3352 cmd += tempfile;
3353 cmd += _T("\" ");
3354 cmd += rev->m_CommitHash.ToString();
3358 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3359 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3360 else
3361 rev->m_Notes = dlg.m_sInputText;
3362 }catch(...)
3364 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3366 ::DeleteFile(tempfile);
3371 int CAppUtils::GetMsysgitVersion()
3373 if (g_Git.ms_LastMsysGitVersion)
3374 return g_Git.ms_LastMsysGitVersion;
3376 CString cmd;
3377 CString versiondebug;
3378 CString version;
3380 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3381 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3383 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3385 __int64 time=0;
3386 if (!CGit::GetFileModifyTime(gitpath, &time))
3388 if((DWORD)time == regTime)
3390 g_Git.ms_LastMsysGitVersion = regVersion;
3391 return regVersion;
3395 CString err;
3396 int ver = g_Git.GetGitVersion(&versiondebug, &err);
3397 if (ver < 0)
3399 CMessageBox::Show(nullptr, _T("git.exe not correctly set up (") + err + _T(")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\"."), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3400 return -1;
3404 if (!ver)
3406 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3407 return -1;
3411 regTime = time&0xFFFFFFFF;
3412 regVersion = ver;
3413 g_Git.ms_LastMsysGitVersion = ver;
3415 return ver;
3418 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3420 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3422 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3424 if (hShell.IsValid()) {
3425 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3426 if (pfnSHGPSFW) {
3427 IPropertyStore *pps;
3428 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3429 if (SUCCEEDED(hr)) {
3430 PROPVARIANT var;
3431 var.vt = VT_BOOL;
3432 var.boolVal = VARIANT_TRUE;
3433 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3434 pps->Release();
3440 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3442 ASSERT(dialogname.GetLength() < 70);
3443 ASSERT(urlorpath.GetLength() < MAX_PATH);
3444 WCHAR pathbuf[MAX_PATH] = {0};
3446 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3448 wcscat_s(pathbuf, L" - ");
3449 wcscat_s(pathbuf, dialogname);
3450 wcscat_s(pathbuf, L" - ");
3451 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3452 SetWindowText(hWnd, pathbuf);
3455 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3457 if (!g_Git.CheckCleanWorkTree())
3459 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3461 CSysProgressDlg sysProgressDlg;
3462 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3463 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3464 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3465 sysProgressDlg.SetShowProgressBar(false);
3466 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3467 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3469 CString cmd, out;
3470 cmd = _T("git.exe stash");
3471 if (g_Git.Run(cmd, &out, CP_UTF8))
3473 sysProgressDlg.Stop();
3474 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3475 return false;
3477 sysProgressDlg.Stop();
3479 else
3480 return false;
3483 CBisectStartDlg bisectStartDlg;
3485 if (!lastGood.IsEmpty())
3486 bisectStartDlg.m_sLastGood = lastGood;
3487 if (!firstBad.IsEmpty())
3488 bisectStartDlg.m_sFirstBad = firstBad;
3490 if (bisectStartDlg.DoModal() == IDOK)
3492 CProgressDlg progress;
3493 if (bIsMainWnd)
3494 theApp.m_pMainWnd = &progress;
3495 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3496 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3497 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3499 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3501 if (status)
3502 return;
3504 CTGitPath path(g_Git.m_CurrentDir);
3505 if (path.HasSubmodules())
3507 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3509 CString sCmd;
3510 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3511 CAppUtils::RunTortoiseGitProc(sCmd);
3516 INT_PTR ret = progress.DoModal();
3517 return ret == IDOK;
3520 return false;
3523 bool CAppUtils::BisectOperation(const CString& op, const CString& ref, bool bIsMainWnd)
3525 CString cmd = _T("git.exe bisect ") + op;
3527 if (!ref.IsEmpty())
3529 cmd += _T(" ");
3530 cmd += ref;
3533 CProgressDlg progress;
3534 if (bIsMainWnd)
3535 theApp.m_pMainWnd = &progress;
3536 progress.m_GitCmd = cmd;
3538 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3540 if (status)
3541 return;
3543 CTGitPath path = g_Git.m_CurrentDir;
3544 if (path.HasSubmodules())
3546 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3548 CString sCmd;
3549 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3550 CAppUtils::RunTortoiseGitProc(sCmd);
3554 if (op != _T("reset"))
3555 postCmdList.emplace_back(IDS_MENUBISECTRESET, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3558 INT_PTR ret = progress.DoModal();
3559 return ret == IDOK;
3562 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3564 CUserPassword dlg;
3565 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3566 if (username_from_url)
3567 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3569 CStringA username, password;
3570 if (dlg.DoModal() == IDOK)
3572 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3573 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3574 return git_cred_userpass_plaintext_new(out, username, password);
3576 giterr_set_str(GITERR_NONE, "User cancelled.");
3577 return GIT_EUSER;
3580 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3582 if (base_cert->cert_type == GIT_CERT_X509)
3584 git_cert_x509* cert = (git_cert_x509*)base_cert;
3586 if (last_accepted_cert.cmp(cert))
3587 return 0;
3589 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3590 SCOPE_EXIT { CertFreeCertificateContext(pServerCert); };
3592 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3593 if (!verificationError)
3595 last_accepted_cert.set(cert);
3596 return 0;
3599 CString servernameInCert;
3600 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, CStrBuf(servernameInCert, 128), 128);
3602 CString issuer;
3603 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, CStrBuf(issuer, 128), 128);
3605 CCheckCertificateDlg dlg;
3606 dlg.cert = cert;
3607 dlg.m_sCertificateCN = servernameInCert;
3608 dlg.m_sCertificateIssuer = issuer;
3609 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3610 dlg.m_sError = CFormatMessageWrapper(verificationError);
3611 if (dlg.DoModal() == IDOK)
3613 last_accepted_cert.set(cert);
3614 return 0;
3617 return GIT_ECERTIFICATE;
3620 int CAppUtils::ExploreTo(HWND hwnd, CString path)
3622 if (PathFileExists(path))
3624 HRESULT ret = -1;
3625 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3626 if (pidl)
3628 ret = SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3629 ILFree(pidl);
3631 return SUCCEEDED(ret) ? 0 : -1;
3633 // if filepath does not exist any more, navigate to closest matching folder
3636 int pos = path.ReverseFind(_T('\\'));
3637 if (pos <= 3)
3638 break;
3639 path.Truncate(pos);
3640 } while (!PathFileExists(path));
3641 return (INT_PTR)ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW) > 32 ? 0 : -1;
3644 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3646 bool b_local = false, b_remote = false;
3647 BYTE_VECTOR vector;
3649 CString cmd;
3650 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3651 if (g_Git.Run(cmd, &vector))
3653 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK);
3654 return -1;
3657 CTGitPathList list;
3658 if (list.ParserFromLsFile(vector))
3660 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
3661 return -1;
3664 if (list.IsEmpty())
3665 return 0;
3666 for (int i = 0; i < list.GetCount(); ++i)
3668 if (list[i].m_Stage == 2)
3669 b_local = true;
3670 if (list[i].m_Stage == 3)
3671 b_remote = true;
3675 CBlockCacheForPath block(g_Git.m_CurrentDir);
3676 if (path.IsDirectory()) // is submodule conflict
3678 CString err = _T("We're sorry, but you hit a very rare conflict condition with a submodule which cannot be resolved by TortoiseGit. You have to use the command line git for this.");
3679 if (b_local && b_remote)
3681 if (!path.HasAdminDir()) // check if submodule is initialized
3683 err += _T("\n\nYou have to checkout the submodule manually into \"") + path.GetGitPathString() + _T("\" and then reset HEAD to the right commit (see resolve submodule conflict dialog for this).");
3684 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3685 return -1;
3687 CGit subgit;
3688 subgit.m_CurrentDir = g_Git.CombinePath(path);
3689 CGitHash submoduleHead;
3690 if (subgit.GetHash(submoduleHead, _T("HEAD")))
3692 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3693 return -1;
3695 CString baseHash, localHash, remoteHash;
3696 ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash);
3697 if (resolveWith == RESOLVE_WITH_THEIRS && submoduleHead.ToString() != remoteHash)
3699 CString origPath = g_Git.m_CurrentDir;
3700 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3701 if (!GitReset(&remoteHash))
3703 g_Git.m_CurrentDir = origPath;
3704 return -1;
3706 g_Git.m_CurrentDir = origPath;
3708 else if (resolveWith == RESOLVE_WITH_MINE && submoduleHead.ToString() != localHash)
3710 CString origPath = g_Git.m_CurrentDir;
3711 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3712 if (!GitReset(&localHash))
3714 g_Git.m_CurrentDir = origPath;
3715 return -1;
3717 g_Git.m_CurrentDir = origPath;
3720 else
3722 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3723 return -1;
3727 if (resolveWith == RESOLVE_WITH_THEIRS)
3729 CString gitcmd, output;
3730 if (b_local && b_remote)
3731 gitcmd.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3732 else if (b_remote)
3733 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3734 else if (b_local)
3735 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3736 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3738 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3739 return -1;
3742 else if (resolveWith == RESOLVE_WITH_MINE)
3744 CString gitcmd, output;
3745 if (b_local && b_remote)
3746 gitcmd.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3747 else if (b_local)
3748 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3749 else if (b_remote)
3750 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3751 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3753 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3754 return -1;
3758 if (b_local && b_remote && path.m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3760 CString gitcmd, output;
3761 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3762 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3763 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3764 else
3766 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3767 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;