Fix C4302 warnings: 'conversion': truncation from 'type 1' to 'type 2'
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob396cfc01ebb10c306b774d478d1349a764da15c7
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - TortoiseGit
4 // Copyright (C) 2003-2011, 2013-2014 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 #include "MessageBox.h"
25 #include "registry.h"
26 #include "TGitPath.h"
27 #include "Git.h"
28 #include "UnicodeUtils.h"
29 #include "ExportDlg.h"
30 #include "ProgressDlg.h"
31 #include "GitAdminDir.h"
32 #include "ProgressDlg.h"
33 #include "BrowseFolder.h"
34 #include "DirFileEnum.h"
35 #include "MessageBox.h"
36 #include "GitStatus.h"
37 #include "CreateBranchTagDlg.h"
38 #include "GitSwitchDlg.h"
39 #include "ResetDlg.h"
40 #include "DeleteConflictDlg.h"
41 #include "ChangedDlg.h"
42 #include "SendMailDlg.h"
43 #include "GitProgressDlg.h"
44 #include "PushDlg.h"
45 #include "CommitDlg.h"
46 #include "MergeDlg.h"
47 #include "MergeAbortDlg.h"
48 #include "Hooks.h"
49 #include "..\Settings\Settings.h"
50 #include "InputDlg.h"
51 #include "SVNDCommitDlg.h"
52 #include "requestpulldlg.h"
53 #include "PullFetchDlg.h"
54 #include "FileDiffDlg.h"
55 #include "RebaseDlg.h"
56 #include "PropKey.h"
57 #include "StashSave.h"
58 #include "IgnoreDlg.h"
59 #include "FormatMessageWrapper.h"
60 #include "SmartHandle.h"
61 #include "BisectStartDlg.h"
62 #include "SysProgressDlg.h"
63 #include "UserPassword.h"
64 #include "Patch.h"
65 #include "Globals.h"
66 #include "ProgressCommands/ResetProgressCommand.h"
67 #include "ProgressCommands/FetchProgressCommand.h"
68 #include "ProgressCommands/SendMailProgressCommand.h"
69 #include "CertificateValidationHelper.h"
70 #include "CheckCertificateDlg.h"
71 #include "SubmoduleResolveConflictDlg.h"
72 #include "GitDiff.h"
73 #include "../TGitCache/CacheInterface.h"
75 static struct last_accepted_cert {
76 BYTE* data;
77 size_t len;
79 last_accepted_cert()
80 : data(nullptr)
81 , len(0)
84 ~last_accepted_cert()
86 free(data);
88 boolean cmp(git_cert_x509* cert)
90 return len > 0 && len == cert->len && memcmp(data, cert->data, len) == 0;
92 void set(git_cert_x509* cert)
94 free(data);
95 len = cert->len;
96 if (len == 0)
98 data = nullptr;
99 return;
101 data = new BYTE[len];
102 memcpy(data, cert->data, len);
104 } last_accepted_cert;
106 static bool DoFetch(const CString& url, const bool fetchAllRemotes, const bool loadPuttyAgent, const int prune, const bool bDepth, const int nDepth, const int fetchTags, const CString& remoteBranch, boolean runRebase);
108 CAppUtils::CAppUtils(void)
112 CAppUtils::~CAppUtils(void)
116 bool CAppUtils::StashSave(const CString& msg, bool showPull, bool pullShowPush, bool showMerge, const CString& mergeRev)
118 CStashSaveDlg dlg;
119 dlg.m_sMessage = msg;
120 if (dlg.DoModal() == IDOK)
122 CString cmd;
123 cmd = _T("git.exe stash save");
125 if (CAppUtils::GetMsysgitVersion() >= 0x01070700)
127 if (dlg.m_bIncludeUntracked)
128 cmd += _T(" --include-untracked");
129 else if (dlg.m_bAll)
130 cmd += _T(" --all");
133 if (!dlg.m_sMessage.IsEmpty())
135 CString message = dlg.m_sMessage;
136 message.Replace(_T("\""), _T("\"\""));
137 cmd += _T(" -- \"") + message + _T("\"");
140 CProgressDlg progress;
141 progress.m_GitCmd = cmd;
142 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
144 if (status)
145 return;
147 if (showPull)
148 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ CAppUtils::Pull(pullShowPush, true); }));
149 if (showMerge)
150 postCmdList.push_back(PostCmd(IDI_MERGE, IDS_MENUMERGE, [&]{ CAppUtils::Merge(&mergeRev, true); }));
152 return (progress.DoModal() == IDOK);
154 return false;
157 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
159 CString cmd,out;
160 cmd = _T("git.exe stash apply ");
161 if (ref.Find(_T("refs/")) == 0)
162 ref = ref.Mid(5);
163 if (ref.Find(_T("stash{")) == 0)
164 ref = _T("stash@") + ref.Mid(5);
165 cmd += ref;
167 CSysProgressDlg sysProgressDlg;
168 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
169 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
170 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
171 sysProgressDlg.SetShowProgressBar(false);
172 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
173 sysProgressDlg.ShowModeless((HWND)NULL, true);
175 int ret = g_Git.Run(cmd, &out, CP_UTF8);
177 sysProgressDlg.Stop();
179 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
180 if (ret && !(ret == 1 && hasConflicts))
182 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
184 else
186 CString message;
187 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
188 if (hasConflicts)
189 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
190 if (showChanges)
192 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
193 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
195 CChangedDlg dlg;
196 dlg.m_pathList.AddPath(CTGitPath());
197 dlg.DoModal();
199 return true;
201 else
203 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
204 return true;
207 return false;
210 bool CAppUtils::StashPop(bool showChanges /* true */)
212 CString cmd,out;
213 cmd=_T("git.exe stash pop ");
215 CSysProgressDlg sysProgressDlg;
216 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
217 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
218 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
219 sysProgressDlg.SetShowProgressBar(false);
220 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
221 sysProgressDlg.ShowModeless((HWND)NULL, true);
223 int ret = g_Git.Run(cmd, &out, CP_UTF8);
225 sysProgressDlg.Stop();
227 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
228 if (ret && !(ret == 1 && hasConflicts))
230 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
232 else
234 CString message;
235 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
236 if (hasConflicts)
237 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
238 if (showChanges)
240 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
241 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
243 CChangedDlg dlg;
244 dlg.m_pathList.AddPath(CTGitPath());
245 dlg.DoModal();
247 return true;
249 else
251 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
252 return true;
255 return false;
258 BOOL CAppUtils::StartExtMerge(
259 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
260 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
261 HWND resolveMsgHwnd, bool bDeleteBaseTheirsMineOnClose)
264 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
265 CString ext = mergedfile.GetFileExtension();
266 CString com = regCom;
267 bool bInternal = false;
269 if (!ext.IsEmpty())
271 // is there an extension specific merge tool?
272 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
273 if (!CString(mergetool).IsEmpty())
275 com = mergetool;
278 // is there a filename specific merge tool?
279 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
280 if (!CString(mergetool).IsEmpty())
282 com = mergetool;
285 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
287 // Maybe we should use TortoiseIDiff?
288 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
289 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
290 (ext == _T(".png")) || (ext == _T(".ico")) ||
291 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
292 (ext == _T(".dib")) || (ext == _T(".emf")) ||
293 (ext == _T(".cur")))
295 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
296 com = _T("\"") + com + _T("\"");
297 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
298 com = com + _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
300 else
302 // use TortoiseGitMerge
303 bInternal = true;
304 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
305 com = _T("\"") + com + _T("\"");
306 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
307 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
308 com += _T(" /saverequired");
309 if (resolveMsgHwnd)
311 CString s;
312 s.Format(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
313 com += s;
315 if (bDeleteBaseTheirsMineOnClose)
316 com += _T(" /deletebasetheirsmineonclose");
318 if (!g_sGroupingUUID.IsEmpty())
320 com += L" /groupuuid:\"";
321 com += g_sGroupingUUID;
322 com += L"\"";
325 // check if the params are set. If not, just add the files to the command line
326 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
328 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
329 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
330 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
331 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
333 if (basefile.IsEmpty())
335 com.Replace(_T("/base:%base"), _T(""));
336 com.Replace(_T("%base"), _T(""));
338 else
339 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
340 if (theirfile.IsEmpty())
342 com.Replace(_T("/theirs:%theirs"), _T(""));
343 com.Replace(_T("%theirs"), _T(""));
345 else
346 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
347 if (yourfile.IsEmpty())
349 com.Replace(_T("/mine:%mine"), _T(""));
350 com.Replace(_T("%mine"), _T(""));
352 else
353 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
354 if (mergedfile.IsEmpty())
356 com.Replace(_T("/merged:%merged"), _T(""));
357 com.Replace(_T("%merged"), _T(""));
359 else
360 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
361 if (basename.IsEmpty())
363 if (basefile.IsEmpty())
365 com.Replace(_T("/basename:%bname"), _T(""));
366 com.Replace(_T("%bname"), _T(""));
368 else
370 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
373 else
374 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
375 if (theirname.IsEmpty())
377 if (theirfile.IsEmpty())
379 com.Replace(_T("/theirsname:%tname"), _T(""));
380 com.Replace(_T("%tname"), _T(""));
382 else
384 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
387 else
388 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
389 if (yourname.IsEmpty())
391 if (yourfile.IsEmpty())
393 com.Replace(_T("/minename:%yname"), _T(""));
394 com.Replace(_T("%yname"), _T(""));
396 else
398 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
401 else
402 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
403 if (mergedname.IsEmpty())
405 if (mergedfile.IsEmpty())
407 com.Replace(_T("/mergedname:%mname"), _T(""));
408 com.Replace(_T("%mname"), _T(""));
410 else
412 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
415 else
416 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
418 if ((bReadOnly)&&(bInternal))
419 com += _T(" /readonly");
421 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
423 return FALSE;
426 return TRUE;
429 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
431 CString viewer;
432 // use TortoiseGitMerge
433 viewer = CPathUtils::GetAppDirectory();
434 viewer += _T("TortoiseGitMerge.exe");
436 viewer = _T("\"") + viewer + _T("\"");
437 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
438 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
439 if (bReversed)
440 viewer += _T(" /reversedpatch");
441 if (!sOriginalDescription.IsEmpty())
442 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
443 if (!sPatchedDescription.IsEmpty())
444 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
445 if (!g_sGroupingUUID.IsEmpty())
447 viewer += L" /groupuuid:\"";
448 viewer += g_sGroupingUUID;
449 viewer += L"\"";
451 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
453 return FALSE;
455 return TRUE;
458 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
460 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file2.GetFilename().MakeLower());
461 if (!difftool.IsEmpty())
462 return difftool;
463 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file1.GetFilename().MakeLower());
464 if (!difftool.IsEmpty())
465 return difftool;
467 // Is there an extension specific diff tool?
468 CString ext = file2.GetFileExtension().MakeLower();
469 if (!ext.IsEmpty())
471 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
472 if (!difftool.IsEmpty())
473 return difftool;
474 // Maybe we should use TortoiseIDiff?
475 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
476 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
477 (ext == _T(".png")) || (ext == _T(".ico")) ||
478 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
479 (ext == _T(".dib")) || (ext == _T(".emf")) ||
480 (ext == _T(".cur")))
482 return
483 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
484 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
485 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
489 // Finally, pick a generic external diff tool
490 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
491 return difftool;
494 bool CAppUtils::StartExtDiff(
495 const CString& file1, const CString& file2,
496 const CString& sName1, const CString& sName2,
497 const CString& originalFile1, const CString& originalFile2,
498 const git_revnum_t& hash1, const git_revnum_t& hash2,
499 const DiffFlags& flags, int jumpToLine)
501 CString viewer;
503 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
504 if (!flags.bBlame || !(DWORD)blamediff)
506 viewer = PickDiffTool(file1, file2);
507 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
508 bool bCommentedOut = viewer.Left(1) == _T("#");
509 if (flags.bAlternativeTool)
511 // Invert external vs. internal diff tool selection.
512 if (bCommentedOut)
513 viewer.Delete(0); // uncomment
514 else
515 viewer = "";
517 else if (bCommentedOut)
518 viewer = "";
521 bool bInternal = viewer.IsEmpty();
522 if (bInternal)
524 viewer =
525 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
526 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
527 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
528 if (!g_sGroupingUUID.IsEmpty())
530 viewer += L" /groupuuid:\"";
531 viewer += g_sGroupingUUID;
532 viewer += L"\"";
534 if (flags.bBlame)
535 viewer += _T(" /blame");
537 // check if the params are set. If not, just add the files to the command line
538 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
540 viewer += _T(" \"")+file1+_T("\"");
541 viewer += _T(" \"")+file2+_T("\"");
543 if (viewer.Find(_T("%base")) >= 0)
545 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
547 if (viewer.Find(_T("%mine")) >= 0)
549 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
552 if (sName1.IsEmpty())
553 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
554 else
555 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
557 if (sName2.IsEmpty())
558 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
559 else
560 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
562 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
563 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
565 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
566 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
568 if (flags.bReadOnly && bInternal)
569 viewer += _T(" /readonly");
571 if (jumpToLine > 0)
573 CString temp;
574 temp.Format(_T(" /line:%d"), jumpToLine);
575 viewer += temp;
578 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
581 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
583 CString viewer;
584 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
585 viewer = v;
586 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
588 // use TortoiseGitUDiff
589 viewer = CPathUtils::GetAppDirectory();
590 viewer += _T("TortoiseGitUDiff.exe");
591 // enquote the path to TortoiseGitUDiff
592 viewer = _T("\"") + viewer + _T("\"");
593 // add the params
594 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
595 if (!g_sGroupingUUID.IsEmpty())
597 viewer += L" /groupuuid:\"";
598 viewer += g_sGroupingUUID;
599 viewer += L"\"";
602 if (viewer.Find(_T("%1"))>=0)
604 if (viewer.Find(_T("\"%1\"")) >= 0)
605 viewer.Replace(_T("%1"), patchfile);
606 else
607 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
609 else
610 viewer += _T(" \"") + patchfile + _T("\"");
611 if (viewer.Find(_T("%title")) >= 0)
613 viewer.Replace(_T("%title"), title);
616 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
618 return FALSE;
620 return TRUE;
623 BOOL CAppUtils::StartTextViewer(CString file)
625 CString viewer;
626 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
627 viewer = txt;
628 viewer = viewer + _T("\\Shell\\Open\\Command\\");
629 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
630 viewer = txtexe;
632 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
633 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 1]);
634 ExpandEnvironmentStrings(viewer, buf.get(), len);
635 viewer = buf.get();
636 len = ExpandEnvironmentStrings(file, NULL, 0);
637 std::unique_ptr<TCHAR[]> buf2(new TCHAR[len + 1]);
638 ExpandEnvironmentStrings(file, buf2.get(), len);
639 file = buf2.get();
640 file = _T("\"")+file+_T("\"");
641 if (viewer.IsEmpty())
643 return CAppUtils::ShowOpenWithDialog(file) ? TRUE : FALSE;
645 if (viewer.Find(_T("\"%1\"")) >= 0)
647 viewer.Replace(_T("\"%1\""), file);
649 else if (viewer.Find(_T("%1")) >= 0)
651 viewer.Replace(_T("%1"), file);
653 else
655 viewer += _T(" ");
656 viewer += file;
659 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
661 return FALSE;
663 return TRUE;
666 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
668 DWORD length = 0;
669 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
670 if (!hFile)
671 return TRUE;
672 length = ::GetFileSize(hFile, NULL);
673 if (length < 4)
674 return TRUE;
675 return FALSE;
679 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
681 LOGFONT logFont;
682 HDC hScreenDC = ::GetDC(NULL);
683 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
684 ::ReleaseDC(NULL, hScreenDC);
685 logFont.lfWidth = 0;
686 logFont.lfEscapement = 0;
687 logFont.lfOrientation = 0;
688 logFont.lfWeight = FW_NORMAL;
689 logFont.lfItalic = 0;
690 logFont.lfUnderline = 0;
691 logFont.lfStrikeOut = 0;
692 logFont.lfCharSet = DEFAULT_CHARSET;
693 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
694 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
695 logFont.lfQuality = DRAFT_QUALITY;
696 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
697 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
698 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
701 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
703 CString key,remote;
704 CString cmd,out;
705 if( pRemote == NULL)
707 remote=_T("origin");
709 else
711 remote=*pRemote;
713 if(keyfile == NULL)
715 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
716 key = g_Git.GetConfigValue(cmd);
718 else
719 key=*keyfile;
721 if(key.IsEmpty())
722 return false;
724 CString proc=CPathUtils::GetAppDirectory();
725 proc += _T("pageant.exe \"");
726 proc += key;
727 proc += _T("\"");
729 CString tempfile = GetTempFile();
730 ::DeleteFile(tempfile);
732 proc += _T(" -c \"");
733 proc += CPathUtils::GetAppDirectory();
734 proc += _T("tgittouch.exe\"");
735 proc += _T(" \"");
736 proc += tempfile;
737 proc += _T("\"");
739 CString appDir = CPathUtils::GetAppDirectory();
740 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
741 if(!b)
742 return b;
744 int i=0;
745 while(!::PathFileExists(tempfile))
747 Sleep(100);
748 ++i;
749 if(i>10*60*5)
750 break; //timeout 5 minutes
753 if( i== 10*60*5)
755 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
757 ::DeleteFile(tempfile);
758 return true;
760 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
762 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
763 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
764 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
767 CString sCmd;
768 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
770 LaunchApplication(sCmd, NULL, false, NULL, uac);
771 return true;
773 bool CAppUtils::LaunchRemoteSetting()
775 CTGitPath path(g_Git.m_CurrentDir);
776 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
777 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
778 dlg.SetTreeWidth(220);
779 dlg.m_DefaultPage = _T("gitremote");
781 dlg.DoModal();
782 dlg.HandleRestart();
783 return true;
786 * Launch the external blame viewer
788 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile, const CString& Rev, const CString& sParams)
790 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
791 viewer += _T("TortoiseGitBlame.exe");
792 viewer += _T("\" \"") + sBlameFile + _T("\"");
793 //viewer += _T(" \"") + sLogFile + _T("\"");
794 //viewer += _T(" \"") + sOriginalFile + _T("\"");
795 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
796 viewer += CString(_T(" /rev:"))+Rev;
797 if (!g_sGroupingUUID.IsEmpty())
799 viewer += L" /groupuuid:\"";
800 viewer += g_sGroupingUUID;
801 viewer += L"\"";
803 viewer += _T(" ")+sParams;
805 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
808 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
810 CString sText;
811 if (pWnd == NULL)
812 return false;
813 bool bStyled = false;
814 pWnd->GetWindowText(sText);
815 // the rich edit control doesn't count the CR char!
816 // to be exact: CRLF is treated as one char.
817 sText.Remove(_T('\r'));
819 // style each line separately
820 int offset = 0;
821 int nNewlinePos;
824 nNewlinePos = sText.Find('\n', offset);
825 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
827 int start = 0;
828 int end = 0;
829 while (FindStyleChars(sLine, '*', start, end))
831 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
832 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
833 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
834 bStyled = true;
835 start = end;
837 start = 0;
838 end = 0;
839 while (FindStyleChars(sLine, '^', start, end))
841 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
842 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
843 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
844 bStyled = true;
845 start = end;
847 start = 0;
848 end = 0;
849 while (FindStyleChars(sLine, '_', start, end))
851 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
852 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
853 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
854 bStyled = true;
855 start = end;
857 offset = nNewlinePos+1;
858 } while(nNewlinePos>=0);
859 return bStyled;
862 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
864 int i=start;
865 int last = sText.GetLength() - 1;
866 bool bFoundMarker = false;
867 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
868 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
870 // find a starting marker
871 while (i < last)
873 TCHAR prevChar = c;
874 c = nextChar;
875 nextChar = sText[i + 1];
877 // IsCharAlphaNumeric can be somewhat expensive.
878 // Long lines of "*****" or "----" will be pre-empted efficiently
879 // by the (c != nextChar) condition.
881 if ((c == stylechar) && (c != nextChar))
883 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
885 start = ++i;
886 bFoundMarker = true;
887 break;
890 ++i;
892 if (!bFoundMarker)
893 return false;
895 // find ending marker
896 // c == sText[i - 1]
898 bFoundMarker = false;
899 while (i <= last)
901 TCHAR prevChar = c;
902 c = sText[i];
903 if (c == stylechar)
905 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
907 end = i;
908 ++i;
909 bFoundMarker = true;
910 break;
913 ++i;
915 return bFoundMarker;
918 // from CSciEdit
919 namespace {
920 bool IsValidURLChar(wchar_t ch)
922 return iswalnum(ch) ||
923 ch == L'_' || ch == L'/' || ch == L';' || ch == L'?' || ch == L'&' || ch == L'=' ||
924 ch == L'%' || ch == L':' || ch == L'.' || ch == L'#' || ch == L'-' || ch == L'+' ||
925 ch == L'|' || ch == L'>' || ch == L'<';
928 bool IsUrl(const CString& sText)
930 if (!PathIsURLW(sText))
931 return false;
932 CString prefixes[] = { L"http://", L"https://", L"git://", L"ftp://", L"file://", L"mailto:" };
933 for (const CString& prefix : prefixes)
935 if (sText.Find(prefix) == 0 && sText.GetLength() != prefix.GetLength())
936 return true;
938 return false;
942 BOOL CAppUtils::StyleURLs(const CString& msg, CWnd* pWnd)
944 std::vector<CHARRANGE> positions = FindURLMatches(msg);
945 CAppUtils::SetCharFormat(pWnd, CFM_LINK, CFE_LINK, positions);
947 return positions.empty() ? FALSE : TRUE;
951 * implements URL searching with the same logic as CSciEdit::StyleURLs
953 std::vector<CHARRANGE> CAppUtils::FindURLMatches(const CString& msg)
955 std::vector<CHARRANGE> result;
957 int len = msg.GetLength();
958 int starturl = -1;
960 for (int i = 0; i <= msg.GetLength(); ++i)
962 if ((i < len) && IsValidURLChar(msg[i]))
964 if (starturl < 0)
965 starturl = i;
967 else
969 if (starturl >= 0)
971 bool strip = true;
972 if (msg[starturl] == '<' && i < len) // try to detect and do not strip URLs put within <>
974 while (starturl <= i && msg[starturl] == '<') // strip leading '<'
975 ++starturl;
976 strip = false;
977 i = starturl;
978 while (i < len && msg[i] != '\r' && msg[i] != '\n' && msg[i] != '>') // find first '>' or new line after resetting i to start position
979 ++i;
981 if (!IsUrl(msg.Mid(starturl, i - starturl)))
983 starturl = -1;
984 continue;
987 int skipTrailing = 0;
988 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] == '<'))
989 ++skipTrailing;
991 CHARRANGE range = { starturl, i - skipTrailing };
992 result.push_back(range);
994 starturl = -1;
998 return result;
1001 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1002 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1003 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1004 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
1005 bool /* blame = false */,
1006 bool bMerge,
1007 bool bCombine)
1009 int diffContext = 0;
1010 if (GetMsysgitVersion() > 0x01080100)
1011 diffContext = g_Git.GetConfigValueInt32(_T("diff.context"), -1);
1012 CString tempfile=GetTempFile();
1013 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext))
1015 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
1016 return false;
1018 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
1020 #if 0
1021 CString sCmd;
1022 sCmd.Format(_T("%s /command:showcompare /unified"),
1023 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
1024 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1025 if (rev1.IsValid())
1026 sCmd += _T(" /revision1:") + rev1.ToString();
1027 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1028 if (rev2.IsValid())
1029 sCmd += _T(" /revision2:") + rev2.ToString();
1030 if (peg.IsValid())
1031 sCmd += _T(" /pegrevision:") + peg.ToString();
1032 if (headpeg.IsValid())
1033 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1035 if (bAlternateDiff)
1036 sCmd += _T(" /alternatediff");
1038 if (bIgnoreAncestry)
1039 sCmd += _T(" /ignoreancestry");
1041 if (hWnd)
1043 sCmd += _T(" /hwnd:");
1044 TCHAR buf[30];
1045 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
1046 sCmd += buf;
1049 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1050 #endif
1051 return TRUE;
1054 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1056 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1057 scriptsdir += _T("Diff-Scripts");
1058 CSimpleFileFind files(scriptsdir);
1059 while (files.FindNextFileNoDirectories())
1061 CString file = files.GetFilePath();
1062 CString filename = files.GetFileName();
1063 CString ext = file.Mid(file.ReverseFind('-') + 1);
1064 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
1065 std::set<CString> extensions;
1066 extensions.insert(ext);
1067 CString kind;
1068 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
1070 kind = _T(" //E:vbscript");
1072 if (file.Right(2).CompareNoCase(_T("js"))==0)
1074 kind = _T(" //E:javascript");
1076 // open the file, read the first line and find possible extensions
1077 // this script can handle
1080 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1081 CString extline;
1082 if (f.ReadString(extline))
1084 if ((extline.GetLength() > 15 ) &&
1085 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
1086 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
1088 if (extline[0] == '/')
1089 extline = extline.Mid(15);
1090 else
1091 extline = extline.Mid(14);
1092 CString sToken;
1093 int curPos = 0;
1094 sToken = extline.Tokenize(_T(";"), curPos);
1095 while (!sToken.IsEmpty())
1097 if (!sToken.IsEmpty())
1099 if (sToken[0] != '.')
1100 sToken = _T(".") + sToken;
1101 extensions.insert(sToken);
1103 sToken = extline.Tokenize(_T(";"), curPos);
1107 f.Close();
1109 catch (CFileException* e)
1111 e->Delete();
1114 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
1116 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1118 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1120 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
1121 CString diffregstring = diffreg;
1122 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1123 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1126 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1128 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1130 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
1131 CString diffregstring = diffreg;
1132 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1133 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1139 return true;
1142 bool CAppUtils::Export(const CString* BashHash, const CTGitPath* orgPath)
1144 // ask from where the export has to be done
1145 CExportDlg dlg;
1146 if(BashHash)
1147 dlg.m_initialRefName=*BashHash;
1148 if (orgPath)
1150 if (PathIsRelative(orgPath->GetWinPath()))
1151 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1152 else
1153 dlg.m_orgPath = *orgPath;
1156 if (dlg.DoModal() == IDOK)
1158 CString cmd;
1159 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1160 dlg.m_strFile, g_Git.FixBranchName(dlg.m_VersionName));
1162 CProgressDlg pro;
1163 pro.m_GitCmd=cmd;
1164 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1166 if (status)
1167 return;
1168 postCmdList.push_back(PostCmd(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); }));
1171 CGit git;
1172 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1174 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1175 pro.m_Git = &git;
1177 return (pro.DoModal() == IDOK);
1179 return false;
1182 bool CAppUtils::CreateBranchTag(bool IsTag, const CString* CommitHash, bool switch_new_brach)
1184 CCreateBranchTagDlg dlg;
1185 dlg.m_bIsTag=IsTag;
1186 dlg.m_bSwitch=switch_new_brach;
1188 if(CommitHash)
1189 dlg.m_initialRefName = *CommitHash;
1191 if(dlg.DoModal()==IDOK)
1193 CString cmd;
1194 CString force;
1195 CString track;
1196 if(dlg.m_bTrack == TRUE)
1197 track=_T(" --track ");
1198 else if(dlg.m_bTrack == FALSE)
1199 track=_T(" --no-track");
1201 if(dlg.m_bForce)
1202 force=_T(" -f ");
1204 if(IsTag)
1206 CString sign;
1207 if(dlg.m_bSign)
1208 sign=_T("-s");
1210 cmd.Format(_T("git.exe tag %s %s %s %s"),
1211 force,
1212 sign,
1213 dlg.m_BranchTagName,
1214 g_Git.FixBranchName(dlg.m_VersionName)
1217 if(!dlg.m_Message.Trim().IsEmpty())
1219 CString tempfile = ::GetTempFile();
1220 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1222 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1223 return FALSE;
1225 cmd += _T(" -F ")+tempfile;
1228 else
1230 cmd.Format(_T("git.exe branch %s %s %s %s"),
1231 track,
1232 force,
1233 dlg.m_BranchTagName,
1234 g_Git.FixBranchName(dlg.m_VersionName)
1237 CString out;
1238 if(g_Git.Run(cmd,&out,CP_UTF8))
1240 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1241 return FALSE;
1243 if( !IsTag && dlg.m_bSwitch )
1245 // it is a new branch and the user has requested to switch to it
1246 PerformSwitch(dlg.m_BranchTagName);
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 (dlg.m_VersionName.Left(11) ==_T("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)
1287 branch.Format(_T("-B %s "), sNewBranch);
1289 else
1291 branch.Format(_T("-b %s "), sNewBranch);
1293 if (bTrack == TRUE)
1294 track = _T("--track ");
1295 else if (bTrack == FALSE)
1296 track = _T("--no-track ");
1298 if (bForce)
1299 force = _T("-f ");
1300 if (bMerge)
1301 merge = _T("--merge ");
1303 cmd.Format(_T("git.exe checkout %s%s%s%s%s --"),
1304 force,
1305 track,
1306 merge,
1307 branch,
1308 g_Git.FixBranchName(ref));
1310 CProgressDlg progress;
1311 progress.m_GitCmd = cmd;
1313 CString currentBranch;
1314 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1315 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1317 if (!status)
1319 CTGitPath gitPath = g_Git.m_CurrentDir;
1320 if (gitPath.HasSubmodules())
1322 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1324 CString sCmd;
1325 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1326 RunTortoiseGitProc(sCmd);
1327 }));
1329 if (hasBranch)
1330 postCmdList.push_back(PostCmd(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); }));
1333 CString newBranch;
1334 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1335 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
1337 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []{
1338 CTGitPathList pathlist;
1339 CTGitPathList selectedlist;
1340 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
1341 CString str;
1342 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1343 }));
1345 else
1347 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); }));
1348 if (!bMerge)
1349 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); }));
1353 INT_PTR ret = progress.DoModal();
1355 return ret == IDOK;
1358 class CIgnoreFile : public CStdioFile
1360 public:
1361 STRING_VECTOR m_Items;
1362 CString m_eol;
1364 virtual BOOL ReadString(CString& rString)
1366 if (GetPosition() == 0)
1368 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1369 char buf[3] = { 0, 0, 0 };
1370 Read(buf, 3);
1371 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1373 SeekToBegin();
1377 CStringA strA;
1378 char lastChar = '\0';
1379 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1381 if (c == '\r')
1382 continue;
1383 if (c == '\n')
1385 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1386 break;
1388 strA.AppendChar(c);
1390 if (strA.IsEmpty())
1391 return FALSE;
1393 rString = CUnicodeUtils::GetUnicode(strA);
1394 return TRUE;
1397 void ResetState()
1399 m_Items.clear();
1400 m_eol = _T("");
1404 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1406 file.ResetState();
1407 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1409 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1410 return false;
1413 if (file.GetLength() > 0)
1415 CString fileText;
1416 while (file.ReadString(fileText))
1417 file.m_Items.push_back(fileText);
1418 file.Seek(file.GetLength() - 1, 0);
1419 char lastchar[1] = { 0 };
1420 file.Read(lastchar, 1);
1421 file.SeekToEnd();
1422 if (lastchar[0] != '\n')
1424 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1425 file.Write(eol, eol.GetLength());
1428 else
1429 file.SeekToEnd();
1431 return true;
1434 bool CAppUtils::IgnoreFile(const CTGitPathList& path,bool IsMask)
1436 CIgnoreDlg ignoreDlg;
1437 if (ignoreDlg.DoModal() == IDOK)
1439 CString ignorefile;
1440 ignorefile = g_Git.m_CurrentDir + _T("\\");
1442 switch (ignoreDlg.m_IgnoreFile)
1444 case 0:
1445 ignorefile += _T(".gitignore");
1446 break;
1447 case 2:
1448 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1449 ignorefile += _T("info/exclude");
1450 break;
1453 CIgnoreFile file;
1456 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1457 return false;
1459 for (int i = 0; i < path.GetCount(); ++i)
1461 if (ignoreDlg.m_IgnoreFile == 1)
1463 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1464 if (!OpenIgnoreFile(file, ignorefile))
1465 return false;
1468 CString ignorePattern;
1469 if (ignoreDlg.m_IgnoreType == 0)
1471 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1472 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1474 ignorePattern += _T("/");
1476 if (IsMask)
1478 ignorePattern += _T("*") + path[i].GetFileExtension();
1480 else
1482 ignorePattern += path[i].GetFileOrDirectoryName();
1485 // escape [ and ] so that files get ignored correctly
1486 ignorePattern.Replace(_T("["), _T("\\["));
1487 ignorePattern.Replace(_T("]"), _T("\\]"));
1489 bool found = false;
1490 for (size_t j = 0; j < file.m_Items.size(); ++j)
1492 if (file.m_Items[j] == ignorePattern)
1494 found = true;
1495 break;
1498 if (!found)
1500 file.m_Items.push_back(ignorePattern);
1501 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1502 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1503 file.Write(ignorePatternA, ignorePatternA.GetLength());
1506 if (ignoreDlg.m_IgnoreFile == 1)
1507 file.Close();
1510 if (ignoreDlg.m_IgnoreFile != 1)
1511 file.Close();
1513 catch(...)
1515 file.Abort();
1516 return false;
1519 return true;
1521 return false;
1524 static bool Reset(const CString& resetTo, int resetType)
1526 CString cmd;
1527 CString type;
1528 switch (resetType)
1530 case 0:
1531 type = _T("--soft");
1532 break;
1533 case 1:
1534 type = _T("--mixed");
1535 break;
1536 case 2:
1537 type = _T("--hard");
1538 break;
1539 default:
1540 resetType = 1;
1541 type = _T("--mixed");
1542 break;
1544 cmd.Format(_T("git.exe reset %s %s --"), type, resetTo);
1546 CProgressDlg progress;
1547 progress.m_GitCmd = cmd;
1549 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1551 if (status)
1553 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); }));
1554 return;
1557 CTGitPath gitPath = g_Git.m_CurrentDir;
1558 if (gitPath.HasSubmodules() && resetType == 2)
1560 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1562 CString sCmd;
1563 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1564 CAppUtils::RunTortoiseGitProc(sCmd);
1565 }));
1569 INT_PTR ret;
1570 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1572 CGitProgressDlg gitdlg;
1573 ResetProgressCommand resetProgressCommand;
1574 gitdlg.SetCommand(&resetProgressCommand);
1575 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1576 resetProgressCommand.SetRevision(resetTo);
1577 resetProgressCommand.SetResetType(resetType);
1578 ret = gitdlg.DoModal();
1580 else
1581 ret = progress.DoModal();
1583 return ret == IDOK;
1586 bool CAppUtils::GitReset(const CString* CommitHash, int type)
1588 CResetDlg dlg;
1589 dlg.m_ResetType=type;
1590 dlg.m_ResetToVersion=*CommitHash;
1591 dlg.m_initialRefName = *CommitHash;
1592 if (dlg.DoModal() == IDOK)
1593 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1595 return false;
1598 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1600 if(mode == FALSE)
1602 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1603 return;
1605 if(base)
1607 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1608 return;
1610 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1611 return;
1614 void CAppUtils::RemoveTempMergeFile(const CTGitPath& path)
1616 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1617 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1618 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1620 CString CAppUtils::GetMergeTempFile(const CString& type, const CTGitPath &merge)
1622 CString file;
1623 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1625 return file;
1628 bool ParseHashesFromLsFile(const BYTE_VECTOR& out, CString& hash1, CString& hash2, CString& hash3)
1630 int pos = 0;
1631 CString one;
1632 CString part;
1634 while (pos >= 0 && pos < (int)out.size())
1636 one.Empty();
1638 CGit::StringAppend(&one, &out[pos], CP_UTF8);
1639 int tabstart = 0;
1640 one.Tokenize(_T("\t"), tabstart);
1642 tabstart = 0;
1643 part = one.Tokenize(_T(" "), tabstart); //Tag
1644 part = one.Tokenize(_T(" "), tabstart); //Mode
1645 part = one.Tokenize(_T(" "), tabstart); //Hash
1646 CString hash = part;
1647 part = one.Tokenize(_T("\t"), tabstart); //Stage
1648 int stage = _ttol(part);
1649 if (stage == 1)
1650 hash1 = hash;
1651 else if (stage == 2)
1652 hash2 = hash;
1653 else if (stage == 3)
1655 hash3 = hash;
1656 return true;
1659 pos = out.findNextString(pos);
1662 return false;
1665 bool CAppUtils::ConflictEdit(const CTGitPath& path, bool /*bAlternativeTool = false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1667 bool bRet = false;
1669 CTGitPath merge=path;
1670 CTGitPath directory = merge.GetDirectory();
1672 // we have the conflicted file (%merged)
1673 // now look for the other required files
1674 //GitStatus stat;
1675 //stat.GetStatus(merge);
1676 //if (stat.status == NULL)
1677 // return false;
1679 BYTE_VECTOR vector;
1681 CString cmd;
1682 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1684 if (g_Git.Run(cmd, &vector))
1686 return FALSE;
1689 if (merge.IsDirectory())
1691 CString baseHash, realBaseHash(GIT_REV_ZERO), localHash(GIT_REV_ZERO), remoteHash(GIT_REV_ZERO);
1692 if (merge.HasAdminDir()) {
1693 CGit subgit;
1694 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1695 CGitHash hash;
1696 subgit.GetHash(hash, _T("HEAD"));
1697 baseHash = hash;
1699 if (ParseHashesFromLsFile(vector, realBaseHash, localHash, remoteHash)) // in base no submodule, but in remote submodule
1700 baseHash = realBaseHash;
1702 CGitDiff::ChangeType changeTypeMine = CGitDiff::Unknown;
1703 CGitDiff::ChangeType changeTypeTheirs = CGitDiff::Unknown;
1705 bool baseOK = false, mineOK = false, theirsOK = false;
1706 CString baseSubject, mineSubject, theirsSubject;
1707 if (merge.HasAdminDir())
1709 CGit subgit;
1710 subgit.m_CurrentDir = g_Git.CombinePath(merge);
1711 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, localHash, baseOK, mineOK, changeTypeMine, baseSubject, mineSubject);
1712 CGitDiff::GetSubmoduleChangeType(subgit, baseHash, remoteHash, baseOK, theirsOK, changeTypeTheirs, baseSubject, theirsSubject);
1714 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)
1716 changeTypeMine = CGitDiff::Identical;
1717 changeTypeTheirs = CGitDiff::NewSubmodule;
1718 baseSubject = _T("no submodule");
1719 mineSubject = baseSubject;
1720 theirsSubject = _T("not initialized");
1722 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
1724 baseHash = localHash;
1725 baseSubject = _T("not initialized");
1726 mineSubject = baseSubject;
1727 theirsSubject = _T("not initialized");
1728 changeTypeMine = CGitDiff::Identical;
1729 changeTypeTheirs = CGitDiff::DeleteSubmodule;
1731 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
1733 baseSubject = _T("not initialized");
1734 mineSubject = baseSubject;
1735 theirsSubject = baseSubject;
1736 if (baseHash == localHash)
1737 changeTypeMine = CGitDiff::Identical;
1739 else
1740 return FALSE;
1742 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog;
1743 resolveSubmoduleConflictDialog.SetDiff(merge.GetGitPathString(), revertTheirMy, baseHash, baseSubject, baseOK, localHash, mineSubject, mineOK, changeTypeMine, remoteHash, theirsSubject, theirsOK, changeTypeTheirs);
1744 resolveSubmoduleConflictDialog.DoModal();
1745 if (resolveSubmoduleConflictDialog.m_bResolved && resolveMsgHwnd)
1747 static UINT WM_REVERTMSG = RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1748 ::PostMessage(resolveMsgHwnd, WM_REVERTMSG, NULL, NULL);
1751 return TRUE;
1754 CTGitPathList list;
1755 if (list.ParserFromLsFile(vector))
1757 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1758 return FALSE;
1761 if (list.IsEmpty())
1762 return FALSE;
1764 CTGitPath theirs;
1765 CTGitPath mine;
1766 CTGitPath base;
1768 if (revertTheirMy)
1770 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1771 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1773 else
1775 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1776 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1778 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1780 CString format;
1782 //format=_T("git.exe cat-file blob \":%d:%s\"");
1783 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1784 CFile tempfile;
1785 //create a empty file, incase stage is not three
1786 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1787 tempfile.Close();
1788 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1789 tempfile.Close();
1790 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1791 tempfile.Close();
1793 bool b_base=false, b_local=false, b_remote=false;
1795 for (int i = 0; i< list.GetCount(); ++i)
1797 CString outfile;
1798 cmd.Empty();
1799 outfile.Empty();
1801 if( list[i].m_Stage == 1)
1803 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1804 b_base = true;
1805 outfile = base.GetWinPathString();
1808 if( list[i].m_Stage == 2 )
1810 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1811 b_local = true;
1812 outfile = mine.GetWinPathString();
1815 if( list[i].m_Stage == 3 )
1817 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1818 b_remote = true;
1819 outfile = theirs.GetWinPathString();
1821 CString output, err;
1822 if(!outfile.IsEmpty())
1823 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1825 CString file;
1826 int start =0 ;
1827 file = output.Tokenize(_T("\t"), start);
1828 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1830 else
1832 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1836 if(b_local && b_remote )
1838 merge.SetFromWin(g_Git.CombinePath(merge));
1839 if( revertTheirMy )
1840 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd, true);
1841 else
1842 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd, true);
1845 else
1847 ::DeleteFile(mine.GetWinPathString());
1848 ::DeleteFile(theirs.GetWinPathString());
1849 ::DeleteFile(base.GetWinPathString());
1851 CDeleteConflictDlg dlg;
1852 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1853 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1854 CGitHash localHash, remoteHash;
1855 if (!g_Git.GetHash(localHash, _T("HEAD")))
1856 dlg.m_LocalHash = localHash.ToString();
1857 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1858 dlg.m_RemoteHash = remoteHash.ToString();
1859 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1860 dlg.m_RemoteHash = remoteHash.ToString();
1861 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1862 dlg.m_RemoteHash = remoteHash.ToString();
1863 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1864 dlg.m_RemoteHash = remoteHash.ToString();
1865 dlg.m_bShowModifiedButton=b_base;
1866 dlg.m_File=merge.GetGitPathString();
1867 if(dlg.DoModal() == IDOK)
1869 CString out;
1870 if(dlg.m_bIsDelete)
1872 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1874 else
1875 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1877 if (g_Git.Run(cmd, &out, CP_UTF8))
1879 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1880 return FALSE;
1882 return TRUE;
1884 else
1885 return FALSE;
1888 #if 0
1889 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1890 base, theirs, mine, merge);
1891 #endif
1892 #if 0
1893 if (stat.status->text_status == svn_wc_status_conflicted)
1895 // we have a text conflict, use our merge tool to resolve the conflict
1897 CTSVNPath theirs(directory);
1898 CTSVNPath mine(directory);
1899 CTSVNPath base(directory);
1900 bool bConflictData = false;
1902 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1904 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1905 bConflictData = true;
1907 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1909 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1910 bConflictData = true;
1912 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1914 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1915 bConflictData = true;
1917 else
1919 mine = merge;
1921 if (bConflictData)
1922 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1923 base, theirs, mine, merge);
1926 if (stat.status->prop_status == svn_wc_status_conflicted)
1928 // we have a property conflict
1929 CTSVNPath prej(directory);
1930 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1932 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1933 // there's a problem: the prej file contains a _description_ of the conflict, and
1934 // that description string might be translated. That means we have no way of parsing
1935 // the file to find out the conflicting values.
1936 // The only thing we can do: show a dialog with the conflict description, then
1937 // let the user either accept the existing property or open the property edit dialog
1938 // to manually change the properties and values. And a button to mark the conflict as
1939 // resolved.
1940 CEditPropConflictDlg dlg;
1941 dlg.SetPrejFile(prej);
1942 dlg.SetConflictedItem(merge);
1943 bRet = (dlg.DoModal() != IDCANCEL);
1947 if (stat.status->tree_conflict)
1949 // we have a tree conflict
1950 SVNInfo info;
1951 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1952 if (pInfoData)
1954 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1956 CTSVNPath theirs(directory);
1957 CTSVNPath mine(directory);
1958 CTSVNPath base(directory);
1959 bool bConflictData = false;
1961 if (pInfoData->treeconflict_theirfile)
1963 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1964 bConflictData = true;
1966 if (pInfoData->treeconflict_basefile)
1968 base.AppendPathString(pInfoData->treeconflict_basefile);
1969 bConflictData = true;
1971 if (pInfoData->treeconflict_myfile)
1973 mine.AppendPathString(pInfoData->treeconflict_myfile);
1974 bConflictData = true;
1976 else
1978 mine = merge;
1980 if (bConflictData)
1981 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1982 base, theirs, mine, merge);
1984 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1986 CString sConflictAction;
1987 CString sConflictReason;
1988 CString sResolveTheirs;
1989 CString sResolveMine;
1990 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1991 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1993 if (pInfoData->treeconflict_nodekind == svn_node_file)
1995 switch (pInfoData->treeconflict_operation)
1997 case svn_wc_operation_update:
1998 switch (pInfoData->treeconflict_action)
2000 case svn_wc_conflict_action_edit:
2001 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
2002 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2003 break;
2004 case svn_wc_conflict_action_add:
2005 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
2006 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2007 break;
2008 case svn_wc_conflict_action_delete:
2009 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
2010 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2011 break;
2013 break;
2014 case svn_wc_operation_switch:
2015 switch (pInfoData->treeconflict_action)
2017 case svn_wc_conflict_action_edit:
2018 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
2019 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2020 break;
2021 case svn_wc_conflict_action_add:
2022 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
2023 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2024 break;
2025 case svn_wc_conflict_action_delete:
2026 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
2027 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2028 break;
2030 break;
2031 case svn_wc_operation_merge:
2032 switch (pInfoData->treeconflict_action)
2034 case svn_wc_conflict_action_edit:
2035 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
2036 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2037 break;
2038 case svn_wc_conflict_action_add:
2039 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
2040 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
2041 break;
2042 case svn_wc_conflict_action_delete:
2043 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
2044 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2045 break;
2047 break;
2050 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
2052 switch (pInfoData->treeconflict_operation)
2054 case svn_wc_operation_update:
2055 switch (pInfoData->treeconflict_action)
2057 case svn_wc_conflict_action_edit:
2058 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
2059 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2060 break;
2061 case svn_wc_conflict_action_add:
2062 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
2063 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2064 break;
2065 case svn_wc_conflict_action_delete:
2066 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
2067 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2068 break;
2070 break;
2071 case svn_wc_operation_switch:
2072 switch (pInfoData->treeconflict_action)
2074 case svn_wc_conflict_action_edit:
2075 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
2076 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2077 break;
2078 case svn_wc_conflict_action_add:
2079 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
2080 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2081 break;
2082 case svn_wc_conflict_action_delete:
2083 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
2084 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2085 break;
2087 break;
2088 case svn_wc_operation_merge:
2089 switch (pInfoData->treeconflict_action)
2091 case svn_wc_conflict_action_edit:
2092 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
2093 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2094 break;
2095 case svn_wc_conflict_action_add:
2096 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
2097 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
2098 break;
2099 case svn_wc_conflict_action_delete:
2100 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
2101 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
2102 break;
2104 break;
2108 UINT uReasonID = 0;
2109 switch (pInfoData->treeconflict_reason)
2111 case svn_wc_conflict_reason_edited:
2112 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
2113 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2114 break;
2115 case svn_wc_conflict_reason_obstructed:
2116 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
2117 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2118 break;
2119 case svn_wc_conflict_reason_deleted:
2120 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
2121 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2122 break;
2123 case svn_wc_conflict_reason_added:
2124 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
2125 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2126 break;
2127 case svn_wc_conflict_reason_missing:
2128 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
2129 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
2130 break;
2131 case svn_wc_conflict_reason_unversioned:
2132 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
2133 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
2134 break;
2136 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
2138 CTreeConflictEditorDlg dlg;
2139 dlg.SetConflictInfoText(sConflictReason);
2140 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
2141 dlg.SetPath(treeConflictPath);
2142 INT_PTR dlgRet = dlg.DoModal();
2143 bRet = (dlgRet != IDCANCEL);
2147 #endif
2148 return bRet;
2151 bool CAppUtils::IsSSHPutty()
2153 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2154 sshclient=sshclient.MakeLower();
2155 if(sshclient.Find(_T("plink.exe"),0)>=0)
2157 return true;
2159 return false;
2162 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2164 if (!OpenClipboard(NULL))
2165 return CString();
2167 CString sClipboardText;
2168 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2169 if (hglb)
2171 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2172 sClipboardText = CString(lpstr);
2173 GlobalUnlock(hglb);
2175 hglb = GetClipboardData(CF_UNICODETEXT);
2176 if (hglb)
2178 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2179 sClipboardText = lpstr;
2180 GlobalUnlock(hglb);
2182 CloseClipboard();
2184 if(!sClipboardText.IsEmpty())
2186 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2187 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2189 if(sClipboardText.Find( _T("http://")) == 0)
2190 return sClipboardText;
2192 if(sClipboardText.Find( _T("https://")) == 0)
2193 return sClipboardText;
2195 if(sClipboardText.Find( _T("git://")) == 0)
2196 return sClipboardText;
2198 if(sClipboardText.Find( _T("ssh://")) == 0)
2199 return sClipboardText;
2201 if (sClipboardText.Find(_T("git@")) == 0)
2202 return sClipboardText;
2204 if(sClipboardText.GetLength()>=2)
2205 if( sClipboardText[1] == _T(':') )
2206 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2207 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2208 return sClipboardText;
2210 // trim prefixes like "git clone "
2211 if (!skipGitPrefix.IsEmpty() && sClipboardText.Find(skipGitPrefix) == 0)
2213 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2214 int spacePos = -1;
2215 while (paramsCount >= 0)
2217 --paramsCount;
2218 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2219 if (spacePos == -1)
2220 break;
2222 if (spacePos > 0 && paramsCount < 0)
2223 sClipboardText = sClipboardText.Left(spacePos);
2224 return sClipboardText;
2228 return CString(_T(""));
2231 CString CAppUtils::ChooseRepository(const CString* path)
2233 CBrowseFolder browseFolder;
2234 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2236 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2237 CString strCloneDirectory;
2238 if(path)
2239 strCloneDirectory=*path;
2240 else
2242 strCloneDirectory = regLastResopitory;
2245 CString title;
2246 title.LoadString(IDS_CHOOSE_REPOSITORY);
2248 browseFolder.SetInfo(title);
2250 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2252 regLastResopitory = strCloneDirectory;
2253 return strCloneDirectory;
2255 else
2257 return CString();
2261 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2263 CSendMailDlg dlg;
2265 dlg.m_PathList = list;
2267 if(dlg.DoModal()==IDOK)
2269 if (dlg.m_PathList.IsEmpty())
2270 return FALSE;
2272 CGitProgressDlg progDlg;
2273 if (bIsMainWnd)
2274 theApp.m_pMainWnd = &progDlg;
2275 SendMailProgressCommand sendMailProgressCommand;
2276 progDlg.SetCommand(&sendMailProgressCommand);
2278 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2279 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2281 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2282 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2284 progDlg.DoModal();
2286 return true;
2288 return false;
2291 bool CAppUtils::SendPatchMail(const CString& cmd, const CString& formatpatchoutput, bool bIsMainWnd)
2293 CTGitPathList list;
2294 CString log=formatpatchoutput;
2295 int start=log.Find(cmd);
2296 if(start >=0)
2297 CString one=log.Tokenize(_T("\n"),start);
2298 else
2299 start = 0;
2301 while(start>=0)
2303 CString one=log.Tokenize(_T("\n"),start);
2304 one=one.Trim();
2305 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2306 continue;
2307 one.Replace(_T('/'),_T('\\'));
2308 CTGitPath path;
2309 path.SetFromWin(one);
2310 list.AddPath(path);
2312 if (!list.IsEmpty())
2314 return SendPatchMail(list, bIsMainWnd);
2316 else
2318 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2319 return true;
2324 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2326 CString output;
2327 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2328 if(output.IsEmpty())
2329 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2330 else
2332 return CUnicodeUtils::GetCPCode(output);
2335 int CAppUtils::SaveCommitUnicodeFile(const CString& filename, CString &message)
2339 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2340 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2342 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2344 if (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE)
2345 message.TrimRight(L" \r\n");
2347 int len = message.GetLength();
2348 int start = 0;
2349 while (start >= 0 && start < len)
2351 int oldStart = start;
2352 start = message.Find(L"\n", oldStart);
2353 CString line = message.Mid(oldStart);
2354 if (start != -1)
2356 line = line.Left(start - oldStart);
2357 ++start; // move forward so we don't find the same char again
2359 if (stripComments && (line.GetLength() >= 1 && line.GetAt(0) == '#') || (start < 0 && line.IsEmpty()))
2360 continue;
2361 line.TrimRight(L" \r");
2362 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2363 file.Write(lineA.GetBuffer(), lineA.GetLength());
2365 file.Close();
2366 return 0;
2368 catch (CFileException *e)
2370 e->Delete();
2371 return -1;
2375 bool CAppUtils::Pull(bool showPush, bool showStashPop)
2377 CPullFetchDlg dlg;
2378 dlg.m_IsPull = TRUE;
2379 if (dlg.DoModal() == IDOK)
2381 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2382 if (dlg.m_bRebase)
2383 return DoFetch(dlg.m_RemoteURL,
2384 FALSE, // Fetch all remotes
2385 dlg.m_bAutoLoad == BST_CHECKED,
2386 dlg.m_bPrune,
2387 dlg.m_bDepth == BST_CHECKED,
2388 dlg.m_nDepth,
2389 dlg.m_bFetchTags,
2390 dlg.m_RemoteBranchName,
2391 TRUE); // Rebase after fetching
2393 CString url = dlg.m_RemoteURL;
2395 if (dlg.m_bAutoLoad)
2397 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2400 CString cmd;
2401 CGitHash hashOld;
2402 if (g_Git.GetHash(hashOld, _T("HEAD")))
2404 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
2405 return false;
2408 CString cmdRebase;
2409 CString noff;
2410 CString ffonly;
2411 CString squash;
2412 CString nocommit;
2413 CString depth;
2414 CString notags;
2415 CString prune;
2417 if (!dlg.m_bFetchTags)
2418 notags = _T("--no-tags ");
2420 if (dlg.m_bFetchTags == TRUE)
2421 notags = _T("--tags ");
2423 if (dlg.m_bNoFF)
2424 noff=_T("--no-ff ");
2426 if (dlg.m_bFFonly)
2427 ffonly = _T("--ff-only ");
2429 if (dlg.m_bSquash)
2430 squash = _T("--squash ");
2432 if (dlg.m_bNoCommit)
2433 nocommit = _T("--no-commit ");
2435 if (dlg.m_bDepth)
2436 depth.Format(_T("--depth %d "), dlg.m_nDepth);
2438 int ver = CAppUtils::GetMsysgitVersion();
2440 if (dlg.m_bPrune == TRUE)
2441 prune = _T("--prune ");
2442 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2443 prune = _T("--no-prune ");
2445 if(ver >= 0x01070203) //above 1.7.0.2
2446 cmdRebase += _T("--progress ");
2448 cmd.Format(_T("git.exe pull -v %s%s%s%s%s%s%s%s\"%s\" %s"), cmdRebase, noff, ffonly, squash, nocommit, depth, notags, prune, url, dlg.m_RemoteBranchName);
2449 CProgressDlg progress;
2450 progress.m_GitCmd = cmd;
2452 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2453 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2455 if (status)
2457 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
2458 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ StashSave(_T(""), true); }));
2459 return;
2462 if (showStashPop)
2463 postCmdList.push_back(PostCmd(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ StashPop(); }));
2465 if (g_Git.GetHash(hashNew, _T("HEAD")))
2466 MessageBox(nullptr, g_Git.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR);
2467 else
2469 postCmdList.push_back(PostCmd(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2471 CFileDiffDlg dlg;
2472 dlg.SetDiff(NULL, hashNew.ToString(), hashOld.ToString());
2473 dlg.DoModal();
2474 }));
2475 postCmdList.push_back(PostCmd(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2477 CLogDlg dlg;
2478 dlg.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld.ToString() + _T("..") + hashNew.ToString(), 0);
2479 dlg.DoModal();
2480 }));
2483 if (showPush)
2484 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(_T("")); }));
2486 CTGitPath gitPath = g_Git.m_CurrentDir;
2487 if (gitPath.HasSubmodules())
2489 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2491 CString sCmd;
2492 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2493 CAppUtils::RunTortoiseGitProc(sCmd);
2494 }));
2498 INT_PTR ret = progress.DoModal();
2500 if (ret == IDOK && progress.m_GitStatus == 1 && progress.m_LogText.Find(_T("CONFLICT")) >= 0 && CMessageBox::Show(NULL, IDS_SEECHANGES, IDS_APPNAME, MB_YESNO | MB_ICONINFORMATION) == IDYES)
2502 CChangedDlg changeddlg;
2503 changeddlg.m_pathList.AddPath(CTGitPath());
2504 changeddlg.DoModal();
2506 return true;
2509 return ret == IDOK;
2512 return false;
2515 bool CAppUtils::RebaseAfterFetch(const CString& upstream)
2517 while (true)
2519 CRebaseDlg dlg;
2520 if (!upstream.IsEmpty())
2521 dlg.m_Upstream = upstream;
2522 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2523 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2524 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2525 INT_PTR response = dlg.DoModal();
2526 if (response == IDOK)
2528 return true;
2530 else if (response == IDC_REBASE_POST_BUTTON)
2532 CString cmd = _T("/command:log");
2533 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2534 CAppUtils::RunTortoiseGitProc(cmd);
2535 return true;
2537 else if (response == IDC_REBASE_POST_BUTTON + 1)
2539 CString cmd, out, err;
2540 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2541 g_Git.m_CurrentDir,
2542 g_Git.FixBranchName(dlg.m_Upstream),
2543 g_Git.FixBranchName(dlg.m_Branch));
2544 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2546 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2547 return false;
2549 CAppUtils::SendPatchMail(cmd, out);
2550 return true;
2552 else if (response == IDC_REBASE_POST_BUTTON + 2)
2553 continue;
2554 else if (response == IDCANCEL)
2555 return false;
2556 return false;
2560 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, boolean runRebase)
2562 if (loadPuttyAgent)
2564 if (fetchAllRemotes)
2566 STRING_VECTOR list;
2567 g_Git.GetRemoteList(list);
2569 STRING_VECTOR::const_iterator it = list.begin();
2570 while (it != list.end())
2572 CString remote(*it);
2573 CAppUtils::LaunchPAgent(NULL, &remote);
2574 ++it;
2577 else
2578 CAppUtils::LaunchPAgent(NULL, &url);
2581 CString cmd, arg;
2582 int ver = CAppUtils::GetMsysgitVersion();
2583 if (ver >= 0x01070203) //above 1.7.0.2
2584 arg += _T(" --progress");
2586 if (bDepth)
2587 arg.AppendFormat(_T(" --depth %d"), nDepth);
2589 if (prune == TRUE)
2590 arg += _T(" --prune");
2591 else if (prune == FALSE && ver >= 0x01080500)
2592 arg += _T(" --no-prune");
2594 if (fetchTags == 1)
2595 arg += _T(" --tags");
2596 else if (fetchTags == 0)
2597 arg += _T(" --no-tags");
2599 if (fetchAllRemotes)
2600 cmd.Format(_T("git.exe fetch --all -v%s"), arg);
2601 else
2602 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), arg, url, remoteBranch);
2604 CProgressDlg progress;
2605 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2607 if (status)
2609 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase); }));
2610 return;
2613 postCmdList.push_back(PostCmd(IDI_LOG, IDS_MENULOG, []
2615 CString cmd = _T("/command:log");
2616 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2617 CAppUtils::RunTortoiseGitProc(cmd);
2618 }));
2620 postCmdList.push_back(PostCmd(IDI_REVERT, IDS_PROC_RESET, []
2622 CString pullRemote, pullBranch;
2623 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2624 CString defaultUpstream;
2625 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2626 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2627 CAppUtils::GitReset(&defaultUpstream, 2);
2628 }));
2630 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); }));
2632 if (!runRebase && !GitAdminDir::IsBareRepo(g_Git.m_CurrentDir))
2633 postCmdList.push_back(PostCmd(IDI_REBASE, IDS_MENUREBASE, [&]{ runRebase = false; CAppUtils::RebaseAfterFetch(); }));
2636 progress.m_GitCmd = cmd;
2637 INT_PTR userResponse;
2639 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2641 CGitProgressDlg gitdlg;
2642 FetchProgressCommand fetchProgressCommand;
2643 if (!fetchAllRemotes)
2644 fetchProgressCommand.SetUrl(url);
2645 gitdlg.SetCommand(&fetchProgressCommand);
2646 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2647 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2648 if (!fetchAllRemotes)
2649 fetchProgressCommand.SetRefSpec(remoteBranch);
2650 userResponse = gitdlg.DoModal();
2651 return userResponse == IDOK;
2654 userResponse = progress.DoModal();
2655 if (!progress.m_GitStatus)
2657 if (runRebase)
2658 return CAppUtils::RebaseAfterFetch();
2661 return userResponse == IDOK;
2664 bool CAppUtils::Fetch(const CString& remoteName, bool allRemotes)
2666 CPullFetchDlg dlg;
2667 dlg.m_PreSelectRemote = remoteName;
2668 dlg.m_IsPull=FALSE;
2669 dlg.m_bAllRemotes = allRemotes;
2671 if(dlg.DoModal()==IDOK)
2672 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);
2674 return false;
2677 bool CAppUtils::Push(const CString& selectLocalBranch)
2679 CPushDlg dlg;
2680 dlg.m_BranchSourceName = selectLocalBranch;
2682 if (dlg.DoModal() == IDOK)
2684 CString error;
2685 DWORD exitcode = 0xFFFFFFFF;
2686 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2688 if (exitcode)
2690 CString temp;
2691 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2692 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2693 return false;
2697 CString arg;
2699 if(dlg.m_bPack)
2700 arg += _T("--thin ");
2701 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2702 arg += _T("--tags ");
2703 if(dlg.m_bForce)
2704 arg += _T("--force ");
2705 if (dlg.m_bForceWithLease)
2706 arg += _T("--force-with-lease ");
2707 if (dlg.m_bSetUpstream)
2708 arg += _T("--set-upstream ");
2709 if (dlg.m_RecurseSubmodules == 1)
2710 arg += _T("--recurse-submodules=check ");
2711 if (dlg.m_RecurseSubmodules == 2)
2712 arg += _T("--recurse-submodules=on-demand ");
2714 int ver = CAppUtils::GetMsysgitVersion();
2716 if(ver >= 0x01070203) //above 1.7.0.2
2717 arg += _T("--progress ");
2719 CProgressDlg progress;
2721 STRING_VECTOR remotesList;
2722 if (dlg.m_bPushAllRemotes)
2723 g_Git.GetRemoteList(remotesList);
2724 else
2725 remotesList.push_back(dlg.m_URL);
2727 for (unsigned int i = 0; i < remotesList.size(); ++i)
2729 if (dlg.m_bAutoLoad)
2730 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2732 CString cmd;
2733 if (dlg.m_bPushAllBranches)
2735 cmd.Format(_T("git.exe push --all %s\"%s\""),
2736 arg,
2737 remotesList[i]);
2739 if (dlg.m_bTags)
2741 progress.m_GitCmdList.push_back(cmd);
2742 cmd.Format(_T("git.exe push --tags %s\"%s\""), arg, remotesList[i]);
2745 else
2747 cmd.Format(_T("git.exe push %s\"%s\" %s"),
2748 arg,
2749 remotesList[i],
2750 dlg.m_BranchSourceName);
2751 if (!dlg.m_BranchRemoteName.IsEmpty())
2753 cmd += _T(":") + dlg.m_BranchRemoteName;
2756 progress.m_GitCmdList.push_back(cmd);
2759 CString superprojectRoot;
2760 GitAdminDir::HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2761 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2763 // need to execute hooks as those might be needed by post action commands
2764 DWORD exitcode = 0xFFFFFFFF;
2765 CString error;
2766 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2768 if (exitcode)
2770 CString temp;
2771 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2772 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2776 if (status)
2778 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2779 if (rejected)
2781 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, []{ Pull(true); }));
2782 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(dlg.m_bPushAllRemotes ? _T("") : dlg.m_URL, !!dlg.m_bPushAllRemotes); }));
2784 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2785 return;
2788 postCmdList.push_back(PostCmd(IDS_PROC_REQUESTPULL, [&]{ RequestPull(dlg.m_BranchRemoteName); }));
2789 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2790 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); }));
2791 if (!superprojectRoot.IsEmpty())
2793 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2795 CString sCmd;
2796 sCmd.Format(_T("/command:commit /path:\"%s\""), superprojectRoot);
2797 RunTortoiseGitProc(sCmd);
2798 }));
2802 INT_PTR ret = progress.DoModal();
2803 return ret == IDOK;
2805 return FALSE;
2808 bool CAppUtils::RequestPull(const CString& endrevision, const CString& repositoryUrl, bool bIsMainWnd)
2810 CRequestPullDlg dlg;
2811 dlg.m_RepositoryURL = repositoryUrl;
2812 dlg.m_EndRevision = endrevision;
2813 if (dlg.DoModal()==IDOK)
2815 CString cmd;
2816 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2818 CSysProgressDlg sysProgressDlg;
2819 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2820 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2821 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2822 sysProgressDlg.SetShowProgressBar(false);
2823 sysProgressDlg.ShowModeless((HWND)NULL, true);
2825 CString tempFileName = GetTempFile();
2826 CString err;
2827 DeleteFile(tempFileName);
2828 CreateDirectory(tempFileName, NULL);
2829 tempFileName += _T("\\pullrequest.txt");
2830 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2832 CString msg;
2833 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2834 CMessageBox::Show(NULL, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK);
2835 return false;
2838 if (sysProgressDlg.HasUserCancelled())
2840 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2841 ::DeleteFile(tempFileName);
2842 return false;
2845 sysProgressDlg.Stop();
2847 if (dlg.m_bSendMail)
2849 CSendMailDlg sendmaildlg;
2850 sendmaildlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2851 sendmaildlg.m_bCustomSubject = true;
2853 if (sendmaildlg.DoModal() == IDOK)
2855 if (sendmaildlg.m_PathList.IsEmpty())
2856 return FALSE;
2858 CGitProgressDlg progDlg;
2859 if (bIsMainWnd)
2860 theApp.m_pMainWnd = &progDlg;
2861 SendMailProgressCommand sendMailProgressCommand;
2862 progDlg.SetCommand(&sendMailProgressCommand);
2864 sendMailProgressCommand.SetPathList(sendmaildlg.m_PathList);
2865 progDlg.SetItemCount(sendmaildlg.m_PathList.GetCount());
2867 CSendMailCombineable sendMailCombineable(sendmaildlg.m_To, sendmaildlg.m_CC, sendmaildlg.m_Subject, !!sendmaildlg.m_bAttachment, !!sendmaildlg.m_bCombine);
2868 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2870 progDlg.DoModal();
2872 return true;
2874 return false;
2877 CAppUtils::LaunchAlternativeEditor(tempFileName);
2879 return true;
2882 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2884 CString strDir(szPath);
2885 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2887 strDir.AppendChar(_T('\\'));
2889 std::vector<CString> vPath;
2890 CString strTemp;
2891 bool bSuccess = false;
2893 for (int i=0;i<strDir.GetLength();++i)
2895 if (strDir.GetAt(i) != _T('\\'))
2897 strTemp.AppendChar(strDir.GetAt(i));
2899 else
2901 vPath.push_back(strTemp);
2902 strTemp.AppendChar(_T('\\'));
2906 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2908 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2911 return bSuccess;
2914 void CAppUtils::RemoveTrailSlash(CString &path)
2916 if(path.IsEmpty())
2917 return ;
2919 // For URL, do not trim the slash just after the host name component.
2920 int index = path.Find(_T("://"));
2921 if (index >= 0)
2923 index += 4;
2924 index = path.Find(_T('/'), index);
2925 if (index == path.GetLength() - 1)
2926 return;
2929 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2931 path=path.Left(path.GetLength()-1);
2932 if(path.IsEmpty())
2933 return;
2937 bool CAppUtils::CheckUserData()
2939 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2941 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2943 CTGitPath path(g_Git.m_CurrentDir);
2944 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2945 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2946 dlg.SetTreeWidth(220);
2947 dlg.m_DefaultPage = _T("gitconfig");
2949 dlg.DoModal();
2950 dlg.HandleRestart();
2953 else
2954 return false;
2957 return true;
2960 BOOL CAppUtils::Commit(const CString& bugid, BOOL bWholeProject, CString &sLogMsg,
2961 CTGitPathList &pathList,
2962 CTGitPathList &selectedList,
2963 bool bSelectFilesForCommit)
2965 bool bFailed = true;
2967 if (!CheckUserData())
2968 return false;
2970 while (bFailed)
2972 bFailed = false;
2973 CCommitDlg dlg;
2974 dlg.m_sBugID = bugid;
2976 dlg.m_bWholeProject = bWholeProject;
2978 dlg.m_sLogMessage = sLogMsg;
2979 dlg.m_pathList = pathList;
2980 dlg.m_checkedPathList = selectedList;
2981 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2982 if (dlg.DoModal() == IDOK)
2984 if (dlg.m_pathList.IsEmpty())
2985 return false;
2986 // if the user hasn't changed the list of selected items
2987 // we don't use that list. Because if we would use the list
2988 // of pre-checked items, the dialog would show different
2989 // checked items on the next startup: it would only try
2990 // to check the parent folder (which might not even show)
2991 // instead, we simply use an empty list and let the
2992 // default checking do its job.
2993 if (!dlg.m_pathList.IsEqual(pathList))
2994 selectedList = dlg.m_pathList;
2995 pathList = dlg.m_updatedPathList;
2996 sLogMsg = dlg.m_sLogMessage;
2997 bSelectFilesForCommit = true;
2999 switch (dlg.m_PostCmd)
3001 case GIT_POSTCOMMIT_CMD_DCOMMIT:
3002 CAppUtils::SVNDCommit();
3003 break;
3004 case GIT_POSTCOMMIT_CMD_PUSH:
3005 CAppUtils::Push();
3006 break;
3007 case GIT_POSTCOMMIT_CMD_CREATETAG:
3008 CAppUtils::CreateBranchTag(TRUE);
3009 break;
3010 case GIT_POSTCOMMIT_CMD_PULL:
3011 CAppUtils::Pull(true);
3012 break;
3013 default:
3014 break;
3017 // CGitProgressDlg progDlg;
3018 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3019 // if (parser.HasVal(_T("closeonend")))
3020 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3021 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3022 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3023 // progDlg.SetPathList(dlg.m_pathList);
3024 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3025 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3026 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3027 // progDlg.SetItemCount(dlg.m_itemsCount);
3028 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3029 // progDlg.DoModal();
3030 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3031 // err = (DWORD)progDlg.DidErrorsOccur();
3032 // bFailed = progDlg.DidErrorsOccur();
3033 // bRet = progDlg.DidErrorsOccur();
3034 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3035 // if (DWORD(bFailRepeat)==0)
3036 // bFailed = false; // do not repeat if the user chose not to in the settings.
3039 return true;
3043 BOOL CAppUtils::SVNDCommit()
3045 CSVNDCommitDlg dcommitdlg;
3046 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
3047 if (gitSetting == _T("")) {
3048 if (dcommitdlg.DoModal() != IDOK)
3050 return false;
3052 else
3054 if (dcommitdlg.m_remember)
3056 if (dcommitdlg.m_rmdir)
3058 gitSetting = _T("true");
3060 else
3062 gitSetting = _T("false");
3064 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
3066 CString msg;
3067 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
3068 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3074 BOOL IsStash = false;
3075 if(!g_Git.CheckCleanWorkTree())
3077 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3079 CSysProgressDlg sysProgressDlg;
3080 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3081 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3082 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3083 sysProgressDlg.SetShowProgressBar(false);
3084 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3085 sysProgressDlg.ShowModeless((HWND)NULL, true);
3087 CString cmd,out;
3088 cmd=_T("git.exe stash");
3089 if (g_Git.Run(cmd, &out, CP_UTF8))
3091 sysProgressDlg.Stop();
3092 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
3093 return false;
3095 sysProgressDlg.Stop();
3097 IsStash =true;
3099 else
3101 return false;
3105 CProgressDlg progress;
3106 if (dcommitdlg.m_rmdir)
3108 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
3110 else
3112 progress.m_GitCmd=_T("git.exe svn dcommit");
3114 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
3116 ::DeleteFile(g_Git.m_CurrentDir + _T("\\sys$command"));
3117 if( IsStash)
3119 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
3121 CSysProgressDlg sysProgressDlg;
3122 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3123 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3124 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3125 sysProgressDlg.SetShowProgressBar(false);
3126 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3127 sysProgressDlg.ShowModeless((HWND)NULL, true);
3129 CString cmd,out;
3130 cmd=_T("git.exe stash pop");
3131 if (g_Git.Run(cmd, &out, CP_UTF8))
3133 sysProgressDlg.Stop();
3134 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
3135 return false;
3137 sysProgressDlg.Stop();
3139 else
3141 return false;
3144 return TRUE;
3146 return FALSE;
3149 BOOL CAppUtils::Merge(const CString* commit, bool showStashPop)
3151 if (!CheckUserData())
3152 return FALSE;
3154 CMergeDlg dlg;
3155 if(commit)
3156 dlg.m_initialRefName = *commit;
3158 if(dlg.DoModal()==IDOK)
3160 CString cmd;
3161 CString args;
3163 if(dlg.m_bNoFF)
3164 args += _T(" --no-ff");
3166 if(dlg.m_bSquash)
3167 args += _T(" --squash");
3169 if(dlg.m_bNoCommit)
3170 args += _T(" --no-commit");
3172 if (dlg.m_bLog)
3174 CString fmt;
3175 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
3176 args += fmt;
3179 if (!dlg.m_MergeStrategy.IsEmpty())
3181 args += _T(" --strategy=") + dlg.m_MergeStrategy;
3182 if (!dlg.m_StrategyOption.IsEmpty())
3184 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
3185 if (!dlg.m_StrategyParam.IsEmpty())
3186 args += _T("=") + dlg.m_StrategyParam;
3190 if(!dlg.m_strLogMesage.IsEmpty())
3192 CString logmsg = dlg.m_strLogMesage;
3193 logmsg.Replace(_T("\\\""), _T("\\\\\""));
3194 logmsg.Replace(_T("\""), _T("\\\""));
3195 args += _T(" -m \"") + logmsg + _T("\"");
3197 cmd.Format(_T("git.exe merge%s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
3199 CProgressDlg Prodlg;
3200 Prodlg.m_GitCmd = cmd;
3202 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3204 if (status)
3206 int hasConflicts = g_Git.HasWorkingTreeConflicts();
3207 if (hasConflicts < 0)
3208 CMessageBox::Show(nullptr, g_Git.GetGitLastErr(L"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS), _T("TortoiseGit"), MB_ICONEXCLAMATION);
3209 else if (hasConflicts)
3211 // there are conflict files
3213 postCmdList.push_back(PostCmd(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3215 CString sCmd;
3216 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3217 CAppUtils::RunTortoiseGitProc(sCmd);
3218 }));
3221 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSTASHSAVE, [&]{ CAppUtils::StashSave(_T(""), false, false, true, g_Git.FixBranchName(dlg.m_VersionName)); }));
3222 return;
3225 if (showStashPop)
3226 postCmdList.push_back(PostCmd(IDI_RELOCATE, IDS_MENUSTASHPOP, []{ StashPop(); }));
3228 if (dlg.m_bNoCommit)
3230 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []
3232 CString sCmd;
3233 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3234 CAppUtils::RunTortoiseGitProc(sCmd);
3235 }));
3236 return;
3239 if (dlg.m_bIsBranch && dlg.m_VersionName.Find(L"remotes/") == -1) // do not ask to remove remote branches
3241 postCmdList.push_back(PostCmd(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3243 CString msg;
3244 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
3245 if (CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3247 CString cmd, out;
3248 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
3249 if (g_Git.Run(cmd, &out, CP_UTF8))
3250 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3252 }));
3254 if (dlg.m_bIsBranch)
3255 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(); }));
3257 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3258 if (hasGitSVN)
3259 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ SVNDCommit(); }));
3262 Prodlg.DoModal();
3263 return !Prodlg.m_GitStatus;
3265 return false;
3268 BOOL CAppUtils::MergeAbort()
3270 CMergeAbortDlg dlg;
3271 if (dlg.DoModal() == IDOK)
3272 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3274 return FALSE;
3277 void CAppUtils::EditNote(GitRevLoglist* rev)
3279 if (!CheckUserData())
3280 return;
3282 CInputDlg dlg;
3283 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3284 dlg.m_sInputText = rev->m_Notes;
3285 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3286 //dlg.m_pProjectProperties = &m_ProjectProperties;
3287 dlg.m_bUseLogWidth = true;
3288 if(dlg.DoModal() == IDOK)
3290 CString cmd,output;
3291 cmd=_T("notes add -f -F \"");
3293 CString tempfile=::GetTempFile();
3294 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3296 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3297 return;
3299 cmd += tempfile;
3300 cmd += _T("\" ");
3301 cmd += rev->m_CommitHash.ToString();
3305 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3307 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3310 else
3312 rev->m_Notes = dlg.m_sInputText;
3314 }catch(...)
3316 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3318 ::DeleteFile(tempfile);
3323 int CAppUtils::GetMsysgitVersion()
3325 if (g_Git.ms_LastMsysGitVersion)
3326 return g_Git.ms_LastMsysGitVersion;
3328 CString cmd;
3329 CString versiondebug;
3330 CString version;
3332 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3333 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3335 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3337 __int64 time=0;
3338 if (!g_Git.GetFileModifyTime(gitpath, &time))
3340 if((DWORD)time == regTime)
3342 g_Git.ms_LastMsysGitVersion = regVersion;
3343 return regVersion;
3347 CString err;
3348 cmd = _T("git.exe --version");
3349 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
3351 CMessageBox::Show(NULL, _T("git.exe not correctly set up (") + err + _T(")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\"."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
3352 return -1;
3355 int start=0;
3356 int ver = 0;
3358 versiondebug = version;
3362 CString str=version.Tokenize(_T("."), start);
3363 int space = str.ReverseFind(_T(' '));
3364 str = str.Mid(space+1,start);
3365 ver = _ttol(str);
3366 ver <<=24;
3368 version = version.Mid(start);
3369 start = 0;
3371 str = version.Tokenize(_T("."), start);
3373 ver |= (_ttol(str) & 0xFF) << 16;
3375 str = version.Tokenize(_T("."), start);
3376 ver |= (_ttol(str) & 0xFF) << 8;
3378 str = version.Tokenize(_T("."), start);
3379 ver |= (_ttol(str) & 0xFF);
3381 catch(...)
3383 if (!ver)
3385 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3386 return -1;
3390 regTime = time&0xFFFFFFFF;
3391 regVersion = ver;
3392 g_Git.ms_LastMsysGitVersion = ver;
3394 return ver;
3397 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3399 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3401 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3403 if (hShell.IsValid()) {
3404 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3405 if (pfnSHGPSFW) {
3406 IPropertyStore *pps;
3407 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3408 if (SUCCEEDED(hr)) {
3409 PROPVARIANT var;
3410 var.vt = VT_BOOL;
3411 var.boolVal = VARIANT_TRUE;
3412 pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3413 pps->Release();
3419 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3421 ASSERT(dialogname.GetLength() < 70);
3422 ASSERT(urlorpath.GetLength() < MAX_PATH);
3423 WCHAR pathbuf[MAX_PATH] = {0};
3425 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3427 wcscat_s(pathbuf, L" - ");
3428 wcscat_s(pathbuf, dialogname);
3429 wcscat_s(pathbuf, L" - ");
3430 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3431 SetWindowText(hWnd, pathbuf);
3434 bool CAppUtils::BisectStart(const CString& lastGood, const CString& firstBad, bool bIsMainWnd)
3436 if (!g_Git.CheckCleanWorkTree())
3438 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3440 CSysProgressDlg sysProgressDlg;
3441 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3442 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3443 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3444 sysProgressDlg.SetShowProgressBar(false);
3445 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3446 sysProgressDlg.ShowModeless((HWND)NULL, true);
3448 CString cmd, out;
3449 cmd = _T("git.exe stash");
3450 if (g_Git.Run(cmd, &out, CP_UTF8))
3452 sysProgressDlg.Stop();
3453 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3454 return false;
3456 sysProgressDlg.Stop();
3458 else
3459 return false;
3462 CBisectStartDlg bisectStartDlg;
3464 if (!lastGood.IsEmpty())
3465 bisectStartDlg.m_sLastGood = lastGood;
3466 if (!firstBad.IsEmpty())
3467 bisectStartDlg.m_sFirstBad = firstBad;
3469 if (bisectStartDlg.DoModal() == IDOK)
3471 CProgressDlg progress;
3472 if (bIsMainWnd)
3473 theApp.m_pMainWnd = &progress;
3474 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3475 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3476 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3478 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3480 if (status)
3481 return;
3483 CTGitPath path(g_Git.m_CurrentDir);
3484 if (path.HasSubmodules())
3486 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3488 CString sCmd;
3489 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3490 CAppUtils::RunTortoiseGitProc(sCmd);
3491 }));
3497 INT_PTR ret = progress.DoModal();
3498 return ret == IDOK;
3501 return false;
3504 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3506 CUserPassword dlg;
3507 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3508 if (username_from_url)
3509 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3511 CStringA username, password;
3512 if (dlg.DoModal() == IDOK)
3514 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3515 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3516 return git_cred_userpass_plaintext_new(out, username, password);
3518 giterr_set_str(GITERR_NONE, "User cancelled.");
3519 return GIT_EUSER;
3522 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3524 if (base_cert->cert_type == GIT_CERT_X509)
3526 git_cert_x509* cert = (git_cert_x509*)base_cert;
3528 if (last_accepted_cert.cmp(cert))
3529 return 0;
3531 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3533 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3534 if (!verificationError)
3536 last_accepted_cert.set(cert);
3537 CertFreeCertificateContext(pServerCert);
3538 return 0;
3541 CString servernameInCert;
3542 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, servernameInCert.GetBuffer(128), 128);
3543 servernameInCert.ReleaseBuffer();
3545 CString issuer;
3546 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, issuer.GetBuffer(128), 128);
3547 issuer.ReleaseBuffer();
3549 CertFreeCertificateContext(pServerCert);
3551 CCheckCertificateDlg dlg;
3552 dlg.cert = cert;
3553 dlg.m_sCertificateCN = servernameInCert;
3554 dlg.m_sCertificateIssuer = issuer;
3555 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3556 dlg.m_sError = CFormatMessageWrapper(verificationError);
3557 if (dlg.DoModal() == IDOK)
3559 last_accepted_cert.set(cert);
3560 return 0;
3563 return GIT_ECERTIFICATE;
3566 void CAppUtils::ExploreTo(HWND hwnd, CString path)
3568 if (PathFileExists(path))
3570 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3571 if (pidl)
3573 SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3574 ILFree(pidl);
3576 return;
3578 // if filepath does not exist any more, navigate to closest matching folder
3581 int pos = path.ReverseFind(_T('\\'));
3582 if (pos <= 3)
3583 break;
3584 path = path.Left(pos);
3585 } while (!PathFileExists(path));
3586 ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW);
3589 int CAppUtils::ResolveConflict(CTGitPath& path, resolve_with resolveWith)
3591 bool b_local = false, b_remote = false;
3592 BYTE_VECTOR vector;
3594 CString cmd;
3595 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), path.GetGitPathString());
3596 if (g_Git.Run(cmd, &vector))
3598 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK);
3599 return -1;
3602 CTGitPathList list;
3603 if (list.ParserFromLsFile(vector))
3605 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
3606 return -1;
3609 if (list.IsEmpty())
3610 return 0;
3611 for (int i = 0; i < list.GetCount(); ++i)
3613 if (list[i].m_Stage == 2)
3614 b_local = true;
3615 if (list[i].m_Stage == 3)
3616 b_remote = true;
3620 CBlockCacheForPath block(g_Git.m_CurrentDir);
3621 if (path.IsDirectory()) // is submodule conflict
3623 CString err = _T("We're sorry, but you hit a very rare conflict condition with a submodule which cannot be resolved by TortoiseGit. You have to use the command line git for this.");
3624 if (b_local && b_remote)
3626 if (!path.HasAdminDir()) // check if submodule is initialized
3628 err += _T("\n\nYou have to checkout the submodule manually into \"") + path.GetGitPathString() + _T("\" and then reset HEAD to the right commit (see resolve submodule conflict dialog for this).");
3629 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3630 return -1;
3632 CGit subgit;
3633 subgit.m_CurrentDir = g_Git.CombinePath(path);
3634 CGitHash submoduleHead;
3635 if (subgit.GetHash(submoduleHead, _T("HEAD")))
3637 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3638 return -1;
3640 CString baseHash, localHash, remoteHash;
3641 ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash);
3642 if (resolveWith == RESOLVE_WITH_THEIRS && submoduleHead.ToString() != remoteHash)
3644 CString origPath = g_Git.m_CurrentDir;
3645 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3646 if (!GitReset(&remoteHash))
3648 g_Git.m_CurrentDir = origPath;
3649 return -1;
3651 g_Git.m_CurrentDir = origPath;
3653 else if (resolveWith == RESOLVE_WITH_MINE && submoduleHead.ToString() != localHash)
3655 CString origPath = g_Git.m_CurrentDir;
3656 g_Git.m_CurrentDir = g_Git.CombinePath(path);
3657 if (!GitReset(&localHash))
3659 g_Git.m_CurrentDir = origPath;
3660 return -1;
3662 g_Git.m_CurrentDir = origPath;
3665 else
3667 MessageBox(nullptr, err, _T("TortoiseGit"), MB_ICONERROR);
3668 return -1;
3672 if (resolveWith == RESOLVE_WITH_THEIRS)
3674 CString gitcmd, output;
3675 if (b_local && b_remote)
3676 gitcmd.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), path.GetGitPathString());
3677 else if (b_remote)
3678 gitcmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
3679 else if (b_local)
3680 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), path.GetGitPathString());
3681 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3683 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3684 return -1;
3687 else if (resolveWith == RESOLVE_WITH_MINE)
3689 CString gitcmd, output;
3690 if (b_local && b_remote)
3691 gitcmd.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), path.GetGitPathString());
3692 else if (b_local)
3693 gitcmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
3694 else if (b_remote)
3695 gitcmd.Format(_T("git.exe rm -f -- \"%s\""), path.GetGitPathString());
3696 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3698 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3699 return -1;
3703 if (b_local && b_remote && path.m_Action & CTGitPath::LOGACTIONS_UNMERGED)
3705 CString gitcmd, output;
3706 gitcmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
3707 if (g_Git.Run(gitcmd, &output, CP_UTF8))
3708 CMessageBox::Show(nullptr, output, _T("TortoiseGit"), MB_ICONERROR);
3709 else
3711 path.m_Action |= CTGitPath::LOGACTIONS_MODIFIED;
3712 path.m_Action &= ~CTGitPath::LOGACTIONS_UNMERGED;
3716 RemoveTempMergeFile(path);
3717 return 0;
3720 bool CAppUtils::ShellOpen(const CString& file, HWND hwnd /*= nullptr */)
3722 if ((INT_PTR)ShellExecute(hwnd, NULL, file, NULL, NULL, SW_SHOW) > HINSTANCE_ERROR)
3723 return true;
3725 return ShowOpenWithDialog(file, hwnd);
3728 bool CAppUtils::ShowOpenWithDialog(const CString& file, HWND hwnd /*= nullptr */)
3730 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("shell32.dll"));
3731 if (hShell)
3733 typedef HRESULT STDAPICALLTYPE SHOpenWithDialoFN(_In_opt_ HWND hwndParent, _In_ const OPENASINFO *poainfo);
3734 SHOpenWithDialoFN *pfnSHOpenWithDialog = (SHOpenWithDialoFN*)GetProcAddress(hShell, "SHOpenWithDialog");
3735 if (pfnSHOpenWithDialog)
3737 OPENASINFO oi = { 0 };
3738 oi.pcszFile = file;
3739 oi.oaifInFlags = OAIF_EXEC;
3740 return SUCCEEDED(pfnSHOpenWithDialog(hwnd, &oi));
3743 CString cmd = _T("RUNDLL32 Shell32,OpenAs_RunDLL ");
3744 cmd += file;
3745 return CAppUtils::LaunchApplication(cmd, NULL, false);