Allow ! to be part of an URL
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob1192c7b598e3bffd075ba0d4eda1425ea4fe58ba
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'!';
890 bool IsUrl(const CString& sText)
892 if (!PathIsURLW(sText))
893 return false;
894 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" })
896 if (CStringUtils::StartsWith(sText, prefix) && sText.GetLength() != prefix.GetLength())
897 return true;
899 return false;
903 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
905 std::vector<CHARRANGE> positions = FindURLMatches(msg);
906 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
908 return positions.empty() ? FALSE : TRUE;
912 * implements URL searching with the same logic as CSciEdit::StyleURLs
914 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
916 std::vector<CHARRANGE> result;
918 int len = msg.GetLength();
919 int starturl = -1;
921 for (int i = 0; i <= msg.GetLength(); ++i)
923 if ((i < len) && IsValidURLChar(msg[i]))
925 if (starturl < 0)
926 starturl = i;
928 else
930 if (starturl >= 0)
932 bool strip = true;
933 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
935 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
936 ++starturl;
937 strip = false;
938 i = starturl;
939 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
940 ++i;
942 if (!IsUrl(msg.Mid(starturl, i - starturl)))
944 starturl = -1;
945 continue;
948 int skipTrailing = 0;
949 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] == '!'))
950 ++skipTrailing;
952 CHARRANGE range = { starturl, i - skipTrailing };
953 result.push_back(range);
955 starturl = -1;
959 return result;
962 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
963 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
964 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
965 bool bAlternateDiff /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
966 bool /* blame = false */,
967 bool bMerge,
968 bool bCombine,
969 bool bNoPrefix)
971 int diffContext = g_Git.GetConfigValueInt32(L"diff.context", -1);
972 CString tempfile=GetTempFile();
973 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext, bNoPrefix))
975 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
976 return false;
978 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + L":" + rev2, FALSE, bAlternateDiff);
980 #if 0
981 CString sCmd;
982 sCmd.Format(_T("%s /command:showcompare /unified"),
983 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
984 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
985 if (rev1.IsValid())
986 sCmd += _T(" /revision1:") + rev1.ToString();
987 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
988 if (rev2.IsValid())
989 sCmd += _T(" /revision2:") + rev2.ToString();
990 if (peg.IsValid())
991 sCmd += _T(" /pegrevision:") + peg.ToString();
992 if (headpeg.IsValid())
993 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
995 if (bAlternateDiff)
996 sCmd += _T(" /alternatediff");
998 if (bIgnoreAncestry)
999 sCmd += _T(" /ignoreancestry");
1001 if (hWnd)
1003 sCmd += _T(" /hwnd:");
1004 TCHAR buf[30];
1005 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
1006 sCmd += buf;
1009 return CAppUtils::LaunchApplication(sCmd, 0, false);
1010 #endif
1011 return TRUE;
1014 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1016 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1017 scriptsdir += _T("Diff-Scripts");
1018 CSimpleFileFind files(scriptsdir);
1019 while (files.FindNextFileNoDirectories())
1021 CString file = files.GetFilePath();
1022 CString filename = files.GetFileName();
1023 CString ext = file.Mid(file.ReverseFind('-') + 1);
1024 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
1025 std::set<CString> extensions;
1026 extensions.insert(ext);
1027 CString kind;
1028 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
1029 kind = _T(" //E:vbscript");
1030 if (file.Right(2).CompareNoCase(_T("js"))==0)
1031 kind = _T(" //E:javascript");
1032 // open the file, read the first line and find possible extensions
1033 // this script can handle
1036 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1037 CString extline;
1038 if (f.ReadString(extline))
1040 if ((extline.GetLength() > 15 ) &&
1041 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
1042 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
1044 if (extline[0] == '/')
1045 extline = extline.Mid(15);
1046 else
1047 extline = extline.Mid(14);
1048 CString sToken;
1049 int curPos = 0;
1050 sToken = extline.Tokenize(_T(";"), curPos);
1051 while (!sToken.IsEmpty())
1053 if (!sToken.IsEmpty())
1055 if (sToken[0] != '.')
1056 sToken = _T(".") + sToken;
1057 extensions.insert(sToken);
1059 sToken = extline.Tokenize(_T(";"), curPos);
1063 f.Close();
1065 catch (CFileException* e)
1067 e->Delete();
1070 for (const auto& extension : extensions)
1072 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1074 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1076 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension);
1077 CString diffregstring = diffreg;
1078 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1079 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1082 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1084 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1086 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension);
1087 CString diffregstring = diffreg;
1088 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1089 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1095 return true;
1098 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1100 // ask from where the export has to be done
1101 CExportDlg dlg;
1102 if(BashHash)
1103 dlg.m_initialRefName=*BashHash;
1104 if (orgPath)
1106 if (PathIsRelative(orgPath->GetWinPath()))
1107 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1108 else
1109 dlg.m_orgPath = *orgPath;
1112 if (dlg.DoModal() == IDOK)
1114 CString cmd;
1115 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1116 (LPCTSTR)dlg.m_strFile, (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName));
1118 CProgressDlg pro;
1119 pro.m_GitCmd=cmd;
1120 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1122 if (status)
1123 return;
1124 postCmdList.emplace_back(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); });
1127 CGit git;
1128 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1130 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1131 pro.m_Git = &git;
1133 return (pro.DoModal() == IDOK);
1135 return false;
1138 bool CAppUtils::UpdateBranchDescription(const CString& branch, CString description)
1140 if (branch.IsEmpty())
1141 return false;
1143 CString key;
1144 key.Format(L"branch.%s.description", (LPCTSTR)branch);
1145 description.Replace(L"\r", L"");
1146 description.Trim();
1147 if (description.IsEmpty())
1148 g_Git.UnsetConfigValue(key);
1149 else
1150 g_Git.SetConfigValue(key, description);
1152 return true;
1155 bool CAppUtils::CreateBranchTag(bool isTag /*true*/, const CString* commitHash /*nullptr*/, bool switchNewBranch /*false*/, LPCTSTR name /*nullptr*/)
1157 CCreateBranchTagDlg dlg;
1158 dlg.m_bIsTag = isTag;
1159 dlg.m_bSwitch = switchNewBranch;
1161 if (commitHash)
1162 dlg.m_initialRefName = *commitHash;
1164 if (name)
1165 dlg.m_BranchTagName = name;
1167 if(dlg.DoModal()==IDOK)
1169 CString cmd;
1170 CString force;
1171 CString track;
1172 if(dlg.m_bTrack == TRUE)
1173 track=_T(" --track ");
1174 else if(dlg.m_bTrack == FALSE)
1175 track=_T(" --no-track");
1177 if(dlg.m_bForce)
1178 force=_T(" -f ");
1180 if (isTag)
1182 CString sign;
1183 if(dlg.m_bSign)
1184 sign=_T("-s");
1186 cmd.Format(_T("git.exe tag %s %s %s %s"),
1187 (LPCTSTR)force,
1188 (LPCTSTR)sign,
1189 (LPCTSTR)dlg.m_BranchTagName,
1190 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1193 if(!dlg.m_Message.Trim().IsEmpty())
1195 CString tempfile = ::GetTempFile();
1196 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1198 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1199 return FALSE;
1201 cmd += _T(" -F ")+tempfile;
1204 else
1206 cmd.Format(_T("git.exe branch %s %s %s %s"),
1207 (LPCTSTR)track,
1208 (LPCTSTR)force,
1209 (LPCTSTR)dlg.m_BranchTagName,
1210 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1213 CString out;
1214 if(g_Git.Run(cmd,&out,CP_UTF8))
1216 CMessageBox::Show(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1217 return FALSE;
1219 if (!isTag && dlg.m_bSwitch)
1221 // it is a new branch and the user has requested to switch to it
1222 PerformSwitch(dlg.m_BranchTagName);
1224 if (!isTag && !dlg.m_Message.IsEmpty())
1225 UpdateBranchDescription(dlg.m_BranchTagName, dlg.m_Message);
1227 return TRUE;
1229 return FALSE;
1232 bool CAppUtils::Switch(const CString& initialRefName)
1234 CGitSwitchDlg dlg;
1235 if(!initialRefName.IsEmpty())
1236 dlg.m_initialRefName = initialRefName;
1238 if (dlg.DoModal() == IDOK)
1240 CString branch;
1241 if (dlg.m_bBranch)
1242 branch = dlg.m_NewBranch;
1244 // if refs/heads/ is not stripped, checkout will detach HEAD
1245 // checkout prefers branches on name clashes (with tags)
1246 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1247 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1249 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1251 return FALSE;
1254 bool CAppUtils::PerformSwitch(const CString& ref, bool bForce /* false */, const CString& sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1256 CString cmd;
1257 CString track;
1258 CString force;
1259 CString branch;
1260 CString merge;
1262 if(!sNewBranch.IsEmpty()){
1263 if (bBranchOverride)
1264 branch.Format(_T("-B %s "), (LPCTSTR)sNewBranch);
1265 else
1266 branch.Format(_T("-b %s "), (LPCTSTR)sNewBranch);
1267 if (bTrack == TRUE)
1268 track = _T("--track ");
1269 else if (bTrack == FALSE)
1270 track = _T("--no-track ");
1272 if (bForce)
1273 force = _T("-f ");
1274 if (bMerge)
1275 merge = _T("--merge ");
1277 cmd.Format(_T("git.exe checkout %s%s%s%s%s --"),
1278 (LPCTSTR)force,
1279 (LPCTSTR)track,
1280 (LPCTSTR)merge,
1281 (LPCTSTR)branch,
1282 (LPCTSTR)g_Git.FixBranchName(ref));
1284 CProgressDlg progress;
1285 progress.m_GitCmd = cmd;
1287 CString currentBranch;
1288 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1289 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1291 if (!status)
1293 CTGitPath gitPath = g_Git.m_CurrentDir;
1294 if (gitPath.HasSubmodules())
1296 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1298 CString sCmd;
1299 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1300 RunTortoiseGitProc(sCmd);
1303 if (hasBranch)
1304 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); });
1307 CString newBranch;
1308 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1309 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); });
1311 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []{
1312 CTGitPathList pathlist;
1313 CTGitPathList selectedlist;
1314 pathlist.AddPath(CTGitPath());
1315 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
1316 CString str;
1317 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1320 else
1322 if (bMerge && g_Git.HasWorkingTreeConflicts() > 0)
1324 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
1326 CString sCmd;
1327 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1328 CAppUtils::RunTortoiseGitProc(sCmd);
1331 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); });
1332 if (!bMerge)
1333 postCmdList.emplace_back(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); });
1336 progress.m_PostExecCallback = [&](DWORD& exitCode, CString& extraMsg)
1338 if (bMerge && !exitCode && g_Git.HasWorkingTreeConflicts() > 0)
1340 exitCode = 1; // Treat it as failure
1341 extraMsg = _T("Has merge conflict");
1345 INT_PTR ret = progress.DoModal();
1347 return ret == IDOK;
1350 class CIgnoreFile : public CStdioFile
1352 public:
1353 STRING_VECTOR m_Items;
1354 CString m_eol;
1356 virtual BOOL ReadString(CString& rString)
1358 if (GetPosition() == 0)
1360 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1361 char buf[3] = { 0, 0, 0 };
1362 Read(buf, 3);
1363 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1364 SeekToBegin();
1367 CStringA strA;
1368 char lastChar = '\0';
1369 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1371 if (c == '\r')
1372 continue;
1373 if (c == '\n')
1375 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1376 break;
1378 strA.AppendChar(c);
1380 if (strA.IsEmpty())
1381 return FALSE;
1383 rString = CUnicodeUtils::GetUnicode(strA);
1384 return TRUE;
1387 void ResetState()
1389 m_Items.clear();
1390 m_eol.Empty();
1394 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1396 file.ResetState();
1397 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1399 CMessageBox::Show(nullptr, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1400 return false;
1403 if (file.GetLength() > 0)
1405 CString fileText;
1406 while (file.ReadString(fileText))
1407 file.m_Items.push_back(fileText);
1408 file.Seek(file.GetLength() - 1, 0);
1409 char lastchar[1] = { 0 };
1410 file.Read(lastchar, 1);
1411 file.SeekToEnd();
1412 if (lastchar[0] != '\n')
1414 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1415 file.Write(eol, eol.GetLength());
1418 else
1419 file.SeekToEnd();
1421 return true;
1424 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1426 CIgnoreDlg ignoreDlg;
1427 if (ignoreDlg.DoModal() == IDOK)
1429 CString ignorefile;
1430 ignorefile = g_Git.m_CurrentDir + _T("\\");
1432 switch (ignoreDlg.m_IgnoreFile)
1434 case 0:
1435 ignorefile += _T(".gitignore");
1436 break;
1437 case 2:
1438 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1439 ignorefile += _T("info");
1440 if (!PathFileExists(ignorefile))
1441 CreateDirectory(ignorefile, nullptr);
1442 ignorefile += _T("\\exclude");
1443 break;
1446 CIgnoreFile file;
1449 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1450 return false;
1452 for (int i = 0; i < path.GetCount(); ++i)
1454 if (ignoreDlg.m_IgnoreFile == 1)
1456 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1457 if (!OpenIgnoreFile(file, ignorefile))
1458 return false;
1461 CString ignorePattern;
1462 if (ignoreDlg.m_IgnoreType == 0)
1464 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1465 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1467 ignorePattern += _T("/");
1469 if (IsMask)
1470 ignorePattern += _T("*") + path[i].GetFileExtension();
1471 else
1472 ignorePattern += path[i].GetFileOrDirectoryName();
1474 // escape [ and ] so that files get ignored correctly
1475 ignorePattern.Replace(_T("["), _T("\\["));
1476 ignorePattern.Replace(_T("]"), _T("\\]"));
1478 bool found = false;
1479 for (size_t j = 0; j < file.m_Items.size(); ++j)
1481 if (file.m_Items[j] == ignorePattern)
1483 found = true;
1484 break;
1487 if (!found)
1489 file.m_Items.push_back(ignorePattern);
1490 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1491 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1492 file.Write(ignorePatternA, ignorePatternA.GetLength());
1495 if (ignoreDlg.m_IgnoreFile == 1)
1496 file.Close();
1499 if (ignoreDlg.m_IgnoreFile != 1)
1500 file.Close();
1502 catch(...)
1504 file.Abort();
1505 return false;
1508 return true;
1510 return false;
1513 static bool Reset(const CString& resetTo, int resetType)
1515 CString cmd;
1516 CString type;
1517 switch (resetType)
1519 case 0:
1520 type = _T("--soft");
1521 break;
1522 case 1:
1523 type = _T("--mixed");
1524 break;
1525 case 2:
1526 type = _T("--hard");
1527 break;
1528 default:
1529 resetType = 1;
1530 type = _T("--mixed");
1531 break;
1533 cmd.Format(_T("git.exe reset %s %s --"), (LPCTSTR)type, (LPCTSTR)resetTo);
1535 CProgressDlg progress;
1536 progress.m_GitCmd = cmd;
1538 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1540 if (status)
1542 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); });
1543 return;
1546 CTGitPath gitPath = g_Git.m_CurrentDir;
1547 if (gitPath.HasSubmodules() && resetType == 2)
1549 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1551 CString sCmd;
1552 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
1553 CAppUtils::RunTortoiseGitProc(sCmd);
1558 INT_PTR ret;
1559 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1561 CGitProgressDlg gitdlg;
1562 ResetProgressCommand resetProgressCommand;
1563 gitdlg.SetCommand(&resetProgressCommand);
1564 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1565 resetProgressCommand.SetRevision(resetTo);
1566 resetProgressCommand.SetResetType(resetType);
1567 ret = gitdlg.DoModal();
1569 else
1570 ret = progress.DoModal();
1572 return ret == IDOK;
1575 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1577 CResetDlg dlg;
1578 dlg.m_ResetType=type;
1579 dlg.m_ResetToVersion=*CommitHash;
1580 dlg.m_initialRefName = *CommitHash;
1581 if (dlg.DoModal() == IDOK)
1582 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1584 return false;
1587 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1589 if(mode == FALSE)
1591 descript.LoadString(IDS_SVNACTION_DELETE);
1592 return;
1594 if(base)
1596 descript.LoadString(IDS_SVNACTION_MODIFIED);
1597 return;
1599 descript.LoadString(IDS_PROC_CREATED);
1602 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1604 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1605 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1606 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1608 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1610 CString file;
1611 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1613 return file;
1616 bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, CString& hash2, CString& hash3)
1618 size_t pos = 0;
1619 CString one;
1620 CString part;
1622 while (pos < out.size())
1624 one.Empty();
1626 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1627 int tabstart = 0;
1628 one.Tokenize(_T("\t"), tabstart);
1630 tabstart = 0;
1631 part = one.Tokenize(_T(" "), tabstart); //Tag
1632 part = one.Tokenize(_T(" "), tabstart); //Mode
1633 part = one.Tokenize(_T(" "), tabstart); //Hash
1634 CString hash = part;
1635 part = one.Tokenize(_T("\t"), tabstart); //Stage
1636 int stage = _ttol(part);
1637 if (stage == 1)
1638 hash1 = hash;
1639 else if (stage == 2)
1640 hash2 = hash;
1641 else if (stage == 3)
1643 hash3 = hash;
1644 return true;
1647 pos = out.findNextString(pos);
1650 return false;
1653 bool CAppUtils::ConflictEdit(const CTGitPath& path, bool bAlternativeTool /*= false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1655 bool bRet = false;
1657 CTGitPath merge=path;
1658 CTGitPath directory = merge.GetDirectory();
1660 // we have the conflicted file (%merged)
1661 // now look for the other required files
1662 //GitStatus stat;
1663 //stat.GetStatus(merge);
1664 //if (stat.status == nullptr)
1665 // return false;
1667 BYTE_VECTOR vector;
1669 CString cmd;
1670 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1672 if (g_Git.Run(cmd, &vector))
1673 return FALSE;
1675 if (merge.IsDirectory())
1677 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1678 if (merge.HasAdminDir()) {
1679 CGit subgit;
1680 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1681 CGitHash hash;
1682 subgit.GetHash(hash, _T("HEAD"));
1683 baseHash = hash;
1685 if (ParseHashesFromLsFile(vector, realBaseHash, localHash, remoteHash)) // in base no submodule, but in remote submodule
1686 baseHash = realBaseHash;
1688 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1689 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1691 bool baseOK = false, mineOK = false, theirsOK = false;
1692 CString baseSubject, mineSubject, theirsSubject;
1693 if (merge.HasAdminDir())
1695 CGit subgit;
1696 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1697 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1698 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1700 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)
1702 changeTypeMine = CGitDiff::Identical;
1703 changeTypeTheirs = CGitDiff::NewSubmodule;
1704 baseSubject = _T("no submodule");
1705 mineSubject = baseSubject;
1706 theirsSubject = _T("not initialized");
1708 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
1710 baseHash = localHash;
1711 baseSubject = _T("not initialized");
1712 mineSubject = baseSubject;
1713 theirsSubject = _T("not initialized");
1714 changeTypeMine = CGitDiff::Identical;
1715 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1717 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
1719 baseSubject = _T("not initialized");
1720 mineSubject = baseSubject;
1721 theirsSubject = baseSubject;
1722 if (baseHash == localHash)
1723 changeTypeMine = CGitDiff::Identical;
1725 else
1726 return FALSE;
1728 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1729 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), revertTheirMy, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1730 resolveSubmoduleConflictDialog.DoModal();
1731 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1733 static UINT WM_REVERTMSG = RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1734 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1737 return TRUE;
1740 CTGitPathList list;
1741 if (list.ParserFromLsFile(vector))
1743 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1744 return FALSE;
1747 if (list.IsEmpty())
1748 return FALSE;
1750 CTGitPath theirs;
1751 CTGitPath mine;
1752 CTGitPath base;
1754 if (revertTheirMy)
1756 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1757 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1759 else
1761 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1762 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1764 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1766 CString format;
1768 //format=_T("git.exe cat-file blob \":%d:%s\"");
1769 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1770 CFile tempfile;
1771 //create a empty file, incase stage is not three
1772 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1773 tempfile.Close();
1774 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1775 tempfile.Close();
1776 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1777 tempfile.Close();
1779 bool b_base=false, b_local=false, b_remote=false;
1781 for (int i = 0; i< list.GetCount(); ++i)
1783 CString outfile;
1784 cmd.Empty();
1785 outfile.Empty();
1787 if( list[i].m_Stage == 1)
1789 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1790 b_base = true;
1791 outfile = base.GetWinPathString();
1794 if( list[i].m_Stage == 2 )
1796 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1797 b_local = true;
1798 outfile = mine.GetWinPathString();
1801 if( list[i].m_Stage == 3 )
1803 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1804 b_remote = true;
1805 outfile = theirs.GetWinPathString();
1807 CString output, err;
1808 if(!outfile.IsEmpty())
1809 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1811 CString file;
1812 int start =0 ;
1813 file = output.Tokenize(_T("\t"), start);
1814 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1816 else
1817 CMessageBox::Show(nullptr, output + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1820 if(b_local && b_remote )
1822 merge.SetFromWin(g_Git.CombinePath(merge));
1823 if( revertTheirMy )
1824 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, mine, theirs, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1825 else
1826 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1828 else
1830 ::DeleteFile(mine.GetWinPathString());
1831 ::DeleteFile(theirs.GetWinPathString());
1832 ::DeleteFile(base.GetWinPathString());
1834 CDeleteConflictDlg dlg;
1835 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1836 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1837 CGitHash localHash, remoteHash;
1838 if (!g_Git.GetHash(localHash, _T("HEAD")))
1839 dlg.m_LocalHash = localHash.ToString();
1840 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1841 dlg.m_RemoteHash = remoteHash.ToString();
1842 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1843 dlg.m_RemoteHash = remoteHash.ToString();
1844 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1845 dlg.m_RemoteHash = remoteHash.ToString();
1846 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1847 dlg.m_RemoteHash = remoteHash.ToString();
1848 dlg.m_bShowModifiedButton=b_base;
1849 dlg.m_File=merge.GetGitPathString();
1850 if(dlg.DoModal() == IDOK)
1852 CString out;
1853 if(dlg.m_bIsDelete)
1854 cmd.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1855 else
1856 cmd.Format(_T("git.exe add -- \"%s\""), (LPCTSTR)merge.GetGitPathString());
1858 if (g_Git.Run(cmd, &out, CP_UTF8))
1860 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1861 return FALSE;
1863 return TRUE;
1865 else
1866 return FALSE;
1869 #if 0
1870 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1871 base, theirs, mine, merge);
1872 #endif
1873 #if 0
1874 if (stat.status->text_status == svn_wc_status_conflicted)
1876 // we have a text conflict, use our merge tool to resolve the conflict
1878 CTSVNPath theirs(directory);
1879 CTSVNPath mine(directory);
1880 CTSVNPath base(directory);
1881 bool bConflictData = false;
1883 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1885 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1886 bConflictData = true;
1888 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1890 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1891 bConflictData = true;
1893 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1895 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1896 bConflictData = true;
1898 else
1899 mine = merge;
1900 if (bConflictData)
1901 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1902 base, theirs, mine, merge);
1905 if (stat.status->prop_status == svn_wc_status_conflicted)
1907 // we have a property conflict
1908 CTSVNPath prej(directory);
1909 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1911 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1912 // there's a problem: the prej file contains a _description_ of the conflict, and
1913 // that description string might be translated. That means we have no way of parsing
1914 // the file to find out the conflicting values.
1915 // The only thing we can do: show a dialog with the conflict description, then
1916 // let the user either accept the existing property or open the property edit dialog
1917 // to manually change the properties and values. And a button to mark the conflict as
1918 // resolved.
1919 CEditPropConflictDlg dlg;
1920 dlg.SetPrejFile(prej);
1921 dlg.SetConflictedItem(merge);
1922 bRet = (dlg.DoModal() != IDCANCEL);
1926 if (stat.status->tree_conflict)
1928 // we have a tree conflict
1929 SVNInfo info;
1930 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1931 if (pInfoData)
1933 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1935 CTSVNPath theirs(directory);
1936 CTSVNPath mine(directory);
1937 CTSVNPath base(directory);
1938 bool bConflictData = false;
1940 if (pInfoData->treeconflict_theirfile)
1942 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1943 bConflictData = true;
1945 if (pInfoData->treeconflict_basefile)
1947 base.AppendPathString(pInfoData->treeconflict_basefile);
1948 bConflictData = true;
1950 if (pInfoData->treeconflict_myfile)
1952 mine.AppendPathString(pInfoData->treeconflict_myfile);
1953 bConflictData = true;
1955 else
1956 mine = merge;
1957 if (bConflictData)
1958 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1959 base, theirs, mine, merge);
1961 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1963 CString sConflictAction;
1964 CString sConflictReason;
1965 CString sResolveTheirs;
1966 CString sResolveMine;
1967 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1968 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1970 if (pInfoData->treeconflict_nodekind == svn_node_file)
1972 switch (pInfoData->treeconflict_operation)
1974 case svn_wc_operation_update:
1975 switch (pInfoData->treeconflict_action)
1977 case svn_wc_conflict_action_edit:
1978 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1979 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1980 break;
1981 case svn_wc_conflict_action_add:
1982 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1983 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1984 break;
1985 case svn_wc_conflict_action_delete:
1986 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1987 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1988 break;
1990 break;
1991 case svn_wc_operation_switch:
1992 switch (pInfoData->treeconflict_action)
1994 case svn_wc_conflict_action_edit:
1995 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1996 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1997 break;
1998 case svn_wc_conflict_action_add:
1999 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
2000 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2001 break;
2002 case svn_wc_conflict_action_delete:
2003 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
2004 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2005 break;
2007 break;
2008 case svn_wc_operation_merge:
2009 switch (pInfoData->treeconflict_action)
2011 case svn_wc_conflict_action_edit:
2012 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
2013 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2014 break;
2015 case svn_wc_conflict_action_add:
2016 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
2017 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2018 break;
2019 case svn_wc_conflict_action_delete:
2020 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
2021 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2022 break;
2024 break;
2027 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
2029 switch (pInfoData->treeconflict_operation)
2031 case svn_wc_operation_update:
2032 switch (pInfoData->treeconflict_action)
2034 case svn_wc_conflict_action_edit:
2035 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
2036 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2037 break;
2038 case svn_wc_conflict_action_add:
2039 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
2040 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2041 break;
2042 case svn_wc_conflict_action_delete:
2043 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
2044 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2045 break;
2047 break;
2048 case svn_wc_operation_switch:
2049 switch (pInfoData->treeconflict_action)
2051 case svn_wc_conflict_action_edit:
2052 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
2053 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2054 break;
2055 case svn_wc_conflict_action_add:
2056 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
2057 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2058 break;
2059 case svn_wc_conflict_action_delete:
2060 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
2061 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2062 break;
2064 break;
2065 case svn_wc_operation_merge:
2066 switch (pInfoData->treeconflict_action)
2068 case svn_wc_conflict_action_edit:
2069 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
2070 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2071 break;
2072 case svn_wc_conflict_action_add:
2073 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
2074 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2075 break;
2076 case svn_wc_conflict_action_delete:
2077 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
2078 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2079 break;
2081 break;
2085 UINT uReasonID = 0;
2086 switch (pInfoData->treeconflict_reason)
2088 case svn_wc_conflict_reason_edited:
2089 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
2090 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2091 break;
2092 case svn_wc_conflict_reason_obstructed:
2093 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
2094 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2095 break;
2096 case svn_wc_conflict_reason_deleted:
2097 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
2098 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2099 break;
2100 case svn_wc_conflict_reason_added:
2101 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
2102 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2103 break;
2104 case svn_wc_conflict_reason_missing:
2105 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
2106 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2107 break;
2108 case svn_wc_conflict_reason_unversioned:
2109 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
2110 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2111 break;
2113 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
2115 CTreeConflictEditorDlg dlg;
2116 dlg.SetConflictInfoText(sConflictReason);
2117 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
2118 dlg.SetPath(treeConflictPath);
2119 INT_PTR dlgRet = dlg.DoModal();
2120 bRet = (dlgRet != IDCANCEL);
2124 #endif
2125 return bRet;
2128 bool CAppUtils::IsSSHPutty()
2130 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2131 sshclient=sshclient.MakeLower();
2132 if(sshclient.Find(_T("plink.exe"),0)>=0)
2133 return true;
2134 return false;
2137 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2139 if (!OpenClipboard(nullptr))
2140 return CString();
2142 CString sClipboardText;
2143 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2144 if (hglb)
2146 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2147 sClipboardText = CString(lpstr);
2148 GlobalUnlock(hglb);
2150 hglb = GetClipboardData(CF_UNICODETEXT);
2151 if (hglb)
2153 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2154 sClipboardText = lpstr;
2155 GlobalUnlock(hglb);
2157 CloseClipboard();
2159 if(!sClipboardText.IsEmpty())
2161 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2162 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2164 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ssh://", L"git@" })
2166 if (CStringUtils::StartsWith(sClipboardText, prefix) && sClipboardText.GetLength() != prefix.GetLength())
2167 return sClipboardText;
2170 if(sClipboardText.GetLength()>=2)
2171 if( sClipboardText[1] == _T(':') )
2172 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2173 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2174 return sClipboardText;
2176 // trim prefixes like "git clone "
2177 if (!skipGitPrefix.IsEmpty() && CStringUtils::StartsWith(sClipboardText, skipGitPrefix))
2179 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2180 int spacePos = -1;
2181 while (paramsCount >= 0)
2183 --paramsCount;
2184 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2185 if (spacePos == -1)
2186 break;
2188 if (spacePos > 0 && paramsCount < 0)
2189 sClipboardText.Truncate(spacePos);
2190 return sClipboardText;
2194 return CString();
2197 CString CAppUtils::ChooseRepository(const CString* path)
2199 CBrowseFolder browseFolder;
2200 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2202 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2203 CString strCloneDirectory;
2204 if(path)
2205 strCloneDirectory=*path;
2206 else
2207 strCloneDirectory = regLastResopitory;
2209 CString title;
2210 title.LoadString(IDS_CHOOSE_REPOSITORY);
2212 browseFolder.SetInfo(title);
2214 if (browseFolder.Show(nullptr, strCloneDirectory) == CBrowseFolder::OK)
2216 regLastResopitory = strCloneDirectory;
2217 return strCloneDirectory;
2219 else
2220 return CString();
2223 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2225 CSendMailDlg dlg;
2227 dlg.m_PathList = list;
2229 if(dlg.DoModal()==IDOK)
2231 if (dlg.m_PathList.IsEmpty())
2232 return FALSE;
2234 CGitProgressDlg progDlg;
2235 if (bIsMainWnd)
2236 theApp.m_pMainWnd = &progDlg;
2237 SendMailProgressCommand sendMailProgressCommand;
2238 progDlg.SetCommand(&sendMailProgressCommand);
2240 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2241 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2243 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2244 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2246 progDlg.DoModal();
2248 return true;
2250 return false;
2253 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2255 CTGitPathList list;
2256 CString log=formatpatchoutput;
2257 int start=log.Find(cmd);
2258 if(start >=0)
2259 CString one=log.Tokenize(_T("\n"),start);
2260 else
2261 start = 0;
2263 while(start>=0)
2265 CString one=log.Tokenize(_T("\n"),start);
2266 one=one.Trim();
2267 if (one.IsEmpty() || one.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS))) == 0)
2268 continue;
2269 one.Replace(_T('/'),_T('\\'));
2270 CTGitPath path;
2271 path.SetFromWin(one);
2272 list.AddPath(path);
2274 if (!list.IsEmpty())
2275 return SendPatchMail(list, bIsMainWnd);
2276 else
2278 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2279 return true;
2284 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2286 CString output;
2287 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2288 if(output.IsEmpty())
2289 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2290 else
2291 return CUnicodeUtils::GetCPCode(output);
2293 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2297 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2298 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2300 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2301 TCHAR commentChar = L'#';
2302 if (stripComments)
2304 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2305 if (!commentCharValue.IsEmpty())
2306 commentChar = commentCharValue[0];
2309 bool sanitize = (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE);
2310 if (sanitize)
2311 message.Trim(L" \r\n");
2313 int len = message.GetLength();
2314 int start = 0;
2315 int emptyLineCnt = 0;
2316 while (start >= 0 && start < len)
2318 int oldStart = start;
2319 start = message.Find(L"\n", oldStart);
2320 CString line = message.Mid(oldStart);
2321 if (start != -1)
2323 line.Truncate(start - oldStart);
2324 ++start; // move forward so we don't find the same char again
2326 if (stripComments && (!line.IsEmpty() && line.GetAt(0) == commentChar) || (start < 0 && line.IsEmpty()))
2327 continue;
2328 line.TrimRight(L" \r");
2329 if (sanitize)
2331 if (line.IsEmpty())
2333 ++emptyLineCnt;
2334 continue;
2336 if (emptyLineCnt) // squash multiple newlines
2337 file.Write("\n", 1);
2338 emptyLineCnt = 0;
2340 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2341 file.Write((LPCSTR)lineA, lineA.GetLength());
2343 file.Close();
2344 return 0;
2346 catch (CFileException *e)
2348 e->Delete();
2349 return -1;
2353 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)
2355 if (bAutoLoad)
2356 CAppUtils::LaunchPAgent(nullptr, &url);
2358 CGitHash hashOld;
2359 if (g_Git.GetHash(hashOld, L"HEAD"))
2361 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2362 return false;
2365 CString args;
2366 if (CRegDWORD(L"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE) == FALSE)
2367 args += L" --no-rebase";
2369 if (bFetchTags == BST_UNCHECKED)
2370 args += L" --no-tags";
2371 else if (bFetchTags == BST_CHECKED)
2372 args += L" --tags";
2374 if (bNoFF)
2375 args += L" --no-ff";
2377 if (bFFonly)
2378 args += L" --ff-only";
2380 if (bSquash)
2381 args += L" --squash";
2383 if (bNoCommit)
2384 args += L" --no-commit";
2386 if (nDepth)
2387 args.AppendFormat(L" --depth %d", *nDepth);
2389 if (bPrune == BST_CHECKED)
2390 args += L" --prune";
2391 else if (bPrune == BST_UNCHECKED)
2392 args += L" --no-prune";
2394 if (bUnrelated)
2395 args += L" --allow-unrelated-histories";
2397 CString cmd;
2398 cmd.Format(L"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR)args, (LPCTSTR)url, (LPCTSTR)remoteBranchName);
2399 CProgressDlg progress;
2400 progress.m_GitCmd = cmd;
2402 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2403 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2405 if (status)
2407 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2409 STRING_VECTOR remotes;
2410 g_Git.GetRemoteList(remotes);
2411 if (std::find(remotes.begin(), remotes.end(), url) != remotes.end())
2413 CString currentBranch;
2414 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2415 currentBranch.Empty();
2416 CString remoteRef = L"remotes/" + url + L"/" + remoteBranchName;
2417 if (!currentBranch.IsEmpty() && remoteBranchName.IsEmpty())
2419 CString pullRemote, pullBranch;
2420 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2421 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2422 remoteRef = L"remotes/" + pullRemote + L"/" + pullBranch;
2424 CGitHash common;
2425 g_Git.IsFastForward(L"HEAD", remoteRef, &common);
2426 if (common.IsEmpty())
2427 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoPull(url, bAutoLoad, bFetchTags, bNoFF, bFFonly, bSquash, bNoCommit, nDepth, bPrune, remoteBranchName, showPush, showStashPop, true); });
2431 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(); });
2432 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(L"", true); });
2433 return;
2436 if (showStashPop)
2437 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
2439 if (g_Git.GetHash(hashNew, L"HEAD"))
2440 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash after pulling."), L"TortoiseGit", MB_ICONERROR);
2441 else
2443 postCmdList.emplace_back(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2445 CFileDiffDlg dlg;
2446 dlg.SetDiff(nullptr, hashOld.ToString(), hashNew.ToString());
2447 dlg.DoModal();
2449 postCmdList.emplace_back(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2451 CLogDlg dlg;
2452 dlg.SetParams(CTGitPath(L""), CTGitPath(L""), L"", hashOld.ToString() + L".." + hashNew.ToString(), 0);
2453 dlg.DoModal();
2457 if (showPush)
2458 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
2460 CTGitPath gitPath = g_Git.m_CurrentDir;
2461 if (gitPath.HasSubmodules())
2463 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2465 CString sCmd;
2466 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2467 CAppUtils::RunTortoiseGitProc(sCmd);
2472 INT_PTR ret = progress.DoModal();
2474 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)
2476 CChangedDlg changeddlg;
2477 changeddlg.m_pathList.AddPath(CTGitPath());
2478 changeddlg.DoModal();
2480 return true;
2483 return ret == IDOK;
2486 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2488 if (IsTGitRebaseActive())
2489 return false;
2491 CPullFetchDlg dlg;
2492 dlg.m_IsPull = TRUE;
2493 if (dlg.DoModal() == IDOK)
2495 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2496 if (dlg.m_bRebase)
2497 return DoFetch(dlg.m_RemoteURL,
2498 FALSE, // Fetch all remotes
2499 dlg.m_bAutoLoad == BST_CHECKED,
2500 dlg.m_bPrune,
2501 dlg.m_bDepth == BST_CHECKED,
2502 dlg.m_nDepth,
2503 dlg.m_bFetchTags,
2504 dlg.m_RemoteBranchName,
2505 dlg.m_bRebaseActivatedInConfigForPull ? 2 : 1, // Rebase after fetching
2506 dlg.m_bRebasePreserveMerges == TRUE); // Preserve merges on rebase
2508 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);
2511 return false;
2514 bool CAppUtils::RebaseAfterFetch(const CString& upstream, int rebase, bool preserveMerges)
2516 while (true)
2518 CRebaseDlg dlg;
2519 if (!upstream.IsEmpty())
2520 dlg.m_Upstream = upstream;
2521 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2522 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2523 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2524 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2525 dlg.m_bRebaseAutoStart = (rebase == 2);
2526 dlg.m_bPreserveMerges = preserveMerges;
2527 INT_PTR response = dlg.DoModal();
2528 if (response == IDOK)
2529 return true;
2530 else if (response == IDC_REBASE_POST_BUTTON)
2532 CString cmd = _T("/command:log");
2533 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2534 CAppUtils::RunTortoiseGitProc(cmd);
2535 return true;
2537 else if (response == IDC_REBASE_POST_BUTTON + 1)
2538 return Push();
2539 else if (response == IDC_REBASE_POST_BUTTON + 2)
2541 CString cmd, out, err;
2542 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2543 (LPCTSTR)g_Git.m_CurrentDir,
2544 (LPCTSTR)g_Git.FixBranchName(dlg.m_Upstream),
2545 (LPCTSTR)g_Git.FixBranchName(dlg.m_Branch));
2546 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2548 CMessageBox::Show(nullptr, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2549 return false;
2551 CAppUtils::SendPatchMail(cmd, out);
2552 return true;
2554 else if (response == IDC_REBASE_POST_BUTTON + 3)
2555 continue;
2556 else if (response == IDCANCEL)
2557 return false;
2558 return false;
2562 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)
2564 if (loadPuttyAgent)
2566 if (fetchAllRemotes)
2568 STRING_VECTOR list;
2569 g_Git.GetRemoteList(list);
2571 for (const auto& remote : list)
2572 CAppUtils::LaunchPAgent(nullptr, &remote);
2574 else
2575 CAppUtils::LaunchPAgent(nullptr, &url);
2578 CString upstream = _T("FETCH_HEAD");
2579 CGitHash oldUpstreamHash;
2580 if (runRebase)
2582 STRING_VECTOR list;
2583 g_Git.GetRemoteList(list);
2584 for (auto it = list.cbegin(); it != list.cend(); ++it)
2586 if (url == *it)
2588 CString remote, trackedBranch;
2589 g_Git.GetRemoteTrackedBranchForHEAD(remote, trackedBranch);
2590 if (!remote.IsEmpty() && !trackedBranch.IsEmpty())
2592 upstream = L"remotes/" + remote + L"/" + trackedBranch;
2593 g_Git.GetHash(oldUpstreamHash, upstream);
2595 break;
2600 CString cmd, arg;
2601 arg = _T(" --progress");
2603 if (bDepth)
2604 arg.AppendFormat(_T(" --depth %d"), nDepth);
2606 if (prune == TRUE)
2607 arg += _T(" --prune");
2608 else if (prune == FALSE)
2609 arg += _T(" --no-prune");
2611 if (fetchTags == 1)
2612 arg += _T(" --tags");
2613 else if (fetchTags == 0)
2614 arg += _T(" --no-tags");
2616 if (fetchAllRemotes)
2617 cmd.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR)arg);
2618 else
2619 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR)arg, (LPCTSTR)url, (LPCTSTR)remoteBranch);
2621 CProgressDlg progress;
2622 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2624 if (status)
2626 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase, rebasePreserveMerges); });
2627 return;
2630 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2632 CString cmd = _T("/command:log");
2633 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2634 CAppUtils::RunTortoiseGitProc(cmd);
2637 postCmdList.emplace_back(IDI_REVERT, IDS_PROC_RESET, []
2639 CString pullRemote, pullBranch;
2640 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2641 CString defaultUpstream;
2642 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2643 defaultUpstream.Format(_T("remotes/%s/%s"), (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
2644 CAppUtils::GitReset(&defaultUpstream, 2);
2647 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); });
2649 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2650 postCmdList.emplace_back(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); });
2653 progress.m_GitCmd = cmd;
2655 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2657 CGitProgressDlg gitdlg;
2658 FetchProgressCommand fetchProgressCommand;
2659 if (!fetchAllRemotes)
2660 fetchProgressCommand.SetUrl(url);
2661 gitdlg.SetCommand(&fetchProgressCommand);
2662 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2663 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2664 if (!fetchAllRemotes)
2665 fetchProgressCommand.SetRefSpec(remoteBranch);
2666 return gitdlg.DoModal() == IDOK;
2669 progress.m_PostExecCallback = [&](DWORD& exitCode, CString&)
2671 if (exitCode || !runRebase)
2672 return;
2674 CGitHash remoteBranchHash;
2675 g_Git.GetHash(remoteBranchHash, upstream);
2676 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)
2677 return;
2679 if (runRebase == 1 && g_Git.IsFastForward(L"HEAD", upstream))
2681 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);
2682 if (ret == 3)
2683 return;
2684 if (ret == 1)
2686 CProgressDlg mergeProgress;
2687 mergeProgress.m_GitCmd = L"git.exe merge --ff-only " + upstream;
2688 mergeProgress.m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
2689 mergeProgress.m_PostCmdCallback = [](DWORD status, PostCmdList& postCmdList)
2691 if (status && g_Git.HasWorkingTreeConflicts())
2693 // there are conflict files
2694 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2696 CString sCmd;
2697 sCmd.Format(L"/command:commit /path:\"%s\"", g_Git.m_CurrentDir);
2698 CAppUtils::RunTortoiseGitProc(sCmd);
2702 mergeProgress.DoModal();
2703 return;
2707 CAppUtils::RebaseAfterFetch(upstream, runRebase, rebasePreserveMerges);
2710 return progress.DoModal() == IDOK;
2713 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2715 CPullFetchDlg dlg;
2716 dlg.m_PreSelectRemote = remoteName;
2717 dlg.m_IsPull=FALSE;
2718 dlg.m_bAllRemotes = allRemotes;
2720 if(dlg.DoModal()==IDOK)
2721 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);
2723 return false;
2726 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)
2728 CString error;
2729 DWORD exitcode = 0xFFFFFFFF;
2730 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2732 if (exitcode)
2734 CString temp;
2735 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2736 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2737 return false;
2741 int iRecurseSubmodules = 0;
2742 if (GetMsysgitVersion() >= 0x02070000)
2744 CString sRecurseSubmodules = g_Git.GetConfigValue(_T("push.recurseSubmodules"));
2745 if (sRecurseSubmodules == _T("check"))
2746 iRecurseSubmodules = 1;
2747 else if (sRecurseSubmodules == _T("on-demand"))
2748 iRecurseSubmodules = 2;
2751 CString arg;
2752 if (pack)
2753 arg += _T("--thin ");
2754 if (tags && !allBranches)
2755 arg += _T("--tags ");
2756 if (force)
2757 arg += _T("--force ");
2758 if (forceWithLease)
2759 arg += _T("--force-with-lease ");
2760 if (setUpstream)
2761 arg += _T("--set-upstream ");
2762 if (recurseSubmodules == 0 && recurseSubmodules != iRecurseSubmodules)
2763 arg += _T("--recurse-submodules=no ");
2764 if (recurseSubmodules == 1 && recurseSubmodules != iRecurseSubmodules)
2765 arg += _T("--recurse-submodules=check ");
2766 if (recurseSubmodules == 2 && recurseSubmodules != iRecurseSubmodules)
2767 arg += _T("--recurse-submodules=on-demand ");
2769 arg += _T("--progress ");
2771 CProgressDlg progress;
2773 STRING_VECTOR remotesList;
2774 if (allRemotes)
2775 g_Git.GetRemoteList(remotesList);
2776 else
2777 remotesList.push_back(remote);
2779 for (unsigned int i = 0; i < remotesList.size(); ++i)
2781 if (autoloadKey)
2782 CAppUtils::LaunchPAgent(nullptr, &remotesList[i]);
2784 CString cmd;
2785 if (allBranches)
2787 cmd.Format(_T("git.exe push --all %s\"%s\""),
2788 (LPCTSTR)arg,
2789 (LPCTSTR)remotesList[i]);
2791 if (tags)
2793 progress.m_GitCmdList.push_back(cmd);
2794 cmd.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR)arg, (LPCTSTR)remotesList[i]);
2797 else
2799 cmd.Format(_T("git.exe push %s\"%s\" %s"),
2800 (LPCTSTR)arg,
2801 (LPCTSTR)remotesList[i],
2802 (LPCTSTR)localBranch);
2803 if (!remoteBranch.IsEmpty())
2805 cmd += L":";
2806 cmd += remoteBranch;
2809 progress.m_GitCmdList.push_back(cmd);
2811 if (!allBranches && !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE))
2813 cmd.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR)localBranch);
2814 progress.m_GitCmdList.push_back(cmd);
2818 CString superprojectRoot;
2819 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2820 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2822 // need to execute hooks as those might be needed by post action commands
2823 DWORD exitcode = 0xFFFFFFFF;
2824 CString error;
2825 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2827 if (exitcode)
2829 CString temp;
2830 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2831 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2835 if (status)
2837 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2838 if (rejected)
2840 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, []{ Pull(true); });
2841 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(allRemotes ? _T("") : remote, allRemotes); });
2843 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2844 return;
2847 postCmdList.emplace_back(IDS_PROC_REQUESTPULL, [&]{ RequestPull(remoteBranch); });
2848 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2849 postCmdList.emplace_back(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); });
2850 if (!superprojectRoot.IsEmpty())
2852 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2854 CString sCmd;
2855 sCmd.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR)superprojectRoot);
2856 RunTortoiseGitProc(sCmd);
2861 INT_PTR ret = progress.DoModal();
2862 return ret == IDOK;
2865 bool CAppUtils::Push(const CString& selectLocalBranch)
2867 CPushDlg dlg;
2868 dlg.m_BranchSourceName = selectLocalBranch;
2870 if (dlg.DoModal() == IDOK)
2871 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);
2873 return FALSE;
2876 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2878 CRequestPullDlg dlg;
2879 dlg.m_RepositoryURL = repositoryUrl;
2880 dlg.m_EndRevision = endrevision;
2881 if (dlg.DoModal()==IDOK)
2883 CString cmd;
2884 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR)dlg.m_StartRevision, (LPCTSTR)dlg.m_RepositoryURL, (LPCTSTR)dlg.m_EndRevision);
2886 CSysProgressDlg sysProgressDlg;
2887 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2888 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2889 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2890 sysProgressDlg.SetShowProgressBar(false);
2891 sysProgressDlg.ShowModeless((HWND)nullptr, true);
2893 CString tempFileName = GetTempFile();
2894 CString err;
2895 DeleteFile(tempFileName);
2896 CreateDirectory(tempFileName, nullptr);
2897 tempFileName += _T("\\pullrequest.txt");
2898 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2900 CString msg;
2901 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2902 MessageBox(nullptr, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2903 return false;
2906 if (sysProgressDlg.HasUserCancelled())
2908 CMessageBox::Show(nullptr, IDS_USERCANCELLED, IDS_APPNAME, MB_OK);
2909 ::DeleteFile(tempFileName);
2910 return false;
2913 sysProgressDlg.Stop();
2915 if (dlg.m_bSendMail)
2917 CSendMailDlg sendmaildlg;
2918 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2919 sendmaildlg.m_bCustomSubject = true;
2921 if (sendmaildlg.DoModal() == IDOK)
2923 if (sendmaildlg.m_PathList.IsEmpty())
2924 return FALSE;
2926 CGitProgressDlg progDlg;
2927 if (bIsMainWnd)
2928 theApp.m_pMainWnd = &progDlg;
2929 SendMailProgressCommand sendMailProgressCommand;
2930 progDlg.SetCommand(&sendMailProgressCommand);
2932 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2933 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2935 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2936 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2938 progDlg.DoModal();
2940 return true;
2942 return false;
2945 CAppUtils::LaunchAlternativeEditor(tempFileName);
2947 return true;
2950 void CAppUtils::RemoveTrailSlash(CString &path)
2952 if(path.IsEmpty())
2953 return ;
2955 // For URL, do not trim the slash just after the host name component.
2956 int index = path.Find(_T("://"));
2957 if (index >= 0)
2959 index += 4;
2960 index = path.Find(_T('/'), index);
2961 if (index == path.GetLength() - 1)
2962 return;
2965 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2967 path.Truncate(path.GetLength() - 1);
2968 if(path.IsEmpty())
2969 return;
2973 bool CAppUtils::CheckUserData()
2975 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2977 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO | MB_ICONERROR) == IDYES)
2979 CTGitPath path(g_Git.m_CurrentDir);
2980 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2981 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2982 dlg.SetTreeWidth(220);
2983 dlg.m_DefaultPage = _T("gitconfig");
2985 dlg.DoModal();
2986 dlg.HandleRestart();
2989 else
2990 return false;
2993 return true;
2996 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
2997 CTGitPathList &pathList,
2998 CTGitPathList &selectedList,
2999 bool bSelectFilesForCommit)
3001 bool bFailed = true;
3003 if (!CheckUserData())
3004 return false;
3006 while (bFailed)
3008 bFailed = false;
3009 CCommitDlg dlg;
3010 dlg.m_sBugID = bugid;
3012 dlg.m_bWholeProject = bWholeProject;
3014 dlg.m_sLogMessage = sLogMsg;
3015 dlg.m_pathList = pathList;
3016 dlg.m_checkedPathList = selectedList;
3017 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
3018 if (dlg.DoModal() == IDOK)
3020 if (dlg.m_pathList.IsEmpty())
3021 return false;
3022 // if the user hasn't changed the list of selected items
3023 // we don't use that list. Because if we would use the list
3024 // of pre-checked items, the dialog would show different
3025 // checked items on the next startup: it would only try
3026 // to check the parent folder (which might not even show)
3027 // instead, we simply use an empty list and let the
3028 // default checking do its job.
3029 if (!dlg.m_pathList.IsEqual(pathList))
3030 selectedList = dlg.m_pathList;
3031 pathList = dlg.m_updatedPathList;
3032 sLogMsg = dlg.m_sLogMessage;
3033 bSelectFilesForCommit = true;
3035 switch (dlg.m_PostCmd)
3037 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3038 CAppUtils::SVNDCommit();
3039 break;
3040 case GIT_POSTCOMMIT_CMD_PUSH:
3041 CAppUtils::Push();
3042 break;
3043 case GIT_POSTCOMMIT_CMD_CREATETAG:
3044 CAppUtils::CreateBranchTag(TRUE);
3045 break;
3046 case GIT_POSTCOMMIT_CMD_PULL:
3047 CAppUtils::Pull(true);
3048 break;
3049 default:
3050 break;
3053 // CGitProgressDlg progDlg;
3054 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3055 // if (parser.HasVal(_T("closeonend")))
3056 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3057 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3058 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3059 // progDlg.SetPathList(dlg.m_pathList);
3060 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3061 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3062 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3063 // progDlg.SetItemCount(dlg.m_itemsCount);
3064 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3065 // progDlg.DoModal();
3066 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3067 // err = (DWORD)progDlg.DidErrorsOccur();
3068 // bFailed = progDlg.DidErrorsOccur();
3069 // bRet = progDlg.DidErrorsOccur();
3070 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3071 // if (DWORD(bFailRepeat)==0)
3072 // bFailed = false; // do not repeat if the user chose not to in the settings.
3075 return true;
3078 BOOL CAppUtils::SVNDCommit()
3080 CSVNDCommitDlg dcommitdlg;
3081 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
3082 if (gitSetting.IsEmpty()) {
3083 if (dcommitdlg.DoModal() != IDOK)
3084 return false;
3085 else
3087 if (dcommitdlg.m_remember)
3089 if (dcommitdlg.m_rmdir)
3090 gitSetting = _T("true");
3091 else
3092 gitSetting = _T("false");
3093 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
3095 CString msg;
3096 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
3097 CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3103 BOOL IsStash = false;
3104 if(!g_Git.CheckCleanWorkTree())
3106 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3108 CSysProgressDlg sysProgressDlg;
3109 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3110 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3111 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3112 sysProgressDlg.SetShowProgressBar(false);
3113 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3114 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3116 CString cmd,out;
3117 cmd=_T("git.exe stash");
3118 if (g_Git.Run(cmd, &out, CP_UTF8))
3120 sysProgressDlg.Stop();
3121 MessageBox(nullptr, out,_T("TortoiseGit"), MB_OK | MB_ICONERROR);
3122 return false;
3124 sysProgressDlg.Stop();
3126 IsStash =true;
3128 else
3129 return false;
3132 CProgressDlg progress;
3133 if (dcommitdlg.m_rmdir)
3134 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
3135 else
3136 progress.m_GitCmd=_T("git.exe svn dcommit");
3137 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3139 if( IsStash)
3141 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
3143 CSysProgressDlg sysProgressDlg;
3144 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3145 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3146 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3147 sysProgressDlg.SetShowProgressBar(false);
3148 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3149 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3151 CString cmd,out;
3152 cmd=_T("git.exe stash pop");
3153 if (g_Git.Run(cmd, &out, CP_UTF8))
3155 sysProgressDlg.Stop();
3156 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3157 return false;
3159 sysProgressDlg.Stop();
3161 else
3162 return false;
3164 return TRUE;
3166 return FALSE;
3169 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)
3171 CString args;
3172 if (noFF)
3173 args += L" --no-ff";
3174 else if (ffOnly)
3175 args += L" --ff-only";
3177 if (squash)
3178 args += L" --squash";
3180 if (noCommit)
3181 args += L" --no-commit";
3183 if (unrelated)
3184 args += L" --allow-unrelated-histories";
3186 if (log)
3187 args.AppendFormat(L" --log=%d", *log);
3189 if (!mergeStrategy.IsEmpty())
3191 args += L" --strategy=" + mergeStrategy;
3192 if (!strategyOption.IsEmpty())
3194 args += L" --strategy-option=" + strategyOption;
3195 if (!strategyParam.IsEmpty())
3196 args += L'=' + strategyParam;
3200 if (!logMessage.IsEmpty())
3202 CString logmsg = logMessage;
3203 logmsg.Replace(L"\\\"", L"\\\\\"");
3204 logmsg.Replace(L"\"", L"\\\"");
3205 args += L" -m \"" + logmsg + L"\"";
3208 CString mergeVersion = g_Git.FixBranchName(version);
3209 CString cmd;
3210 cmd.Format(L"git.exe merge%s %s", (LPCTSTR)args, (LPCTSTR)mergeVersion);
3212 CProgressDlg Prodlg;
3213 Prodlg.m_GitCmd = cmd;
3215 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3217 if (status)
3219 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3220 if (hasConflicts < 0)
3221 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
3222 else if (hasConflicts)
3224 // there are conflict files
3226 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3228 CString sCmd;
3229 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3230 CAppUtils::RunTortoiseGitProc(sCmd);
3234 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3236 CGitHash common;
3237 g_Git.IsFastForward(L"HEAD", mergeVersion, &common);
3238 if (common.IsEmpty())
3239 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoMerge(noFF, ffOnly, squash, noCommit, log, true, mergeStrategy, strategyOption, strategyParam, logMessage, version, isBranch, showStashPop); });
3242 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [=]{ CAppUtils::StashSave(L"", false, false, true, mergeVersion); });
3244 return;
3247 if (showStashPop)
3248 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
3250 if (noCommit)
3252 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3254 CString sCmd;
3255 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3256 CAppUtils::RunTortoiseGitProc(sCmd);
3258 return;
3261 if (isBranch && !CStringUtils::StartsWith(version, L"remotes/")) // do not ask to remove remote branches
3263 postCmdList.emplace_back(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3265 CString msg;
3266 msg.Format(IDS_PROC_DELETEBRANCHTAG, version);
3267 if (CMessageBox::Show(nullptr, msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3269 CString cmd, out;
3270 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)version);
3271 if (g_Git.Run(cmd, &out, CP_UTF8))
3272 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3276 if (isBranch)
3277 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
3279 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3280 if (hasGitSVN)
3281 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ CAppUtils::SVNDCommit(); });
3284 Prodlg.DoModal();
3285 return !Prodlg.m_GitStatus;
3288 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3290 if (!CheckUserData())
3291 return FALSE;
3293 if (IsTGitRebaseActive())
3294 return FALSE;
3296 CMergeDlg dlg;
3297 if (commit)
3298 dlg.m_initialRefName = *commit;
3300 if (dlg.DoModal() == IDOK)
3301 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);
3303 return FALSE;
3306 BOOL CAppUtils::MergeAbort()
3308 CMergeAbortDlg dlg;
3309 if (dlg.DoModal() == IDOK)
3310 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3312 return FALSE;
3315 void CAppUtils::EditNote(GitRevLoglist* rev)
3317 if (!CheckUserData())
3318 return;
3320 CInputDlg dlg;
3321 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3322 dlg.m_sInputText = rev->m_Notes;
3323 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3324 //dlg.m_pProjectProperties = &m_ProjectProperties;
3325 dlg.m_bUseLogWidth = true;
3326 if(dlg.DoModal() == IDOK)
3328 CString cmd,output;
3329 cmd=_T("notes add -f -F \"");
3331 CString tempfile=::GetTempFile();
3332 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3334 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3335 return;
3337 cmd += tempfile;
3338 cmd += _T("\" ");
3339 cmd += rev->m_CommitHash.ToString();
3343 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3344 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3345 else
3346 rev->m_Notes = dlg.m_sInputText;
3347 }catch(...)
3349 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3351 ::DeleteFile(tempfile);
3356 int CAppUtils::GetMsysgitVersion()
3358 if (g_Git.ms_LastMsysGitVersion)
3359 return g_Git.ms_LastMsysGitVersion;
3361 CString cmd;
3362 CString versiondebug;
3363 CString version;
3365 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3366 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3368 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3370 __int64 time=0;
3371 if (!CGit::GetFileModifyTime(gitpath, &time))
3373 if((DWORD)time == regTime)
3375 g_Git.ms_LastMsysGitVersion = regVersion;
3376 return regVersion;
3380 CString err;
3381 int ver = g_Git.GetGitVersion(&versiondebug, &err);
3382 if (ver < 0)
3384 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);
3385 return -1;
3389 if (!ver)
3391 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3392 return -1;
3396 regTime = time&0xFFFFFFFF;
3397 regVersion = ver;
3398 g_Git.ms_LastMsysGitVersion = ver;
3400 return ver;
3403 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3405 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3407 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3409 if (hShell.IsValid()) {
3410 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3411 if (pfnSHGPSFW) {
3412 IPropertyStore *pps;
3413 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3414 if (SUCCEEDED(hr)) {
3415 PROPVARIANT var;
3416 var.vt = VT_BOOL;
3417 var.boolVal = VARIANT_TRUE;
3418 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3419 pps->Release();
3425 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3427 ASSERT(dialogname.GetLength() < 70);
3428 ASSERT(urlorpath.GetLength() < MAX_PATH);
3429 WCHAR pathbuf[MAX_PATH] = {0};
3431 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3433 wcscat_s(pathbuf, L" - ");
3434 wcscat_s(pathbuf, dialogname);
3435 wcscat_s(pathbuf, L" - ");
3436 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3437 SetWindowText(hWnd, pathbuf);
3440 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3442 if (!g_Git.CheckCleanWorkTree())
3444 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3446 CSysProgressDlg sysProgressDlg;
3447 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3448 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3449 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3450 sysProgressDlg.SetShowProgressBar(false);
3451 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3452 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3454 CString cmd, out;
3455 cmd = _T("git.exe stash");
3456 if (g_Git.Run(cmd, &out, CP_UTF8))
3458 sysProgressDlg.Stop();
3459 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3460 return false;
3462 sysProgressDlg.Stop();
3464 else
3465 return false;
3468 CBisectStartDlg bisectStartDlg;
3470 if (!lastGood.IsEmpty())
3471 bisectStartDlg.m_sLastGood = lastGood;
3472 if (!firstBad.IsEmpty())
3473 bisectStartDlg.m_sFirstBad = firstBad;
3475 if (bisectStartDlg.DoModal() == IDOK)
3477 CProgressDlg progress;
3478 if (bIsMainWnd)
3479 theApp.m_pMainWnd = &progress;
3480 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3481 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3482 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3484 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3486 if (status)
3487 return;
3489 CTGitPath path(g_Git.m_CurrentDir);
3490 if (path.HasSubmodules())
3492 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3494 CString sCmd;
3495 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3496 CAppUtils::RunTortoiseGitProc(sCmd);
3501 INT_PTR ret = progress.DoModal();
3502 return ret == IDOK;
3505 return false;
3508 bool CAppUtils::BisectOperation(const CString& op, const CString& ref, bool bIsMainWnd)
3510 CString cmd = _T("git.exe bisect ") + op;
3512 if (!ref.IsEmpty())
3514 cmd += _T(" ");
3515 cmd += ref;
3518 CProgressDlg progress;
3519 if (bIsMainWnd)
3520 theApp.m_pMainWnd = &progress;
3521 progress.m_GitCmd = cmd;
3523 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3525 if (status)
3526 return;
3528 CTGitPath path = g_Git.m_CurrentDir;
3529 if (path.HasSubmodules())
3531 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3533 CString sCmd;
3534 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR)g_Git.m_CurrentDir);
3535 CAppUtils::RunTortoiseGitProc(sCmd);
3539 if (op != _T("reset"))
3540 postCmdList.emplace_back(IDS_MENUBISECTRESET, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3543 INT_PTR ret = progress.DoModal();
3544 return ret == IDOK;
3547 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3549 CUserPassword dlg;
3550 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3551 if (username_from_url)
3552 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3554 CStringA username, password;
3555 if (dlg.DoModal() == IDOK)
3557 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3558 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3559 return git_cred_userpass_plaintext_new(out, username, password);
3561 giterr_set_str(GITERR_NONE, "User cancelled.");
3562 return GIT_EUSER;
3565 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3567 if (base_cert->cert_type == GIT_CERT_X509)
3569 git_cert_x509* cert = (git_cert_x509*)base_cert;
3571 if (last_accepted_cert.cmp(cert))
3572 return 0;
3574 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3575 SCOPE_EXIT { CertFreeCertificateContext(pServerCert); };
3577 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3578 if (!verificationError)
3580 last_accepted_cert.set(cert);
3581 return 0;
3584 CString servernameInCert;
3585 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, CStrBuf(servernameInCert, 128), 128);
3587 CString issuer;
3588 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, CStrBuf(issuer, 128), 128);
3590 CCheckCertificateDlg dlg;
3591 dlg.cert = cert;
3592 dlg.m_sCertificateCN = servernameInCert;
3593 dlg.m_sCertificateIssuer = issuer;
3594 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3595 dlg.m_sError = CFormatMessageWrapper(verificationError);
3596 if (dlg.DoModal() == IDOK)
3598 last_accepted_cert.set(cert);
3599 return 0;
3602 return GIT_ECERTIFICATE;
3605 int CAppUtils::ExploreTo(HWND hwnd, CString path)
3607 if (PathFileExists(path))
3609 HRESULT ret = -1;
3610 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3611 if (pidl)
3613 ret = SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3614 ILFree(pidl);
3616 return SUCCEEDED(ret) ? 0 : -1;
3618 // if filepath does not exist any more, navigate to closest matching folder
3621 int pos = path.ReverseFind(_T('\\'));
3622 if (pos <= 3)
3623 break;
3624 path.Truncate(pos);
3625 } while (!PathFileExists(path));
3626 return (INT_PTR)ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW) > 32 ? 0 : -1;
3629 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3631 bool b_local = false, b_remote = false;
3632 BYTE_VECTOR vector;
3634 CString cmd;
3635 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3636 if (g_Git.Run(cmd, &vector))
3638 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK);
3639 return -1;
3642 CTGitPathList list;
3643 if (list.ParserFromLsFile(vector))
3645 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
3646 return -1;
3649 if (list.IsEmpty())
3650 return 0;
3651 for (int i = 0; i < list.GetCount(); ++i)
3653 if (list[i].m_Stage == 2)
3654 b_local = true;
3655 if (list[i].m_Stage == 3)
3656 b_remote = true;
3660 CBlockCacheForPath block(g_Git.m_CurrentDir);
3661 if (path.IsDirectory()) // is submodule conflict
3663 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.");
3664 if (b_local && b_remote)
3666 if (!path.HasAdminDir()) // check if submodule is initialized
3668 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).");
3669 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3670 return -1;
3672 CGit subgit;
3673 subgit.m_CurrentDir = g_Git.CombinePath(path);
3674 CGitHash submoduleHead;
3675 if (subgit.GetHash(submoduleHead, _T("HEAD")))
3677 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3678 return -1;
3680 CString baseHash, localHash, remoteHash;
3681 ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash);
3682 if (resolveWith == RESOLVE_WITH_THEIRS && submoduleHead.ToString() != remoteHash)
3684 CString origPath = g_Git.m_CurrentDir;
3685 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3686 if (!GitReset(&remoteHash))
3688 g_Git.m_CurrentDir = origPath;
3689 return -1;
3691 g_Git.m_CurrentDir = origPath;
3693 else if (resolveWith == RESOLVE_WITH_MINE && submoduleHead.ToString() != localHash)
3695 CString origPath = g_Git.m_CurrentDir;
3696 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3697 if (!GitReset(&localHash))
3699 g_Git.m_CurrentDir = origPath;
3700 return -1;
3702 g_Git.m_CurrentDir = origPath;
3705 else
3707 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3708 return -1;
3712 if (resolveWith == RESOLVE_WITH_THEIRS)
3714 CString gitcmd, output;
3715 if (b_local && b_remote)
3716 gitcmd.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3717 else if (b_remote)
3718 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3719 else if (b_local)
3720 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3721 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3723 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3724 return -1;
3727 else if (resolveWith == RESOLVE_WITH_MINE)
3729 CString gitcmd, output;
3730 if (b_local && b_remote)
3731 gitcmd.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3732 else if (b_local)
3733 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3734 else if (b_remote)
3735 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3736 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3738 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3739 return -1;
3743 if (b_local && b_remote && path.m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3745 CString gitcmd, output;
3746 gitcmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
3747 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3748 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3749 else
3751 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3752 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
3756 RemoveTempMergeFile(path);
3757 return 0;
3760 bool CAppUtils::ShellOpen(const CString& file, HWND hwnd /*= nullptr */)
3762 if ((INT_PTR)ShellExecute(hwnd, nullptr, file, nullptr, nullptr, SW_SHOW) > HINSTANCE_ERROR)
3763 return true;
3765 return ShowOpenWithDialog(file, hwnd);
3768 bool CAppUtils::ShowOpenWithDialog(const CString& file, HWND hwnd /*= nullptr */)
3770 OPENASINFO oi = { 0 };
3771 oi.pcszFile = file;
3772 oi.oaifInFlags = OAIF_EXEC;
3773 return SUCCEEDED(SHOpenWithDialog(hwnd, &oi));
3776 bool CAppUtils::IsTGitRebaseActive()
3778 CString adminDir;
3779 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3780 return false;
3782 if (!PathIsDirectory(adminDir + L"tgitrebase.active"))
3783 return false;
3785 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_REMOVESTALEBUTTON, IDS_ABORTBUTTON) == 2)
3786 return true;
3788 RemoveDirectory(adminDir + L"tgitrebase.active");
3790 return false;