Detect email addresses in log messages and make them clickable
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobe539f357585edf241fc558eea0d3bb7abcf5f218
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 (com.Left(1).Compare(L"#") == 0)
268 com.Delete(0);
269 else
270 com.Empty();
273 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
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 = viewer.Left(1) == _T("#");
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 = viewer.Left(1) == _T("#");
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 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
648 LOGFONT logFont;
649 HDC hScreenDC = ::GetDC(nullptr);
650 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
651 ::ReleaseDC(nullptr, hScreenDC);
652 logFont.lfWidth = 0;
653 logFont.lfEscapement = 0;
654 logFont.lfOrientation = 0;
655 logFont.lfWeight = FW_NORMAL;
656 logFont.lfItalic = 0;
657 logFont.lfUnderline = 0;
658 logFont.lfStrikeOut = 0;
659 logFont.lfCharSet = DEFAULT_CHARSET;
660 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
661 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
662 logFont.lfQuality = DRAFT_QUALITY;
663 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
664 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
665 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
668 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
670 CString key,remote;
671 CString cmd,out;
672 if (!pRemote)
673 remote=_T("origin");
674 else
675 remote=*pRemote;
677 if (!keyfile)
679 cmd.Format(_T("remote.%s.puttykeyfile"), (LPCTSTR)remote);
680 key = g_Git.GetConfigValue(cmd);
682 else
683 key=*keyfile;
685 if(key.IsEmpty())
686 return false;
688 CString proc=CPathUtils::GetAppDirectory();
689 proc += _T("pageant.exe \"");
690 proc += key;
691 proc += _T("\"");
693 CString tempfile = GetTempFile();
694 ::DeleteFile(tempfile);
696 proc += _T(" -c \"");
697 proc += CPathUtils::GetAppDirectory();
698 proc += _T("tgittouch.exe\"");
699 proc += _T(" \"");
700 proc += tempfile;
701 proc += _T("\"");
703 CString appDir = CPathUtils::GetAppDirectory();
704 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
705 if(!b)
706 return b;
708 int i=0;
709 while(!::PathFileExists(tempfile))
711 Sleep(100);
712 ++i;
713 if(i>10*60*5)
714 break; //timeout 5 minutes
717 if( i== 10*60*5)
718 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
719 ::DeleteFile(tempfile);
720 return true;
722 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
724 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
725 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
726 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
729 CString sCmd;
730 sCmd.Format(_T("\"%s\" \"%s\""), (LPCTSTR)editTool, (LPCTSTR)filename);
732 LaunchApplication(sCmd, 0, false, nullptr, uac);
733 return true;
735 bool CAppUtils::LaunchRemoteSetting()
737 CTGitPath path(g_Git.m_CurrentDir);
738 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
739 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
740 dlg.SetTreeWidth(220);
741 dlg.m_DefaultPage = _T("gitremote");
743 dlg.DoModal();
744 dlg.HandleRestart();
745 return true;
748 * Launch the external blame viewer
750 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile, const CString& Rev, const CString& sParams)
752 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
753 viewer += _T("TortoiseGitBlame.exe");
754 viewer += _T("\" \"") + sBlameFile + _T("\"");
755 //viewer += _T(" \"") + sLogFile + _T("\"");
756 //viewer += _T(" \"") + sOriginalFile + _T("\"");
757 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
758 viewer += CString(_T(" /rev:"))+Rev;
759 if (!g_sGroupingUUID.IsEmpty())
761 viewer += L" /groupuuid:\"";
762 viewer += g_sGroupingUUID;
763 viewer += L"\"";
765 viewer += _T(" ")+sParams;
767 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
770 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
772 CString sText;
773 if (!pWnd)
774 return false;
775 bool bStyled = false;
776 pWnd->GetWindowText(sText);
777 // the rich edit control doesn't count the CR char!
778 // to be exact: CRLF is treated as one char.
779 sText.Remove(_T('\r'));
781 // style each line separately
782 int offset = 0;
783 int nNewlinePos;
786 nNewlinePos = sText.Find('\n', offset);
787 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
789 int start = 0;
790 int end = 0;
791 while (FindStyleChars(sLine, '*', start, end))
793 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
794 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
795 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
796 bStyled = true;
797 start = end;
799 start = 0;
800 end = 0;
801 while (FindStyleChars(sLine, '^', start, end))
803 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
804 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
805 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
806 bStyled = true;
807 start = end;
809 start = 0;
810 end = 0;
811 while (FindStyleChars(sLine, '_', start, end))
813 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
814 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
815 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
816 bStyled = true;
817 start = end;
819 offset = nNewlinePos+1;
820 } while(nNewlinePos>=0);
821 return bStyled;
824 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
826 int i=start;
827 int last = sText.GetLength() - 1;
828 bool bFoundMarker = false;
829 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
830 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
832 // find a starting marker
833 while (i < last)
835 TCHAR prevChar = c;
836 c = nextChar;
837 nextChar = sText[i + 1];
839 // IsCharAlphaNumeric can be somewhat expensive.
840 // Long lines of "*****" or "----" will be pre-empted efficiently
841 // by the (c != nextChar) condition.
843 if ((c == stylechar) && (c != nextChar))
845 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
847 start = ++i;
848 bFoundMarker = true;
849 break;
852 ++i;
854 if (!bFoundMarker)
855 return false;
857 // find ending marker
858 // c == sText[i - 1]
860 bFoundMarker = false;
861 while (i <= last)
863 TCHAR prevChar = c;
864 c = sText[i];
865 if (c == stylechar)
867 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
869 end = i;
870 ++i;
871 bFoundMarker = true;
872 break;
875 ++i;
877 return bFoundMarker;
880 // from CSciEdit
881 namespace {
882 bool IsValidURLChar(wchar_t ch)
884 return iswalnum(ch) ||
885 ch == L'_' || ch == L'/' || ch == L';' || ch == L'?' || ch == L'&' || ch == L'=' ||
886 ch == L'%' || ch == L':' || ch == L'.' || ch == L'#' || ch == L'-' || ch == L'+' ||
887 ch == L'|' || ch == L'>' || ch == L'<' || ch == L'!' || ch == L'@';
890 bool IsUrlOrEmail(const CString& sText)
892 if (!PathIsURLW(sText))
894 auto atpos = sText.Find(L'@');
895 if (atpos <= 0)
896 return false;
897 if (sText.ReverseFind(L'.') > atpos)
898 return true;
899 return false;
901 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" })
903 if (CStringUtils::StartsWith(sText, prefix) && sText.GetLength() != prefix.GetLength())
904 return true;
906 return false;
910 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
912 std::vector<CHARRANGE> positions = FindURLMatches(msg);
913 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
915 return positions.empty() ? FALSE : TRUE;
919 * implements URL searching with the same logic as CSciEdit::StyleURLs
921 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
923 std::vector<CHARRANGE> result;
925 int len = msg.GetLength();
926 int starturl = -1;
928 for (int i = 0; i <= msg.GetLength(); ++i)
930 if ((i < len) && IsValidURLChar(msg[i]))
932 if (starturl < 0)
933 starturl = i;
935 else
937 if (starturl >= 0)
939 bool strip = true;
940 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
942 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
943 ++starturl;
944 strip = false;
945 i = starturl;
946 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
947 ++i;
949 if (!IsUrlOrEmail(msg.Mid(starturl, i - starturl)))
951 starturl = -1;
952 continue;
955 int skipTrailing = 0;
956 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] == '!'))
957 ++skipTrailing;
959 CHARRANGE range = { starturl, i - skipTrailing };
960 result.push_back(range);
962 starturl = -1;
966 return result;
969 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
970 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
971 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
972 bool bAlternateDiff /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
973 bool /* blame = false */,
974 bool bMerge,
975 bool bCombine,
976 bool bNoPrefix)
978 int diffContext = g_Git.GetConfigValueInt32(L"diff.context", -1);
979 CString tempfile=GetTempFile();
980 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext, bNoPrefix))
982 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
983 return false;
985 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + L":" + rev2, FALSE, bAlternateDiff);
987 #if 0
988 CString sCmd;
989 sCmd.Format(_T("%s /command:showcompare /unified"),
990 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
991 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
992 if (rev1.IsValid())
993 sCmd += _T(" /revision1:") + rev1.ToString();
994 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
995 if (rev2.IsValid())
996 sCmd += _T(" /revision2:") + rev2.ToString();
997 if (peg.IsValid())
998 sCmd += _T(" /pegrevision:") + peg.ToString();
999 if (headpeg.IsValid())
1000 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1002 if (bAlternateDiff)
1003 sCmd += _T(" /alternatediff");
1005 if (bIgnoreAncestry)
1006 sCmd += _T(" /ignoreancestry");
1008 if (hWnd)
1010 sCmd += _T(" /hwnd:");
1011 TCHAR buf[30];
1012 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
1013 sCmd += buf;
1016 return CAppUtils::LaunchApplication(sCmd, 0, false);
1017 #endif
1018 return TRUE;
1021 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1023 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1024 scriptsdir += _T("Diff-Scripts");
1025 CSimpleFileFind files(scriptsdir);
1026 while (files.FindNextFileNoDirectories())
1028 CString file = files.GetFilePath();
1029 CString filename = files.GetFileName();
1030 CString ext = file.Mid(file.ReverseFind('-') + 1);
1031 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
1032 std::set<CString> extensions;
1033 extensions.insert(ext);
1034 CString kind;
1035 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
1036 kind = _T(" //E:vbscript");
1037 if (file.Right(2).CompareNoCase(_T("js"))==0)
1038 kind = _T(" //E:javascript");
1039 // open the file, read the first line and find possible extensions
1040 // this script can handle
1043 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1044 CString extline;
1045 if (f.ReadString(extline))
1047 if ((extline.GetLength() > 15 ) &&
1048 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
1049 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
1051 if (extline[0] == '/')
1052 extline = extline.Mid(15);
1053 else
1054 extline = extline.Mid(14);
1055 CString sToken;
1056 int curPos = 0;
1057 sToken = extline.Tokenize(_T(";"), curPos);
1058 while (!sToken.IsEmpty())
1060 if (!sToken.IsEmpty())
1062 if (sToken[0] != '.')
1063 sToken = _T(".") + sToken;
1064 extensions.insert(sToken);
1066 sToken = extline.Tokenize(_T(";"), curPos);
1070 f.Close();
1072 catch (CFileException* e)
1074 e->Delete();
1077 for (const auto& extension : extensions)
1079 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1081 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1083 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension);
1084 CString diffregstring = diffreg;
1085 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1086 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1089 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1091 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1093 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension);
1094 CString diffregstring = diffreg;
1095 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1096 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1102 return true;
1105 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1107 // ask from where the export has to be done
1108 CExportDlg dlg;
1109 if(BashHash)
1110 dlg.m_initialRefName=*BashHash;
1111 if (orgPath)
1113 if (PathIsRelative(orgPath->GetWinPath()))
1114 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1115 else
1116 dlg.m_orgPath = *orgPath;
1119 if (dlg.DoModal() == IDOK)
1121 CString cmd;
1122 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1123 (LPCTSTR)dlg.m_strFile, (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName));
1125 CProgressDlg pro;
1126 pro.m_GitCmd=cmd;
1127 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1129 if (status)
1130 return;
1131 postCmdList.emplace_back(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); });
1134 CGit git;
1135 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1137 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1138 pro.m_Git = &git;
1140 return (pro.DoModal() == IDOK);
1142 return false;
1145 bool CAppUtils::UpdateBranchDescription(const CString& branch, CString description)
1147 if (branch.IsEmpty())
1148 return false;
1150 CString key;
1151 key.Format(L"branch.%s.description", (LPCTSTR)branch);
1152 description.Replace(L"\r", L"");
1153 description.Trim();
1154 if (description.IsEmpty())
1155 g_Git.UnsetConfigValue(key);
1156 else
1157 g_Git.SetConfigValue(key, description);
1159 return true;
1162 bool CAppUtils::CreateBranchTag(bool isTag /*true*/, const CString* commitHash /*nullptr*/, bool switchNewBranch /*false*/, LPCTSTR name /*nullptr*/)
1164 CCreateBranchTagDlg dlg;
1165 dlg.m_bIsTag = isTag;
1166 dlg.m_bSwitch = switchNewBranch;
1168 if (commitHash)
1169 dlg.m_initialRefName = *commitHash;
1171 if (name)
1172 dlg.m_BranchTagName = name;
1174 if(dlg.DoModal()==IDOK)
1176 CString cmd;
1177 CString force;
1178 CString track;
1179 if(dlg.m_bTrack == TRUE)
1180 track=_T(" --track ");
1181 else if(dlg.m_bTrack == FALSE)
1182 track=_T(" --no-track");
1184 if(dlg.m_bForce)
1185 force=_T(" -f ");
1187 if (isTag)
1189 CString sign;
1190 if(dlg.m_bSign)
1191 sign=_T("-s");
1193 cmd.Format(_T("git.exe tag %s %s %s %s"),
1194 (LPCTSTR)force,
1195 (LPCTSTR)sign,
1196 (LPCTSTR)dlg.m_BranchTagName,
1197 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1200 if(!dlg.m_Message.Trim().IsEmpty())
1202 CString tempfile = ::GetTempFile();
1203 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1205 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1206 return FALSE;
1208 cmd += _T(" -F ")+tempfile;
1211 else
1213 cmd.Format(_T("git.exe branch %s %s %s %s"),
1214 (LPCTSTR)track,
1215 (LPCTSTR)force,
1216 (LPCTSTR)dlg.m_BranchTagName,
1217 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1220 CString out;
1221 if(g_Git.Run(cmd,&out,CP_UTF8))
1223 CMessageBox::Show(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1224 return FALSE;
1226 if (!isTag && dlg.m_bSwitch)
1228 // it is a new branch and the user has requested to switch to it
1229 PerformSwitch(dlg.m_BranchTagName);
1231 if (!isTag && !dlg.m_Message.IsEmpty())
1232 UpdateBranchDescription(dlg.m_BranchTagName, dlg.m_Message);
1234 return TRUE;
1236 return FALSE;
1239 bool CAppUtils::Switch(const CString& initialRefName)
1241 CGitSwitchDlg dlg;
1242 if(!initialRefName.IsEmpty())
1243 dlg.m_initialRefName = initialRefName;
1245 if (dlg.DoModal() == IDOK)
1247 CString branch;
1248 if (dlg.m_bBranch)
1249 branch = dlg.m_NewBranch;
1251 // if refs/heads/ is not stripped, checkout will detach HEAD
1252 // checkout prefers branches on name clashes (with tags)
1253 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1254 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1256 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1258 return FALSE;
1261 bool CAppUtils::PerformSwitch(const CString& ref, bool bForce /* false */, const CString& sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1263 CString cmd;
1264 CString track;
1265 CString force;
1266 CString branch;
1267 CString merge;
1269 if(!sNewBranch.IsEmpty()){
1270 if (bBranchOverride)
1271 branch.Format(_T("-B %s "), (LPCTSTR)sNewBranch);
1272 else
1273 branch.Format(_T("-b %s "), (LPCTSTR)sNewBranch);
1274 if (bTrack == TRUE)
1275 track = _T("--track ");
1276 else if (bTrack == FALSE)
1277 track = _T("--no-track ");
1279 if (bForce)
1280 force = _T("-f ");
1281 if (bMerge)
1282 merge = _T("--merge ");
1284 cmd.Format(_T("git.exe checkout %s%s%s%s%s --"),
1285 (LPCTSTR)force,
1286 (LPCTSTR)track,
1287 (LPCTSTR)merge,
1288 (LPCTSTR)branch,
1289 (LPCTSTR)g_Git.FixBranchName(ref));
1291 CProgressDlg progress;
1292 progress.m_GitCmd = cmd;
1294 CString currentBranch;
1295 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1296 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1298 if (!status)
1300 CTGitPath gitPath = g_Git.m_CurrentDir;
1301 if (gitPath.HasSubmodules())
1303 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1305 CString sCmd;
1306 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1307 RunTortoiseGitProc(sCmd);
1310 if (hasBranch)
1311 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); });
1314 CString newBranch;
1315 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1316 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); });
1318 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []{
1319 CTGitPathList pathlist;
1320 CTGitPathList selectedlist;
1321 pathlist.AddPath(CTGitPath());
1322 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
1323 CString str;
1324 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1327 else
1329 if (bMerge && g_Git.HasWorkingTreeConflicts() > 0)
1331 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
1333 CString sCmd;
1334 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1335 CAppUtils::RunTortoiseGitProc(sCmd);
1338 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); });
1339 if (!bMerge)
1340 postCmdList.emplace_back(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); });
1343 progress.m_PostExecCallback = [&](DWORD& exitCode, CString& extraMsg)
1345 if (bMerge && !exitCode && g_Git.HasWorkingTreeConflicts() > 0)
1347 exitCode = 1; // Treat it as failure
1348 extraMsg = _T("Has merge conflict");
1352 INT_PTR ret = progress.DoModal();
1354 return ret == IDOK;
1357 class CIgnoreFile : public CStdioFile
1359 public:
1360 STRING_VECTOR m_Items;
1361 CString m_eol;
1363 virtual BOOL ReadString(CString& rString)
1365 if (GetPosition() == 0)
1367 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1368 char buf[3] = { 0, 0, 0 };
1369 Read(buf, 3);
1370 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1371 SeekToBegin();
1374 CStringA strA;
1375 char lastChar = '\0';
1376 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1378 if (c == '\r')
1379 continue;
1380 if (c == '\n')
1382 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1383 break;
1385 strA.AppendChar(c);
1387 if (strA.IsEmpty())
1388 return FALSE;
1390 rString = CUnicodeUtils::GetUnicode(strA);
1391 return TRUE;
1394 void ResetState()
1396 m_Items.clear();
1397 m_eol.Empty();
1401 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1403 file.ResetState();
1404 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1406 CMessageBox::Show(nullptr, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1407 return false;
1410 if (file.GetLength() > 0)
1412 CString fileText;
1413 while (file.ReadString(fileText))
1414 file.m_Items.push_back(fileText);
1415 file.Seek(file.GetLength() - 1, 0);
1416 char lastchar[1] = { 0 };
1417 file.Read(lastchar, 1);
1418 file.SeekToEnd();
1419 if (lastchar[0] != '\n')
1421 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1422 file.Write(eol, eol.GetLength());
1425 else
1426 file.SeekToEnd();
1428 return true;
1431 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1433 CIgnoreDlg ignoreDlg;
1434 if (ignoreDlg.DoModal() == IDOK)
1436 CString ignorefile;
1437 ignorefile = g_Git.m_CurrentDir + _T("\\");
1439 switch (ignoreDlg.m_IgnoreFile)
1441 case 0:
1442 ignorefile += _T(".gitignore");
1443 break;
1444 case 2:
1445 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1446 ignorefile += _T("info");
1447 if (!PathFileExists(ignorefile))
1448 CreateDirectory(ignorefile, nullptr);
1449 ignorefile += _T("\\exclude");
1450 break;
1453 CIgnoreFile file;
1456 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1457 return false;
1459 for (int i = 0; i < path.GetCount(); ++i)
1461 if (ignoreDlg.m_IgnoreFile == 1)
1463 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1464 if (!OpenIgnoreFile(file, ignorefile))
1465 return false;
1468 CString ignorePattern;
1469 if (ignoreDlg.m_IgnoreType == 0)
1471 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1472 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1474 ignorePattern += _T("/");
1476 if (IsMask)
1477 ignorePattern += _T("*") + path[i].GetFileExtension();
1478 else
1479 ignorePattern += path[i].GetFileOrDirectoryName();
1481 // escape [ and ] so that files get ignored correctly
1482 ignorePattern.Replace(_T("["), _T("\\["));
1483 ignorePattern.Replace(_T("]"), _T("\\]"));
1485 bool found = false;
1486 for (size_t j = 0; j < file.m_Items.size(); ++j)
1488 if (file.m_Items[j] == ignorePattern)
1490 found = true;
1491 break;
1494 if (!found)
1496 file.m_Items.push_back(ignorePattern);
1497 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1498 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1499 file.Write(ignorePatternA, ignorePatternA.GetLength());
1502 if (ignoreDlg.m_IgnoreFile == 1)
1503 file.Close();
1506 if (ignoreDlg.m_IgnoreFile != 1)
1507 file.Close();
1509 catch(...)
1511 file.Abort();
1512 return false;
1515 return true;
1517 return false;
1520 static bool Reset(const CString& resetTo, int resetType)
1522 CString cmd;
1523 CString type;
1524 switch (resetType)
1526 case 0:
1527 type = _T("--soft");
1528 break;
1529 case 1:
1530 type = _T("--mixed");
1531 break;
1532 case 2:
1533 type = _T("--hard");
1534 break;
1535 default:
1536 resetType = 1;
1537 type = _T("--mixed");
1538 break;
1540 cmd.Format(_T("git.exe reset %s %s --"), (LPCTSTR)type, (LPCTSTR)resetTo);
1542 CProgressDlg progress;
1543 progress.m_GitCmd = cmd;
1545 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1547 if (status)
1549 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); });
1550 return;
1553 CTGitPath gitPath = g_Git.m_CurrentDir;
1554 if (gitPath.HasSubmodules() && resetType == 2)
1556 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1558 CString sCmd;
1559 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1560 CAppUtils::RunTortoiseGitProc(sCmd);
1565 INT_PTR ret;
1566 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1568 CGitProgressDlg gitdlg;
1569 ResetProgressCommand resetProgressCommand;
1570 gitdlg.SetCommand(&resetProgressCommand);
1571 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1572 resetProgressCommand.SetRevision(resetTo);
1573 resetProgressCommand.SetResetType(resetType);
1574 ret = gitdlg.DoModal();
1576 else
1577 ret = progress.DoModal();
1579 return ret == IDOK;
1582 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1584 CResetDlg dlg;
1585 dlg.m_ResetType=type;
1586 dlg.m_ResetToVersion=*CommitHash;
1587 dlg.m_initialRefName = *CommitHash;
1588 if (dlg.DoModal() == IDOK)
1589 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1591 return false;
1594 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1596 if(mode == FALSE)
1598 descript.LoadString(IDS_SVNACTION_DELETE);
1599 return;
1601 if(base)
1603 descript.LoadString(IDS_SVNACTION_MODIFIED);
1604 return;
1606 descript.LoadString(IDS_PROC_CREATED);
1609 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1611 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1612 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1613 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1615 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1617 CString file;
1618 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1620 return file;
1623 bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, CString& hash2, CString& hash3)
1625 size_t pos = 0;
1626 CString one;
1627 CString part;
1629 while (pos < out.size())
1631 one.Empty();
1633 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1634 int tabstart = 0;
1635 one.Tokenize(_T("\t"), tabstart);
1637 tabstart = 0;
1638 part = one.Tokenize(_T(" "), tabstart); //Tag
1639 part = one.Tokenize(_T(" "), tabstart); //Mode
1640 part = one.Tokenize(_T(" "), tabstart); //Hash
1641 CString hash = part;
1642 part = one.Tokenize(_T("\t"), tabstart); //Stage
1643 int stage = _ttol(part);
1644 if (stage == 1)
1645 hash1 = hash;
1646 else if (stage == 2)
1647 hash2 = hash;
1648 else if (stage == 3)
1650 hash3 = hash;
1651 return true;
1654 pos = out.findNextString(pos);
1657 return false;
1660 bool CAppUtils::ConflictEdit(const CTGitPath& path, bool bAlternativeTool /*= false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1662 bool bRet = false;
1664 CTGitPath merge=path;
1665 CTGitPath directory = merge.GetDirectory();
1667 // we have the conflicted file (%merged)
1668 // now look for the other required files
1669 //GitStatus stat;
1670 //stat.GetStatus(merge);
1671 //if (stat.status == nullptr)
1672 // return false;
1674 BYTE_VECTOR vector;
1676 CString cmd;
1677 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1679 if (g_Git.Run(cmd, &vector))
1680 return FALSE;
1682 if (merge.IsDirectory())
1684 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1685 if (merge.HasAdminDir()) {
1686 CGit subgit;
1687 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1688 CGitHash hash;
1689 subgit.GetHash(hash, _T("HEAD"));
1690 baseHash = hash;
1692 if (ParseHashesFromLsFile(vector, realBaseHash, localHash, remoteHash)) // in base no submodule, but in remote submodule
1693 baseHash = realBaseHash;
1695 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1696 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1698 bool baseOK = false, mineOK = false, theirsOK = false;
1699 CString baseSubject, mineSubject, theirsSubject;
1700 if (merge.HasAdminDir())
1702 CGit subgit;
1703 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1704 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1705 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1707 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)
1709 changeTypeMine = CGitDiff::Identical;
1710 changeTypeTheirs = CGitDiff::NewSubmodule;
1711 baseSubject = _T("no submodule");
1712 mineSubject = baseSubject;
1713 theirsSubject = _T("not initialized");
1715 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
1717 baseHash = localHash;
1718 baseSubject = _T("not initialized");
1719 mineSubject = baseSubject;
1720 theirsSubject = _T("not initialized");
1721 changeTypeMine = CGitDiff::Identical;
1722 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1724 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
1726 baseSubject = _T("not initialized");
1727 mineSubject = baseSubject;
1728 theirsSubject = baseSubject;
1729 if (baseHash == localHash)
1730 changeTypeMine = CGitDiff::Identical;
1732 else
1733 return FALSE;
1735 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1736 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), revertTheirMy, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1737 resolveSubmoduleConflictDialog.DoModal();
1738 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1740 static UINT WM_REVERTMSG = RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1741 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1744 return TRUE;
1747 CTGitPathList list;
1748 if (list.ParserFromLsFile(vector))
1750 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1751 return FALSE;
1754 if (list.IsEmpty())
1755 return FALSE;
1757 CTGitPath theirs;
1758 CTGitPath mine;
1759 CTGitPath base;
1761 if (revertTheirMy)
1763 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1764 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1766 else
1768 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1769 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1771 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1773 CString format;
1775 //format=_T("git.exe cat-file blob \":%d:%s\"");
1776 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1777 CFile tempfile;
1778 //create a empty file, incase stage is not three
1779 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1780 tempfile.Close();
1781 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1782 tempfile.Close();
1783 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1784 tempfile.Close();
1786 bool b_base=false, b_local=false, b_remote=false;
1788 for (int i = 0; i< list.GetCount(); ++i)
1790 CString outfile;
1791 cmd.Empty();
1792 outfile.Empty();
1794 if( list[i].m_Stage == 1)
1796 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1797 b_base = true;
1798 outfile = base.GetWinPathString();
1801 if( list[i].m_Stage == 2 )
1803 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1804 b_local = true;
1805 outfile = mine.GetWinPathString();
1808 if( list[i].m_Stage == 3 )
1810 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1811 b_remote = true;
1812 outfile = theirs.GetWinPathString();
1814 CString output, err;
1815 if(!outfile.IsEmpty())
1816 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1818 CString file;
1819 int start =0 ;
1820 file = output.Tokenize(_T("\t"), start);
1821 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1823 else
1824 CMessageBox::Show(nullptr, output + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1827 if(b_local && b_remote )
1829 merge.SetFromWin(g_Git.CombinePath(merge));
1830 if( revertTheirMy )
1831 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, mine, theirs, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1832 else
1833 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1835 else
1837 ::DeleteFile(mine.GetWinPathString());
1838 ::DeleteFile(theirs.GetWinPathString());
1839 ::DeleteFile(base.GetWinPathString());
1841 CDeleteConflictDlg dlg;
1842 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1843 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1844 CGitHash localHash, remoteHash;
1845 if (!g_Git.GetHash(localHash, _T("HEAD")))
1846 dlg.m_LocalHash = localHash.ToString();
1847 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1848 dlg.m_RemoteHash = remoteHash.ToString();
1849 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1850 dlg.m_RemoteHash = remoteHash.ToString();
1851 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1852 dlg.m_RemoteHash = remoteHash.ToString();
1853 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1854 dlg.m_RemoteHash = remoteHash.ToString();
1855 dlg.m_bShowModifiedButton=b_base;
1856 dlg.m_File=merge.GetGitPathString();
1857 if(dlg.DoModal() == IDOK)
1859 CString out;
1860 if(dlg.m_bIsDelete)
1861 cmd.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1862 else
1863 cmd.Format(_T("git.exe add -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1865 if (g_Git.Run(cmd, &out, CP_UTF8))
1867 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1868 return FALSE;
1870 return TRUE;
1872 else
1873 return FALSE;
1876 #if 0
1877 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1878 base, theirs, mine, merge);
1879 #endif
1880 #if 0
1881 if (stat.status->text_status == svn_wc_status_conflicted)
1883 // we have a text conflict, use our merge tool to resolve the conflict
1885 CTSVNPath theirs(directory);
1886 CTSVNPath mine(directory);
1887 CTSVNPath base(directory);
1888 bool bConflictData = false;
1890 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1892 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1893 bConflictData = true;
1895 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1897 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1898 bConflictData = true;
1900 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1902 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1903 bConflictData = true;
1905 else
1906 mine = merge;
1907 if (bConflictData)
1908 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1909 base, theirs, mine, merge);
1912 if (stat.status->prop_status == svn_wc_status_conflicted)
1914 // we have a property conflict
1915 CTSVNPath prej(directory);
1916 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1918 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1919 // there's a problem: the prej file contains a _description_ of the conflict, and
1920 // that description string might be translated. That means we have no way of parsing
1921 // the file to find out the conflicting values.
1922 // The only thing we can do: show a dialog with the conflict description, then
1923 // let the user either accept the existing property or open the property edit dialog
1924 // to manually change the properties and values. And a button to mark the conflict as
1925 // resolved.
1926 CEditPropConflictDlg dlg;
1927 dlg.SetPrejFile(prej);
1928 dlg.SetConflictedItem(merge);
1929 bRet = (dlg.DoModal() != IDCANCEL);
1933 if (stat.status->tree_conflict)
1935 // we have a tree conflict
1936 SVNInfo info;
1937 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1938 if (pInfoData)
1940 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1942 CTSVNPath theirs(directory);
1943 CTSVNPath mine(directory);
1944 CTSVNPath base(directory);
1945 bool bConflictData = false;
1947 if (pInfoData->treeconflict_theirfile)
1949 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1950 bConflictData = true;
1952 if (pInfoData->treeconflict_basefile)
1954 base.AppendPathString(pInfoData->treeconflict_basefile);
1955 bConflictData = true;
1957 if (pInfoData->treeconflict_myfile)
1959 mine.AppendPathString(pInfoData->treeconflict_myfile);
1960 bConflictData = true;
1962 else
1963 mine = merge;
1964 if (bConflictData)
1965 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1966 base, theirs, mine, merge);
1968 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1970 CString sConflictAction;
1971 CString sConflictReason;
1972 CString sResolveTheirs;
1973 CString sResolveMine;
1974 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1975 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1977 if (pInfoData->treeconflict_nodekind == svn_node_file)
1979 switch (pInfoData->treeconflict_operation)
1981 case svn_wc_operation_update:
1982 switch (pInfoData->treeconflict_action)
1984 case svn_wc_conflict_action_edit:
1985 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1986 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1987 break;
1988 case svn_wc_conflict_action_add:
1989 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1990 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1991 break;
1992 case svn_wc_conflict_action_delete:
1993 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1994 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1995 break;
1997 break;
1998 case svn_wc_operation_switch:
1999 switch (pInfoData->treeconflict_action)
2001 case svn_wc_conflict_action_edit:
2002 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
2003 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2004 break;
2005 case svn_wc_conflict_action_add:
2006 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
2007 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2008 break;
2009 case svn_wc_conflict_action_delete:
2010 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
2011 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2012 break;
2014 break;
2015 case svn_wc_operation_merge:
2016 switch (pInfoData->treeconflict_action)
2018 case svn_wc_conflict_action_edit:
2019 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
2020 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2021 break;
2022 case svn_wc_conflict_action_add:
2023 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
2024 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2025 break;
2026 case svn_wc_conflict_action_delete:
2027 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
2028 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2029 break;
2031 break;
2034 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
2036 switch (pInfoData->treeconflict_operation)
2038 case svn_wc_operation_update:
2039 switch (pInfoData->treeconflict_action)
2041 case svn_wc_conflict_action_edit:
2042 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
2043 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2044 break;
2045 case svn_wc_conflict_action_add:
2046 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
2047 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2048 break;
2049 case svn_wc_conflict_action_delete:
2050 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
2051 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2052 break;
2054 break;
2055 case svn_wc_operation_switch:
2056 switch (pInfoData->treeconflict_action)
2058 case svn_wc_conflict_action_edit:
2059 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
2060 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2061 break;
2062 case svn_wc_conflict_action_add:
2063 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
2064 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2065 break;
2066 case svn_wc_conflict_action_delete:
2067 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
2068 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2069 break;
2071 break;
2072 case svn_wc_operation_merge:
2073 switch (pInfoData->treeconflict_action)
2075 case svn_wc_conflict_action_edit:
2076 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
2077 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2078 break;
2079 case svn_wc_conflict_action_add:
2080 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
2081 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2082 break;
2083 case svn_wc_conflict_action_delete:
2084 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
2085 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2086 break;
2088 break;
2092 UINT uReasonID = 0;
2093 switch (pInfoData->treeconflict_reason)
2095 case svn_wc_conflict_reason_edited:
2096 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
2097 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2098 break;
2099 case svn_wc_conflict_reason_obstructed:
2100 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
2101 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2102 break;
2103 case svn_wc_conflict_reason_deleted:
2104 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
2105 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2106 break;
2107 case svn_wc_conflict_reason_added:
2108 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
2109 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2110 break;
2111 case svn_wc_conflict_reason_missing:
2112 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
2113 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2114 break;
2115 case svn_wc_conflict_reason_unversioned:
2116 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
2117 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2118 break;
2120 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
2122 CTreeConflictEditorDlg dlg;
2123 dlg.SetConflictInfoText(sConflictReason);
2124 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
2125 dlg.SetPath(treeConflictPath);
2126 INT_PTR dlgRet = dlg.DoModal();
2127 bRet = (dlgRet != IDCANCEL);
2131 #endif
2132 return bRet;
2135 bool CAppUtils::IsSSHPutty()
2137 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2138 sshclient=sshclient.MakeLower();
2139 if(sshclient.Find(_T("plink.exe"),0)>=0)
2140 return true;
2141 return false;
2144 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2146 if (!OpenClipboard(nullptr))
2147 return CString();
2149 CString sClipboardText;
2150 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2151 if (hglb)
2153 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2154 sClipboardText = CString(lpstr);
2155 GlobalUnlock(hglb);
2157 hglb = GetClipboardData(CF_UNICODETEXT);
2158 if (hglb)
2160 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2161 sClipboardText = lpstr;
2162 GlobalUnlock(hglb);
2164 CloseClipboard();
2166 if(!sClipboardText.IsEmpty())
2168 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2169 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2171 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ssh://", L"git@" })
2173 if (CStringUtils::StartsWith(sClipboardText, prefix) && sClipboardText.GetLength() != prefix.GetLength())
2174 return sClipboardText;
2177 if(sClipboardText.GetLength()>=2)
2178 if( sClipboardText[1] == _T(':') )
2179 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2180 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2181 return sClipboardText;
2183 // trim prefixes like "git clone "
2184 if (!skipGitPrefix.IsEmpty() && CStringUtils::StartsWith(sClipboardText, skipGitPrefix))
2186 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2187 int spacePos = -1;
2188 while (paramsCount >= 0)
2190 --paramsCount;
2191 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2192 if (spacePos == -1)
2193 break;
2195 if (spacePos > 0 && paramsCount < 0)
2196 sClipboardText.Truncate(spacePos);
2197 return sClipboardText;
2201 return CString();
2204 CString CAppUtils::ChooseRepository(const CString* path)
2206 CBrowseFolder browseFolder;
2207 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2209 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2210 CString strCloneDirectory;
2211 if(path)
2212 strCloneDirectory=*path;
2213 else
2214 strCloneDirectory = regLastResopitory;
2216 CString title;
2217 title.LoadString(IDS_CHOOSE_REPOSITORY);
2219 browseFolder.SetInfo(title);
2221 if (browseFolder.Show(nullptr, strCloneDirectory) == CBrowseFolder::OK)
2223 regLastResopitory = strCloneDirectory;
2224 return strCloneDirectory;
2226 else
2227 return CString();
2230 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2232 CSendMailDlg dlg;
2234 dlg.m_PathList = list;
2236 if(dlg.DoModal()==IDOK)
2238 if (dlg.m_PathList.IsEmpty())
2239 return FALSE;
2241 CGitProgressDlg progDlg;
2242 if (bIsMainWnd)
2243 theApp.m_pMainWnd = &progDlg;
2244 SendMailProgressCommand sendMailProgressCommand;
2245 progDlg.SetCommand(&sendMailProgressCommand);
2247 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2248 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2250 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2251 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2253 progDlg.DoModal();
2255 return true;
2257 return false;
2260 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2262 CTGitPathList list;
2263 CString log=formatpatchoutput;
2264 int start=log.Find(cmd);
2265 if(start >=0)
2266 CString one=log.Tokenize(_T("\n"),start);
2267 else
2268 start = 0;
2270 while(start>=0)
2272 CString one=log.Tokenize(_T("\n"),start);
2273 one=one.Trim();
2274 if (one.IsEmpty() || one.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS))) == 0)
2275 continue;
2276 one.Replace(_T('/'),_T('\\'));
2277 CTGitPath path;
2278 path.SetFromWin(one);
2279 list.AddPath(path);
2281 if (!list.IsEmpty())
2282 return SendPatchMail(list, bIsMainWnd);
2283 else
2285 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2286 return true;
2291 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2293 CString output;
2294 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2295 if(output.IsEmpty())
2296 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2297 else
2298 return CUnicodeUtils::GetCPCode(output);
2300 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2304 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2305 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2307 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2308 TCHAR commentChar = L'#';
2309 if (stripComments)
2311 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2312 if (!commentCharValue.IsEmpty())
2313 commentChar = commentCharValue[0];
2316 bool sanitize = (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE);
2317 if (sanitize)
2318 message.Trim(L" \r\n");
2320 int len = message.GetLength();
2321 int start = 0;
2322 int emptyLineCnt = 0;
2323 while (start >= 0 && start < len)
2325 int oldStart = start;
2326 start = message.Find(L"\n", oldStart);
2327 CString line = message.Mid(oldStart);
2328 if (start != -1)
2330 line.Truncate(start - oldStart);
2331 ++start; // move forward so we don't find the same char again
2333 if (stripComments && (!line.IsEmpty() && line.GetAt(0) == commentChar) || (start < 0 && line.IsEmpty()))
2334 continue;
2335 line.TrimRight(L" \r");
2336 if (sanitize)
2338 if (line.IsEmpty())
2340 ++emptyLineCnt;
2341 continue;
2343 if (emptyLineCnt) // squash multiple newlines
2344 file.Write("\n", 1);
2345 emptyLineCnt = 0;
2347 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2348 file.Write((LPCSTR)lineA, lineA.GetLength());
2350 file.Close();
2351 return 0;
2353 catch (CFileException *e)
2355 e->Delete();
2356 return -1;
2360 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)
2362 if (bAutoLoad)
2363 CAppUtils::LaunchPAgent(nullptr, &url);
2365 CGitHash hashOld;
2366 if (g_Git.GetHash(hashOld, L"HEAD"))
2368 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2369 return false;
2372 CString args;
2373 if (CRegDWORD(L"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE) == FALSE)
2374 args += L" --no-rebase";
2376 if (bFetchTags == BST_UNCHECKED)
2377 args += L" --no-tags";
2378 else if (bFetchTags == BST_CHECKED)
2379 args += L" --tags";
2381 if (bNoFF)
2382 args += L" --no-ff";
2384 if (bFFonly)
2385 args += L" --ff-only";
2387 if (bSquash)
2388 args += L" --squash";
2390 if (bNoCommit)
2391 args += L" --no-commit";
2393 if (nDepth)
2394 args.AppendFormat(L" --depth %d", *nDepth);
2396 if (bPrune == BST_CHECKED)
2397 args += L" --prune";
2398 else if (bPrune == BST_UNCHECKED)
2399 args += L" --no-prune";
2401 if (bUnrelated)
2402 args += L" --allow-unrelated-histories";
2404 CString cmd;
2405 cmd.Format(L"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR)args, (LPCTSTR)url, (LPCTSTR)remoteBranchName);
2406 CProgressDlg progress;
2407 progress.m_GitCmd = cmd;
2409 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2410 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2412 if (status)
2414 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2416 STRING_VECTOR remotes;
2417 g_Git.GetRemoteList(remotes);
2418 if (std::find(remotes.begin(), remotes.end(), url) != remotes.end())
2420 CString currentBranch;
2421 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2422 currentBranch.Empty();
2423 CString remoteRef = L"remotes/" + url + L"/" + remoteBranchName;
2424 if (!currentBranch.IsEmpty() && remoteBranchName.IsEmpty())
2426 CString pullRemote, pullBranch;
2427 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2428 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2429 remoteRef = L"remotes/" + pullRemote + L"/" + pullBranch;
2431 CGitHash common;
2432 g_Git.IsFastForward(L"HEAD", remoteRef, &common);
2433 if (common.IsEmpty())
2434 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoPull(url, bAutoLoad, bFetchTags, bNoFF, bFFonly, bSquash, bNoCommit, nDepth, bPrune, remoteBranchName, showPush, showStashPop, true); });
2438 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(); });
2439 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(L"", true); });
2440 return;
2443 if (showStashPop)
2444 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
2446 if (g_Git.GetHash(hashNew, L"HEAD"))
2447 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash after pulling."), L"TortoiseGit", MB_ICONERROR);
2448 else
2450 postCmdList.emplace_back(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2452 CFileDiffDlg dlg;
2453 dlg.SetDiff(nullptr, hashOld.ToString(), hashNew.ToString());
2454 dlg.DoModal();
2456 postCmdList.emplace_back(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2458 CLogDlg dlg;
2459 dlg.SetParams(CTGitPath(L""), CTGitPath(L""), L"", hashOld.ToString() + L".." + hashNew.ToString(), 0);
2460 dlg.DoModal();
2464 if (showPush)
2465 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
2467 CTGitPath gitPath = g_Git.m_CurrentDir;
2468 if (gitPath.HasSubmodules())
2470 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2472 CString sCmd;
2473 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2474 CAppUtils::RunTortoiseGitProc(sCmd);
2479 INT_PTR ret = progress.DoModal();
2481 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)
2483 CChangedDlg changeddlg;
2484 changeddlg.m_pathList.AddPath(CTGitPath());
2485 changeddlg.DoModal();
2487 return true;
2490 return ret == IDOK;
2493 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2495 if (IsTGitRebaseActive())
2496 return false;
2498 CPullFetchDlg dlg;
2499 dlg.m_IsPull = TRUE;
2500 if (dlg.DoModal() == IDOK)
2502 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2503 if (dlg.m_bRebase)
2504 return DoFetch(dlg.m_RemoteURL,
2505 FALSE, // Fetch all remotes
2506 dlg.m_bAutoLoad == BST_CHECKED,
2507 dlg.m_bPrune,
2508 dlg.m_bDepth == BST_CHECKED,
2509 dlg.m_nDepth,
2510 dlg.m_bFetchTags,
2511 dlg.m_RemoteBranchName,
2512 dlg.m_bRebaseActivatedInConfigForPull ? 2 : 1, // Rebase after fetching
2513 dlg.m_bRebasePreserveMerges == TRUE); // Preserve merges on rebase
2515 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);
2518 return false;
2521 bool CAppUtils::RebaseAfterFetch(const CString& upstream, int rebase, bool preserveMerges)
2523 while (true)
2525 CRebaseDlg dlg;
2526 if (!upstream.IsEmpty())
2527 dlg.m_Upstream = upstream;
2528 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2529 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2530 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2531 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2532 dlg.m_bRebaseAutoStart = (rebase == 2);
2533 dlg.m_bPreserveMerges = preserveMerges;
2534 INT_PTR response = dlg.DoModal();
2535 if (response == IDOK)
2536 return true;
2537 else if (response == IDC_REBASE_POST_BUTTON)
2539 CString cmd = _T("/command:log");
2540 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2541 CAppUtils::RunTortoiseGitProc(cmd);
2542 return true;
2544 else if (response == IDC_REBASE_POST_BUTTON + 1)
2545 return Push();
2546 else if (response == IDC_REBASE_POST_BUTTON + 2)
2548 CString cmd, out, err;
2549 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2550 (LPCTSTR)g_Git.m_CurrentDir,
2551 (LPCTSTR)g_Git.FixBranchName(dlg.m_Upstream),
2552 (LPCTSTR)g_Git.FixBranchName(dlg.m_Branch));
2553 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2555 CMessageBox::Show(nullptr, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2556 return false;
2558 CAppUtils::SendPatchMail(cmd, out);
2559 return true;
2561 else if (response == IDC_REBASE_POST_BUTTON + 3)
2562 continue;
2563 else if (response == IDCANCEL)
2564 return false;
2565 return false;
2569 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)
2571 if (loadPuttyAgent)
2573 if (fetchAllRemotes)
2575 STRING_VECTOR list;
2576 g_Git.GetRemoteList(list);
2578 for (const auto& remote : list)
2579 CAppUtils::LaunchPAgent(nullptr, &remote);
2581 else
2582 CAppUtils::LaunchPAgent(nullptr, &url);
2585 CString upstream = _T("FETCH_HEAD");
2586 CGitHash oldUpstreamHash;
2587 if (runRebase)
2589 STRING_VECTOR list;
2590 g_Git.GetRemoteList(list);
2591 for (auto it = list.cbegin(); it != list.cend(); ++it)
2593 if (url == *it)
2595 CString remote, trackedBranch;
2596 g_Git.GetRemoteTrackedBranchForHEAD(remote, trackedBranch);
2597 if (!remote.IsEmpty() && !trackedBranch.IsEmpty())
2599 upstream = L"remotes/" + remote + L"/" + trackedBranch;
2600 g_Git.GetHash(oldUpstreamHash, upstream);
2602 break;
2607 CString cmd, arg;
2608 arg = _T(" --progress");
2610 if (bDepth)
2611 arg.AppendFormat(_T(" --depth %d"), nDepth);
2613 if (prune == TRUE)
2614 arg += _T(" --prune");
2615 else if (prune == FALSE)
2616 arg += _T(" --no-prune");
2618 if (fetchTags == 1)
2619 arg += _T(" --tags");
2620 else if (fetchTags == 0)
2621 arg += _T(" --no-tags");
2623 if (fetchAllRemotes)
2624 cmd.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR)arg);
2625 else
2626 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR)arg, (LPCTSTR)url, (LPCTSTR)remoteBranch);
2628 CProgressDlg progress;
2629 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2631 if (status)
2633 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase, rebasePreserveMerges); });
2634 return;
2637 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2639 CString cmd = _T("/command:log");
2640 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2641 CAppUtils::RunTortoiseGitProc(cmd);
2644 postCmdList.emplace_back(IDI_REVERT, IDS_PROC_RESET, []
2646 CString pullRemote, pullBranch;
2647 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2648 CString defaultUpstream;
2649 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2650 defaultUpstream.Format(_T("remotes/%s/%s"), (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
2651 CAppUtils::GitReset(&defaultUpstream, 2);
2654 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); });
2656 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2657 postCmdList.emplace_back(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); });
2660 progress.m_GitCmd = cmd;
2662 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2664 CGitProgressDlg gitdlg;
2665 FetchProgressCommand fetchProgressCommand;
2666 if (!fetchAllRemotes)
2667 fetchProgressCommand.SetUrl(url);
2668 gitdlg.SetCommand(&fetchProgressCommand);
2669 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2670 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2671 if (!fetchAllRemotes)
2672 fetchProgressCommand.SetRefSpec(remoteBranch);
2673 return gitdlg.DoModal() == IDOK;
2676 progress.m_PostExecCallback = [&](DWORD& exitCode, CString&)
2678 if (exitCode || !runRebase)
2679 return;
2681 CGitHash remoteBranchHash;
2682 g_Git.GetHash(remoteBranchHash, upstream);
2683 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)
2684 return;
2686 if (runRebase == 1 && g_Git.IsFastForward(L"HEAD", upstream))
2688 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);
2689 if (ret == 3)
2690 return;
2691 if (ret == 1)
2693 CProgressDlg mergeProgress;
2694 mergeProgress.m_GitCmd = L"git.exe merge --ff-only " + upstream;
2695 mergeProgress.m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
2696 mergeProgress.m_PostCmdCallback = [](DWORD status, PostCmdList& postCmdList)
2698 if (status && g_Git.HasWorkingTreeConflicts())
2700 // there are conflict files
2701 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2703 CString sCmd;
2704 sCmd.Format(L"/command:commit /path:\"%s\"", g_Git.m_CurrentDir);
2705 CAppUtils::RunTortoiseGitProc(sCmd);
2709 mergeProgress.DoModal();
2710 return;
2714 CAppUtils::RebaseAfterFetch(upstream, runRebase, rebasePreserveMerges);
2717 return progress.DoModal() == IDOK;
2720 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2722 CPullFetchDlg dlg;
2723 dlg.m_PreSelectRemote = remoteName;
2724 dlg.m_IsPull=FALSE;
2725 dlg.m_bAllRemotes = allRemotes;
2727 if(dlg.DoModal()==IDOK)
2728 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);
2730 return false;
2733 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)
2735 CString error;
2736 DWORD exitcode = 0xFFFFFFFF;
2737 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2739 if (exitcode)
2741 CString temp;
2742 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2743 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2744 return false;
2748 int iRecurseSubmodules = 0;
2749 if (GetMsysgitVersion() >= 0x02070000)
2751 CString sRecurseSubmodules = g_Git.GetConfigValue(_T("push.recurseSubmodules"));
2752 if (sRecurseSubmodules == _T("check"))
2753 iRecurseSubmodules = 1;
2754 else if (sRecurseSubmodules == _T("on-demand"))
2755 iRecurseSubmodules = 2;
2758 CString arg;
2759 if (pack)
2760 arg += _T("--thin ");
2761 if (tags && !allBranches)
2762 arg += _T("--tags ");
2763 if (force)
2764 arg += _T("--force ");
2765 if (forceWithLease)
2766 arg += _T("--force-with-lease ");
2767 if (setUpstream)
2768 arg += _T("--set-upstream ");
2769 if (recurseSubmodules == 0 && recurseSubmodules != iRecurseSubmodules)
2770 arg += _T("--recurse-submodules=no ");
2771 if (recurseSubmodules == 1 && recurseSubmodules != iRecurseSubmodules)
2772 arg += _T("--recurse-submodules=check ");
2773 if (recurseSubmodules == 2 && recurseSubmodules != iRecurseSubmodules)
2774 arg += _T("--recurse-submodules=on-demand ");
2776 arg += _T("--progress ");
2778 CProgressDlg progress;
2780 STRING_VECTOR remotesList;
2781 if (allRemotes)
2782 g_Git.GetRemoteList(remotesList);
2783 else
2784 remotesList.push_back(remote);
2786 for (unsigned int i = 0; i < remotesList.size(); ++i)
2788 if (autoloadKey)
2789 CAppUtils::LaunchPAgent(nullptr, &remotesList[i]);
2791 CString cmd;
2792 if (allBranches)
2794 cmd.Format(_T("git.exe push --all %s\"%s\""),
2795 (LPCTSTR)arg,
2796 (LPCTSTR)remotesList[i]);
2798 if (tags)
2800 progress.m_GitCmdList.push_back(cmd);
2801 cmd.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR)arg, (LPCTSTR)remotesList[i]);
2804 else
2806 cmd.Format(_T("git.exe push %s\"%s\" %s"),
2807 (LPCTSTR)arg,
2808 (LPCTSTR)remotesList[i],
2809 (LPCTSTR)localBranch);
2810 if (!remoteBranch.IsEmpty())
2812 cmd += L":";
2813 cmd += remoteBranch;
2816 progress.m_GitCmdList.push_back(cmd);
2818 if (!allBranches && !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE))
2820 cmd.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR)localBranch);
2821 progress.m_GitCmdList.push_back(cmd);
2825 CString superprojectRoot;
2826 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2827 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2829 // need to execute hooks as those might be needed by post action commands
2830 DWORD exitcode = 0xFFFFFFFF;
2831 CString error;
2832 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2834 if (exitcode)
2836 CString temp;
2837 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2838 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2842 if (status)
2844 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2845 if (rejected)
2847 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, []{ Pull(true); });
2848 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(allRemotes ? _T("") : remote, allRemotes); });
2850 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2851 return;
2854 postCmdList.emplace_back(IDS_PROC_REQUESTPULL, [&]{ RequestPull(remoteBranch); });
2855 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2856 postCmdList.emplace_back(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); });
2857 if (!superprojectRoot.IsEmpty())
2859 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2861 CString sCmd;
2862 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)superprojectRoot);
2863 RunTortoiseGitProc(sCmd);
2868 INT_PTR ret = progress.DoModal();
2869 return ret == IDOK;
2872 bool CAppUtils::Push(const CString& selectLocalBranch)
2874 CPushDlg dlg;
2875 dlg.m_BranchSourceName = selectLocalBranch;
2877 if (dlg.DoModal() == IDOK)
2878 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);
2880 return FALSE;
2883 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2885 CRequestPullDlg dlg;
2886 dlg.m_RepositoryURL = repositoryUrl;
2887 dlg.m_EndRevision = endrevision;
2888 if (dlg.DoModal()==IDOK)
2890 CString cmd;
2891 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR)dlg.m_StartRevision, (LPCTSTR)dlg.m_RepositoryURL, (LPCTSTR)dlg.m_EndRevision);
2893 CSysProgressDlg sysProgressDlg;
2894 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2895 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2896 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2897 sysProgressDlg.SetShowProgressBar(false);
2898 sysProgressDlg.ShowModeless((HWND)nullptr, true);
2900 CString tempFileName = GetTempFile();
2901 CString err;
2902 DeleteFile(tempFileName);
2903 CreateDirectory(tempFileName, nullptr);
2904 tempFileName += _T("\\pullrequest.txt");
2905 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2907 CString msg;
2908 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2909 MessageBox(nullptr, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2910 return false;
2913 if (sysProgressDlg.HasUserCancelled())
2915 CMessageBox::Show(nullptr, IDS_USERCANCELLED, IDS_APPNAME, MB_OK);
2916 ::DeleteFile(tempFileName);
2917 return false;
2920 sysProgressDlg.Stop();
2922 if (dlg.m_bSendMail)
2924 CSendMailDlg sendmaildlg;
2925 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2926 sendmaildlg.m_bCustomSubject = true;
2928 if (sendmaildlg.DoModal() == IDOK)
2930 if (sendmaildlg.m_PathList.IsEmpty())
2931 return FALSE;
2933 CGitProgressDlg progDlg;
2934 if (bIsMainWnd)
2935 theApp.m_pMainWnd = &progDlg;
2936 SendMailProgressCommand sendMailProgressCommand;
2937 progDlg.SetCommand(&sendMailProgressCommand);
2939 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2940 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2942 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2943 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2945 progDlg.DoModal();
2947 return true;
2949 return false;
2952 CAppUtils::LaunchAlternativeEditor(tempFileName);
2954 return true;
2957 void CAppUtils::RemoveTrailSlash(CString &path)
2959 if(path.IsEmpty())
2960 return ;
2962 // For URL, do not trim the slash just after the host name component.
2963 int index = path.Find(_T("://"));
2964 if (index >= 0)
2966 index += 4;
2967 index = path.Find(_T('/'), index);
2968 if (index == path.GetLength() - 1)
2969 return;
2972 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2974 path.Truncate(path.GetLength() - 1);
2975 if(path.IsEmpty())
2976 return;
2980 bool CAppUtils::CheckUserData()
2982 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2984 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO | MB_ICONERROR) == IDYES)
2986 CTGitPath path(g_Git.m_CurrentDir);
2987 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2988 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2989 dlg.SetTreeWidth(220);
2990 dlg.m_DefaultPage = _T("gitconfig");
2992 dlg.DoModal();
2993 dlg.HandleRestart();
2996 else
2997 return false;
3000 return true;
3003 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
3004 CTGitPathList &pathList,
3005 CTGitPathList &selectedList,
3006 bool bSelectFilesForCommit)
3008 bool bFailed = true;
3010 if (!CheckUserData())
3011 return false;
3013 while (bFailed)
3015 bFailed = false;
3016 CCommitDlg dlg;
3017 dlg.m_sBugID = bugid;
3019 dlg.m_bWholeProject = bWholeProject;
3021 dlg.m_sLogMessage = sLogMsg;
3022 dlg.m_pathList = pathList;
3023 dlg.m_checkedPathList = selectedList;
3024 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
3025 if (dlg.DoModal() == IDOK)
3027 if (dlg.m_pathList.IsEmpty())
3028 return false;
3029 // if the user hasn't changed the list of selected items
3030 // we don't use that list. Because if we would use the list
3031 // of pre-checked items, the dialog would show different
3032 // checked items on the next startup: it would only try
3033 // to check the parent folder (which might not even show)
3034 // instead, we simply use an empty list and let the
3035 // default checking do its job.
3036 if (!dlg.m_pathList.IsEqual(pathList))
3037 selectedList = dlg.m_pathList;
3038 pathList = dlg.m_updatedPathList;
3039 sLogMsg = dlg.m_sLogMessage;
3040 bSelectFilesForCommit = true;
3042 switch (dlg.m_PostCmd)
3044 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3045 CAppUtils::SVNDCommit();
3046 break;
3047 case GIT_POSTCOMMIT_CMD_PUSH:
3048 CAppUtils::Push();
3049 break;
3050 case GIT_POSTCOMMIT_CMD_CREATETAG:
3051 CAppUtils::CreateBranchTag(TRUE);
3052 break;
3053 case GIT_POSTCOMMIT_CMD_PULL:
3054 CAppUtils::Pull(true);
3055 break;
3056 default:
3057 break;
3060 // CGitProgressDlg progDlg;
3061 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3062 // if (parser.HasVal(_T("closeonend")))
3063 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3064 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3065 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3066 // progDlg.SetPathList(dlg.m_pathList);
3067 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3068 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3069 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3070 // progDlg.SetItemCount(dlg.m_itemsCount);
3071 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3072 // progDlg.DoModal();
3073 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3074 // err = (DWORD)progDlg.DidErrorsOccur();
3075 // bFailed = progDlg.DidErrorsOccur();
3076 // bRet = progDlg.DidErrorsOccur();
3077 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3078 // if (DWORD(bFailRepeat)==0)
3079 // bFailed = false; // do not repeat if the user chose not to in the settings.
3082 return true;
3085 BOOL CAppUtils::SVNDCommit()
3087 CSVNDCommitDlg dcommitdlg;
3088 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
3089 if (gitSetting.IsEmpty()) {
3090 if (dcommitdlg.DoModal() != IDOK)
3091 return false;
3092 else
3094 if (dcommitdlg.m_remember)
3096 if (dcommitdlg.m_rmdir)
3097 gitSetting = _T("true");
3098 else
3099 gitSetting = _T("false");
3100 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
3102 CString msg;
3103 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
3104 CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3110 BOOL IsStash = false;
3111 if(!g_Git.CheckCleanWorkTree())
3113 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3115 CSysProgressDlg sysProgressDlg;
3116 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3117 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3118 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3119 sysProgressDlg.SetShowProgressBar(false);
3120 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3121 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3123 CString cmd,out;
3124 cmd=_T("git.exe stash");
3125 if (g_Git.Run(cmd, &out, CP_UTF8))
3127 sysProgressDlg.Stop();
3128 MessageBox(nullptr, out,_T("TortoiseGit"), MB_OK | MB_ICONERROR);
3129 return false;
3131 sysProgressDlg.Stop();
3133 IsStash =true;
3135 else
3136 return false;
3139 CProgressDlg progress;
3140 if (dcommitdlg.m_rmdir)
3141 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
3142 else
3143 progress.m_GitCmd=_T("git.exe svn dcommit");
3144 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3146 if( IsStash)
3148 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
3150 CSysProgressDlg sysProgressDlg;
3151 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3152 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3153 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3154 sysProgressDlg.SetShowProgressBar(false);
3155 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3156 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3158 CString cmd,out;
3159 cmd=_T("git.exe stash pop");
3160 if (g_Git.Run(cmd, &out, CP_UTF8))
3162 sysProgressDlg.Stop();
3163 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3164 return false;
3166 sysProgressDlg.Stop();
3168 else
3169 return false;
3171 return TRUE;
3173 return FALSE;
3176 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)
3178 CString args;
3179 if (noFF)
3180 args += L" --no-ff";
3181 else if (ffOnly)
3182 args += L" --ff-only";
3184 if (squash)
3185 args += L" --squash";
3187 if (noCommit)
3188 args += L" --no-commit";
3190 if (unrelated)
3191 args += L" --allow-unrelated-histories";
3193 if (log)
3194 args.AppendFormat(L" --log=%d", *log);
3196 if (!mergeStrategy.IsEmpty())
3198 args += L" --strategy=" + mergeStrategy;
3199 if (!strategyOption.IsEmpty())
3201 args += L" --strategy-option=" + strategyOption;
3202 if (!strategyParam.IsEmpty())
3203 args += L'=' + strategyParam;
3207 if (!logMessage.IsEmpty())
3209 CString logmsg = logMessage;
3210 logmsg.Replace(L"\\\"", L"\\\\\"");
3211 logmsg.Replace(L"\"", L"\\\"");
3212 args += L" -m \"" + logmsg + L"\"";
3215 CString mergeVersion = g_Git.FixBranchName(version);
3216 CString cmd;
3217 cmd.Format(L"git.exe merge%s %s", (LPCTSTR)args, (LPCTSTR)mergeVersion);
3219 CProgressDlg Prodlg;
3220 Prodlg.m_GitCmd = cmd;
3222 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3224 if (status)
3226 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3227 if (hasConflicts < 0)
3228 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
3229 else if (hasConflicts)
3231 // there are conflict files
3233 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3235 CString sCmd;
3236 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3237 CAppUtils::RunTortoiseGitProc(sCmd);
3241 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3243 CGitHash common;
3244 g_Git.IsFastForward(L"HEAD", mergeVersion, &common);
3245 if (common.IsEmpty())
3246 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoMerge(noFF, ffOnly, squash, noCommit, log, true, mergeStrategy, strategyOption, strategyParam, logMessage, version, isBranch, showStashPop); });
3249 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [=]{ CAppUtils::StashSave(L"", false, false, true, mergeVersion); });
3251 return;
3254 if (showStashPop)
3255 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
3257 if (noCommit)
3259 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3261 CString sCmd;
3262 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3263 CAppUtils::RunTortoiseGitProc(sCmd);
3265 return;
3268 if (isBranch && !CStringUtils::StartsWith(version, L"remotes/")) // do not ask to remove remote branches
3270 postCmdList.emplace_back(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3272 CString msg;
3273 msg.Format(IDS_PROC_DELETEBRANCHTAG, version);
3274 if (CMessageBox::Show(nullptr, msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3276 CString cmd, out;
3277 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)version);
3278 if (g_Git.Run(cmd, &out, CP_UTF8))
3279 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3283 if (isBranch)
3284 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
3286 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3287 if (hasGitSVN)
3288 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ CAppUtils::SVNDCommit(); });
3291 Prodlg.DoModal();
3292 return !Prodlg.m_GitStatus;
3295 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3297 if (!CheckUserData())
3298 return FALSE;
3300 if (IsTGitRebaseActive())
3301 return FALSE;
3303 CMergeDlg dlg;
3304 if (commit)
3305 dlg.m_initialRefName = *commit;
3307 if (dlg.DoModal() == IDOK)
3308 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);
3310 return FALSE;
3313 BOOL CAppUtils::MergeAbort()
3315 CMergeAbortDlg dlg;
3316 if (dlg.DoModal() == IDOK)
3317 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3319 return FALSE;
3322 void CAppUtils::EditNote(GitRevLoglist* rev)
3324 if (!CheckUserData())
3325 return;
3327 CInputDlg dlg;
3328 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3329 dlg.m_sInputText = rev->m_Notes;
3330 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3331 //dlg.m_pProjectProperties = &m_ProjectProperties;
3332 dlg.m_bUseLogWidth = true;
3333 if(dlg.DoModal() == IDOK)
3335 CString cmd,output;
3336 cmd=_T("notes add -f -F \"");
3338 CString tempfile=::GetTempFile();
3339 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3341 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3342 return;
3344 cmd += tempfile;
3345 cmd += _T("\" ");
3346 cmd += rev->m_CommitHash.ToString();
3350 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3351 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3352 else
3353 rev->m_Notes = dlg.m_sInputText;
3354 }catch(...)
3356 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3358 ::DeleteFile(tempfile);
3363 int CAppUtils::GetMsysgitVersion()
3365 if (g_Git.ms_LastMsysGitVersion)
3366 return g_Git.ms_LastMsysGitVersion;
3368 CString cmd;
3369 CString versiondebug;
3370 CString version;
3372 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3373 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3375 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3377 __int64 time=0;
3378 if (!CGit::GetFileModifyTime(gitpath, &time))
3380 if((DWORD)time == regTime)
3382 g_Git.ms_LastMsysGitVersion = regVersion;
3383 return regVersion;
3387 CString err;
3388 int ver = g_Git.GetGitVersion(&versiondebug, &err);
3389 if (ver < 0)
3391 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);
3392 return -1;
3396 if (!ver)
3398 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3399 return -1;
3403 regTime = time&0xFFFFFFFF;
3404 regVersion = ver;
3405 g_Git.ms_LastMsysGitVersion = ver;
3407 return ver;
3410 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3412 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3414 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3416 if (hShell.IsValid()) {
3417 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3418 if (pfnSHGPSFW) {
3419 IPropertyStore *pps;
3420 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3421 if (SUCCEEDED(hr)) {
3422 PROPVARIANT var;
3423 var.vt = VT_BOOL;
3424 var.boolVal = VARIANT_TRUE;
3425 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3426 pps->Release();
3432 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3434 ASSERT(dialogname.GetLength() < 70);
3435 ASSERT(urlorpath.GetLength() < MAX_PATH);
3436 WCHAR pathbuf[MAX_PATH] = {0};
3438 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3440 wcscat_s(pathbuf, L" - ");
3441 wcscat_s(pathbuf, dialogname);
3442 wcscat_s(pathbuf, L" - ");
3443 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3444 SetWindowText(hWnd, pathbuf);
3447 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3449 if (!g_Git.CheckCleanWorkTree())
3451 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3453 CSysProgressDlg sysProgressDlg;
3454 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3455 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3456 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3457 sysProgressDlg.SetShowProgressBar(false);
3458 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3459 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3461 CString cmd, out;
3462 cmd = _T("git.exe stash");
3463 if (g_Git.Run(cmd, &out, CP_UTF8))
3465 sysProgressDlg.Stop();
3466 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3467 return false;
3469 sysProgressDlg.Stop();
3471 else
3472 return false;
3475 CBisectStartDlg bisectStartDlg;
3477 if (!lastGood.IsEmpty())
3478 bisectStartDlg.m_sLastGood = lastGood;
3479 if (!firstBad.IsEmpty())
3480 bisectStartDlg.m_sFirstBad = firstBad;
3482 if (bisectStartDlg.DoModal() == IDOK)
3484 CProgressDlg progress;
3485 if (bIsMainWnd)
3486 theApp.m_pMainWnd = &progress;
3487 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3488 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3489 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3491 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3493 if (status)
3494 return;
3496 CTGitPath path(g_Git.m_CurrentDir);
3497 if (path.HasSubmodules())
3499 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3501 CString sCmd;
3502 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3503 CAppUtils::RunTortoiseGitProc(sCmd);
3508 INT_PTR ret = progress.DoModal();
3509 return ret == IDOK;
3512 return false;
3515 bool CAppUtils::BisectOperation(const CString& op, const CString& ref, bool bIsMainWnd)
3517 CString cmd = _T("git.exe bisect ") + op;
3519 if (!ref.IsEmpty())
3521 cmd += _T(" ");
3522 cmd += ref;
3525 CProgressDlg progress;
3526 if (bIsMainWnd)
3527 theApp.m_pMainWnd = &progress;
3528 progress.m_GitCmd = cmd;
3530 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3532 if (status)
3533 return;
3535 CTGitPath path = g_Git.m_CurrentDir;
3536 if (path.HasSubmodules())
3538 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3540 CString sCmd;
3541 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3542 CAppUtils::RunTortoiseGitProc(sCmd);
3546 if (op != _T("reset"))
3547 postCmdList.emplace_back(IDS_MENUBISECTRESET, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3550 INT_PTR ret = progress.DoModal();
3551 return ret == IDOK;
3554 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3556 CUserPassword dlg;
3557 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3558 if (username_from_url)
3559 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3561 CStringA username, password;
3562 if (dlg.DoModal() == IDOK)
3564 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3565 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3566 return git_cred_userpass_plaintext_new(out, username, password);
3568 giterr_set_str(GITERR_NONE, "User cancelled.");
3569 return GIT_EUSER;
3572 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3574 if (base_cert->cert_type == GIT_CERT_X509)
3576 git_cert_x509* cert = (git_cert_x509*)base_cert;
3578 if (last_accepted_cert.cmp(cert))
3579 return 0;
3581 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3582 SCOPE_EXIT { CertFreeCertificateContext(pServerCert); };
3584 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3585 if (!verificationError)
3587 last_accepted_cert.set(cert);
3588 return 0;
3591 CString servernameInCert;
3592 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, CStrBuf(servernameInCert, 128), 128);
3594 CString issuer;
3595 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, CStrBuf(issuer, 128), 128);
3597 CCheckCertificateDlg dlg;
3598 dlg.cert = cert;
3599 dlg.m_sCertificateCN = servernameInCert;
3600 dlg.m_sCertificateIssuer = issuer;
3601 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3602 dlg.m_sError = CFormatMessageWrapper(verificationError);
3603 if (dlg.DoModal() == IDOK)
3605 last_accepted_cert.set(cert);
3606 return 0;
3609 return GIT_ECERTIFICATE;
3612 int CAppUtils::ExploreTo(HWND hwnd, CString path)
3614 if (PathFileExists(path))
3616 HRESULT ret = -1;
3617 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3618 if (pidl)
3620 ret = SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3621 ILFree(pidl);
3623 return SUCCEEDED(ret) ? 0 : -1;
3625 // if filepath does not exist any more, navigate to closest matching folder
3628 int pos = path.ReverseFind(_T('\\'));
3629 if (pos <= 3)
3630 break;
3631 path.Truncate(pos);
3632 } while (!PathFileExists(path));
3633 return (INT_PTR)ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW) > 32 ? 0 : -1;
3636 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3638 bool b_local = false, b_remote = false;
3639 BYTE_VECTOR vector;
3641 CString cmd;
3642 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3643 if (g_Git.Run(cmd, &vector))
3645 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK);
3646 return -1;
3649 CTGitPathList list;
3650 if (list.ParserFromLsFile(vector))
3652 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
3653 return -1;
3656 if (list.IsEmpty())
3657 return 0;
3658 for (int i = 0; i < list.GetCount(); ++i)
3660 if (list[i].m_Stage == 2)
3661 b_local = true;
3662 if (list[i].m_Stage == 3)
3663 b_remote = true;
3667 CBlockCacheForPath block(g_Git.m_CurrentDir);
3668 if (path.IsDirectory()) // is submodule conflict
3670 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.");
3671 if (b_local && b_remote)
3673 if (!path.HasAdminDir()) // check if submodule is initialized
3675 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).");
3676 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3677 return -1;
3679 CGit subgit;
3680 subgit.m_CurrentDir = g_Git.CombinePath(path);
3681 CGitHash submoduleHead;
3682 if (subgit.GetHash(submoduleHead, _T("HEAD")))
3684 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3685 return -1;
3687 CString baseHash, localHash, remoteHash;
3688 ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash);
3689 if (resolveWith == RESOLVE_WITH_THEIRS && submoduleHead.ToString() != remoteHash)
3691 CString origPath = g_Git.m_CurrentDir;
3692 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3693 if (!GitReset(&remoteHash))
3695 g_Git.m_CurrentDir = origPath;
3696 return -1;
3698 g_Git.m_CurrentDir = origPath;
3700 else if (resolveWith == RESOLVE_WITH_MINE && submoduleHead.ToString() != localHash)
3702 CString origPath = g_Git.m_CurrentDir;
3703 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3704 if (!GitReset(&localHash))
3706 g_Git.m_CurrentDir = origPath;
3707 return -1;
3709 g_Git.m_CurrentDir = origPath;
3712 else
3714 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3715 return -1;
3719 if (resolveWith == RESOLVE_WITH_THEIRS)
3721 CString gitcmd, output;
3722 if (b_local && b_remote)
3723 gitcmd.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3724 else if (b_remote)
3725 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3726 else if (b_local)
3727 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3728 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3730 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3731 return -1;
3734 else if (resolveWith == RESOLVE_WITH_MINE)
3736 CString gitcmd, output;
3737 if (b_local && b_remote)
3738 gitcmd.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3739 else if (b_local)
3740 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3741 else if (b_remote)
3742 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3743 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3745 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3746 return -1;
3750 if (b_local && b_remote && path.m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3752 CString gitcmd, output;
3753 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3754 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3755 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3756 else
3758 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3759 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
3763 RemoveTempMergeFile(path);
3764 return 0;
3767 bool CAppUtils::ShellOpen(const CString& file, HWND hwnd /*= nullptr */)
3769 if ((INT_PTR)ShellExecute(hwnd, nullptr, file, nullptr, nullptr, SW_SHOW) > HINSTANCE_ERROR)
3770 return true;
3772 return ShowOpenWithDialog(file, hwnd);
3775 bool CAppUtils::ShowOpenWithDialog(const CString& file, HWND hwnd /*= nullptr */)
3777 OPENASINFO oi = { 0 };
3778 oi.pcszFile = file;
3779 oi.oaifInFlags = OAIF_EXEC;
3780 return SUCCEEDED(SHOpenWithDialog(hwnd, &oi));
3783 bool CAppUtils::IsTGitRebaseActive()
3785 CString adminDir;
3786 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3787 return false;
3789 if (!PathIsDirectory(adminDir + L"tgitrebase.active"))
3790 return false;
3792 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_REMOVESTALEBUTTON, IDS_ABORTBUTTON) == 2)
3793 return true;
3795 RemoveDirectory(adminDir + L"tgitrebase.active");
3797 return false;