Call GatherData after we loaded the conditions we want to show
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob0a11c21bf1011e7a2084221e08ab2c75811c5e05
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2017 - TortoiseGit
4 // Copyright (C) 2003-2011, 2013-2014 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 #include "MessageBox.h"
25 #include "registry.h"
26 #include "TGitPath.h"
27 #include "Git.h"
28 #include "UnicodeUtils.h"
29 #include "ExportDlg.h"
30 #include "ProgressDlg.h"
31 #include "GitAdminDir.h"
32 #include "ProgressDlg.h"
33 #include "BrowseFolder.h"
34 #include "DirFileEnum.h"
35 #include "CreateBranchTagDlg.h"
36 #include "GitSwitchDlg.h"
37 #include "ResetDlg.h"
38 #include "DeleteConflictDlg.h"
39 #include "ChangedDlg.h"
40 #include "SendMailDlg.h"
41 #include "GitProgressDlg.h"
42 #include "PushDlg.h"
43 #include "CommitDlg.h"
44 #include "MergeDlg.h"
45 #include "MergeAbortDlg.h"
46 #include "Hooks.h"
47 #include "..\Settings\Settings.h"
48 #include "InputDlg.h"
49 #include "SVNDCommitDlg.h"
50 #include "requestpulldlg.h"
51 #include "PullFetchDlg.h"
52 #include "RebaseDlg.h"
53 #include "PropKey.h"
54 #include "StashSave.h"
55 #include "IgnoreDlg.h"
56 #include "FormatMessageWrapper.h"
57 #include "SmartHandle.h"
58 #include "BisectStartDlg.h"
59 #include "SysProgressDlg.h"
60 #include "UserPassword.h"
61 #include "SendmailPatch.h"
62 #include "Globals.h"
63 #include "ProgressCommands/ResetProgressCommand.h"
64 #include "ProgressCommands/FetchProgressCommand.h"
65 #include "ProgressCommands/SendMailProgressCommand.h"
66 #include "CertificateValidationHelper.h"
67 #include "CheckCertificateDlg.h"
68 #include "SubmoduleResolveConflictDlg.h"
69 #include "GitDiff.h"
70 #include "../TGitCache/CacheInterface.h"
72 static struct last_accepted_cert {
73 BYTE* data;
74 size_t len;
76 last_accepted_cert()
77 : data(nullptr)
78 , len(0)
81 ~last_accepted_cert()
83 free(data);
85 boolean cmp(git_cert_x509* cert)
87 return len > 0 && len == cert->len && memcmp(data, cert->data, len) == 0;
89 void set(git_cert_x509* cert)
91 free(data);
92 len = cert->len;
93 if (len == 0)
95 data = nullptr;
96 return;
98 data = new BYTE[len];
99 memcpy(data, cert->data, len);
101 } last_accepted_cert;
103 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);
105 bool CAppUtils::StashSave(const CString& msg, bool showPull, bool pullShowPush, bool showMerge, const CString& mergeRev)
107 CStashSaveDlg dlg;
108 dlg.m_sMessage = msg;
109 if (dlg.DoModal() == IDOK)
111 CString cmd = L"git.exe stash save";
113 if (dlg.m_bIncludeUntracked)
114 cmd += L" --include-untracked";
115 else if (dlg.m_bAll)
116 cmd += L" --all";
118 if (!dlg.m_sMessage.IsEmpty())
120 CString message = dlg.m_sMessage;
121 message.Replace(L"\"", L"\"\"");
122 cmd += L" -- \"" + message + L'"';
125 CProgressDlg progress;
126 progress.m_GitCmd = cmd;
127 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
129 if (status)
130 return;
132 if (showPull)
133 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(pullShowPush, true); });
134 if (showMerge)
135 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ CAppUtils::Merge(&mergeRev, true); });
137 return (progress.DoModal() == IDOK);
139 return false;
142 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
144 CString cmd = L"git.exe stash apply ";
145 if (CStringUtils::StartsWith(ref, L"refs/"))
146 ref = ref.Mid(5);
147 if (CStringUtils::StartsWith(ref, L"stash{"))
148 ref = L"stash@" + ref.Mid(5);
149 cmd += ref;
151 CSysProgressDlg sysProgressDlg;
152 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
153 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
154 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
155 sysProgressDlg.SetShowProgressBar(false);
156 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
157 sysProgressDlg.ShowModeless((HWND)nullptr, true);
159 CString out;
160 int ret = g_Git.Run(cmd, &out, CP_UTF8);
162 sysProgressDlg.Stop();
164 bool hasConflicts = (out.Find(L"CONFLICT") >= 0);
165 if (ret && !(ret == 1 && hasConflicts))
166 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + L'\n' + out, L"TortoiseGit", MB_OK | MB_ICONERROR);
167 else
169 CString message;
170 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
171 if (hasConflicts)
172 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
173 if (showChanges)
175 if (CMessageBox::Show(nullptr, message + L'\n' + CString(MAKEINTRESOURCE(IDS_SEECHANGES)), L"TortoiseGit", MB_YESNO | MB_ICONINFORMATION) == IDYES)
177 CChangedDlg dlg;
178 dlg.m_pathList.AddPath(CTGitPath());
179 dlg.DoModal();
181 return true;
183 else
185 MessageBox(nullptr, message ,L"TortoiseGit", MB_OK | MB_ICONINFORMATION);
186 return true;
189 return false;
192 bool CAppUtils::StashPop(int showChanges /* = 1 */)
194 CString cmd = L"git.exe stash pop";
196 CSysProgressDlg sysProgressDlg;
197 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
198 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
199 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
200 sysProgressDlg.SetShowProgressBar(false);
201 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
202 sysProgressDlg.ShowModeless((HWND)nullptr, true);
204 CString out;
205 int ret = g_Git.Run(cmd, &out, CP_UTF8);
207 sysProgressDlg.Stop();
209 bool hasConflicts = (out.Find(L"CONFLICT") >= 0);
210 if (ret && !(ret == 1 && hasConflicts))
211 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + L'\n' + out, L"TortoiseGit", MB_OK | MB_ICONERROR);
212 else
214 CString message;
215 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
216 if (hasConflicts)
217 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
218 if (showChanges == 1 || (showChanges == 0 && hasConflicts))
220 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)
222 CChangedDlg dlg;
223 dlg.m_pathList.AddPath(CTGitPath());
224 dlg.DoModal();
226 return true;
228 else if (showChanges > 1)
230 MessageBox(nullptr, message, L"TortoiseGit", MB_OK | MB_ICONINFORMATION);
231 return true;
233 else if (showChanges == 0)
234 return true;
236 return false;
239 BOOL CAppUtils::StartExtMerge(bool bAlternative,
240 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
241 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
242 HWND resolveMsgHwnd, bool bDeleteBaseTheirsMineOnClose)
244 CRegString regCom = CRegString(L"Software\\TortoiseGit\\Merge");
245 CString ext = mergedfile.GetFileExtension();
246 CString com = regCom;
247 bool bInternal = false;
249 if (!ext.IsEmpty())
251 // is there an extension specific merge tool?
252 CRegString mergetool(L"Software\\TortoiseGit\\MergeTools\\" + ext.MakeLower());
253 if (!CString(mergetool).IsEmpty())
254 com = mergetool;
256 // is there a filename specific merge tool?
257 CRegString mergetool(L"Software\\TortoiseGit\\MergeTools\\." + mergedfile.GetFilename().MakeLower());
258 if (!CString(mergetool).IsEmpty())
259 com = mergetool;
261 if (bAlternative && !com.IsEmpty())
263 if (CStringUtils::StartsWith(com, L"#"))
264 com.Delete(0);
265 else
266 com.Empty();
269 if (com.IsEmpty() || CStringUtils::StartsWith(com, L"#"))
271 // Maybe we should use TortoiseIDiff?
272 if ((ext == L".jpg") || (ext == L".jpeg") ||
273 (ext == L".bmp") || (ext == L".gif") ||
274 (ext == L".png") || (ext == L".ico") ||
275 (ext == L".tif") || (ext == L".tiff") ||
276 (ext == L".dib") || (ext == L".emf") ||
277 (ext == L".cur"))
279 com = CPathUtils::GetAppDirectory() + L"TortoiseGitIDiff.exe";
280 com = L'"' + com + L'"';
281 com = com + L" /base:%base /theirs:%theirs /mine:%mine /result:%merged";
282 com = com + L" /basetitle:%bname /theirstitle:%tname /minetitle:%yname";
283 if (resolveMsgHwnd)
284 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
286 else
288 // use TortoiseGitMerge
289 bInternal = true;
290 com = CPathUtils::GetAppDirectory() + L"TortoiseGitMerge.exe";
291 com = L'"' + com + L'"';
292 com = com + L" /base:%base /theirs:%theirs /mine:%mine /merged:%merged";
293 com = com + L" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname";
294 com += L" /saverequired";
295 if (resolveMsgHwnd)
296 com.AppendFormat(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
297 if (bDeleteBaseTheirsMineOnClose)
298 com += L" /deletebasetheirsmineonclose";
300 if (!g_sGroupingUUID.IsEmpty())
302 com += L" /groupuuid:\"";
303 com += g_sGroupingUUID;
304 com += L'"';
307 // check if the params are set. If not, just add the files to the command line
308 if ((com.Find(L"%merged") < 0) && (com.Find(L"%base") < 0) && (com.Find(L"%theirs") < 0) && (com.Find(L"%mine") < 0))
310 com += L" \"" + basefile.GetWinPathString() + L'"';
311 com += L" \"" + theirfile.GetWinPathString() + L'"';
312 com += L" \"" + yourfile.GetWinPathString() + L'"';
313 com += L" \"" + mergedfile.GetWinPathString() + L'"';
315 if (basefile.IsEmpty())
317 com.Replace(L"/base:%base", L"");
318 com.Replace(L"%base", L"");
320 else
321 com.Replace(L"%base", L'"' + basefile.GetWinPathString() + L'"');
322 if (theirfile.IsEmpty())
324 com.Replace(L"/theirs:%theirs", L"");
325 com.Replace(L"%theirs", L"");
327 else
328 com.Replace(L"%theirs", L'"' + theirfile.GetWinPathString() + L'"');
329 if (yourfile.IsEmpty())
331 com.Replace(L"/mine:%mine", L"");
332 com.Replace(L"%mine", L"");
334 else
335 com.Replace(L"%mine", L'"' + yourfile.GetWinPathString() + L'"');
336 if (mergedfile.IsEmpty())
338 com.Replace(L"/merged:%merged", L"");
339 com.Replace(L"%merged", L"");
341 else
342 com.Replace(L"%merged", L'"' + mergedfile.GetWinPathString() + L'"');
343 if (basename.IsEmpty())
345 if (basefile.IsEmpty())
347 com.Replace(L"/basename:%bname", L"");
348 com.Replace(L"%bname", L"");
350 else
351 com.Replace(L"%bname", L'"' + basefile.GetUIFileOrDirectoryName() + L'"');
353 else
354 com.Replace(L"%bname", L'"' + basename + L'"');
355 if (theirname.IsEmpty())
357 if (theirfile.IsEmpty())
359 com.Replace(L"/theirsname:%tname", L"");
360 com.Replace(L"%tname", L"");
362 else
363 com.Replace(L"%tname", L'"' + theirfile.GetUIFileOrDirectoryName() + L'"');
365 else
366 com.Replace(L"%tname", L'"' + theirname + L'"');
367 if (yourname.IsEmpty())
369 if (yourfile.IsEmpty())
371 com.Replace(L"/minename:%yname", L"");
372 com.Replace(L"%yname", L"");
374 else
375 com.Replace(L"%yname", L'"' + yourfile.GetUIFileOrDirectoryName() + L'"');
377 else
378 com.Replace(L"%yname", L'"' + yourname + L'"');
379 if (mergedname.IsEmpty())
381 if (mergedfile.IsEmpty())
383 com.Replace(L"/mergedname:%mname", L"");
384 com.Replace(L"%mname", L"");
386 else
387 com.Replace(L"%mname", L'"' + mergedfile.GetUIFileOrDirectoryName() + L'"');
389 else
390 com.Replace(L"%mname", L'"' + mergedname + L'"');
392 com.Replace(L"%wtroot", L'"' + g_Git.m_CurrentDir + L'"');
394 if ((bReadOnly)&&(bInternal))
395 com += L" /readonly";
397 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
399 return FALSE;
402 return TRUE;
405 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
407 CString viewer;
408 // use TortoiseGitMerge
409 viewer = CPathUtils::GetAppDirectory();
410 viewer += L"TortoiseGitMerge.exe";
412 viewer = L'"' + viewer + L'"';
413 viewer = viewer + L" /diff:\"" + patchfile.GetWinPathString() + L'"';
414 viewer = viewer + L" /patchpath:\"" + dir.GetWinPathString() + L'"';
415 if (bReversed)
416 viewer += L" /reversedpatch";
417 if (!sOriginalDescription.IsEmpty())
418 viewer = viewer + L" /patchoriginal:\"" + sOriginalDescription + L'"';
419 if (!sPatchedDescription.IsEmpty())
420 viewer = viewer + L" /patchpatched:\"" + sPatchedDescription + L'"';
421 if (!g_sGroupingUUID.IsEmpty())
423 viewer += L" /groupuuid:\"";
424 viewer += g_sGroupingUUID;
425 viewer += L'"';
427 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
428 return FALSE;
429 return TRUE;
432 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
434 CString difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + file2.GetFilename().MakeLower());
435 if (!difftool.IsEmpty())
436 return difftool;
437 difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + file1.GetFilename().MakeLower());
438 if (!difftool.IsEmpty())
439 return difftool;
441 // Is there an extension specific diff tool?
442 CString ext = file2.GetFileExtension().MakeLower();
443 if (!ext.IsEmpty())
445 difftool = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + ext);
446 if (!difftool.IsEmpty())
447 return difftool;
448 // Maybe we should use TortoiseIDiff?
449 if ((ext == L".jpg") || (ext == L".jpeg") ||
450 (ext == L".bmp") || (ext == L".gif") ||
451 (ext == L".png") || (ext == L".ico") ||
452 (ext == L".tif") || (ext == L".tiff") ||
453 (ext == L".dib") || (ext == L".emf") ||
454 (ext == L".cur"))
456 return
457 L'"' + CPathUtils::GetAppDirectory() + L"TortoiseGitIDiff.exe" + L'"' +
458 L" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname" +
459 L" /groupuuid:\"" + g_sGroupingUUID + L'"';
463 // Finally, pick a generic external diff tool
464 difftool = CRegString(L"Software\\TortoiseGit\\Diff");
465 return difftool;
468 bool CAppUtils::StartExtDiff(
469 const CString& file1, const CString& file2,
470 const CString& sName1, const CString& sName2,
471 const CString& originalFile1, const CString& originalFile2,
472 const CString& hash1, const CString& hash2,
473 const DiffFlags& flags, int jumpToLine)
475 CString viewer;
477 CRegDWORD blamediff(L"Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge", FALSE);
478 if (!flags.bBlame || !(DWORD)blamediff)
480 viewer = PickDiffTool(file1, file2);
481 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
482 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
483 if (flags.bAlternativeTool)
485 // Invert external vs. internal diff tool selection.
486 if (bCommentedOut)
487 viewer.Delete(0); // uncomment
488 else
489 viewer.Empty();
491 else if (bCommentedOut)
492 viewer.Empty();
495 bool bInternal = viewer.IsEmpty();
496 if (bInternal)
498 viewer =
499 L'"' + CPathUtils::GetAppDirectory() + L"TortoiseGitMerge.exe" + L'"' +
500 L" /base:%base /mine:%mine /basename:%bname /minename:%yname" +
501 L" /basereflectedname:%bpath /minereflectedname:%ypath";
502 if (!g_sGroupingUUID.IsEmpty())
504 viewer += L" /groupuuid:\"";
505 viewer += g_sGroupingUUID;
506 viewer += L'"';
508 if (flags.bBlame)
509 viewer += L" /blame";
511 // check if the params are set. If not, just add the files to the command line
512 if ((viewer.Find(L"%base") < 0) && (viewer.Find(L"%mine") < 0))
514 viewer += L" \"" + file1 + L'"';
515 viewer += L" \"" + file2 + L'"';
517 if (viewer.Find(L"%base") >= 0)
518 viewer.Replace(L"%base", L'"' + file1 + L'"');
519 if (viewer.Find(L"%mine") >= 0)
520 viewer.Replace(L"%mine", L'"' + file2 + L'"');
522 if (sName1.IsEmpty())
523 viewer.Replace(L"%bname", L'"' + file1 + L'"');
524 else
525 viewer.Replace(L"%bname", L'"' + sName1 + L'"');
527 if (sName2.IsEmpty())
528 viewer.Replace(L"%yname", L'"' + file2 + L'"');
529 else
530 viewer.Replace(L"%yname", L'"' + sName2 + L'"');
532 viewer.Replace(L"%bpath", L'"' + originalFile1 + L'"');
533 viewer.Replace(L"%ypath", L'"' + originalFile2 + L'"');
535 viewer.Replace(L"%brev", L'"' + hash1 + L'"');
536 viewer.Replace(L"%yrev", L'"' + hash2 + L'"');
538 viewer.Replace(L"%wtroot", L'"' + g_Git.m_CurrentDir + L'"');
540 if (flags.bReadOnly && bInternal)
541 viewer += L" /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(L"Software\\TortoiseGit\\DiffViewer");
553 viewer = v;
555 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
556 bool bCommentedOut = CStringUtils::StartsWith(viewer, L"#");
557 if (bAlternativeTool)
559 // Invert external vs. internal diff tool selection.
560 if (bCommentedOut)
561 viewer.Delete(0); // uncomment
562 else
563 viewer.Empty();
565 else if (bCommentedOut)
566 viewer.Empty();
568 if (viewer.IsEmpty())
570 // use TortoiseGitUDiff
571 viewer = CPathUtils::GetAppDirectory();
572 viewer += L"TortoiseGitUDiff.exe";
573 // enquote the path to TortoiseGitUDiff
574 viewer = L'"' + viewer + L'"';
575 // add the params
576 viewer = viewer + L" /patchfile:%1 /title:\"%title\"";
577 if (!g_sGroupingUUID.IsEmpty())
579 viewer += L" /groupuuid:\"";
580 viewer += g_sGroupingUUID;
581 viewer += L'"';
584 if (viewer.Find(L"%1") >= 0)
586 if (viewer.Find(L"\"%1\"") >= 0)
587 viewer.Replace(L"%1", patchfile);
588 else
589 viewer.Replace(L"%1", L'"' + patchfile + L'"');
591 else
592 viewer += L" \"" + patchfile + L'"';
593 if (viewer.Find(L"%title") >= 0)
594 viewer.Replace(L"%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(L".txt\\", L"", FALSE, HKEY_CLASSES_ROOT);
605 viewer = txt;
606 viewer = viewer + L"\\Shell\\Open\\Command\\";
607 CRegString txtexe = CRegString(viewer, L"", 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 = L'"' + file + L'"';
619 if (viewer.IsEmpty())
620 return CAppUtils::ShowOpenWithDialog(file) ? TRUE : FALSE;
621 if (viewer.Find(L"\"%1\"") >= 0)
622 viewer.Replace(L"\"%1\"", file);
623 else if (viewer.Find(L"%1") >= 0)
624 viewer.Replace(L"%1", file);
625 else
626 viewer += L' ';
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, FILE_ATTRIBUTE_NORMAL, nullptr);
638 if (!hFile)
639 return TRUE;
640 length = ::GetFileSize(hFile, nullptr);
641 if (length < 4)
642 return TRUE;
643 return FALSE;
646 CString CAppUtils::GetLogFontName()
648 return (CString)CRegString(L"Software\\TortoiseGit\\LogFontName", L"Consolas");
651 DWORD CAppUtils::GetLogFontSize()
653 return (DWORD)CRegDWORD(L"Software\\TortoiseGit\\LogFontSize", 9);
656 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
658 LOGFONT logFont;
659 HDC hScreenDC = ::GetDC(nullptr);
660 logFont.lfHeight = -MulDiv(GetLogFontSize(), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
661 ::ReleaseDC(nullptr, hScreenDC);
662 logFont.lfWidth = 0;
663 logFont.lfEscapement = 0;
664 logFont.lfOrientation = 0;
665 logFont.lfWeight = FW_NORMAL;
666 logFont.lfItalic = 0;
667 logFont.lfUnderline = 0;
668 logFont.lfStrikeOut = 0;
669 logFont.lfCharSet = DEFAULT_CHARSET;
670 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
671 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
672 logFont.lfQuality = DRAFT_QUALITY;
673 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
674 wcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)GetLogFontName());
675 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
678 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
680 CString key,remote;
681 CString cmd,out;
682 if (!pRemote)
683 remote = L"origin";
684 else
685 remote=*pRemote;
687 if (!keyfile)
689 cmd.Format(L"remote.%s.puttykeyfile", (LPCTSTR)remote);
690 key = g_Git.GetConfigValue(cmd);
692 else
693 key=*keyfile;
695 if(key.IsEmpty())
696 return false;
698 CString proc=CPathUtils::GetAppDirectory();
699 proc += L"pageant.exe \"";
700 proc += key;
701 proc += L'"';
703 CString tempfile = GetTempFile();
704 ::DeleteFile(tempfile);
706 proc += L" -c \"";
707 proc += CPathUtils::GetAppDirectory();
708 proc += L"tgittouch.exe\"";
709 proc += L" \"";
710 proc += tempfile;
711 proc += L'"';
713 CString appDir = CPathUtils::GetAppDirectory();
714 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
715 if(!b)
716 return b;
718 int i=0;
719 while(!::PathFileExists(tempfile))
721 Sleep(100);
722 ++i;
723 if(i>10*60*5)
724 break; //timeout 5 minutes
727 if( i== 10*60*5)
728 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
729 ::DeleteFile(tempfile);
730 return true;
733 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
735 CString editTool = CRegString(L"Software\\TortoiseGit\\AlternativeEditor");
736 if (editTool.IsEmpty() || CStringUtils::StartsWith(editTool, L"#"))
737 editTool = CPathUtils::GetAppDirectory() + L"notepad2.exe";
739 CString sCmd;
740 sCmd.Format(L"\"%s\" \"%s\"", (LPCTSTR)editTool, (LPCTSTR)filename);
742 LaunchApplication(sCmd, 0, false, nullptr, uac);
743 return true;
746 bool CAppUtils::LaunchRemoteSetting()
748 CTGitPath path(g_Git.m_CurrentDir);
749 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
750 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
751 dlg.SetTreeWidth(220);
752 dlg.m_DefaultPage = L"gitremote";
754 dlg.DoModal();
755 dlg.HandleRestart();
756 return true;
760 * Launch the external blame viewer
762 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile, const CString& Rev, const CString& sParams)
764 CString viewer = L'"' + CPathUtils::GetAppDirectory();
765 viewer += L"TortoiseGitBlame.exe";
766 viewer += L"\" \"" + sBlameFile + L'"';
767 //viewer += L" \"" + sLogFile + L'"';
768 //viewer += L" \"" + sOriginalFile + L'"';
769 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
770 viewer += L" /rev:" + Rev;
771 if (!g_sGroupingUUID.IsEmpty())
773 viewer += L" /groupuuid:\"";
774 viewer += g_sGroupingUUID;
775 viewer += L'"';
777 viewer += L' ' + sParams;
779 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
782 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
784 CString sText;
785 if (!pWnd)
786 return false;
787 bool bStyled = false;
788 pWnd->GetWindowText(sText);
789 // the rich edit control doesn't count the CR char!
790 // to be exact: CRLF is treated as one char.
791 sText.Remove(L'\r');
793 // style each line separately
794 int offset = 0;
795 int nNewlinePos;
798 nNewlinePos = sText.Find('\n', offset);
799 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
801 int start = 0;
802 int end = 0;
803 while (FindStyleChars(sLine, '*', start, end))
805 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
806 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
807 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
808 bStyled = true;
809 start = end;
811 start = 0;
812 end = 0;
813 while (FindStyleChars(sLine, '^', start, end))
815 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
816 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
817 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
818 bStyled = true;
819 start = end;
821 start = 0;
822 end = 0;
823 while (FindStyleChars(sLine, '_', start, end))
825 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
826 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
827 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
828 bStyled = true;
829 start = end;
831 offset = nNewlinePos+1;
832 } while(nNewlinePos>=0);
833 return bStyled;
836 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
838 int i=start;
839 int last = sText.GetLength() - 1;
840 bool bFoundMarker = false;
841 TCHAR c = i == 0 ? L'\0' : sText[i - 1];
842 TCHAR nextChar = i >= last ? L'\0' : sText[i + 1];
844 // find a starting marker
845 while (i < last)
847 TCHAR prevChar = c;
848 c = nextChar;
849 nextChar = sText[i + 1];
851 // IsCharAlphaNumeric can be somewhat expensive.
852 // Long lines of "*****" or "----" will be pre-empted efficiently
853 // by the (c != nextChar) condition.
855 if ((c == stylechar) && (c != nextChar))
857 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
859 start = ++i;
860 bFoundMarker = true;
861 break;
864 ++i;
866 if (!bFoundMarker)
867 return false;
869 // find ending marker
870 // c == sText[i - 1]
872 bFoundMarker = false;
873 while (i <= last)
875 TCHAR prevChar = c;
876 c = sText[i];
877 if (c == stylechar)
879 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
881 end = i;
882 ++i;
883 bFoundMarker = true;
884 break;
887 ++i;
889 return bFoundMarker;
892 // from CSciEdit
893 namespace {
894 bool IsValidURLChar(wchar_t ch)
896 return iswalnum(ch) ||
897 ch == L'_' || ch == L'/' || ch == L';' || ch == L'?' || ch == L'&' || ch == L'=' ||
898 ch == L'%' || ch == L':' || ch == L'.' || ch == L'#' || ch == L'-' || ch == L'+' ||
899 ch == L'|' || ch == L'>' || ch == L'<' || ch == L'!' || ch == L'@' || ch == L'~';
902 bool IsUrlOrEmail(const CString& sText)
904 if (!PathIsURLW(sText))
906 auto atpos = sText.Find(L'@');
907 if (atpos <= 0)
908 return false;
909 if (sText.Find(L'.', atpos) <= atpos + 1) // a dot must follow after the @, but not directly after it
910 return false;
911 if (sText.Find(L':', atpos) < 0) // do not detect git@example.com:something as an email address
912 return true;
913 return false;
915 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" })
917 if (CStringUtils::StartsWith(sText, prefix) && sText.GetLength() != prefix.GetLength())
918 return true;
920 return false;
924 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
926 std::vector<CHARRANGE> positions = FindURLMatches(msg);
927 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
929 return positions.empty() ? FALSE : TRUE;
933 * implements URL searching with the same logic as CSciEdit::StyleURLs
935 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
937 std::vector<CHARRANGE> result;
939 int len = msg.GetLength();
940 int starturl = -1;
942 for (int i = 0; i <= msg.GetLength(); ++i)
944 if ((i < len) && IsValidURLChar(msg[i]))
946 if (starturl < 0)
947 starturl = i;
949 else
951 if (starturl >= 0)
953 bool strip = true;
954 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
956 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
957 ++starturl;
958 strip = false;
959 i = starturl;
960 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
961 ++i;
964 int skipTrailing = 0;
965 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] == '!'))
966 ++skipTrailing;
968 if (!IsUrlOrEmail(msg.Mid(starturl, i - starturl - skipTrailing)))
970 starturl = -1;
971 continue;
974 CHARRANGE range = { starturl, i - skipTrailing };
975 result.push_back(range);
977 starturl = -1;
981 return result;
984 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const CString& rev1,
985 const CTGitPath& /*url2*/, const CString& rev2,
986 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
987 bool bAlternateDiff /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
988 bool /* blame = false */,
989 bool bMerge,
990 bool bCombine,
991 bool bNoPrefix)
993 int diffContext = g_Git.GetConfigValueInt32(L"diff.context", -1);
994 CString tempfile=GetTempFile();
995 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext, bNoPrefix))
997 MessageBox(hWnd, g_Git.GetGitLastErr(L"Could not get unified diff.", CGit::GIT_CMD_DIFF), L"TortoiseGit", MB_OK);
998 return false;
1000 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1.IsEmpty() ? rev2 : rev1 + L':' + rev2, FALSE, bAlternateDiff);
1002 #if 0
1003 CString sCmd;
1004 sCmd.Format(L"%s /command:showcompare /unified",
1005 (LPCTSTR)(CPathUtils::GetAppDirectory()+L"TortoiseGitProc.exe"));
1006 sCmd += L" /url1:\"" + url1.GetGitPathString() + L'"';
1007 if (rev1.IsValid())
1008 sCmd += L" /revision1:" + rev1.ToString();
1009 sCmd += L" /url2:\"" + url2.GetGitPathString() + L'"';
1010 if (rev2.IsValid())
1011 sCmd += L" /revision2:" + rev2.ToString();
1012 if (peg.IsValid())
1013 sCmd += L" /pegrevision:" + peg.ToString();
1014 if (headpeg.IsValid())
1015 sCmd += L" /headpegrevision:" + headpeg.ToString();
1017 if (bAlternateDiff)
1018 sCmd += L" /alternatediff";
1020 if (bIgnoreAncestry)
1021 sCmd += L" /ignoreancestry";
1023 if (hWnd)
1025 sCmd += L" /hwnd:";
1026 TCHAR buf[30];
1027 swprintf_s(buf, 30, L"%p", (void*)hWnd);
1028 sCmd += buf;
1031 return CAppUtils::LaunchApplication(sCmd, 0, false);
1032 #endif
1033 return TRUE;
1036 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1038 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1039 scriptsdir += L"Diff-Scripts";
1040 CSimpleFileFind files(scriptsdir);
1041 while (files.FindNextFileNoDirectories())
1043 CString file = files.GetFilePath();
1044 CString filename = files.GetFileName();
1045 CString ext = file.Mid(file.ReverseFind('-') + 1);
1046 ext = L"." + ext.Left(ext.ReverseFind(L'.'));
1047 std::set<CString> extensions;
1048 extensions.insert(ext);
1049 CString kind;
1050 if (CStringUtils::EndsWithI(file, L"vbs"))
1051 kind = L" //E:vbscript";
1052 if (CStringUtils::EndsWithI(file, L"js"))
1053 kind = L" //E:javascript";
1054 // open the file, read the first line and find possible extensions
1055 // this script can handle
1058 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1059 CString extline;
1060 if (f.ReadString(extline))
1062 if ((extline.GetLength() > 15 ) &&
1063 (CStringUtils::StartsWith(extline, L"// extensions: ") ||
1064 CStringUtils::StartsWith(extline, L"' extensions: ")))
1066 if (extline[0] == '/')
1067 extline = extline.Mid(15);
1068 else
1069 extline = extline.Mid(14);
1070 CString sToken;
1071 int curPos = 0;
1072 sToken = extline.Tokenize(L";", curPos);
1073 while (!sToken.IsEmpty())
1075 if (!sToken.IsEmpty())
1077 if (sToken[0] != '.')
1078 sToken = L"." + sToken;
1079 extensions.insert(sToken);
1081 sToken = extline.Tokenize(L";", curPos);
1085 f.Close();
1087 catch (CFileException* e)
1089 e->Delete();
1092 for (const auto& extension : extensions)
1094 if (type.IsEmpty() || (type.Compare(L"Diff") == 0))
1096 if (CStringUtils::StartsWithI(filename, L"diff-"))
1098 CRegString diffreg = CRegString(L"Software\\TortoiseGit\\DiffTools\\" + extension);
1099 CString diffregstring = diffreg;
1100 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1101 diffreg = L"wscript.exe \"" + file + L"\" %base %mine" + kind;
1104 if (type.IsEmpty() || (type.Compare(L"Merge") == 0))
1106 if (CStringUtils::StartsWithI(filename, L"merge-"))
1108 CRegString diffreg = CRegString(L"Software\\TortoiseGit\\MergeTools\\" + extension);
1109 CString diffregstring = diffreg;
1110 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1111 diffreg = L"wscript.exe \"" + file + L"\" %merged %theirs %mine %base" + kind;
1117 return true;
1120 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1122 // ask from where the export has to be done
1123 CExportDlg dlg;
1124 if(BashHash)
1125 dlg.m_initialRefName=*BashHash;
1126 if (orgPath)
1128 if (PathIsRelative(orgPath->GetWinPath()))
1129 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1130 else
1131 dlg.m_orgPath = *orgPath;
1134 if (dlg.DoModal() == IDOK)
1136 CString cmd;
1137 cmd.Format(L"git.exe archive --output=\"%s\" --format=zip --verbose %s --",
1138 (LPCTSTR)dlg.m_strFile, (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName));
1140 CProgressDlg pro;
1141 pro.m_GitCmd=cmd;
1142 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1144 if (status)
1145 return;
1146 postCmdList.emplace_back(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); });
1149 CGit git;
1150 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1152 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1153 pro.m_Git = &git;
1155 return (pro.DoModal() == IDOK);
1157 return false;
1160 bool CAppUtils::UpdateBranchDescription(const CString& branch, CString description)
1162 if (branch.IsEmpty())
1163 return false;
1165 CString key;
1166 key.Format(L"branch.%s.description", (LPCTSTR)branch);
1167 description.Remove(L'\r');
1168 description.Trim();
1169 if (description.IsEmpty())
1170 g_Git.UnsetConfigValue(key);
1171 else
1172 g_Git.SetConfigValue(key, description);
1174 return true;
1177 bool CAppUtils::CreateBranchTag(bool isTag /*true*/, const CString* commitHash /*nullptr*/, bool switchNewBranch /*false*/, LPCTSTR name /*nullptr*/)
1179 CCreateBranchTagDlg dlg;
1180 dlg.m_bIsTag = isTag;
1181 dlg.m_bSwitch = switchNewBranch;
1183 if (commitHash)
1184 dlg.m_initialRefName = *commitHash;
1186 if (name)
1187 dlg.m_BranchTagName = name;
1189 if(dlg.DoModal()==IDOK)
1191 CString cmd;
1192 CString force;
1193 CString track;
1194 if(dlg.m_bTrack == TRUE)
1195 track = L"--track";
1196 else if(dlg.m_bTrack == FALSE)
1197 track = L"--no-track";
1199 if(dlg.m_bForce)
1200 force = L"-f";
1202 if (isTag)
1204 CString sign;
1205 if(dlg.m_bSign)
1206 sign = L"-s";
1208 cmd.Format(L"git.exe tag %s %s %s %s",
1209 (LPCTSTR)force,
1210 (LPCTSTR)sign,
1211 (LPCTSTR)dlg.m_BranchTagName,
1212 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1215 if(!dlg.m_Message.Trim().IsEmpty())
1217 CString tempfile = ::GetTempFile();
1218 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1220 MessageBox(nullptr, L"Could not save tag message", L"TortoiseGit", MB_OK | MB_ICONERROR);
1221 return FALSE;
1223 cmd += L" -F " + tempfile;
1226 else
1228 cmd.Format(L"git.exe branch %s %s %s %s",
1229 (LPCTSTR)track,
1230 (LPCTSTR)force,
1231 (LPCTSTR)dlg.m_BranchTagName,
1232 (LPCTSTR)g_Git.FixBranchName(dlg.m_VersionName)
1235 CString out;
1236 if(g_Git.Run(cmd,&out,CP_UTF8))
1238 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1239 return FALSE;
1241 if (!isTag && dlg.m_bSwitch)
1243 // it is a new branch and the user has requested to switch to it
1244 PerformSwitch(dlg.m_BranchTagName);
1246 if (!isTag && !dlg.m_Message.IsEmpty())
1247 UpdateBranchDescription(dlg.m_BranchTagName, dlg.m_Message);
1249 return TRUE;
1251 return FALSE;
1254 bool CAppUtils::Switch(const CString& initialRefName)
1256 CGitSwitchDlg dlg;
1257 if(!initialRefName.IsEmpty())
1258 dlg.m_initialRefName = initialRefName;
1260 if (dlg.DoModal() == IDOK)
1262 CString branch;
1263 if (dlg.m_bBranch)
1264 branch = dlg.m_NewBranch;
1266 // if refs/heads/ is not stripped, checkout will detach HEAD
1267 // checkout prefers branches on name clashes (with tags)
1268 if (CStringUtils::StartsWith(dlg.m_VersionName, L"refs/heads/") && dlg.m_bBranchOverride != TRUE)
1269 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1271 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1273 return FALSE;
1276 bool CAppUtils::PerformSwitch(const CString& ref, bool bForce /* false */, const CString& sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1278 CString cmd;
1279 CString track;
1280 CString force;
1281 CString branch;
1282 CString merge;
1284 if(!sNewBranch.IsEmpty()){
1285 if (bBranchOverride)
1286 branch.Format(L"-B %s ", (LPCTSTR)sNewBranch);
1287 else
1288 branch.Format(L"-b %s ", (LPCTSTR)sNewBranch);
1289 if (bTrack == TRUE)
1290 track = L"--track ";
1291 else if (bTrack == FALSE)
1292 track = L"--no-track ";
1294 if (bForce)
1295 force = L"-f ";
1296 if (bMerge)
1297 merge = L"--merge ";
1299 cmd.Format(L"git.exe checkout %s%s%s%s%s --",
1300 (LPCTSTR)force,
1301 (LPCTSTR)track,
1302 (LPCTSTR)merge,
1303 (LPCTSTR)branch,
1304 (LPCTSTR)g_Git.FixBranchName(ref));
1306 CProgressDlg progress;
1307 progress.m_GitCmd = cmd;
1309 CString currentBranch;
1310 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1311 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1313 if (!status)
1315 CTGitPath gitPath = g_Git.m_CurrentDir;
1316 if (gitPath.HasSubmodules())
1318 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1320 CString sCmd;
1321 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1322 RunTortoiseGitProc(sCmd);
1325 if (hasBranch)
1326 postCmdList.emplace_back(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); });
1329 CString newBranch;
1330 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1331 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); });
1333 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []{
1334 CTGitPathList pathlist;
1335 CTGitPathList selectedlist;
1336 pathlist.AddPath(CTGitPath());
1337 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(L"Software\\TortoiseGit\\SelectFilesForCommit", TRUE));
1338 CString str;
1339 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1342 else
1344 if (bMerge && g_Git.HasWorkingTreeConflicts() > 0)
1346 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
1348 CString sCmd;
1349 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1350 CAppUtils::RunTortoiseGitProc(sCmd);
1353 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); });
1354 if (!bMerge)
1355 postCmdList.emplace_back(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); });
1358 progress.m_PostExecCallback = [&](DWORD& exitCode, CString& extraMsg)
1360 if (bMerge && !exitCode && g_Git.HasWorkingTreeConflicts() > 0)
1362 exitCode = 1; // Treat it as failure
1363 extraMsg = L"Has merge conflict";
1367 INT_PTR ret = progress.DoModal();
1369 return ret == IDOK;
1372 class CIgnoreFile : public CStdioFile
1374 public:
1375 STRING_VECTOR m_Items;
1376 CString m_eol;
1378 virtual BOOL ReadString(CString& rString)
1380 if (GetPosition() == 0)
1382 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1383 char buf[3] = { 0, 0, 0 };
1384 Read(buf, 3);
1385 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1386 SeekToBegin();
1389 CStringA strA;
1390 char lastChar = '\0';
1391 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1393 if (c == '\r')
1394 continue;
1395 if (c == '\n')
1397 m_eol = lastChar == L'\r' ? L"\r\n" : L"\n";
1398 break;
1400 strA.AppendChar(c);
1402 if (strA.IsEmpty())
1403 return FALSE;
1405 rString = CUnicodeUtils::GetUnicode(strA);
1406 return TRUE;
1409 void ResetState()
1411 m_Items.clear();
1412 m_eol.Empty();
1416 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1418 file.ResetState();
1419 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1421 MessageBox(nullptr, filename + L" Open Failure", L"TortoiseGit", MB_OK | MB_ICONERROR);
1422 return false;
1425 if (file.GetLength() > 0)
1427 CString fileText;
1428 while (file.ReadString(fileText))
1429 file.m_Items.push_back(fileText);
1430 file.Seek(file.GetLength() - 1, 0);
1431 char lastchar[1] = { 0 };
1432 file.Read(lastchar, 1);
1433 file.SeekToEnd();
1434 if (lastchar[0] != '\n')
1436 CStringA eol = CStringA(file.m_eol.IsEmpty() ? L"\n" : file.m_eol);
1437 file.Write(eol, eol.GetLength());
1440 else
1441 file.SeekToEnd();
1443 return true;
1446 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1448 CIgnoreDlg ignoreDlg;
1449 if (ignoreDlg.DoModal() == IDOK)
1451 CString ignorefile;
1452 ignorefile = g_Git.m_CurrentDir + L'\\';
1454 switch (ignoreDlg.m_IgnoreFile)
1456 case 0:
1457 ignorefile += L".gitignore";
1458 break;
1459 case 2:
1460 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1461 ignorefile += L"info";
1462 if (!PathFileExists(ignorefile))
1463 CreateDirectory(ignorefile, nullptr);
1464 ignorefile += L"\\exclude";
1465 break;
1468 CIgnoreFile file;
1471 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1472 return false;
1474 for (int i = 0; i < path.GetCount(); ++i)
1476 if (ignoreDlg.m_IgnoreFile == 1)
1478 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + L"\\.gitignore";
1479 if (!OpenIgnoreFile(file, ignorefile))
1480 return false;
1483 CString ignorePattern;
1484 if (ignoreDlg.m_IgnoreType == 0)
1486 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1487 ignorePattern += L'/' + path[i].GetContainingDirectory().GetGitPathString();
1489 ignorePattern += L'/';
1491 if (IsMask)
1492 ignorePattern += L'*' + path[i].GetFileExtension();
1493 else
1494 ignorePattern += path[i].GetFileOrDirectoryName();
1496 // escape [ and ] so that files get ignored correctly
1497 ignorePattern.Replace(L"[", L"\\[");
1498 ignorePattern.Replace(L"]", L"\\]");
1500 bool found = false;
1501 for (size_t j = 0; j < file.m_Items.size(); ++j)
1503 if (file.m_Items[j] == ignorePattern)
1505 found = true;
1506 break;
1509 if (!found)
1511 file.m_Items.push_back(ignorePattern);
1512 ignorePattern += file.m_eol.IsEmpty() ? L"\n" : file.m_eol;
1513 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1514 file.Write(ignorePatternA, ignorePatternA.GetLength());
1517 if (ignoreDlg.m_IgnoreFile == 1)
1518 file.Close();
1521 if (ignoreDlg.m_IgnoreFile != 1)
1522 file.Close();
1524 catch(...)
1526 file.Abort();
1527 return false;
1530 return true;
1532 return false;
1535 static bool Reset(const CString& resetTo, int resetType)
1537 CString cmd;
1538 CString type;
1539 switch (resetType)
1541 case 0:
1542 type = L"--soft";
1543 break;
1544 case 1:
1545 type = L"--mixed";
1546 break;
1547 case 2:
1548 type = L"--hard";
1549 break;
1550 default:
1551 resetType = 1;
1552 type = L"--mixed";
1553 break;
1555 cmd.Format(L"git.exe reset %s %s --", (LPCTSTR)type, (LPCTSTR)resetTo);
1557 CProgressDlg progress;
1558 progress.m_GitCmd = cmd;
1560 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1562 if (status)
1564 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); });
1565 return;
1568 CTGitPath gitPath = g_Git.m_CurrentDir;
1569 if (gitPath.HasSubmodules() && resetType == 2)
1571 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1573 CString sCmd;
1574 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
1575 CAppUtils::RunTortoiseGitProc(sCmd);
1580 INT_PTR ret;
1581 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1583 CGitProgressDlg gitdlg;
1584 ResetProgressCommand resetProgressCommand;
1585 gitdlg.SetCommand(&resetProgressCommand);
1586 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1587 resetProgressCommand.SetRevision(resetTo);
1588 resetProgressCommand.SetResetType(resetType);
1589 ret = gitdlg.DoModal();
1591 else
1592 ret = progress.DoModal();
1594 return ret == IDOK;
1597 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1599 CResetDlg dlg;
1600 dlg.m_ResetType=type;
1601 dlg.m_ResetToVersion=*CommitHash;
1602 dlg.m_initialRefName = *CommitHash;
1603 if (dlg.DoModal() == IDOK)
1604 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1606 return false;
1609 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1611 if(mode == FALSE)
1613 descript.LoadString(IDS_SVNACTION_DELETE);
1614 return;
1616 if(base)
1618 descript.LoadString(IDS_SVNACTION_MODIFIED);
1619 return;
1621 descript.LoadString(IDS_PROC_CREATED);
1624 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1626 ::DeleteFile(CAppUtils::GetMergeTempFile(L"LOCAL", path));
1627 ::DeleteFile(CAppUtils::GetMergeTempFile(L"REMOTE", path));
1628 ::DeleteFile(CAppUtils::GetMergeTempFile(L"BASE", path));
1630 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1632 CString file;
1633 file = g_Git.CombinePath(merge.GetWinPathString() + L'.' + type + merge.GetFileExtension());
1635 return file;
1638 bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, CString& hash2, CString& hash3)
1640 size_t pos = 0;
1641 CString one;
1642 CString part;
1644 while (pos < out.size())
1646 one.Empty();
1648 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1649 int tabstart = 0;
1650 one.Tokenize(L"\t", tabstart);
1652 tabstart = 0;
1653 part = one.Tokenize(L" ", tabstart); //Tag
1654 part = one.Tokenize(L" ", tabstart); //Mode
1655 part = one.Tokenize(L" ", tabstart); //Hash
1656 CString hash = part;
1657 part = one.Tokenize(L"\t", tabstart); //Stage
1658 int stage = _wtol(part);
1659 if (stage == 1)
1660 hash1 = hash;
1661 else if (stage == 2)
1662 hash2 = hash;
1663 else if (stage == 3)
1665 hash3 = hash;
1666 return true;
1669 pos = out.findNextString(pos);
1672 return false;
1675 bool CAppUtils::ConflictEdit(CTGitPath& path, bool bAlternativeTool /*= false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1677 bool bRet = false;
1679 CTGitPath merge=path;
1680 CTGitPath directory = merge.GetDirectory();
1682 // we have the conflicted file (%merged)
1683 // now look for the other required files
1684 //GitStatus stat;
1685 //stat.GetStatus(merge);
1686 //if (stat.status == nullptr)
1687 // return false;
1689 BYTE_VECTOR vector;
1691 CString cmd;
1692 cmd.Format(L"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
1694 if (g_Git.Run(cmd, &vector))
1695 return FALSE;
1697 if (merge.IsDirectory())
1699 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1700 if (merge.HasAdminDir()) {
1701 CGit subgit;
1702 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1703 CGitHash hash;
1704 subgit.GetHash(hash, L"HEAD");
1705 baseHash = hash;
1707 if (ParseHashesFromLsFile(vector, realBaseHash, localHash, remoteHash)) // in base no submodule, but in remote submodule
1708 baseHash = realBaseHash;
1710 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1711 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1713 bool baseOK = false, mineOK = false, theirsOK = false;
1714 CString baseSubject, mineSubject, theirsSubject;
1715 if (merge.HasAdminDir())
1717 CGit subgit;
1718 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1719 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1720 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1722 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)
1724 changeTypeMine = CGitDiff::Identical;
1725 changeTypeTheirs = CGitDiff::NewSubmodule;
1726 baseSubject = L"no submodule";
1727 mineSubject = baseSubject;
1728 theirsSubject = L"not initialized";
1730 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
1732 baseHash = localHash;
1733 baseSubject = L"not initialized";
1734 mineSubject = baseSubject;
1735 theirsSubject = L"not initialized";
1736 changeTypeMine = CGitDiff::Identical;
1737 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1739 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
1741 baseSubject = L"not initialized";
1742 mineSubject = baseSubject;
1743 theirsSubject = baseSubject;
1744 if (baseHash == localHash)
1745 changeTypeMine = CGitDiff::Identical;
1747 else
1748 return FALSE;
1750 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1751 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), revertTheirMy, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1752 resolveSubmoduleConflictDialog.DoModal();
1753 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1755 static UINT WM_REVERTMSG = RegisterWindowMessage(L"GITSLNM_NEEDSREFRESH");
1756 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1759 return TRUE;
1762 CTGitPathList list;
1763 if (list.ParserFromLsFile(vector))
1765 MessageBox(nullptr, L"Parse ls-files failed!", L"TortoiseGit", MB_OK | MB_ICONERROR);
1766 return FALSE;
1769 if (list.IsEmpty())
1770 return FALSE;
1772 CTGitPath theirs;
1773 CTGitPath mine;
1774 CTGitPath base;
1776 if (revertTheirMy)
1778 mine.SetFromGit(GetMergeTempFile(L"REMOTE", merge));
1779 theirs.SetFromGit(GetMergeTempFile(L"LOCAL", merge));
1781 else
1783 mine.SetFromGit(GetMergeTempFile(L"LOCAL", merge));
1784 theirs.SetFromGit(GetMergeTempFile(L"REMOTE", merge));
1786 base.SetFromGit(GetMergeTempFile(L"BASE",merge));
1788 CString format;
1790 //format=L"git.exe cat-file blob \":%d:%s\"";
1791 format = L"git.exe checkout-index --temp --stage=%d -- \"%s\"";
1792 CFile tempfile;
1793 //create a empty file, incase stage is not three
1794 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1795 tempfile.Close();
1796 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1797 tempfile.Close();
1798 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1799 tempfile.Close();
1801 bool b_base=false, b_local=false, b_remote=false;
1803 for (int i = 0; i< list.GetCount(); ++i)
1805 CString outfile;
1806 cmd.Empty();
1807 outfile.Empty();
1809 if( list[i].m_Stage == 1)
1811 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1812 b_base = true;
1813 outfile = base.GetWinPathString();
1816 if( list[i].m_Stage == 2 )
1818 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1819 b_local = true;
1820 outfile = mine.GetWinPathString();
1823 if( list[i].m_Stage == 3 )
1825 cmd.Format(format, list[i].m_Stage, (LPCTSTR)list[i].GetGitPathString());
1826 b_remote = true;
1827 outfile = theirs.GetWinPathString();
1829 CString output, err;
1830 if(!outfile.IsEmpty())
1831 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1833 CString file;
1834 int start =0 ;
1835 file = output.Tokenize(L"\t", start);
1836 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1838 else
1839 CMessageBox::Show(nullptr, output + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
1842 if(b_local && b_remote )
1844 merge.SetFromWin(g_Git.CombinePath(merge));
1845 if( revertTheirMy )
1846 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, mine, theirs, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1847 else
1848 bRet = !!CAppUtils::StartExtMerge(bAlternativeTool, base, theirs, mine, merge, L"BASE", L"REMOTE", L"LOCAL", CString(), false, resolveMsgHwnd, true);
1850 else
1852 ::DeleteFile(mine.GetWinPathString());
1853 ::DeleteFile(theirs.GetWinPathString());
1854 ::DeleteFile(base.GetWinPathString());
1856 CDeleteConflictDlg dlg;
1857 if (!revertTheirMy)
1859 DescribeConflictFile(b_local, b_base, dlg.m_LocalStatus);
1860 DescribeConflictFile(b_remote, b_base, dlg.m_RemoteStatus);
1861 CGitHash localHash, remoteHash;
1862 if (!g_Git.GetHash(localHash, L"HEAD"))
1863 dlg.m_LocalHash = localHash.ToString();
1864 if (!g_Git.GetHash(remoteHash, L"MERGE_HEAD"))
1865 dlg.m_RemoteHash = remoteHash.ToString();
1866 else if (!g_Git.GetHash(remoteHash, L"rebase-apply/original-commit"))
1867 dlg.m_RemoteHash = remoteHash.ToString();
1868 else if (!g_Git.GetHash(remoteHash, L"CHERRY_PICK_HEAD"))
1869 dlg.m_RemoteHash = remoteHash.ToString();
1870 else if (!g_Git.GetHash(remoteHash, L"REVERT_HEAD"))
1871 dlg.m_RemoteHash = remoteHash.ToString();
1873 else
1875 DescribeConflictFile(b_local, b_base, dlg.m_RemoteStatus);
1876 DescribeConflictFile(b_remote, b_base, dlg.m_LocalStatus);
1877 CGitHash localHash, remoteHash;
1878 if (!g_Git.GetHash(remoteHash, L"HEAD"))
1879 dlg.m_RemoteHash = remoteHash.ToString();
1880 if (!g_Git.GetHash(localHash, L"MERGE_HEAD"))
1881 dlg.m_LocalHash = localHash.ToString();
1882 else if (!g_Git.GetHash(localHash, L"rebase-apply/original-commit"))
1883 dlg.m_LocalHash = localHash.ToString();
1884 else if (!g_Git.GetHash(localHash, L"CHERRY_PICK_HEAD"))
1885 dlg.m_LocalHash = localHash.ToString();
1886 else if (!g_Git.GetHash(localHash, L"REVERT_HEAD"))
1887 dlg.m_LocalHash = localHash.ToString();
1889 dlg.m_bShowModifiedButton = b_base;
1890 dlg.m_File=merge.GetGitPathString();
1891 if(dlg.DoModal() == IDOK)
1893 CString out;
1894 if(dlg.m_bIsDelete)
1895 cmd.Format(L"git.exe rm -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
1896 else
1897 cmd.Format(L"git.exe add -- \"%s\"", (LPCTSTR)merge.GetGitPathString());
1899 if (g_Git.Run(cmd, &out, CP_UTF8))
1901 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
1902 return FALSE;
1904 if (!dlg.m_bIsDelete)
1906 path.m_Action |= CTGitPath::LOGACTIONS_ADDED;
1907 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
1909 return TRUE;
1911 else
1912 return FALSE;
1915 #if 0
1916 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1917 base, theirs, mine, merge);
1918 #endif
1919 #if 0
1920 if (stat.status->text_status == svn_wc_status_conflicted)
1922 // we have a text conflict, use our merge tool to resolve the conflict
1924 CTSVNPath theirs(directory);
1925 CTSVNPath mine(directory);
1926 CTSVNPath base(directory);
1927 bool bConflictData = false;
1929 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1931 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1932 bConflictData = true;
1934 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1936 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1937 bConflictData = true;
1939 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1941 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1942 bConflictData = true;
1944 else
1945 mine = merge;
1946 if (bConflictData)
1947 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1948 base, theirs, mine, merge);
1951 if (stat.status->prop_status == svn_wc_status_conflicted)
1953 // we have a property conflict
1954 CTSVNPath prej(directory);
1955 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1957 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1958 // there's a problem: the prej file contains a _description_ of the conflict, and
1959 // that description string might be translated. That means we have no way of parsing
1960 // the file to find out the conflicting values.
1961 // The only thing we can do: show a dialog with the conflict description, then
1962 // let the user either accept the existing property or open the property edit dialog
1963 // to manually change the properties and values. And a button to mark the conflict as
1964 // resolved.
1965 CEditPropConflictDlg dlg;
1966 dlg.SetPrejFile(prej);
1967 dlg.SetConflictedItem(merge);
1968 bRet = (dlg.DoModal() != IDCANCEL);
1972 if (stat.status->tree_conflict)
1974 // we have a tree conflict
1975 SVNInfo info;
1976 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1977 if (pInfoData)
1979 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1981 CTSVNPath theirs(directory);
1982 CTSVNPath mine(directory);
1983 CTSVNPath base(directory);
1984 bool bConflictData = false;
1986 if (pInfoData->treeconflict_theirfile)
1988 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1989 bConflictData = true;
1991 if (pInfoData->treeconflict_basefile)
1993 base.AppendPathString(pInfoData->treeconflict_basefile);
1994 bConflictData = true;
1996 if (pInfoData->treeconflict_myfile)
1998 mine.AppendPathString(pInfoData->treeconflict_myfile);
1999 bConflictData = true;
2001 else
2002 mine = merge;
2003 if (bConflictData)
2004 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
2005 base, theirs, mine, merge);
2007 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
2009 CString sConflictAction;
2010 CString sConflictReason;
2011 CString sResolveTheirs;
2012 CString sResolveMine;
2013 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
2014 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
2016 if (pInfoData->treeconflict_nodekind == svn_node_file)
2018 switch (pInfoData->treeconflict_operation)
2020 case svn_wc_operation_update:
2021 switch (pInfoData->treeconflict_action)
2023 case svn_wc_conflict_action_edit:
2024 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
2025 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2026 break;
2027 case svn_wc_conflict_action_add:
2028 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
2029 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2030 break;
2031 case svn_wc_conflict_action_delete:
2032 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
2033 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2034 break;
2036 break;
2037 case svn_wc_operation_switch:
2038 switch (pInfoData->treeconflict_action)
2040 case svn_wc_conflict_action_edit:
2041 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
2042 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2043 break;
2044 case svn_wc_conflict_action_add:
2045 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
2046 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2047 break;
2048 case svn_wc_conflict_action_delete:
2049 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
2050 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2051 break;
2053 break;
2054 case svn_wc_operation_merge:
2055 switch (pInfoData->treeconflict_action)
2057 case svn_wc_conflict_action_edit:
2058 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
2059 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2060 break;
2061 case svn_wc_conflict_action_add:
2062 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
2063 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2064 break;
2065 case svn_wc_conflict_action_delete:
2066 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
2067 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2068 break;
2070 break;
2073 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
2075 switch (pInfoData->treeconflict_operation)
2077 case svn_wc_operation_update:
2078 switch (pInfoData->treeconflict_action)
2080 case svn_wc_conflict_action_edit:
2081 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
2082 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2083 break;
2084 case svn_wc_conflict_action_add:
2085 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
2086 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2087 break;
2088 case svn_wc_conflict_action_delete:
2089 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
2090 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2091 break;
2093 break;
2094 case svn_wc_operation_switch:
2095 switch (pInfoData->treeconflict_action)
2097 case svn_wc_conflict_action_edit:
2098 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
2099 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2100 break;
2101 case svn_wc_conflict_action_add:
2102 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
2103 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2104 break;
2105 case svn_wc_conflict_action_delete:
2106 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
2107 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2108 break;
2110 break;
2111 case svn_wc_operation_merge:
2112 switch (pInfoData->treeconflict_action)
2114 case svn_wc_conflict_action_edit:
2115 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
2116 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2117 break;
2118 case svn_wc_conflict_action_add:
2119 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
2120 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2121 break;
2122 case svn_wc_conflict_action_delete:
2123 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
2124 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2125 break;
2127 break;
2131 UINT uReasonID = 0;
2132 switch (pInfoData->treeconflict_reason)
2134 case svn_wc_conflict_reason_edited:
2135 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
2136 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2137 break;
2138 case svn_wc_conflict_reason_obstructed:
2139 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
2140 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2141 break;
2142 case svn_wc_conflict_reason_deleted:
2143 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
2144 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2145 break;
2146 case svn_wc_conflict_reason_added:
2147 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
2148 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2149 break;
2150 case svn_wc_conflict_reason_missing:
2151 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
2152 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2153 break;
2154 case svn_wc_conflict_reason_unversioned:
2155 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
2156 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2157 break;
2159 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
2161 CTreeConflictEditorDlg dlg;
2162 dlg.SetConflictInfoText(sConflictReason);
2163 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
2164 dlg.SetPath(treeConflictPath);
2165 INT_PTR dlgRet = dlg.DoModal();
2166 bRet = (dlgRet != IDCANCEL);
2170 #endif
2171 return bRet;
2174 bool CAppUtils::IsSSHPutty()
2176 CString sshclient = g_Git.m_Environment.GetEnv(L"GIT_SSH");
2177 sshclient=sshclient.MakeLower();
2178 return sshclient.Find(L"plink", 0) >= 0;
2181 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2183 if (!OpenClipboard(nullptr))
2184 return CString();
2186 CString sClipboardText;
2187 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2188 if (hglb)
2190 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2191 sClipboardText = CString(lpstr);
2192 GlobalUnlock(hglb);
2194 hglb = GetClipboardData(CF_UNICODETEXT);
2195 if (hglb)
2197 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2198 sClipboardText = lpstr;
2199 GlobalUnlock(hglb);
2201 CloseClipboard();
2203 if(!sClipboardText.IsEmpty())
2205 if (sClipboardText[0] == L'"' && sClipboardText[sClipboardText.GetLength() - 1] == L'"')
2206 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2208 for (const CString& prefix : { L"http://", L"https://", L"git://", L"ssh://", L"git@" })
2210 if (CStringUtils::StartsWith(sClipboardText, prefix) && sClipboardText.GetLength() != prefix.GetLength())
2211 return sClipboardText;
2214 if(sClipboardText.GetLength()>=2)
2215 if (sClipboardText[1] == L':')
2216 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2217 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2218 return sClipboardText;
2220 // trim prefixes like "git clone "
2221 if (!skipGitPrefix.IsEmpty() && CStringUtils::StartsWith(sClipboardText, skipGitPrefix))
2223 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2224 int spacePos = -1;
2225 while (paramsCount >= 0)
2227 --paramsCount;
2228 spacePos = sClipboardText.Find(L' ', spacePos + 1);
2229 if (spacePos == -1)
2230 break;
2232 if (spacePos > 0 && paramsCount < 0)
2233 sClipboardText.Truncate(spacePos);
2234 return sClipboardText;
2238 return CString();
2241 CString CAppUtils::ChooseRepository(const CString* path)
2243 CBrowseFolder browseFolder;
2244 CRegString regLastResopitory = CRegString(L"Software\\TortoiseGit\\TortoiseProc\\LastRepo", L"");
2246 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2247 CString strCloneDirectory;
2248 if(path)
2249 strCloneDirectory=*path;
2250 else
2251 strCloneDirectory = regLastResopitory;
2253 CString title;
2254 title.LoadString(IDS_CHOOSE_REPOSITORY);
2256 browseFolder.SetInfo(title);
2258 if (browseFolder.Show(nullptr, strCloneDirectory) == CBrowseFolder::OK)
2260 regLastResopitory = strCloneDirectory;
2261 return strCloneDirectory;
2263 else
2264 return CString();
2267 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2269 CSendMailDlg dlg;
2271 dlg.m_PathList = list;
2273 if(dlg.DoModal()==IDOK)
2275 if (dlg.m_PathList.IsEmpty())
2276 return FALSE;
2278 CGitProgressDlg progDlg;
2279 if (bIsMainWnd)
2280 theApp.m_pMainWnd = &progDlg;
2281 SendMailProgressCommand sendMailProgressCommand;
2282 progDlg.SetCommand(&sendMailProgressCommand);
2284 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2285 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2287 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2288 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2290 progDlg.DoModal();
2292 return true;
2294 return false;
2297 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2299 CTGitPathList list;
2300 CString log=formatpatchoutput;
2301 int start=log.Find(cmd);
2302 if(start >=0)
2303 log.Tokenize(L"\n", start);
2304 else
2305 start = 0;
2307 while(start>=0)
2309 CString one = log.Tokenize(L"\n", start);
2310 one=one.Trim();
2311 if (one.IsEmpty() || CStringUtils::StartsWith(one, CString(MAKEINTRESOURCE(IDS_SUCCESS))))
2312 continue;
2313 one.Replace(L'/', L'\\');
2314 CTGitPath path;
2315 path.SetFromWin(one);
2316 list.AddPath(path);
2318 if (!list.IsEmpty())
2319 return SendPatchMail(list, bIsMainWnd);
2320 else
2322 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2323 return true;
2328 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2330 CString output;
2331 output = pGit->GetConfigValue(L"i18n.logOutputEncoding");
2332 if(output.IsEmpty())
2333 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(L"i18n.commitencoding"));
2334 else
2335 return CUnicodeUtils::GetCPCode(output);
2337 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2341 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2342 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(L"i18n.commitencoding"));
2344 bool stripComments = (CRegDWORD(L"Software\\TortoiseGit\\StripCommentedLines", FALSE) == TRUE);
2345 TCHAR commentChar = L'#';
2346 if (stripComments)
2348 CString commentCharValue = g_Git.GetConfigValue(L"core.commentchar");
2349 if (!commentCharValue.IsEmpty())
2350 commentChar = commentCharValue[0];
2353 bool sanitize = (CRegDWORD(L"Software\\TortoiseGit\\SanitizeCommitMsg", TRUE) == TRUE);
2354 if (sanitize)
2355 message.Trim(L" \r\n");
2357 int len = message.GetLength();
2358 int start = 0;
2359 int emptyLineCnt = 0;
2360 while (start >= 0 && start < len)
2362 int oldStart = start;
2363 start = message.Find(L'\n', oldStart);
2364 CString line = message.Mid(oldStart);
2365 if (start != -1)
2367 line.Truncate(start - oldStart);
2368 ++start; // move forward so we don't find the same char again
2370 if (stripComments && (!line.IsEmpty() && line.GetAt(0) == commentChar) || (start < 0 && line.IsEmpty()))
2371 continue;
2372 line.TrimRight(L" \r");
2373 if (sanitize)
2375 if (line.IsEmpty())
2377 ++emptyLineCnt;
2378 continue;
2380 if (emptyLineCnt) // squash multiple newlines
2381 file.Write("\n", 1);
2382 emptyLineCnt = 0;
2384 CStringA lineA = CUnicodeUtils::GetMulti(line + L'\n', cp);
2385 file.Write((LPCSTR)lineA, lineA.GetLength());
2387 file.Close();
2388 return 0;
2390 catch (CFileException *e)
2392 e->Delete();
2393 return -1;
2397 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)
2399 if (bAutoLoad)
2400 CAppUtils::LaunchPAgent(nullptr, &url);
2402 CGitHash hashOld;
2403 if (g_Git.GetHash(hashOld, L"HEAD"))
2405 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash."), L"TortoiseGit", MB_ICONERROR);
2406 return false;
2409 CString args;
2410 if (CRegDWORD(L"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE) == FALSE)
2411 args += L" --no-rebase";
2413 if (bFetchTags == BST_UNCHECKED)
2414 args += L" --no-tags";
2415 else if (bFetchTags == BST_CHECKED)
2416 args += L" --tags";
2418 if (bNoFF)
2419 args += L" --no-ff";
2421 if (bFFonly)
2422 args += L" --ff-only";
2424 if (bSquash)
2425 args += L" --squash";
2427 if (bNoCommit)
2428 args += L" --no-commit";
2430 if (nDepth)
2431 args.AppendFormat(L" --depth %d", *nDepth);
2433 if (bPrune == BST_CHECKED)
2434 args += L" --prune";
2435 else if (bPrune == BST_UNCHECKED)
2436 args += L" --no-prune";
2438 if (bUnrelated)
2439 args += L" --allow-unrelated-histories";
2441 CString cmd;
2442 cmd.Format(L"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR)args, (LPCTSTR)url, (LPCTSTR)remoteBranchName);
2443 CProgressDlg progress;
2444 progress.m_GitCmd = cmd;
2446 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2447 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2449 if (status)
2451 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2453 STRING_VECTOR remotes;
2454 g_Git.GetRemoteList(remotes);
2455 if (std::find(remotes.begin(), remotes.end(), url) != remotes.end())
2457 CString currentBranch;
2458 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2459 currentBranch.Empty();
2460 CString remoteRef = L"remotes/" + url + L"/" + remoteBranchName;
2461 if (!currentBranch.IsEmpty() && remoteBranchName.IsEmpty())
2463 CString pullRemote, pullBranch;
2464 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2465 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2466 remoteRef = L"remotes/" + pullRemote + L"/" + pullBranch;
2468 CGitHash common;
2469 g_Git.IsFastForward(L"HEAD", remoteRef, &common);
2470 if (common.IsEmpty())
2471 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoPull(url, bAutoLoad, bFetchTags, bNoFF, bFFonly, bSquash, bNoCommit, nDepth, bPrune, remoteBranchName, showPush, showStashPop, true); });
2475 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(); });
2476 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(L"", true); });
2477 return;
2480 if (showStashPop)
2481 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
2483 if (g_Git.GetHash(hashNew, L"HEAD"))
2484 MessageBox(nullptr, g_Git.GetGitLastErr(L"Could not get HEAD hash after pulling."), L"TortoiseGit", MB_ICONERROR);
2485 else
2487 postCmdList.emplace_back(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2489 CString sCmd;
2490 sCmd.Format(L"/command:showcompare /path:\"%s\" /revision1:%s /revision2:%s", (LPCTSTR)g_Git.m_CurrentDir, (LPCTSTR)hashOld.ToString(), (LPCTSTR)hashNew.ToString());
2491 CAppUtils::RunTortoiseGitProc(sCmd);
2493 postCmdList.emplace_back(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2495 CString sCmd;
2496 sCmd.Format(L"/command:log /path:\"%s\" /range:%s", (LPCTSTR)g_Git.m_CurrentDir, (LPCTSTR)(hashOld.ToString() + L".." + hashNew.ToString()));
2497 CAppUtils::RunTortoiseGitProc(sCmd);
2501 if (showPush)
2502 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
2504 CTGitPath gitPath = g_Git.m_CurrentDir;
2505 if (gitPath.HasSubmodules())
2507 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2509 CString sCmd;
2510 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2511 CAppUtils::RunTortoiseGitProc(sCmd);
2516 INT_PTR ret = progress.DoModal();
2518 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)
2520 CChangedDlg changeddlg;
2521 changeddlg.m_pathList.AddPath(CTGitPath());
2522 changeddlg.DoModal();
2524 return true;
2527 return ret == IDOK;
2530 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2532 if (IsTGitRebaseActive())
2533 return false;
2535 CPullFetchDlg dlg;
2536 dlg.m_IsPull = TRUE;
2537 if (dlg.DoModal() == IDOK)
2539 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2540 if (dlg.m_bRebase)
2541 return DoFetch(dlg.m_RemoteURL,
2542 FALSE, // Fetch all remotes
2543 dlg.m_bAutoLoad == BST_CHECKED,
2544 dlg.m_bPrune,
2545 dlg.m_bDepth == BST_CHECKED,
2546 dlg.m_nDepth,
2547 dlg.m_bFetchTags,
2548 dlg.m_RemoteBranchName,
2549 dlg.m_bRebaseActivatedInConfigForPull ? 2 : 1, // Rebase after fetching
2550 dlg.m_bRebasePreserveMerges == TRUE); // Preserve merges on rebase
2552 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);
2555 return false;
2558 bool CAppUtils::RebaseAfterFetch(const CString& upstream, int rebase, bool preserveMerges)
2560 while (true)
2562 CRebaseDlg dlg;
2563 if (!upstream.IsEmpty())
2564 dlg.m_Upstream = upstream;
2565 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2566 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2567 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2568 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2569 dlg.m_bRebaseAutoStart = (rebase == 2);
2570 dlg.m_bPreserveMerges = preserveMerges;
2571 INT_PTR response = dlg.DoModal();
2572 if (response == IDOK)
2573 return true;
2574 else if (response == IDC_REBASE_POST_BUTTON)
2576 CString cmd = L"/command:log";
2577 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2578 CAppUtils::RunTortoiseGitProc(cmd);
2579 return true;
2581 else if (response == IDC_REBASE_POST_BUTTON + 1)
2582 return Push();
2583 else if (response == IDC_REBASE_POST_BUTTON + 2)
2585 CString cmd, out, err;
2586 cmd.Format(L"git.exe format-patch -o \"%s\" %s..%s",
2587 (LPCTSTR)g_Git.m_CurrentDir,
2588 (LPCTSTR)g_Git.FixBranchName(dlg.m_Upstream),
2589 (LPCTSTR)g_Git.FixBranchName(dlg.m_Branch));
2590 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2592 CMessageBox::Show(nullptr, out + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
2593 return false;
2595 CAppUtils::SendPatchMail(cmd, out);
2596 return true;
2598 else if (response == IDC_REBASE_POST_BUTTON + 3)
2599 continue;
2600 else if (response == IDCANCEL)
2601 return false;
2602 return false;
2606 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)
2608 if (loadPuttyAgent)
2610 if (fetchAllRemotes)
2612 STRING_VECTOR list;
2613 g_Git.GetRemoteList(list);
2615 for (const auto& remote : list)
2616 CAppUtils::LaunchPAgent(nullptr, &remote);
2618 else
2619 CAppUtils::LaunchPAgent(nullptr, &url);
2622 CString upstream = L"FETCH_HEAD";
2623 CGitHash oldUpstreamHash;
2624 if (runRebase)
2626 STRING_VECTOR list;
2627 g_Git.GetRemoteList(list);
2628 for (auto it = list.cbegin(); it != list.cend(); ++it)
2630 if (url == *it)
2632 upstream.Empty();
2633 if (remoteBranch.IsEmpty()) // pulldlg might clear remote branch if its the default tracked branch
2635 CString currentBranch;
2636 if (g_Git.GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch))
2637 currentBranch.Empty();
2638 if (!currentBranch.IsEmpty() && remoteBranch.IsEmpty())
2640 CString pullRemote, pullBranch;
2641 g_Git.GetRemoteTrackedBranch(currentBranch, pullRemote, pullBranch);
2642 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty() && pullRemote == url) // pullRemote == url is just another safety-check and should not be needed
2643 upstream = L"remotes/" + *it + L'/' + pullBranch;
2646 else
2647 upstream = L"remotes/" + *it + L'/' + remoteBranch;
2649 g_Git.GetHash(oldUpstreamHash, upstream);
2650 break;
2655 CString cmd, arg;
2656 arg = L" --progress";
2658 if (bDepth)
2659 arg.AppendFormat(L" --depth %d", nDepth);
2661 if (prune == TRUE)
2662 arg += L" --prune";
2663 else if (prune == FALSE)
2664 arg += L" --no-prune";
2666 if (fetchTags == 1)
2667 arg += L" --tags";
2668 else if (fetchTags == 0)
2669 arg += L" --no-tags";
2671 if (fetchAllRemotes)
2672 cmd.Format(L"git.exe fetch --all -v%s", (LPCTSTR)arg);
2673 else
2674 cmd.Format(L"git.exe fetch -v%s \"%s\" %s", (LPCTSTR)arg, (LPCTSTR)url, (LPCTSTR)remoteBranch);
2676 CProgressDlg progress;
2677 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2679 if (status)
2681 postCmdList.emplace_back(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase, rebasePreserveMerges); });
2682 if (fetchAllRemotes)
2683 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2685 CString cmd = L"/command:log";
2686 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2687 CAppUtils::RunTortoiseGitProc(cmd);
2689 return;
2692 postCmdList.emplace_back(IDI_LOG, IDS_MENULOG, []
2694 CString cmd = L"/command:log";
2695 cmd += L" /path:\"" + g_Git.m_CurrentDir + L'"';
2696 CAppUtils::RunTortoiseGitProc(cmd);
2699 postCmdList.emplace_back(IDI_REVERT, IDS_PROC_RESET, []
2701 CString pullRemote, pullBranch;
2702 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2703 CString defaultUpstream;
2704 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2705 defaultUpstream.Format(L"remotes/%s/%s", (LPCTSTR)pullRemote, (LPCTSTR)pullBranch);
2706 CAppUtils::GitReset(&defaultUpstream, 2);
2709 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); });
2711 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2712 postCmdList.emplace_back(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); });
2715 progress.m_GitCmd = cmd;
2717 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2719 CGitProgressDlg gitdlg;
2720 FetchProgressCommand fetchProgressCommand;
2721 if (!fetchAllRemotes)
2722 fetchProgressCommand.SetUrl(url);
2723 gitdlg.SetCommand(&fetchProgressCommand);
2724 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2725 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2726 if (!fetchAllRemotes)
2727 fetchProgressCommand.SetRefSpec(remoteBranch);
2728 return gitdlg.DoModal() == IDOK;
2731 progress.m_PostExecCallback = [&](DWORD& exitCode, CString&)
2733 if (exitCode || !runRebase)
2734 return;
2736 CGitHash remoteBranchHash;
2737 g_Git.GetHash(remoteBranchHash, upstream);
2738 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)
2739 return;
2741 if (runRebase == 1 && g_Git.IsFastForward(L"HEAD", upstream))
2743 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);
2744 if (ret == 3)
2745 return;
2746 if (ret == 1)
2748 CProgressDlg mergeProgress;
2749 mergeProgress.m_GitCmd = L"git.exe merge --ff-only " + upstream;
2750 mergeProgress.m_AutoClose = AUTOCLOSE_IF_NO_ERRORS;
2751 mergeProgress.m_PostCmdCallback = [](DWORD status, PostCmdList& postCmdList)
2753 if (status && g_Git.HasWorkingTreeConflicts())
2755 // there are conflict files
2756 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2758 CString sCmd;
2759 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
2760 CAppUtils::RunTortoiseGitProc(sCmd);
2764 mergeProgress.DoModal();
2765 return;
2769 CAppUtils::RebaseAfterFetch(upstream, runRebase, rebasePreserveMerges);
2772 return progress.DoModal() == IDOK;
2775 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2777 CPullFetchDlg dlg;
2778 dlg.m_PreSelectRemote = remoteName;
2779 dlg.m_IsPull=FALSE;
2780 dlg.m_bAllRemotes = allRemotes;
2782 if(dlg.DoModal()==IDOK)
2783 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);
2785 return false;
2788 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)
2790 CString error;
2791 DWORD exitcode = 0xFFFFFFFF;
2792 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2794 if (exitcode)
2796 CString temp;
2797 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2798 MessageBox(nullptr, temp, L"TortoiseGit", MB_OK | MB_ICONERROR);
2799 return false;
2803 int iRecurseSubmodules = 0;
2804 if (GetMsysgitVersion() >= 0x02070000)
2806 CString sRecurseSubmodules = g_Git.GetConfigValue(L"push.recurseSubmodules");
2807 if (sRecurseSubmodules == L"check")
2808 iRecurseSubmodules = 1;
2809 else if (sRecurseSubmodules == L"on-demand")
2810 iRecurseSubmodules = 2;
2813 CString arg;
2814 if (pack)
2815 arg += L"--thin ";
2816 if (tags && !allBranches)
2817 arg += L"--tags ";
2818 if (force)
2819 arg += L"--force ";
2820 if (forceWithLease)
2821 arg += L"--force-with-lease ";
2822 if (setUpstream)
2823 arg += L"--set-upstream ";
2824 if (recurseSubmodules == 0 && recurseSubmodules != iRecurseSubmodules)
2825 arg += L"--recurse-submodules=no ";
2826 if (recurseSubmodules == 1 && recurseSubmodules != iRecurseSubmodules)
2827 arg += L"--recurse-submodules=check ";
2828 if (recurseSubmodules == 2 && recurseSubmodules != iRecurseSubmodules)
2829 arg += L"--recurse-submodules=on-demand ";
2831 arg += L"--progress ";
2833 CProgressDlg progress;
2835 STRING_VECTOR remotesList;
2836 if (allRemotes)
2837 g_Git.GetRemoteList(remotesList);
2838 else
2839 remotesList.push_back(remote);
2841 for (unsigned int i = 0; i < remotesList.size(); ++i)
2843 if (autoloadKey)
2844 CAppUtils::LaunchPAgent(nullptr, &remotesList[i]);
2846 CString cmd;
2847 if (allBranches)
2849 cmd.Format(L"git.exe push --all %s\"%s\"",
2850 (LPCTSTR)arg,
2851 (LPCTSTR)remotesList[i]);
2853 if (tags)
2855 progress.m_GitCmdList.push_back(cmd);
2856 cmd.Format(L"git.exe push --tags %s\"%s\"", (LPCTSTR)arg, (LPCTSTR)remotesList[i]);
2859 else
2861 cmd.Format(L"git.exe push %s\"%s\" %s",
2862 (LPCTSTR)arg,
2863 (LPCTSTR)remotesList[i],
2864 (LPCTSTR)localBranch);
2865 if (!remoteBranch.IsEmpty())
2867 cmd += L":";
2868 cmd += remoteBranch;
2871 progress.m_GitCmdList.push_back(cmd);
2873 if (!allBranches && !!CRegDWORD(L"Software\\TortoiseGit\\ShowBranchRevisionNumber", FALSE))
2875 cmd.Format(L"git.exe rev-list --count --first-parent %s", (LPCTSTR)localBranch);
2876 progress.m_GitCmdList.push_back(cmd);
2880 CString superprojectRoot;
2881 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2882 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2884 // need to execute hooks as those might be needed by post action commands
2885 DWORD exitcode = 0xFFFFFFFF;
2886 CString error;
2887 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2889 if (exitcode)
2891 CString temp;
2892 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2893 MessageBox(nullptr, temp, L"TortoiseGit", MB_OK | MB_ICONERROR);
2897 if (status)
2899 bool rejected = progress.GetLogText().Find(L"! [rejected]") > 0;
2900 if (rejected)
2902 postCmdList.emplace_back(IDI_PULL, IDS_MENUPULL, []{ Pull(true); });
2903 postCmdList.emplace_back(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(allRemotes ? L"" : remote, allRemotes); });
2905 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2906 return;
2909 postCmdList.emplace_back(IDS_PROC_REQUESTPULL, [&]{ RequestPull(remoteBranch); });
2910 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(localBranch); });
2911 postCmdList.emplace_back(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); });
2912 if (!superprojectRoot.IsEmpty())
2914 postCmdList.emplace_back(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2916 CString sCmd;
2917 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)superprojectRoot);
2918 RunTortoiseGitProc(sCmd);
2923 INT_PTR ret = progress.DoModal();
2924 return ret == IDOK;
2927 bool CAppUtils::Push(const CString& selectLocalBranch)
2929 CPushDlg dlg;
2930 dlg.m_BranchSourceName = selectLocalBranch;
2932 if (dlg.DoModal() == IDOK)
2933 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);
2935 return FALSE;
2938 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2940 CRequestPullDlg dlg;
2941 dlg.m_RepositoryURL = repositoryUrl;
2942 dlg.m_EndRevision = endrevision;
2943 if (dlg.DoModal()==IDOK)
2945 CString cmd;
2946 cmd.Format(L"git.exe request-pull %s \"%s\" %s", (LPCTSTR)dlg.m_StartRevision, (LPCTSTR)dlg.m_RepositoryURL, (LPCTSTR)dlg.m_EndRevision);
2948 CSysProgressDlg sysProgressDlg;
2949 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2950 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2951 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2952 sysProgressDlg.SetShowProgressBar(false);
2953 sysProgressDlg.ShowModeless((HWND)nullptr, true);
2955 CString tempFileName = GetTempFile();
2956 CString err;
2957 DeleteFile(tempFileName);
2958 CreateDirectory(tempFileName, nullptr);
2959 tempFileName += L"\\pullrequest.txt";
2960 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2962 CString msg;
2963 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2964 MessageBox(nullptr, msg + L'\n' + err, L"TortoiseGit", MB_OK | MB_ICONERROR);
2965 return false;
2968 if (sysProgressDlg.HasUserCancelled())
2970 CMessageBox::Show(nullptr, IDS_USERCANCELLED, IDS_APPNAME, MB_OK);
2971 ::DeleteFile(tempFileName);
2972 return false;
2975 sysProgressDlg.Stop();
2977 if (dlg.m_bSendMail)
2979 CSendMailDlg sendmaildlg;
2980 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2981 sendmaildlg.m_bCustomSubject = true;
2983 if (sendmaildlg.DoModal() == IDOK)
2985 if (sendmaildlg.m_PathList.IsEmpty())
2986 return FALSE;
2988 CGitProgressDlg progDlg;
2989 if (bIsMainWnd)
2990 theApp.m_pMainWnd = &progDlg;
2991 SendMailProgressCommand sendMailProgressCommand;
2992 progDlg.SetCommand(&sendMailProgressCommand);
2994 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2995 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2997 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2998 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
3000 progDlg.DoModal();
3002 return true;
3004 return false;
3007 CAppUtils::LaunchAlternativeEditor(tempFileName);
3009 return true;
3012 void CAppUtils::RemoveTrailSlash(CString &path)
3014 if(path.IsEmpty())
3015 return ;
3017 // For URL, do not trim the slash just after the host name component.
3018 int index = path.Find(L"://");
3019 if (index >= 0)
3021 index += 4;
3022 index = path.Find(L'/', index);
3023 if (index == path.GetLength() - 1)
3024 return;
3027 while (path[path.GetLength() - 1] == L'\\' || path[path.GetLength() - 1] == L'/')
3029 path.Truncate(path.GetLength() - 1);
3030 if(path.IsEmpty())
3031 return;
3035 bool CAppUtils::CheckUserData()
3037 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
3039 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO | MB_ICONERROR) == IDYES)
3041 CTGitPath path(g_Git.m_CurrentDir);
3042 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
3043 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
3044 dlg.SetTreeWidth(220);
3045 dlg.m_DefaultPage = L"gitconfig";
3047 dlg.DoModal();
3048 dlg.HandleRestart();
3051 else
3052 return false;
3055 return true;
3058 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
3059 CTGitPathList &pathList,
3060 CTGitPathList &selectedList,
3061 bool bSelectFilesForCommit)
3063 bool bFailed = true;
3065 if (!CheckUserData())
3066 return false;
3068 while (bFailed)
3070 bFailed = false;
3071 CCommitDlg dlg;
3072 dlg.m_sBugID = bugid;
3074 dlg.m_bWholeProject = bWholeProject;
3076 dlg.m_sLogMessage = sLogMsg;
3077 dlg.m_pathList = pathList;
3078 dlg.m_checkedPathList = selectedList;
3079 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
3080 if (dlg.DoModal() == IDOK)
3082 if (dlg.m_pathList.IsEmpty())
3083 return false;
3084 // if the user hasn't changed the list of selected items
3085 // we don't use that list. Because if we would use the list
3086 // of pre-checked items, the dialog would show different
3087 // checked items on the next startup: it would only try
3088 // to check the parent folder (which might not even show)
3089 // instead, we simply use an empty list and let the
3090 // default checking do its job.
3091 if (!dlg.m_pathList.IsEqual(pathList))
3092 selectedList = dlg.m_pathList;
3093 pathList = dlg.m_updatedPathList;
3094 sLogMsg = dlg.m_sLogMessage;
3095 bSelectFilesForCommit = true;
3097 switch (dlg.m_PostCmd)
3099 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3100 CAppUtils::SVNDCommit();
3101 break;
3102 case GIT_POSTCOMMIT_CMD_PUSH:
3103 CAppUtils::Push();
3104 break;
3105 case GIT_POSTCOMMIT_CMD_CREATETAG:
3106 CAppUtils::CreateBranchTag(TRUE);
3107 break;
3108 case GIT_POSTCOMMIT_CMD_PULL:
3109 CAppUtils::Pull(true);
3110 break;
3111 default:
3112 break;
3115 // CGitProgressDlg progDlg;
3116 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3117 // if (parser.HasVal(L"closeonend"))
3118 // progDlg.SetAutoClose(parser.GetLongVal(L"closeonend"));
3119 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3120 // progDlg.SetPathList(dlg.m_pathList);
3121 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3122 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3123 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3124 // progDlg.SetItemCount(dlg.m_itemsCount);
3125 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3126 // progDlg.DoModal();
3127 // CRegDWORD err = CRegDWORD(L"Software\\TortoiseGit\\ErrorOccurred", FALSE);
3128 // err = (DWORD)progDlg.DidErrorsOccur();
3129 // bFailed = progDlg.DidErrorsOccur();
3130 // bRet = progDlg.DidErrorsOccur();
3131 // CRegDWORD bFailRepeat = CRegDWORD(L"Software\\TortoiseGit\\CommitReopen", FALSE);
3132 // if (DWORD(bFailRepeat)==0)
3133 // bFailed = false; // do not repeat if the user chose not to in the settings.
3136 return true;
3139 BOOL CAppUtils::SVNDCommit()
3141 CSVNDCommitDlg dcommitdlg;
3142 CString gitSetting = g_Git.GetConfigValue(L"svn.rmdir");
3143 if (gitSetting.IsEmpty()) {
3144 if (dcommitdlg.DoModal() != IDOK)
3145 return false;
3146 else
3148 if (dcommitdlg.m_remember)
3150 if (dcommitdlg.m_rmdir)
3151 gitSetting = L"true";
3152 else
3153 gitSetting = L"false";
3154 if (g_Git.SetConfigValue(L"svn.rmdir", gitSetting))
3156 CString msg;
3157 msg.Format(IDS_PROC_SAVECONFIGFAILED, L"svn.rmdir", (LPCTSTR)gitSetting);
3158 MessageBox(nullptr, msg, L"TortoiseGit", MB_OK | MB_ICONERROR);
3164 BOOL IsStash = false;
3165 if(!g_Git.CheckCleanWorkTree())
3167 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3169 CSysProgressDlg sysProgressDlg;
3170 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3171 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3172 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3173 sysProgressDlg.SetShowProgressBar(false);
3174 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3175 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3177 CString out;
3178 if (g_Git.Run(L"git.exe stash", &out, CP_UTF8))
3180 sysProgressDlg.Stop();
3181 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3182 return false;
3184 sysProgressDlg.Stop();
3186 IsStash =true;
3188 else
3189 return false;
3192 CProgressDlg progress;
3193 if (dcommitdlg.m_rmdir)
3194 progress.m_GitCmd = L"git.exe svn dcommit --rmdir";
3195 else
3196 progress.m_GitCmd = L"git.exe svn dcommit";
3197 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3199 if( IsStash)
3201 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
3203 CSysProgressDlg sysProgressDlg;
3204 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3205 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3206 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3207 sysProgressDlg.SetShowProgressBar(false);
3208 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3209 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3211 CString out;
3212 if (g_Git.Run(L"git.exe stash pop", &out, CP_UTF8))
3214 sysProgressDlg.Stop();
3215 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3216 return false;
3218 sysProgressDlg.Stop();
3220 else
3221 return false;
3223 return TRUE;
3225 return FALSE;
3228 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)
3230 CString args;
3231 if (noFF)
3232 args += L" --no-ff";
3233 else if (ffOnly)
3234 args += L" --ff-only";
3236 if (squash)
3237 args += L" --squash";
3239 if (noCommit)
3240 args += L" --no-commit";
3242 if (unrelated)
3243 args += L" --allow-unrelated-histories";
3245 if (log)
3246 args.AppendFormat(L" --log=%d", *log);
3248 if (!mergeStrategy.IsEmpty())
3250 args += L" --strategy=" + mergeStrategy;
3251 if (!strategyOption.IsEmpty())
3253 args += L" --strategy-option=" + strategyOption;
3254 if (!strategyParam.IsEmpty())
3255 args += L'=' + strategyParam;
3259 if (!logMessage.IsEmpty())
3261 CString logmsg = logMessage;
3262 logmsg.Replace(L"\\\"", L"\\\\\"");
3263 logmsg.Replace(L"\"", L"\\\"");
3264 args += L" -m \"" + logmsg + L"\"";
3267 CString mergeVersion = g_Git.FixBranchName(version);
3268 CString cmd;
3269 cmd.Format(L"git.exe merge%s %s", (LPCTSTR)args, (LPCTSTR)mergeVersion);
3271 CProgressDlg Prodlg;
3272 Prodlg.m_GitCmd = cmd;
3274 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3276 if (status)
3278 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3279 if (hasConflicts < 0)
3280 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), L"TortoiseGit", MB_ICONEXCLAMATION);
3281 else if (hasConflicts)
3283 // there are conflict files
3285 postCmdList.emplace_back(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3287 CString sCmd;
3288 sCmd.Format(L"/command:resolve /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3289 CAppUtils::RunTortoiseGitProc(sCmd);
3292 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3294 CString sCmd;
3295 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3296 CAppUtils::RunTortoiseGitProc(sCmd);
3300 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3302 CGitHash common;
3303 g_Git.IsFastForward(L"HEAD", mergeVersion, &common);
3304 if (common.IsEmpty())
3305 postCmdList.emplace_back(IDI_MERGE, IDS_MERGE_UNRELATED, [=] { DoMerge(noFF, ffOnly, squash, noCommit, log, true, mergeStrategy, strategyOption, strategyParam, logMessage, version, isBranch, showStashPop); });
3308 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSTASHSAVE, [=]{ CAppUtils::StashSave(L"", false, false, true, mergeVersion); });
3310 return;
3313 if (showStashPop)
3314 postCmdList.emplace_back(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ CAppUtils::StashPop(); });
3316 if (noCommit || squash)
3318 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUCOMMIT, []
3320 CString sCmd;
3321 sCmd.Format(L"/command:commit /path:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3322 CAppUtils::RunTortoiseGitProc(sCmd);
3324 return;
3327 if (isBranch && !CStringUtils::StartsWith(version, L"remotes/")) // do not ask to remove remote branches
3329 postCmdList.emplace_back(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3331 CString msg;
3332 msg.Format(IDS_PROC_DELETEBRANCHTAG, (LPCTSTR)version);
3333 if (CMessageBox::Show(nullptr, msg, L"TortoiseGit", 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3335 CString cmd, out;
3336 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)version);
3337 if (g_Git.Run(cmd, &out, CP_UTF8))
3338 MessageBox(nullptr, out, L"TortoiseGit", MB_OK);
3342 if (isBranch)
3343 postCmdList.emplace_back(IDI_PUSH, IDS_MENUPUSH, []{ CAppUtils::Push(); });
3345 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3346 if (hasGitSVN)
3347 postCmdList.emplace_back(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ CAppUtils::SVNDCommit(); });
3350 Prodlg.DoModal();
3351 return !Prodlg.m_GitStatus;
3354 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3356 if (!CheckUserData())
3357 return FALSE;
3359 if (IsTGitRebaseActive())
3360 return FALSE;
3362 CMergeDlg dlg;
3363 if (commit)
3364 dlg.m_initialRefName = *commit;
3366 if (dlg.DoModal() == IDOK)
3367 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);
3369 return FALSE;
3372 BOOL CAppUtils::MergeAbort()
3374 CMergeAbortDlg dlg;
3375 if (dlg.DoModal() == IDOK)
3376 return Reset(L"HEAD", dlg.m_ResetType + 1);
3378 return FALSE;
3381 void CAppUtils::EditNote(GitRevLoglist* rev, ProjectProperties* projectProperties)
3383 if (!CheckUserData())
3384 return;
3386 CInputDlg dlg;
3387 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3388 dlg.m_sInputText = rev->m_Notes;
3389 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3390 dlg.m_pProjectProperties = projectProperties;
3391 dlg.m_bUseLogWidth = true;
3392 if(dlg.DoModal() == IDOK)
3394 CString cmd,output;
3395 cmd = L"notes add -f -F \"";
3397 CString tempfile=::GetTempFile();
3398 if (!CStringUtils::WriteStringToTextFile(tempfile, dlg.m_sInputText))
3400 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3401 return;
3403 cmd += tempfile;
3404 cmd += L"\" ";
3405 cmd += rev->m_CommitHash.ToString();
3409 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3410 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3411 }catch(...)
3413 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3415 ::DeleteFile(tempfile);
3417 if (g_Git.GetGitNotes(rev->m_CommitHash, rev->m_Notes))
3418 MessageBox(nullptr, g_Git.GetLibGit2LastErr(L"Could not load notes for commit " + rev->m_CommitHash.ToString() + L'.'), L"TortoiseGit", MB_OK | MB_ICONERROR);
3422 int CAppUtils::GetMsysgitVersion()
3424 if (g_Git.ms_LastMsysGitVersion)
3425 return g_Git.ms_LastMsysGitVersion;
3427 CString cmd;
3428 CString versiondebug;
3429 CString version;
3431 CRegDWORD regTime = CRegDWORD(L"Software\\TortoiseGit\\git_file_time");
3432 CRegDWORD regVersion = CRegDWORD(L"Software\\TortoiseGit\\git_cached_version");
3434 CString gitpath = CGit::ms_LastMsysGitDir + L"\\git.exe";
3436 __int64 time=0;
3437 if (!CGit::GetFileModifyTime(gitpath, &time))
3439 if ((DWORD)CGit::filetime_to_time_t(time) == regTime)
3441 g_Git.ms_LastMsysGitVersion = regVersion;
3442 return regVersion;
3446 CString err;
3447 int ver = g_Git.GetGitVersion(&versiondebug, &err);
3448 if (ver < 0)
3450 MessageBox(nullptr, L"git.exe not correctly set up (" + err + L")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\".", L"TortoiseGit", MB_OK | MB_ICONERROR);
3451 return -1;
3455 if (!ver)
3457 MessageBox(nullptr, L"Could not parse git.exe version number: \"" + versiondebug + L'"', L"TortoiseGit", MB_OK | MB_ICONERROR);
3458 return -1;
3462 regTime = time&0xFFFFFFFF;
3463 regVersion = ver;
3464 g_Git.ms_LastMsysGitVersion = ver;
3466 return ver;
3469 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3471 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3473 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(L"Shell32.dll");
3475 if (hShell.IsValid()) {
3476 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3477 if (pfnSHGPSFW) {
3478 IPropertyStore *pps;
3479 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3480 if (SUCCEEDED(hr)) {
3481 PROPVARIANT var;
3482 var.vt = VT_BOOL;
3483 var.boolVal = VARIANT_TRUE;
3484 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3485 pps->Release();
3491 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3493 ASSERT(dialogname.GetLength() < 70);
3494 ASSERT(urlorpath.GetLength() < MAX_PATH);
3495 WCHAR pathbuf[MAX_PATH] = {0};
3497 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3499 wcscat_s(pathbuf, L" - ");
3500 wcscat_s(pathbuf, dialogname);
3501 wcscat_s(pathbuf, L" - ");
3502 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3503 SetWindowText(hWnd, pathbuf);
3506 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3508 if (!g_Git.CheckCleanWorkTree())
3510 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3512 CSysProgressDlg sysProgressDlg;
3513 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3514 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3515 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3516 sysProgressDlg.SetShowProgressBar(false);
3517 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3518 sysProgressDlg.ShowModeless((HWND)nullptr, true);
3520 CString out;
3521 if (g_Git.Run(L"git.exe stash", &out, CP_UTF8))
3523 sysProgressDlg.Stop();
3524 MessageBox(nullptr, out, L"TortoiseGit", MB_OK | MB_ICONERROR);
3525 return false;
3527 sysProgressDlg.Stop();
3529 else
3530 return false;
3533 CBisectStartDlg bisectStartDlg;
3535 if (!lastGood.IsEmpty())
3536 bisectStartDlg.m_sLastGood = lastGood;
3537 if (!firstBad.IsEmpty())
3538 bisectStartDlg.m_sFirstBad = firstBad;
3540 if (bisectStartDlg.DoModal() == IDOK)
3542 CProgressDlg progress;
3543 if (bIsMainWnd)
3544 theApp.m_pMainWnd = &progress;
3545 progress.m_GitCmdList.push_back(L"git.exe bisect start");
3546 progress.m_GitCmdList.push_back(L"git.exe bisect good " + bisectStartDlg.m_LastGoodRevision);
3547 progress.m_GitCmdList.push_back(L"git.exe bisect bad " + bisectStartDlg.m_FirstBadRevision);
3549 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3551 if (status)
3552 return;
3554 CTGitPath path(g_Git.m_CurrentDir);
3555 if (path.HasSubmodules())
3557 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3559 CString sCmd;
3560 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3561 CAppUtils::RunTortoiseGitProc(sCmd);
3566 INT_PTR ret = progress.DoModal();
3567 return ret == IDOK;
3570 return false;
3573 bool CAppUtils::BisectOperation(const CString& op, const CString& ref, bool bIsMainWnd)
3575 CString cmd = L"git.exe bisect " + op;
3577 if (!ref.IsEmpty())
3579 cmd += L' ';
3580 cmd += ref;
3583 CProgressDlg progress;
3584 if (bIsMainWnd)
3585 theApp.m_pMainWnd = &progress;
3586 progress.m_GitCmd = cmd;
3588 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3590 if (status)
3591 return;
3593 CTGitPath path = g_Git.m_CurrentDir;
3594 if (path.HasSubmodules())
3596 postCmdList.emplace_back(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3598 CString sCmd;
3599 sCmd.Format(L"/command:subupdate /bkpath:\"%s\"", (LPCTSTR)g_Git.m_CurrentDir);
3600 CAppUtils::RunTortoiseGitProc(sCmd);
3604 if (op != L"reset")
3605 postCmdList.emplace_back(IDS_MENUBISECTRESET, []{ CAppUtils::RunTortoiseGitProc(L"/command:bisect /reset"); });
3608 INT_PTR ret = progress.DoModal();
3609 return ret == IDOK;
3612 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3614 CUserPassword dlg;
3615 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3616 if (username_from_url)
3617 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3619 CStringA username, password;
3620 if (dlg.DoModal() == IDOK)
3622 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3623 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3624 return git_cred_userpass_plaintext_new(out, username, password);
3626 giterr_set_str(GITERR_NONE, "User cancelled.");
3627 return GIT_EUSER;
3630 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3632 if (base_cert->cert_type == GIT_CERT_X509)
3634 git_cert_x509* cert = (git_cert_x509*)base_cert;
3636 if (last_accepted_cert.cmp(cert))
3637 return 0;
3639 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3640 SCOPE_EXIT { CertFreeCertificateContext(pServerCert); };
3642 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3643 if (!verificationError)
3645 last_accepted_cert.set(cert);
3646 return 0;
3649 CString servernameInCert;
3650 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, CStrBuf(servernameInCert, 128), 128);
3652 CString issuer;
3653 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, CStrBuf(issuer, 128), 128);
3655 CCheckCertificateDlg dlg;
3656 dlg.cert = cert;
3657 dlg.m_sCertificateCN = servernameInCert;
3658 dlg.m_sCertificateIssuer = issuer;
3659 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3660 dlg.m_sError = CFormatMessageWrapper(verificationError);
3661 if (dlg.DoModal() == IDOK)
3663 last_accepted_cert.set(cert);
3664 return 0;
3667 return GIT_ECERTIFICATE;
3670 int CAppUtils::ExploreTo(HWND hwnd, CString path)
3672 if (PathFileExists(path))
3674 HRESULT ret = E_FAIL;
3675 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3676 if (pidl)
3678 ret = SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3679 ILFree(pidl);
3681 return SUCCEEDED(ret) ? 0 : -1;
3683 // if filepath does not exist any more, navigate to closest matching folder
3686 int pos = path.ReverseFind(L'\\');
3687 if (pos <= 3)
3688 break;
3689 path.Truncate(pos);
3690 } while (!PathFileExists(path));
3691 return (INT_PTR)ShellExecute(hwnd, L"explore", path, nullptr, nullptr, SW_SHOW) > 32 ? 0 : -1;
3694 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3696 bool b_local = false, b_remote = false;
3697 BYTE_VECTOR vector;
3699 CString cmd;
3700 cmd.Format(L"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3701 if (g_Git.Run(cmd, &vector))
3703 MessageBox(nullptr, L"git ls-files failed!", L"TortoiseGit", MB_OK);
3704 return -1;
3707 CTGitPathList list;
3708 if (list.ParserFromLsFile(vector))
3710 MessageBox(nullptr, L"Parse ls-files failed!", L"TortoiseGit", MB_OK);
3711 return -1;
3714 if (list.IsEmpty())
3715 return 0;
3716 for (int i = 0; i < list.GetCount(); ++i)
3718 if (list[i].m_Stage == 2)
3719 b_local = true;
3720 if (list[i].m_Stage == 3)
3721 b_remote = true;
3725 CBlockCacheForPath block(g_Git.m_CurrentDir);
3726 if (path.IsDirectory()) // is submodule conflict
3728 CString err = L"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.";
3729 if (b_local && b_remote)
3731 if (!path.HasAdminDir()) // check if submodule is initialized
3733 err += L"\n\nYou have to checkout the submodule manually into \"" + path.GetGitPathString() + L"\" and then reset HEAD to the right commit (see resolve submodule conflict dialog for this).";
3734 MessageBox(nullptr, err, L"TortoiseGit", MB_ICONERROR);
3735 return -1;
3737 CGit subgit;
3738 subgit.m_CurrentDir = g_Git.CombinePath(path);
3739 CGitHash submoduleHead;
3740 if (subgit.GetHash(submoduleHead, L"HEAD"))
3742 MessageBox(nullptr, err, L"TortoiseGit", MB_ICONERROR);
3743 return -1;
3745 CString baseHash, localHash, remoteHash;
3746 ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash);
3747 if (resolveWith == RESOLVE_WITH_THEIRS && submoduleHead.ToString() != remoteHash)
3749 CString origPath = g_Git.m_CurrentDir;
3750 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3751 if (!GitReset(&remoteHash))
3753 g_Git.m_CurrentDir = origPath;
3754 return -1;
3756 g_Git.m_CurrentDir = origPath;
3758 else if (resolveWith == RESOLVE_WITH_MINE && submoduleHead.ToString() != localHash)
3760 CString origPath = g_Git.m_CurrentDir;
3761 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3762 if (!GitReset(&localHash))
3764 g_Git.m_CurrentDir = origPath;
3765 return -1;
3767 g_Git.m_CurrentDir = origPath;
3770 else
3772 MessageBox(nullptr, err, L"TortoiseGit", MB_ICONERROR);
3773 return -1;
3777 if (resolveWith == RESOLVE_WITH_THEIRS)
3779 CString gitcmd, output;
3780 if (b_local && b_remote)
3781 gitcmd.Format(L"git.exe checkout-index -f --stage=3 -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3782 else if (b_remote)
3783 gitcmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3784 else if (b_local)
3785 gitcmd.Format(L"git.exe rm -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3786 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3788 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3789 return -1;
3792 else if (resolveWith == RESOLVE_WITH_MINE)
3794 CString gitcmd, output;
3795 if (b_local && b_remote)
3796 gitcmd.Format(L"git.exe checkout-index -f --stage=2 -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3797 else if (b_local)
3798 gitcmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3799 else if (b_remote)
3800 gitcmd.Format(L"git.exe rm -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3801 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3803 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3804 return -1;
3808 if (b_local && b_remote && path.m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3810 CString gitcmd, output;
3811 gitcmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
3812 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3813 MessageBox(nullptr, output, L"TortoiseGit", MB_ICONERROR);
3814 else
3816 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3817 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
3821 RemoveTempMergeFile(path);
3822 return 0;
3825 bool CAppUtils::ShellOpen(const CString& file, HWND hwnd /*= nullptr */)
3827 if ((INT_PTR)ShellExecute(hwnd, nullptr, file, nullptr, nullptr, SW_SHOW) > HINSTANCE_ERROR)
3828 return true;
3830 return ShowOpenWithDialog(file, hwnd);
3833 bool CAppUtils::ShowOpenWithDialog(const CString& file, HWND hwnd /*= nullptr */)
3835 OPENASINFO oi = { 0 };
3836 oi.pcszFile = file;
3837 oi.oaifInFlags = OAIF_EXEC;
3838 return SUCCEEDED(SHOpenWithDialog(hwnd, &oi));
3841 bool CAppUtils::IsTGitRebaseActive()
3843 CString adminDir;
3844 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3845 return false;
3847 if (!PathIsDirectory(adminDir + L"tgitrebase.active"))
3848 return false;
3850 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND, IDS_APPNAME, 2, IDI_EXCLAMATION, IDS_REMOVESTALEBUTTON, IDS_ABORTBUTTON) == 2)
3851 return true;
3853 RemoveDirectory(adminDir + L"tgitrebase.active");
3855 return false;