git fetch show progress
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobb5dc92e1ccab16a779548830fab5a3ed7ea33441
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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 "StringUtils.h"
25 #include "MessageBox.h"
26 #include "registry.h"
27 #include "TGitPath.h"
28 #include "Git.h"
29 #include "UnicodeUtils.h"
30 #include "ExportDlg.h"
31 #include "ProgressDlg.h"
32 #include "GitAdminDir.h"
33 #include "ProgressDlg.h"
34 #include "BrowseFolder.h"
35 #include "DirFileEnum.h"
36 #include "MessageBox.h"
37 #include "GitStatus.h"
38 #include "CreateBranchTagDlg.h"
39 #include "GitSwitchDlg.h"
40 #include "ResetDlg.h"
41 #include "DeleteConflictDlg.h"
42 #include "ChangedDlg.h"
43 #include "SendMailDlg.h"
44 #include "GitProgressDlg.h"
45 #include "PushDlg.h"
46 #include "CommitDlg.h"
47 #include "MergeDlg.h"
48 #include "MergeAbortDlg.h"
49 #include "Hooks.h"
50 #include "..\Settings\Settings.h"
51 #include "InputDlg.h"
52 #include "SVNDCommitDlg.h"
53 #include "requestpulldlg.h"
54 #include "PullFetchDlg.h"
55 #include "FileDiffDlg.h"
56 #include "RebaseDlg.h"
57 #include "PropKey.h"
58 #include "StashSave.h"
59 #include "IgnoreDlg.h"
60 #include "FormatMessageWrapper.h"
61 #include "SmartHandle.h"
62 #include "BisectStartDlg.h"
63 #include "SysProgressDlg.h"
64 #include "UserPassword.h"
65 #include "Patch.h"
66 #include "Globals.h"
67 #include "ProgressCommands/ResetProgressCommand.h"
68 #include "ProgressCommands/FetchProgressCommand.h"
69 #include "ProgressCommands/SendMailProgressCommand.h"
70 #include "CertificateValidationHelper.h"
71 #include "CheckCertificateDlg.h"
73 static struct last_accepted_cert {
74 BYTE* data;
75 size_t len;
77 last_accepted_cert()
78 : data(nullptr)
79 , len(0)
82 ~last_accepted_cert()
84 free(data);
86 boolean cmp(git_cert_x509* cert)
88 return len > 0 && len == cert->len && memcmp(data, cert->data, len) == 0;
90 void set(git_cert_x509* cert)
92 free(data);
93 len = cert->len;
94 if (len == 0)
96 data = nullptr;
97 return;
99 data = new BYTE[len];
100 memcpy(data, cert->data, len);
102 } last_accepted_cert;
104 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, const boolean runRebase);
106 CAppUtils::CAppUtils(void)
110 CAppUtils::~CAppUtils(void)
114 bool CAppUtils::StashSave(const CString& msg)
116 CStashSaveDlg dlg;
117 dlg.m_sMessage = msg;
118 if (dlg.DoModal() == IDOK)
120 CString cmd;
121 cmd = _T("git.exe stash save");
123 if (CAppUtils::GetMsysgitVersion() >= 0x01070700)
125 if (dlg.m_bIncludeUntracked)
126 cmd += _T(" --include-untracked");
127 else if (dlg.m_bAll)
128 cmd += _T(" --all");
131 if (!dlg.m_sMessage.IsEmpty())
133 CString message = dlg.m_sMessage;
134 message.Replace(_T("\""), _T("\"\""));
135 cmd += _T(" -- \"") + message + _T("\"");
138 CProgressDlg progress;
139 progress.m_GitCmd = cmd;
140 return (progress.DoModal() == IDOK);
142 return false;
145 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
147 CString cmd,out;
148 cmd = _T("git.exe stash apply ");
149 if (ref.Find(_T("refs/")) == 0)
150 ref = ref.Mid(5);
151 if (ref.Find(_T("stash{")) == 0)
152 ref = _T("stash@") + ref.Mid(5);
153 cmd += ref;
155 CSysProgressDlg sysProgressDlg;
156 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
157 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
158 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
159 sysProgressDlg.SetShowProgressBar(false);
160 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
161 sysProgressDlg.ShowModeless((HWND)NULL, true);
163 int ret = g_Git.Run(cmd, &out, CP_UTF8);
165 sysProgressDlg.Stop();
167 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
168 if (ret && !(ret == 1 && hasConflicts))
170 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
172 else
174 CString message;
175 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
176 if (hasConflicts)
177 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
178 if (showChanges)
180 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
181 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
183 CChangedDlg dlg;
184 dlg.m_pathList.AddPath(CTGitPath());
185 dlg.DoModal();
187 return true;
189 else
191 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
192 return true;
195 return false;
198 bool CAppUtils::StashPop(bool showChanges /* true */)
200 CString cmd,out;
201 cmd=_T("git.exe stash pop ");
203 CSysProgressDlg sysProgressDlg;
204 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
205 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
206 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
207 sysProgressDlg.SetShowProgressBar(false);
208 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
209 sysProgressDlg.ShowModeless((HWND)NULL, true);
211 int ret = g_Git.Run(cmd, &out, CP_UTF8);
213 sysProgressDlg.Stop();
215 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
216 if (ret && !(ret == 1 && hasConflicts))
218 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
220 else
222 CString message;
223 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
224 if (hasConflicts)
225 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
226 if (showChanges)
228 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
229 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
231 CChangedDlg dlg;
232 dlg.m_pathList.AddPath(CTGitPath());
233 dlg.DoModal();
235 return true;
237 else
239 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
240 return true;
243 return false;
246 BOOL CAppUtils::StartExtMerge(
247 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
248 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
249 HWND resolveMsgHwnd)
252 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
253 CString ext = mergedfile.GetFileExtension();
254 CString com = regCom;
255 bool bInternal = false;
257 if (!ext.IsEmpty())
259 // is there an extension specific merge tool?
260 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
261 if (!CString(mergetool).IsEmpty())
263 com = mergetool;
266 // is there a filename specific merge tool?
267 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
268 if (!CString(mergetool).IsEmpty())
270 com = mergetool;
273 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
275 // Maybe we should use TortoiseIDiff?
276 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
277 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
278 (ext == _T(".png")) || (ext == _T(".ico")) ||
279 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
280 (ext == _T(".dib")) || (ext == _T(".emf")) ||
281 (ext == _T(".cur")))
283 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
284 com = _T("\"") + com + _T("\"");
285 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
286 com = com + _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
288 else
290 // use TortoiseGitMerge
291 bInternal = true;
292 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
293 com = _T("\"") + com + _T("\"");
294 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
295 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
296 com += _T(" /saverequired");
297 if (resolveMsgHwnd)
299 CString s;
300 s.Format(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
301 com += s;
304 if (!g_sGroupingUUID.IsEmpty())
306 com += L" /groupuuid:\"";
307 com += g_sGroupingUUID;
308 com += L"\"";
311 // check if the params are set. If not, just add the files to the command line
312 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
314 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
315 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
316 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
317 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
319 if (basefile.IsEmpty())
321 com.Replace(_T("/base:%base"), _T(""));
322 com.Replace(_T("%base"), _T(""));
324 else
325 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
326 if (theirfile.IsEmpty())
328 com.Replace(_T("/theirs:%theirs"), _T(""));
329 com.Replace(_T("%theirs"), _T(""));
331 else
332 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
333 if (yourfile.IsEmpty())
335 com.Replace(_T("/mine:%mine"), _T(""));
336 com.Replace(_T("%mine"), _T(""));
338 else
339 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
340 if (mergedfile.IsEmpty())
342 com.Replace(_T("/merged:%merged"), _T(""));
343 com.Replace(_T("%merged"), _T(""));
345 else
346 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
347 if (basename.IsEmpty())
349 if (basefile.IsEmpty())
351 com.Replace(_T("/basename:%bname"), _T(""));
352 com.Replace(_T("%bname"), _T(""));
354 else
356 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
359 else
360 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
361 if (theirname.IsEmpty())
363 if (theirfile.IsEmpty())
365 com.Replace(_T("/theirsname:%tname"), _T(""));
366 com.Replace(_T("%tname"), _T(""));
368 else
370 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
373 else
374 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
375 if (yourname.IsEmpty())
377 if (yourfile.IsEmpty())
379 com.Replace(_T("/minename:%yname"), _T(""));
380 com.Replace(_T("%yname"), _T(""));
382 else
384 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
387 else
388 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
389 if (mergedname.IsEmpty())
391 if (mergedfile.IsEmpty())
393 com.Replace(_T("/mergedname:%mname"), _T(""));
394 com.Replace(_T("%mname"), _T(""));
396 else
398 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
401 else
402 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
404 if ((bReadOnly)&&(bInternal))
405 com += _T(" /readonly");
407 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
409 return FALSE;
412 return TRUE;
415 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
417 CString viewer;
418 // use TortoiseGitMerge
419 viewer = CPathUtils::GetAppDirectory();
420 viewer += _T("TortoiseGitMerge.exe");
422 viewer = _T("\"") + viewer + _T("\"");
423 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
424 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
425 if (bReversed)
426 viewer += _T(" /reversedpatch");
427 if (!sOriginalDescription.IsEmpty())
428 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
429 if (!sPatchedDescription.IsEmpty())
430 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
431 if (!g_sGroupingUUID.IsEmpty())
433 viewer += L" /groupuuid:\"";
434 viewer += g_sGroupingUUID;
435 viewer += L"\"";
437 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
439 return FALSE;
441 return TRUE;
444 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
446 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file2.GetFilename().MakeLower());
447 if (!difftool.IsEmpty())
448 return difftool;
449 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file1.GetFilename().MakeLower());
450 if (!difftool.IsEmpty())
451 return difftool;
453 // Is there an extension specific diff tool?
454 CString ext = file2.GetFileExtension().MakeLower();
455 if (!ext.IsEmpty())
457 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
458 if (!difftool.IsEmpty())
459 return difftool;
460 // Maybe we should use TortoiseIDiff?
461 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
462 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
463 (ext == _T(".png")) || (ext == _T(".ico")) ||
464 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
465 (ext == _T(".dib")) || (ext == _T(".emf")) ||
466 (ext == _T(".cur")))
468 return
469 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
470 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
471 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
475 // Finally, pick a generic external diff tool
476 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
477 return difftool;
480 bool CAppUtils::StartExtDiff(
481 const CString& file1, const CString& file2,
482 const CString& sName1, const CString& sName2,
483 const CString& originalFile1, const CString& originalFile2,
484 const git_revnum_t& hash1, const git_revnum_t& hash2,
485 const DiffFlags& flags, int jumpToLine)
487 CString viewer;
489 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
490 if (!flags.bBlame || !(DWORD)blamediff)
492 viewer = PickDiffTool(file1, file2);
493 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
494 bool bCommentedOut = viewer.Left(1) == _T("#");
495 if (flags.bAlternativeTool)
497 // Invert external vs. internal diff tool selection.
498 if (bCommentedOut)
499 viewer.Delete(0); // uncomment
500 else
501 viewer = "";
503 else if (bCommentedOut)
504 viewer = "";
507 bool bInternal = viewer.IsEmpty();
508 if (bInternal)
510 viewer =
511 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
512 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
513 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
514 if (!g_sGroupingUUID.IsEmpty())
516 viewer += L" /groupuuid:\"";
517 viewer += g_sGroupingUUID;
518 viewer += L"\"";
520 if (flags.bBlame)
521 viewer += _T(" /blame");
523 // check if the params are set. If not, just add the files to the command line
524 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
526 viewer += _T(" \"")+file1+_T("\"");
527 viewer += _T(" \"")+file2+_T("\"");
529 if (viewer.Find(_T("%base")) >= 0)
531 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
533 if (viewer.Find(_T("%mine")) >= 0)
535 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
538 if (sName1.IsEmpty())
539 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
540 else
541 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
543 if (sName2.IsEmpty())
544 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
545 else
546 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
548 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
549 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
551 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
552 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
554 if (flags.bReadOnly && bInternal)
555 viewer += _T(" /readonly");
557 if (jumpToLine > 0)
559 CString temp;
560 temp.Format(_T(" /line:%d"), jumpToLine);
561 viewer += temp;
564 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
567 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
569 CString viewer;
570 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
571 viewer = v;
572 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
574 // use TortoiseGitUDiff
575 viewer = CPathUtils::GetAppDirectory();
576 viewer += _T("TortoiseGitUDiff.exe");
577 // enquote the path to TortoiseGitUDiff
578 viewer = _T("\"") + viewer + _T("\"");
579 // add the params
580 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
581 if (!g_sGroupingUUID.IsEmpty())
583 viewer += L" /groupuuid:\"";
584 viewer += g_sGroupingUUID;
585 viewer += L"\"";
588 if (viewer.Find(_T("%1"))>=0)
590 if (viewer.Find(_T("\"%1\"")) >= 0)
591 viewer.Replace(_T("%1"), patchfile);
592 else
593 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
595 else
596 viewer += _T(" \"") + patchfile + _T("\"");
597 if (viewer.Find(_T("%title")) >= 0)
599 viewer.Replace(_T("%title"), title);
602 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
604 return FALSE;
606 return TRUE;
609 BOOL CAppUtils::StartTextViewer(CString file)
611 CString viewer;
612 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
613 viewer = txt;
614 viewer = viewer + _T("\\Shell\\Open\\Command\\");
615 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
616 viewer = txtexe;
618 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
619 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 1]);
620 ExpandEnvironmentStrings(viewer, buf.get(), len);
621 viewer = buf.get();
622 len = ExpandEnvironmentStrings(file, NULL, 0);
623 std::unique_ptr<TCHAR[]> buf2(new TCHAR[len + 1]);
624 ExpandEnvironmentStrings(file, buf2.get(), len);
625 file = buf2.get();
626 file = _T("\"")+file+_T("\"");
627 if (viewer.IsEmpty())
629 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
631 if (viewer.Find(_T("\"%1\"")) >= 0)
633 viewer.Replace(_T("\"%1\""), file);
635 else if (viewer.Find(_T("%1")) >= 0)
637 viewer.Replace(_T("%1"), file);
639 else
641 viewer += _T(" ");
642 viewer += file;
645 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
647 return FALSE;
649 return TRUE;
652 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
654 DWORD length = 0;
655 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
656 if (!hFile)
657 return TRUE;
658 length = ::GetFileSize(hFile, NULL);
659 if (length < 4)
660 return TRUE;
661 return FALSE;
665 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
667 LOGFONT logFont;
668 HDC hScreenDC = ::GetDC(NULL);
669 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
670 ::ReleaseDC(NULL, hScreenDC);
671 logFont.lfWidth = 0;
672 logFont.lfEscapement = 0;
673 logFont.lfOrientation = 0;
674 logFont.lfWeight = FW_NORMAL;
675 logFont.lfItalic = 0;
676 logFont.lfUnderline = 0;
677 logFont.lfStrikeOut = 0;
678 logFont.lfCharSet = DEFAULT_CHARSET;
679 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
680 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
681 logFont.lfQuality = DRAFT_QUALITY;
682 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
683 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
684 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
687 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
689 CString key,remote;
690 CString cmd,out;
691 if( pRemote == NULL)
693 remote=_T("origin");
695 else
697 remote=*pRemote;
699 if(keyfile == NULL)
701 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
702 key = g_Git.GetConfigValue(cmd);
704 else
705 key=*keyfile;
707 if(key.IsEmpty())
708 return false;
710 CString proc=CPathUtils::GetAppDirectory();
711 proc += _T("pageant.exe \"");
712 proc += key;
713 proc += _T("\"");
715 CString tempfile = GetTempFile();
716 ::DeleteFile(tempfile);
718 proc += _T(" -c \"");
719 proc += CPathUtils::GetAppDirectory();
720 proc += _T("tgittouch.exe\"");
721 proc += _T(" \"");
722 proc += tempfile;
723 proc += _T("\"");
725 CString appDir = CPathUtils::GetAppDirectory();
726 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
727 if(!b)
728 return b;
730 int i=0;
731 while(!::PathFileExists(tempfile))
733 Sleep(100);
734 ++i;
735 if(i>10*60*5)
736 break; //timeout 5 minutes
739 if( i== 10*60*5)
741 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
743 ::DeleteFile(tempfile);
744 return true;
746 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
748 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
749 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
750 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
753 CString sCmd;
754 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
756 LaunchApplication(sCmd, NULL, false, NULL, uac);
757 return true;
759 bool CAppUtils::LaunchRemoteSetting()
761 CTGitPath path(g_Git.m_CurrentDir);
762 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
763 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
764 dlg.SetTreeWidth(220);
765 dlg.m_DefaultPage = _T("gitremote");
767 dlg.DoModal();
768 dlg.HandleRestart();
769 return true;
772 * Launch the external blame viewer
774 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
776 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
777 viewer += _T("TortoiseGitBlame.exe");
778 viewer += _T("\" \"") + sBlameFile + _T("\"");
779 //viewer += _T(" \"") + sLogFile + _T("\"");
780 //viewer += _T(" \"") + sOriginalFile + _T("\"");
781 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
782 viewer += CString(_T(" /rev:"))+Rev;
783 if (!g_sGroupingUUID.IsEmpty())
785 viewer += L" /groupuuid:\"";
786 viewer += g_sGroupingUUID;
787 viewer += L"\"";
789 viewer += _T(" ")+sParams;
791 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
794 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
796 CString sText;
797 if (pWnd == NULL)
798 return false;
799 bool bStyled = false;
800 pWnd->GetWindowText(sText);
801 // the rich edit control doesn't count the CR char!
802 // to be exact: CRLF is treated as one char.
803 sText.Remove(_T('\r'));
805 // style each line separately
806 int offset = 0;
807 int nNewlinePos;
810 nNewlinePos = sText.Find('\n', offset);
811 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
813 int start = 0;
814 int end = 0;
815 while (FindStyleChars(sLine, '*', start, end))
817 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
818 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
819 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
820 bStyled = true;
821 start = end;
823 start = 0;
824 end = 0;
825 while (FindStyleChars(sLine, '^', start, end))
827 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
828 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
829 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
830 bStyled = true;
831 start = end;
833 start = 0;
834 end = 0;
835 while (FindStyleChars(sLine, '_', start, end))
837 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
838 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
839 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
840 bStyled = true;
841 start = end;
843 offset = nNewlinePos+1;
844 } while(nNewlinePos>=0);
845 return bStyled;
848 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
850 int i=start;
851 int last = sText.GetLength() - 1;
852 bool bFoundMarker = false;
853 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
854 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
856 // find a starting marker
857 while (i < last)
859 TCHAR prevChar = c;
860 c = nextChar;
861 nextChar = sText[i + 1];
863 // IsCharAlphaNumeric can be somewhat expensive.
864 // Long lines of "*****" or "----" will be pre-empted efficiently
865 // by the (c != nextChar) condition.
867 if ((c == stylechar) && (c != nextChar))
869 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
871 start = ++i;
872 bFoundMarker = true;
873 break;
876 ++i;
878 if (!bFoundMarker)
879 return false;
881 // find ending marker
882 // c == sText[i - 1]
884 bFoundMarker = false;
885 while (i <= last)
887 TCHAR prevChar = c;
888 c = sText[i];
889 if (c == stylechar)
891 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
893 end = i;
894 ++i;
895 bFoundMarker = true;
896 break;
899 ++i;
901 return bFoundMarker;
904 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
905 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
906 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
907 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
908 bool /* blame = false */,
909 bool bMerge,
910 bool bCombine)
912 int diffContext = 0;
913 if (GetMsysgitVersion() > 0x01080100)
914 diffContext = g_Git.GetConfigValueInt32(_T("diff.context"), -1);
915 CString tempfile=GetTempFile();
916 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext))
918 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
919 return false;
921 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
923 #if 0
924 CString sCmd;
925 sCmd.Format(_T("%s /command:showcompare /unified"),
926 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
927 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
928 if (rev1.IsValid())
929 sCmd += _T(" /revision1:") + rev1.ToString();
930 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
931 if (rev2.IsValid())
932 sCmd += _T(" /revision2:") + rev2.ToString();
933 if (peg.IsValid())
934 sCmd += _T(" /pegrevision:") + peg.ToString();
935 if (headpeg.IsValid())
936 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
938 if (bAlternateDiff)
939 sCmd += _T(" /alternatediff");
941 if (bIgnoreAncestry)
942 sCmd += _T(" /ignoreancestry");
944 if (hWnd)
946 sCmd += _T(" /hwnd:");
947 TCHAR buf[30];
948 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
949 sCmd += buf;
952 return CAppUtils::LaunchApplication(sCmd, NULL, false);
953 #endif
954 return TRUE;
957 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
959 CString scriptsdir = CPathUtils::GetAppParentDirectory();
960 scriptsdir += _T("Diff-Scripts");
961 CSimpleFileFind files(scriptsdir);
962 while (files.FindNextFileNoDirectories())
964 CString file = files.GetFilePath();
965 CString filename = files.GetFileName();
966 CString ext = file.Mid(file.ReverseFind('-') + 1);
967 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
968 std::set<CString> extensions;
969 extensions.insert(ext);
970 CString kind;
971 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
973 kind = _T(" //E:vbscript");
975 if (file.Right(2).CompareNoCase(_T("js"))==0)
977 kind = _T(" //E:javascript");
979 // open the file, read the first line and find possible extensions
980 // this script can handle
983 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
984 CString extline;
985 if (f.ReadString(extline))
987 if ((extline.GetLength() > 15 ) &&
988 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
989 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
991 if (extline[0] == '/')
992 extline = extline.Mid(15);
993 else
994 extline = extline.Mid(14);
995 CString sToken;
996 int curPos = 0;
997 sToken = extline.Tokenize(_T(";"), curPos);
998 while (!sToken.IsEmpty())
1000 if (!sToken.IsEmpty())
1002 if (sToken[0] != '.')
1003 sToken = _T(".") + sToken;
1004 extensions.insert(sToken);
1006 sToken = extline.Tokenize(_T(";"), curPos);
1010 f.Close();
1012 catch (CFileException* e)
1014 e->Delete();
1017 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
1019 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1021 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1023 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
1024 CString diffregstring = diffreg;
1025 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1026 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1029 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1031 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1033 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
1034 CString diffregstring = diffreg;
1035 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1036 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1042 return true;
1045 bool CAppUtils::Export(CString *BashHash, const CTGitPath *orgPath)
1047 // ask from where the export has to be done
1048 CExportDlg dlg;
1049 if(BashHash)
1050 dlg.m_initialRefName=*BashHash;
1051 if (orgPath)
1053 if (PathIsRelative(orgPath->GetWinPath()))
1054 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1055 else
1056 dlg.m_orgPath = *orgPath;
1059 if (dlg.DoModal() == IDOK)
1061 CString cmd;
1062 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1063 dlg.m_strFile, g_Git.FixBranchName(dlg.m_VersionName));
1065 CProgressDlg pro;
1066 pro.m_GitCmd=cmd;
1067 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1069 if (status)
1070 return;
1071 postCmdList.push_back(PostCmd(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); }));
1074 CGit git;
1075 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1077 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1078 pro.m_Git = &git;
1080 return (pro.DoModal() == IDOK);
1082 return false;
1085 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1087 CCreateBranchTagDlg dlg;
1088 dlg.m_bIsTag=IsTag;
1089 dlg.m_bSwitch=switch_new_brach;
1091 if(CommitHash)
1092 dlg.m_initialRefName = *CommitHash;
1094 if(dlg.DoModal()==IDOK)
1096 CString cmd;
1097 CString force;
1098 CString track;
1099 if(dlg.m_bTrack == TRUE)
1100 track=_T(" --track ");
1101 else if(dlg.m_bTrack == FALSE)
1102 track=_T(" --no-track");
1104 if(dlg.m_bForce)
1105 force=_T(" -f ");
1107 if(IsTag)
1109 CString sign;
1110 if(dlg.m_bSign)
1111 sign=_T("-s");
1113 cmd.Format(_T("git.exe tag %s %s %s %s"),
1114 force,
1115 sign,
1116 dlg.m_BranchTagName,
1117 g_Git.FixBranchName(dlg.m_VersionName)
1120 if(!dlg.m_Message.Trim().IsEmpty())
1122 CString tempfile = ::GetTempFile();
1123 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1125 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1126 return FALSE;
1128 cmd += _T(" -F ")+tempfile;
1131 else
1133 cmd.Format(_T("git.exe branch %s %s %s %s"),
1134 track,
1135 force,
1136 dlg.m_BranchTagName,
1137 g_Git.FixBranchName(dlg.m_VersionName)
1140 CString out;
1141 if(g_Git.Run(cmd,&out,CP_UTF8))
1143 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1144 return FALSE;
1146 if( !IsTag && dlg.m_bSwitch )
1148 // it is a new branch and the user has requested to switch to it
1149 PerformSwitch(dlg.m_BranchTagName);
1152 return TRUE;
1154 return FALSE;
1157 bool CAppUtils::Switch(CString initialRefName)
1159 CGitSwitchDlg dlg;
1160 if(!initialRefName.IsEmpty())
1161 dlg.m_initialRefName = initialRefName;
1163 if (dlg.DoModal() == IDOK)
1165 CString branch;
1166 if (dlg.m_bBranch)
1167 branch = dlg.m_NewBranch;
1169 // if refs/heads/ is not stripped, checkout will detach HEAD
1170 // checkout prefers branches on name clashes (with tags)
1171 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1172 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1174 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1176 return FALSE;
1179 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1181 CString cmd;
1182 CString track;
1183 CString force;
1184 CString branch;
1185 CString merge;
1187 if(!sNewBranch.IsEmpty()){
1188 if (bBranchOverride)
1190 branch.Format(_T("-B %s"), sNewBranch);
1192 else
1194 branch.Format(_T("-b %s"), sNewBranch);
1196 if (bTrack == TRUE)
1197 track = _T("--track");
1198 else if (bTrack == FALSE)
1199 track = _T("--no-track");
1201 if (bForce)
1202 force = _T("-f");
1203 if (bMerge)
1204 merge = _T("--merge");
1206 cmd.Format(_T("git.exe checkout %s %s %s %s %s --"),
1207 force,
1208 track,
1209 merge,
1210 branch,
1211 g_Git.FixBranchName(ref));
1213 CProgressDlg progress;
1214 progress.m_GitCmd = cmd;
1216 CString currentBranch;
1217 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1218 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1220 if (!status)
1222 CTGitPath gitPath = g_Git.m_CurrentDir;
1223 if (gitPath.HasSubmodules())
1225 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1227 CString sCmd;
1228 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1229 RunTortoiseGitProc(sCmd);
1230 }));
1232 if (hasBranch)
1233 postCmdList.push_back(PostCmd(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); }));
1236 CString newBranch;
1237 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1238 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
1240 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []{
1241 CTGitPathList pathlist;
1242 CTGitPathList selectedlist;
1243 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
1244 CString str;
1245 Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
1246 }));
1248 else
1250 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); }));
1251 if (!bMerge)
1252 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); }));
1256 INT_PTR ret = progress.DoModal();
1258 return ret == IDOK;
1261 class CIgnoreFile : public CStdioFile
1263 public:
1264 STRING_VECTOR m_Items;
1265 CString m_eol;
1267 virtual BOOL ReadString(CString& rString)
1269 if (GetPosition() == 0)
1271 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1272 char buf[3] = { 0, 0, 0 };
1273 Read(buf, 3);
1274 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1276 SeekToBegin();
1280 CStringA strA;
1281 char lastChar = '\0';
1282 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1284 if (c == '\r')
1285 continue;
1286 if (c == '\n')
1288 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1289 break;
1291 strA.AppendChar(c);
1293 if (strA.IsEmpty())
1294 return FALSE;
1296 rString = CUnicodeUtils::GetUnicode(strA);
1297 return TRUE;
1300 void ResetState()
1302 m_Items.clear();
1303 m_eol = _T("");
1307 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1309 file.ResetState();
1310 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1312 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1313 return false;
1316 if (file.GetLength() > 0)
1318 CString fileText;
1319 while (file.ReadString(fileText))
1320 file.m_Items.push_back(fileText);
1321 file.Seek(file.GetLength() - 1, 0);
1322 char lastchar[1] = { 0 };
1323 file.Read(lastchar, 1);
1324 file.SeekToEnd();
1325 if (lastchar[0] != '\n')
1327 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1328 file.Write(eol, eol.GetLength());
1331 else
1332 file.SeekToEnd();
1334 return true;
1337 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1339 CIgnoreDlg ignoreDlg;
1340 if (ignoreDlg.DoModal() == IDOK)
1342 CString ignorefile;
1343 ignorefile = g_Git.m_CurrentDir + _T("\\");
1345 switch (ignoreDlg.m_IgnoreFile)
1347 case 0:
1348 ignorefile += _T(".gitignore");
1349 break;
1350 case 2:
1351 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1352 ignorefile += _T("info/exclude");
1353 break;
1356 CIgnoreFile file;
1359 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1360 return false;
1362 for (int i = 0; i < path.GetCount(); ++i)
1364 if (ignoreDlg.m_IgnoreFile == 1)
1366 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1367 if (!OpenIgnoreFile(file, ignorefile))
1368 return false;
1371 CString ignorePattern;
1372 if (ignoreDlg.m_IgnoreType == 0)
1374 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1375 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1377 ignorePattern += _T("/");
1379 if (IsMask)
1381 ignorePattern += _T("*") + path[i].GetFileExtension();
1383 else
1385 ignorePattern += path[i].GetFileOrDirectoryName();
1388 // escape [ and ] so that files get ignored correctly
1389 ignorePattern.Replace(_T("["), _T("\\["));
1390 ignorePattern.Replace(_T("]"), _T("\\]"));
1392 bool found = false;
1393 for (size_t j = 0; j < file.m_Items.size(); ++j)
1395 if (file.m_Items[j] == ignorePattern)
1397 found = true;
1398 break;
1401 if (!found)
1403 file.m_Items.push_back(ignorePattern);
1404 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1405 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1406 file.Write(ignorePatternA, ignorePatternA.GetLength());
1409 if (ignoreDlg.m_IgnoreFile == 1)
1410 file.Close();
1413 if (ignoreDlg.m_IgnoreFile != 1)
1414 file.Close();
1416 catch(...)
1418 file.Abort();
1419 return false;
1422 return true;
1424 return false;
1427 static bool Reset(const CString& resetTo, int resetType)
1429 CString cmd;
1430 CString type;
1431 switch (resetType)
1433 case 0:
1434 type = _T("--soft");
1435 break;
1436 case 1:
1437 type = _T("--mixed");
1438 break;
1439 case 2:
1440 type = _T("--hard");
1441 break;
1442 default:
1443 resetType = 1;
1444 type = _T("--mixed");
1445 break;
1447 cmd.Format(_T("git.exe reset %s %s --"), type, resetTo);
1449 CProgressDlg progress;
1450 progress.m_GitCmd = cmd;
1452 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1454 if (status)
1456 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); }));
1457 return;
1460 CTGitPath gitPath = g_Git.m_CurrentDir;
1461 if (gitPath.HasSubmodules() && resetType == 2)
1463 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1465 CString sCmd;
1466 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1467 CAppUtils::RunTortoiseGitProc(sCmd);
1468 }));
1472 INT_PTR ret;
1473 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1475 CGitProgressDlg gitdlg;
1476 ResetProgressCommand resetProgressCommand;
1477 gitdlg.SetCommand(&resetProgressCommand);
1478 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1479 resetProgressCommand.SetRevision(resetTo);
1480 resetProgressCommand.SetResetType(resetType);
1481 ret = gitdlg.DoModal();
1483 else
1484 ret = progress.DoModal();
1486 return ret == IDOK;
1489 bool CAppUtils::GitReset(CString *CommitHash,int type)
1491 CResetDlg dlg;
1492 dlg.m_ResetType=type;
1493 dlg.m_ResetToVersion=*CommitHash;
1494 dlg.m_initialRefName = *CommitHash;
1495 if (dlg.DoModal() == IDOK)
1496 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1498 return false;
1501 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1503 if(mode == FALSE)
1505 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1506 return;
1508 if(base)
1510 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1511 return;
1513 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1514 return;
1517 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1519 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1520 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1521 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1523 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1525 CString file;
1526 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1528 return file;
1531 bool ParseHashesFromLsFile(BYTE_VECTOR &out, CString &hash1, CString &hash2, CString &hash3)
1533 unsigned int pos = 0;
1534 CString one;
1535 CString part;
1537 while (pos >= 0 && pos < out.size())
1539 one.Empty();
1541 g_Git.StringAppend(&one, &out[pos], CP_UTF8);
1542 int tabstart = 0;
1543 one.Tokenize(_T("\t"), tabstart);
1545 tabstart = 0;
1546 part = one.Tokenize(_T(" "), tabstart); //Tag
1547 part = one.Tokenize(_T(" "), tabstart); //Mode
1548 part = one.Tokenize(_T(" "), tabstart); //Hash
1549 CString hash = part;
1550 part = one.Tokenize(_T("\t"), tabstart); //Stage
1551 int stage = _ttol(part);
1552 if (stage == 1)
1553 hash1 = hash;
1554 else if (stage == 2)
1555 hash2 = hash;
1556 else if (stage == 3)
1558 hash3 = hash;
1559 return true;
1562 pos = out.findNextString(pos);
1565 return false;
1568 bool CAppUtils::ConflictEdit(CTGitPath& path, bool /*bAlternativeTool = false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1570 bool bRet = false;
1572 CTGitPath merge=path;
1573 CTGitPath directory = merge.GetDirectory();
1575 // we have the conflicted file (%merged)
1576 // now look for the other required files
1577 //GitStatus stat;
1578 //stat.GetStatus(merge);
1579 //if (stat.status == NULL)
1580 // return false;
1582 BYTE_VECTOR vector;
1584 CString cmd;
1585 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1587 if (g_Git.Run(cmd, &vector))
1589 return FALSE;
1592 if (merge.IsDirectory())
1594 CString baseHash, localHash, remoteHash;
1595 if (!ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash))
1596 return FALSE;
1598 CString msg;
1599 msg.Format(_T("BASE: %s\nLOCAL: %s\nREMOTE: %s"), baseHash, localHash, remoteHash);
1600 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK);
1601 return TRUE;
1604 CTGitPathList list;
1605 if (list.ParserFromLsFile(vector))
1607 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1608 return FALSE;
1611 if (list.IsEmpty())
1612 return FALSE;
1614 CTGitPath theirs;
1615 CTGitPath mine;
1616 CTGitPath base;
1618 if (revertTheirMy)
1620 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1621 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1623 else
1625 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1626 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1628 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1630 CString format;
1632 //format=_T("git.exe cat-file blob \":%d:%s\"");
1633 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1634 CFile tempfile;
1635 //create a empty file, incase stage is not three
1636 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1637 tempfile.Close();
1638 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1639 tempfile.Close();
1640 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1641 tempfile.Close();
1643 bool b_base=false, b_local=false, b_remote=false;
1645 for (int i = 0; i< list.GetCount(); ++i)
1647 CString cmd;
1648 CString outfile;
1649 cmd.Empty();
1650 outfile.Empty();
1652 if( list[i].m_Stage == 1)
1654 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1655 b_base = true;
1656 outfile = base.GetWinPathString();
1659 if( list[i].m_Stage == 2 )
1661 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1662 b_local = true;
1663 outfile = mine.GetWinPathString();
1666 if( list[i].m_Stage == 3 )
1668 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1669 b_remote = true;
1670 outfile = theirs.GetWinPathString();
1672 CString output, err;
1673 if(!outfile.IsEmpty())
1674 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1676 CString file;
1677 int start =0 ;
1678 file = output.Tokenize(_T("\t"), start);
1679 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1681 else
1683 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1687 if(b_local && b_remote )
1689 merge.SetFromWin(g_Git.CombinePath(merge));
1690 if( revertTheirMy )
1691 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1692 else
1693 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1696 else
1698 ::DeleteFile(mine.GetWinPathString());
1699 ::DeleteFile(theirs.GetWinPathString());
1700 ::DeleteFile(base.GetWinPathString());
1702 CDeleteConflictDlg dlg;
1703 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1704 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1705 CGitHash localHash, remoteHash;
1706 if (!g_Git.GetHash(localHash, _T("HEAD")))
1707 dlg.m_LocalHash = localHash.ToString();
1708 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1709 dlg.m_RemoteHash = remoteHash.ToString();
1710 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1711 dlg.m_RemoteHash = remoteHash.ToString();
1712 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1713 dlg.m_RemoteHash = remoteHash.ToString();
1714 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1715 dlg.m_RemoteHash = remoteHash.ToString();
1716 dlg.m_bShowModifiedButton=b_base;
1717 dlg.m_File=merge.GetGitPathString();
1718 if(dlg.DoModal() == IDOK)
1720 CString cmd,out;
1721 if(dlg.m_bIsDelete)
1723 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1725 else
1726 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1728 if (g_Git.Run(cmd, &out, CP_UTF8))
1730 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1731 return FALSE;
1733 return TRUE;
1735 else
1736 return FALSE;
1739 #if 0
1740 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1741 base, theirs, mine, merge);
1742 #endif
1743 #if 0
1744 if (stat.status->text_status == svn_wc_status_conflicted)
1746 // we have a text conflict, use our merge tool to resolve the conflict
1748 CTSVNPath theirs(directory);
1749 CTSVNPath mine(directory);
1750 CTSVNPath base(directory);
1751 bool bConflictData = false;
1753 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1755 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1756 bConflictData = true;
1758 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1760 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1761 bConflictData = true;
1763 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1765 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1766 bConflictData = true;
1768 else
1770 mine = merge;
1772 if (bConflictData)
1773 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1774 base, theirs, mine, merge);
1777 if (stat.status->prop_status == svn_wc_status_conflicted)
1779 // we have a property conflict
1780 CTSVNPath prej(directory);
1781 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1783 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1784 // there's a problem: the prej file contains a _description_ of the conflict, and
1785 // that description string might be translated. That means we have no way of parsing
1786 // the file to find out the conflicting values.
1787 // The only thing we can do: show a dialog with the conflict description, then
1788 // let the user either accept the existing property or open the property edit dialog
1789 // to manually change the properties and values. And a button to mark the conflict as
1790 // resolved.
1791 CEditPropConflictDlg dlg;
1792 dlg.SetPrejFile(prej);
1793 dlg.SetConflictedItem(merge);
1794 bRet = (dlg.DoModal() != IDCANCEL);
1798 if (stat.status->tree_conflict)
1800 // we have a tree conflict
1801 SVNInfo info;
1802 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1803 if (pInfoData)
1805 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1807 CTSVNPath theirs(directory);
1808 CTSVNPath mine(directory);
1809 CTSVNPath base(directory);
1810 bool bConflictData = false;
1812 if (pInfoData->treeconflict_theirfile)
1814 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1815 bConflictData = true;
1817 if (pInfoData->treeconflict_basefile)
1819 base.AppendPathString(pInfoData->treeconflict_basefile);
1820 bConflictData = true;
1822 if (pInfoData->treeconflict_myfile)
1824 mine.AppendPathString(pInfoData->treeconflict_myfile);
1825 bConflictData = true;
1827 else
1829 mine = merge;
1831 if (bConflictData)
1832 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1833 base, theirs, mine, merge);
1835 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1837 CString sConflictAction;
1838 CString sConflictReason;
1839 CString sResolveTheirs;
1840 CString sResolveMine;
1841 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1842 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1844 if (pInfoData->treeconflict_nodekind == svn_node_file)
1846 switch (pInfoData->treeconflict_operation)
1848 case svn_wc_operation_update:
1849 switch (pInfoData->treeconflict_action)
1851 case svn_wc_conflict_action_edit:
1852 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1853 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1854 break;
1855 case svn_wc_conflict_action_add:
1856 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1857 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1858 break;
1859 case svn_wc_conflict_action_delete:
1860 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1861 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1862 break;
1864 break;
1865 case svn_wc_operation_switch:
1866 switch (pInfoData->treeconflict_action)
1868 case svn_wc_conflict_action_edit:
1869 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1870 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1871 break;
1872 case svn_wc_conflict_action_add:
1873 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1874 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1875 break;
1876 case svn_wc_conflict_action_delete:
1877 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1878 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1879 break;
1881 break;
1882 case svn_wc_operation_merge:
1883 switch (pInfoData->treeconflict_action)
1885 case svn_wc_conflict_action_edit:
1886 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1887 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1888 break;
1889 case svn_wc_conflict_action_add:
1890 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1891 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1892 break;
1893 case svn_wc_conflict_action_delete:
1894 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1895 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1896 break;
1898 break;
1901 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1903 switch (pInfoData->treeconflict_operation)
1905 case svn_wc_operation_update:
1906 switch (pInfoData->treeconflict_action)
1908 case svn_wc_conflict_action_edit:
1909 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1910 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1911 break;
1912 case svn_wc_conflict_action_add:
1913 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1914 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1915 break;
1916 case svn_wc_conflict_action_delete:
1917 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1918 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1919 break;
1921 break;
1922 case svn_wc_operation_switch:
1923 switch (pInfoData->treeconflict_action)
1925 case svn_wc_conflict_action_edit:
1926 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1927 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1928 break;
1929 case svn_wc_conflict_action_add:
1930 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1931 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1932 break;
1933 case svn_wc_conflict_action_delete:
1934 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1935 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1936 break;
1938 break;
1939 case svn_wc_operation_merge:
1940 switch (pInfoData->treeconflict_action)
1942 case svn_wc_conflict_action_edit:
1943 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1944 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1945 break;
1946 case svn_wc_conflict_action_add:
1947 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1948 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1949 break;
1950 case svn_wc_conflict_action_delete:
1951 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1952 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1953 break;
1955 break;
1959 UINT uReasonID = 0;
1960 switch (pInfoData->treeconflict_reason)
1962 case svn_wc_conflict_reason_edited:
1963 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1964 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1965 break;
1966 case svn_wc_conflict_reason_obstructed:
1967 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1968 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1969 break;
1970 case svn_wc_conflict_reason_deleted:
1971 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1972 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1973 break;
1974 case svn_wc_conflict_reason_added:
1975 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1976 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1977 break;
1978 case svn_wc_conflict_reason_missing:
1979 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1980 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1981 break;
1982 case svn_wc_conflict_reason_unversioned:
1983 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1984 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1985 break;
1987 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1989 CTreeConflictEditorDlg dlg;
1990 dlg.SetConflictInfoText(sConflictReason);
1991 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1992 dlg.SetPath(treeConflictPath);
1993 INT_PTR dlgRet = dlg.DoModal();
1994 bRet = (dlgRet != IDCANCEL);
1998 #endif
1999 return bRet;
2002 bool CAppUtils::IsSSHPutty()
2004 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2005 sshclient=sshclient.MakeLower();
2006 if(sshclient.Find(_T("plink.exe"),0)>=0)
2008 return true;
2010 return false;
2013 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
2015 if (!OpenClipboard(NULL))
2016 return CString();
2018 CString sClipboardText;
2019 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2020 if (hglb)
2022 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2023 sClipboardText = CString(lpstr);
2024 GlobalUnlock(hglb);
2026 hglb = GetClipboardData(CF_UNICODETEXT);
2027 if (hglb)
2029 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2030 sClipboardText = lpstr;
2031 GlobalUnlock(hglb);
2033 CloseClipboard();
2035 if(!sClipboardText.IsEmpty())
2037 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2038 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2040 if(sClipboardText.Find( _T("http://")) == 0)
2041 return sClipboardText;
2043 if(sClipboardText.Find( _T("https://")) == 0)
2044 return sClipboardText;
2046 if(sClipboardText.Find( _T("git://")) == 0)
2047 return sClipboardText;
2049 if(sClipboardText.Find( _T("ssh://")) == 0)
2050 return sClipboardText;
2052 if (sClipboardText.Find(_T("git@")) == 0)
2053 return sClipboardText;
2055 if(sClipboardText.GetLength()>=2)
2056 if( sClipboardText[1] == _T(':') )
2057 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2058 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2059 return sClipboardText;
2061 // trim prefixes like "git clone "
2062 if (!skipGitPrefix.IsEmpty() && sClipboardText.Find(skipGitPrefix) == 0)
2064 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2065 int spacePos = -1;
2066 while (paramsCount >= 0)
2068 --paramsCount;
2069 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2070 if (spacePos == -1)
2071 break;
2073 if (spacePos > 0 && paramsCount < 0)
2074 sClipboardText = sClipboardText.Left(spacePos);
2075 return sClipboardText;
2079 return CString(_T(""));
2082 CString CAppUtils::ChooseRepository(CString *path)
2084 CBrowseFolder browseFolder;
2085 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2087 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2088 CString strCloneDirectory;
2089 if(path)
2090 strCloneDirectory=*path;
2091 else
2093 strCloneDirectory = regLastResopitory;
2096 CString title;
2097 title.LoadString(IDS_CHOOSE_REPOSITORY);
2099 browseFolder.SetInfo(title);
2101 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2103 regLastResopitory = strCloneDirectory;
2104 return strCloneDirectory;
2106 else
2108 return CString();
2112 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2114 CSendMailDlg dlg;
2116 dlg.m_PathList = list;
2118 if(dlg.DoModal()==IDOK)
2120 if (dlg.m_PathList.IsEmpty())
2121 return FALSE;
2123 CGitProgressDlg progDlg;
2124 if (bIsMainWnd)
2125 theApp.m_pMainWnd = &progDlg;
2126 SendMailProgressCommand sendMailProgressCommand;
2127 progDlg.SetCommand(&sendMailProgressCommand);
2129 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2130 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2132 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2133 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2135 progDlg.DoModal();
2137 return true;
2139 return false;
2142 bool CAppUtils::SendPatchMail(CString &cmd, CString &formatpatchoutput, bool bIsMainWnd)
2144 CTGitPathList list;
2145 CString log=formatpatchoutput;
2146 int start=log.Find(cmd);
2147 if(start >=0)
2148 CString one=log.Tokenize(_T("\n"),start);
2149 else
2150 start = 0;
2152 while(start>=0)
2154 CString one=log.Tokenize(_T("\n"),start);
2155 one=one.Trim();
2156 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2157 continue;
2158 one.Replace(_T('/'),_T('\\'));
2159 CTGitPath path;
2160 path.SetFromWin(one);
2161 list.AddPath(path);
2163 if (!list.IsEmpty())
2165 return SendPatchMail(list, bIsMainWnd);
2167 else
2169 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2170 return true;
2175 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2177 CString output;
2178 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2179 if(output.IsEmpty())
2180 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2181 else
2183 return CUnicodeUtils::GetCPCode(output);
2186 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2190 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2191 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2193 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2195 if (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE)
2196 message.TrimRight(L" \r\n");
2198 int len = message.GetLength();
2199 int start = 0;
2200 while (start >= 0 && start < len)
2202 int oldStart = start;
2203 start = message.Find(L"\n", oldStart);
2204 CString line = message.Mid(oldStart);
2205 if (start != -1)
2207 line = line.Left(start - oldStart);
2208 ++start; // move forward so we don't find the same char again
2210 if (stripComments && (line.GetLength() >= 1 && line.GetAt(0) == '#') || (start < 0 && line.IsEmpty()))
2211 continue;
2212 line.TrimRight(L" \r");
2213 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2214 file.Write(lineA.GetBuffer(), lineA.GetLength());
2216 file.Close();
2217 return 0;
2219 catch (CFileException *e)
2221 e->Delete();
2222 return -1;
2226 bool CAppUtils::Pull(bool showPush)
2228 CPullFetchDlg dlg;
2229 dlg.m_IsPull = TRUE;
2230 if (dlg.DoModal() == IDOK)
2232 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2233 if (dlg.m_bRebase)
2234 return DoFetch(dlg.m_RemoteURL,
2235 FALSE, // Fetch all remotes
2236 dlg.m_bAutoLoad == BST_CHECKED,
2237 dlg.m_bPrune,
2238 dlg.m_bDepth == BST_CHECKED,
2239 dlg.m_nDepth,
2240 dlg.m_bFetchTags,
2241 dlg.m_RemoteBranchName,
2242 TRUE); // Rebase after fetching
2244 CString url = dlg.m_RemoteURL;
2246 if (dlg.m_bAutoLoad)
2248 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2251 CString cmd;
2252 CGitHash hashOld;
2253 if (g_Git.GetHash(hashOld, _T("HEAD")))
2255 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
2256 return false;
2259 CString cmdRebase;
2260 CString noff;
2261 CString ffonly;
2262 CString squash;
2263 CString nocommit;
2264 CString depth;
2265 CString notags;
2266 CString prune;
2268 if (!dlg.m_bFetchTags)
2269 notags = _T("--no-tags ");
2271 if (dlg.m_bFetchTags == TRUE)
2272 notags = _T("--tags ");
2274 if (dlg.m_bNoFF)
2275 noff=_T("--no-ff ");
2277 if (dlg.m_bFFonly)
2278 ffonly = _T("--ff-only ");
2280 if (dlg.m_bSquash)
2281 squash = _T("--squash ");
2283 if (dlg.m_bNoCommit)
2284 nocommit = _T("--no-commit ");
2286 if (dlg.m_bDepth)
2287 depth.Format(_T("--depth %d "), dlg.m_nDepth);
2289 int ver = CAppUtils::GetMsysgitVersion();
2291 if (dlg.m_bPrune == TRUE)
2292 prune = _T("--prune ");
2293 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2294 prune = _T("--no-prune ");
2296 if(ver >= 0x01070203) //above 1.7.0.2
2297 cmdRebase += _T("--progress ");
2299 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);
2300 CProgressDlg progress;
2301 progress.m_GitCmd = cmd;
2303 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2304 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2306 if (status)
2308 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
2309 return;
2312 if (g_Git.GetHash(hashNew, _T("HEAD")))
2313 MessageBox(nullptr, g_Git.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR);
2314 else
2316 postCmdList.push_back(PostCmd(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2318 CFileDiffDlg dlg;
2319 dlg.SetDiff(NULL, hashNew.ToString(), hashOld.ToString());
2320 dlg.DoModal();
2321 }));
2322 postCmdList.push_back(PostCmd(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2324 CLogDlg dlg;
2325 dlg.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld.ToString() + _T("..") + hashNew.ToString(), 0);
2326 dlg.DoModal();
2327 }));
2330 if (showPush)
2331 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(_T("")); }));
2333 CTGitPath gitPath = g_Git.m_CurrentDir;
2334 if (gitPath.HasSubmodules())
2336 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2338 CString sCmd;
2339 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2340 CAppUtils::RunTortoiseGitProc(sCmd);
2341 }));
2345 INT_PTR ret = progress.DoModal();
2347 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)
2349 CChangedDlg dlg;
2350 dlg.m_pathList.AddPath(CTGitPath());
2351 dlg.DoModal();
2353 return true;
2356 return ret == IDOK;
2359 return false;
2362 bool CAppUtils::RebaseAfterFetch(const CString& upstream)
2364 while (true)
2366 CRebaseDlg dlg;
2367 if (!upstream.IsEmpty())
2368 dlg.m_Upstream = upstream;
2369 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2370 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2371 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2372 INT_PTR response = dlg.DoModal();
2373 if (response == IDOK)
2375 return true;
2377 else if (response == IDC_REBASE_POST_BUTTON)
2379 CString cmd = _T("/command:log");
2380 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2381 CAppUtils::RunTortoiseGitProc(cmd);
2382 return true;
2384 else if (response == IDC_REBASE_POST_BUTTON + 1)
2386 CString cmd, out, err;
2387 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2388 g_Git.m_CurrentDir,
2389 g_Git.FixBranchName(dlg.m_Upstream),
2390 g_Git.FixBranchName(dlg.m_Branch));
2391 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2393 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2394 return false;
2396 CAppUtils::SendPatchMail(cmd, out);
2397 return true;
2399 else if (response == IDC_REBASE_POST_BUTTON + 2)
2400 continue;
2401 else if (response == IDCANCEL)
2402 return false;
2403 return false;
2407 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, const boolean runRebase)
2409 if (loadPuttyAgent)
2411 if (fetchAllRemotes)
2413 STRING_VECTOR list;
2414 g_Git.GetRemoteList(list);
2416 STRING_VECTOR::const_iterator it = list.begin();
2417 while (it != list.end())
2419 CString remote(*it);
2420 CAppUtils::LaunchPAgent(NULL, &remote);
2421 ++it;
2424 else
2425 CAppUtils::LaunchPAgent(NULL, &url);
2428 CString cmd, arg;
2429 int ver = CAppUtils::GetMsysgitVersion();
2430 if (ver >= 0x01070203) //above 1.7.0.2
2431 arg += _T(" --progress");
2433 if (bDepth)
2434 arg.AppendFormat(_T(" --depth %d"), nDepth);
2436 if (prune == TRUE)
2437 arg += _T(" --prune");
2438 else if (prune == FALSE && ver >= 0x01080500)
2439 arg += _T(" --no-prune");
2441 if (fetchTags == 1)
2442 arg += _T(" --tags");
2443 else if (fetchTags == 0)
2444 arg += _T(" --no-tags");
2446 if (fetchAllRemotes)
2447 cmd.Format(_T("git.exe fetch --all -v%s"), arg);
2448 else
2449 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), arg, url, remoteBranch);
2451 CProgressDlg progress;
2452 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2454 if (status)
2456 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase); }));
2457 return;
2460 postCmdList.push_back(PostCmd(IDI_LOG, IDS_MENULOG, []
2462 CString cmd = _T("/command:log");
2463 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2464 CAppUtils::RunTortoiseGitProc(cmd);
2465 }));
2467 postCmdList.push_back(PostCmd(IDI_REVERT, IDS_PROC_RESET, []
2469 CString pullRemote, pullBranch;
2470 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2471 CString defaultUpstream;
2472 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2473 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2474 CAppUtils::GitReset(&defaultUpstream, 2);
2475 }));
2477 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); }));
2479 if (!runRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2480 postCmdList.push_back(PostCmd(IDI_REBASE, IDS_MENUREBASE, []{ CAppUtils::RebaseAfterFetch(); }));
2483 progress.m_GitCmd = cmd;
2484 INT_PTR userResponse;
2486 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2488 CGitProgressDlg gitdlg;
2489 FetchProgressCommand fetchProgressCommand;
2490 if (!fetchAllRemotes)
2491 fetchProgressCommand.SetUrl(url);
2492 gitdlg.SetCommand(&fetchProgressCommand);
2493 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2494 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2495 if (!fetchAllRemotes)
2496 fetchProgressCommand.SetRefSpec(remoteBranch);
2497 userResponse = gitdlg.DoModal();
2498 return userResponse == IDOK;
2501 userResponse = progress.DoModal();
2502 if (!progress.m_GitStatus)
2504 if (runRebase)
2505 return CAppUtils::RebaseAfterFetch();
2508 return userResponse == IDOK;
2511 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool allRemotes)
2513 CPullFetchDlg dlg;
2514 dlg.m_PreSelectRemote = remoteName;
2515 dlg.m_bAllowRebase = allowRebase;
2516 dlg.m_IsPull=FALSE;
2517 dlg.m_bAllRemotes = allRemotes;
2519 if(dlg.DoModal()==IDOK)
2520 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);
2522 return false;
2525 bool CAppUtils::Push(CString selectLocalBranch)
2527 CPushDlg dlg;
2528 dlg.m_BranchSourceName = selectLocalBranch;
2530 if (dlg.DoModal() == IDOK)
2532 CString error;
2533 DWORD exitcode = 0xFFFFFFFF;
2534 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2536 if (exitcode)
2538 CString temp;
2539 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2540 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2541 return false;
2545 CString arg;
2547 if(dlg.m_bPack)
2548 arg += _T("--thin ");
2549 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2550 arg += _T("--tags ");
2551 if(dlg.m_bForce)
2552 arg += _T("--force ");
2553 if (dlg.m_bForceWithLease)
2554 arg += _T("--force-with-lease ");
2555 if (dlg.m_bSetUpstream)
2556 arg += _T("--set-upstream ");
2557 if (dlg.m_RecurseSubmodules == 1)
2558 arg += _T("--recurse-submodules=check ");
2559 if (dlg.m_RecurseSubmodules == 2)
2560 arg += _T("--recurse-submodules=on-demand ");
2562 int ver = CAppUtils::GetMsysgitVersion();
2564 if(ver >= 0x01070203) //above 1.7.0.2
2565 arg += _T("--progress ");
2567 CProgressDlg progress;
2569 STRING_VECTOR remotesList;
2570 if (dlg.m_bPushAllRemotes)
2571 g_Git.GetRemoteList(remotesList);
2572 else
2573 remotesList.push_back(dlg.m_URL);
2575 for (unsigned int i = 0; i < remotesList.size(); ++i)
2577 if (dlg.m_bAutoLoad)
2578 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2580 CString cmd;
2581 if (dlg.m_bPushAllBranches)
2583 cmd.Format(_T("git.exe push --all %s \"%s\""),
2584 arg,
2585 remotesList[i]);
2587 if (dlg.m_bTags)
2589 progress.m_GitCmdList.push_back(cmd);
2590 cmd.Format(_T("git.exe push --tags %s \"%s\""), arg, remotesList[i]);
2593 else
2595 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2596 arg,
2597 remotesList[i],
2598 dlg.m_BranchSourceName);
2599 if (!dlg.m_BranchRemoteName.IsEmpty())
2601 cmd += _T(":") + dlg.m_BranchRemoteName;
2604 progress.m_GitCmdList.push_back(cmd);
2607 CString superprojectRoot;
2608 g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2609 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2611 // need to execute hooks as those might be needed by post action commands
2612 DWORD exitcode = 0xFFFFFFFF;
2613 CString error;
2614 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2616 if (exitcode)
2618 CString temp;
2619 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2620 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2624 if (status)
2626 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2627 if (rejected)
2629 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, []{ Pull(true); }));
2630 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(dlg.m_bPushAllRemotes ? _T("") : dlg.m_URL, true, !!dlg.m_bPushAllRemotes); }));
2632 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2633 return;
2636 postCmdList.push_back(PostCmd(IDS_PROC_REQUESTPULL, [&]{ RequestPull(dlg.m_BranchRemoteName); }));
2637 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2638 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); }));
2639 if (!superprojectRoot.IsEmpty())
2641 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2643 CString sCmd;
2644 sCmd.Format(_T("/command:commit /path:\"%s\""), superprojectRoot);
2645 RunTortoiseGitProc(sCmd);
2646 }));
2650 INT_PTR ret = progress.DoModal();
2651 return ret == IDOK;
2653 return FALSE;
2656 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl, bool bIsMainWnd)
2658 CRequestPullDlg dlg;
2659 dlg.m_RepositoryURL = repositoryUrl;
2660 dlg.m_EndRevision = endrevision;
2661 if (dlg.DoModal()==IDOK)
2663 CString cmd;
2664 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2666 CSysProgressDlg sysProgressDlg;
2667 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2668 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2669 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2670 sysProgressDlg.SetShowProgressBar(false);
2671 sysProgressDlg.ShowModeless((HWND)NULL, true);
2673 CString tempFileName = GetTempFile();
2674 CString err;
2675 DeleteFile(tempFileName);
2676 CreateDirectory(tempFileName, NULL);
2677 tempFileName += _T("\\pullrequest.txt");
2678 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2680 CString msg;
2681 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2682 CMessageBox::Show(NULL, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK);
2683 return false;
2686 if (sysProgressDlg.HasUserCancelled())
2688 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2689 ::DeleteFile(tempFileName);
2690 return false;
2693 sysProgressDlg.Stop();
2695 if (dlg.m_bSendMail)
2697 CSendMailDlg dlg;
2698 dlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2699 dlg.m_bCustomSubject = true;
2701 if (dlg.DoModal() == IDOK)
2703 if (dlg.m_PathList.IsEmpty())
2704 return FALSE;
2706 CGitProgressDlg progDlg;
2707 if (bIsMainWnd)
2708 theApp.m_pMainWnd = &progDlg;
2709 SendMailProgressCommand sendMailProgressCommand;
2710 progDlg.SetCommand(&sendMailProgressCommand);
2712 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2713 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2715 CSendMailCombineable sendMailCombineable(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2716 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2718 progDlg.DoModal();
2720 return true;
2722 return false;
2725 CAppUtils::LaunchAlternativeEditor(tempFileName);
2727 return true;
2730 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2732 CString strDir(szPath);
2733 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2735 strDir.AppendChar(_T('\\'));
2737 std::vector<CString> vPath;
2738 CString strTemp;
2739 bool bSuccess = false;
2741 for (int i=0;i<strDir.GetLength();++i)
2743 if (strDir.GetAt(i) != _T('\\'))
2745 strTemp.AppendChar(strDir.GetAt(i));
2747 else
2749 vPath.push_back(strTemp);
2750 strTemp.AppendChar(_T('\\'));
2754 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2756 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2759 return bSuccess;
2762 void CAppUtils::RemoveTrailSlash(CString &path)
2764 if(path.IsEmpty())
2765 return ;
2767 // For URL, do not trim the slash just after the host name component.
2768 int index = path.Find(_T("://"));
2769 if (index >= 0)
2771 index += 4;
2772 index = path.Find(_T('/'), index);
2773 if (index == path.GetLength() - 1)
2774 return;
2777 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2779 path=path.Left(path.GetLength()-1);
2780 if(path.IsEmpty())
2781 return;
2785 bool CAppUtils::CheckUserData()
2787 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2789 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2791 CTGitPath path(g_Git.m_CurrentDir);
2792 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2793 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2794 dlg.SetTreeWidth(220);
2795 dlg.m_DefaultPage = _T("gitconfig");
2797 dlg.DoModal();
2798 dlg.HandleRestart();
2801 else
2802 return false;
2805 return true;
2808 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2809 CTGitPathList &pathList,
2810 CTGitPathList &selectedList,
2811 bool bSelectFilesForCommit)
2813 bool bFailed = true;
2815 if (!CheckUserData())
2816 return false;
2818 while (bFailed)
2820 bFailed = false;
2821 CCommitDlg dlg;
2822 dlg.m_sBugID = bugid;
2824 dlg.m_bWholeProject = bWholeProject;
2826 dlg.m_sLogMessage = sLogMsg;
2827 dlg.m_pathList = pathList;
2828 dlg.m_checkedPathList = selectedList;
2829 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2830 if (dlg.DoModal() == IDOK)
2832 if (dlg.m_pathList.IsEmpty())
2833 return false;
2834 // if the user hasn't changed the list of selected items
2835 // we don't use that list. Because if we would use the list
2836 // of pre-checked items, the dialog would show different
2837 // checked items on the next startup: it would only try
2838 // to check the parent folder (which might not even show)
2839 // instead, we simply use an empty list and let the
2840 // default checking do its job.
2841 if (!dlg.m_pathList.IsEqual(pathList))
2842 selectedList = dlg.m_pathList;
2843 pathList = dlg.m_updatedPathList;
2844 sLogMsg = dlg.m_sLogMessage;
2845 bSelectFilesForCommit = true;
2847 switch (dlg.m_PostCmd)
2849 case GIT_POSTCOMMIT_CMD_DCOMMIT:
2850 CAppUtils::SVNDCommit();
2851 break;
2852 case GIT_POSTCOMMIT_CMD_PUSH:
2853 CAppUtils::Push();
2854 break;
2855 case GIT_POSTCOMMIT_CMD_CREATETAG:
2856 CAppUtils::CreateBranchTag(TRUE);
2857 break;
2858 case GIT_POSTCOMMIT_CMD_PULL:
2859 CAppUtils::Pull(true);
2860 break;
2861 default:
2862 break;
2865 // CGitProgressDlg progDlg;
2866 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2867 // if (parser.HasVal(_T("closeonend")))
2868 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2869 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2870 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2871 // progDlg.SetPathList(dlg.m_pathList);
2872 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2873 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2874 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2875 // progDlg.SetItemCount(dlg.m_itemsCount);
2876 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2877 // progDlg.DoModal();
2878 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2879 // err = (DWORD)progDlg.DidErrorsOccur();
2880 // bFailed = progDlg.DidErrorsOccur();
2881 // bRet = progDlg.DidErrorsOccur();
2882 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2883 // if (DWORD(bFailRepeat)==0)
2884 // bFailed = false; // do not repeat if the user chose not to in the settings.
2887 return true;
2891 BOOL CAppUtils::SVNDCommit()
2893 CSVNDCommitDlg dcommitdlg;
2894 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2895 if (gitSetting == _T("")) {
2896 if (dcommitdlg.DoModal() != IDOK)
2898 return false;
2900 else
2902 if (dcommitdlg.m_remember)
2904 if (dcommitdlg.m_rmdir)
2906 gitSetting = _T("true");
2908 else
2910 gitSetting = _T("false");
2912 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2914 CString msg;
2915 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2916 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2922 BOOL IsStash = false;
2923 if(!g_Git.CheckCleanWorkTree())
2925 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2927 CSysProgressDlg sysProgressDlg;
2928 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2929 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2930 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2931 sysProgressDlg.SetShowProgressBar(false);
2932 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2933 sysProgressDlg.ShowModeless((HWND)NULL, true);
2935 CString cmd,out;
2936 cmd=_T("git.exe stash");
2937 if (g_Git.Run(cmd, &out, CP_UTF8))
2939 sysProgressDlg.Stop();
2940 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2941 return false;
2943 sysProgressDlg.Stop();
2945 IsStash =true;
2947 else
2949 return false;
2953 CProgressDlg progress;
2954 if (dcommitdlg.m_rmdir)
2956 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2958 else
2960 progress.m_GitCmd=_T("git.exe svn dcommit");
2962 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2964 ::DeleteFile(g_Git.m_CurrentDir + _T("\\sys$command"));
2965 if( IsStash)
2967 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2969 CSysProgressDlg sysProgressDlg;
2970 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2971 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2972 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2973 sysProgressDlg.SetShowProgressBar(false);
2974 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2975 sysProgressDlg.ShowModeless((HWND)NULL, true);
2977 CString cmd,out;
2978 cmd=_T("git.exe stash pop");
2979 if (g_Git.Run(cmd, &out, CP_UTF8))
2981 sysProgressDlg.Stop();
2982 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2983 return false;
2985 sysProgressDlg.Stop();
2987 else
2989 return false;
2992 return TRUE;
2994 return FALSE;
2997 BOOL CAppUtils::Merge(CString *commit)
2999 if (!CheckUserData())
3000 return FALSE;
3002 CMergeDlg dlg;
3003 if(commit)
3004 dlg.m_initialRefName = *commit;
3006 if(dlg.DoModal()==IDOK)
3008 CString cmd;
3009 CString args;
3011 if(dlg.m_bNoFF)
3012 args += _T(" --no-ff");
3014 if(dlg.m_bSquash)
3015 args += _T(" --squash");
3017 if(dlg.m_bNoCommit)
3018 args += _T(" --no-commit");
3020 if (dlg.m_bLog)
3022 CString fmt;
3023 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
3024 args += fmt;
3027 if (!dlg.m_MergeStrategy.IsEmpty())
3029 args += _T(" --strategy=") + dlg.m_MergeStrategy;
3030 if (!dlg.m_StrategyOption.IsEmpty())
3032 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
3033 if (!dlg.m_StrategyParam.IsEmpty())
3034 args += _T("=") + dlg.m_StrategyParam;
3038 if(!dlg.m_strLogMesage.IsEmpty())
3040 CString logmsg = dlg.m_strLogMesage;
3041 logmsg.Replace(_T("\""), _T("\\\""));
3042 args += _T(" -m \"") + logmsg + _T("\"");
3044 cmd.Format(_T("git.exe merge %s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
3046 CProgressDlg Prodlg;
3047 Prodlg.m_GitCmd = cmd;
3049 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3051 if (status)
3053 CTGitPathList list;
3054 if (!g_Git.ListConflictFile(list) && !list.IsEmpty())
3056 // there are conflict files
3058 postCmdList.push_back(PostCmd(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3060 CString sCmd;
3061 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3062 CAppUtils::RunTortoiseGitProc(sCmd);
3063 }));
3065 return;
3068 if (dlg.m_bNoCommit)
3070 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []
3072 CString sCmd;
3073 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3074 CAppUtils::RunTortoiseGitProc(sCmd);
3075 }));
3076 return;
3079 if (dlg.m_bIsBranch && dlg.m_VersionName.Find(L"remotes/") == -1) // do not ask to remove remote branches
3081 postCmdList.push_back(PostCmd(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3083 CString msg;
3084 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
3085 if (CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3087 CString cmd, out;
3088 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
3089 if (g_Git.Run(cmd, &out, CP_UTF8))
3090 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3092 }));
3094 if (dlg.m_bIsBranch)
3095 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(); }));
3097 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3098 if (hasGitSVN)
3099 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ SVNDCommit(); }));
3102 Prodlg.DoModal();
3103 return !Prodlg.m_GitStatus;
3105 return false;
3108 BOOL CAppUtils::MergeAbort()
3110 CMergeAbortDlg dlg;
3111 if (dlg.DoModal() == IDOK)
3112 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3114 return FALSE;
3117 void CAppUtils::EditNote(GitRev *rev)
3119 if (!CheckUserData())
3120 return;
3122 CInputDlg dlg;
3123 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3124 dlg.m_sInputText = rev->m_Notes;
3125 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3126 //dlg.m_pProjectProperties = &m_ProjectProperties;
3127 dlg.m_bUseLogWidth = true;
3128 if(dlg.DoModal() == IDOK)
3130 CString cmd,output;
3131 cmd=_T("notes add -f -F \"");
3133 CString tempfile=::GetTempFile();
3134 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3136 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3137 return;
3139 cmd += tempfile;
3140 cmd += _T("\" ");
3141 cmd += rev->m_CommitHash.ToString();
3145 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3147 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3150 else
3152 rev->m_Notes = dlg.m_sInputText;
3154 }catch(...)
3156 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3158 ::DeleteFile(tempfile);
3163 int CAppUtils::GetMsysgitVersion()
3165 if (g_Git.ms_LastMsysGitVersion)
3166 return g_Git.ms_LastMsysGitVersion;
3168 CString cmd;
3169 CString versiondebug;
3170 CString version;
3172 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3173 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3175 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3177 __int64 time=0;
3178 if (!g_Git.GetFileModifyTime(gitpath, &time))
3180 if((DWORD)time == regTime)
3182 g_Git.ms_LastMsysGitVersion = regVersion;
3183 return regVersion;
3187 CString err;
3188 cmd = _T("git.exe --version");
3189 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
3191 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);
3192 return -1;
3195 int start=0;
3196 int ver = 0;
3198 versiondebug = version;
3202 CString str=version.Tokenize(_T("."), start);
3203 int space = str.ReverseFind(_T(' '));
3204 str = str.Mid(space+1,start);
3205 ver = _ttol(str);
3206 ver <<=24;
3208 version = version.Mid(start);
3209 start = 0;
3211 str = version.Tokenize(_T("."), start);
3213 ver |= (_ttol(str) & 0xFF) << 16;
3215 str = version.Tokenize(_T("."), start);
3216 ver |= (_ttol(str) & 0xFF) << 8;
3218 str = version.Tokenize(_T("."), start);
3219 ver |= (_ttol(str) & 0xFF);
3221 catch(...)
3223 if (!ver)
3225 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3226 return -1;
3230 regTime = time&0xFFFFFFFF;
3231 regVersion = ver;
3232 g_Git.ms_LastMsysGitVersion = ver;
3234 return ver;
3237 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3239 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3241 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3243 if (hShell.IsValid()) {
3244 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3245 if (pfnSHGPSFW) {
3246 IPropertyStore *pps;
3247 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3248 if (SUCCEEDED(hr)) {
3249 PROPVARIANT var;
3250 var.vt = VT_BOOL;
3251 var.boolVal = VARIANT_TRUE;
3252 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3253 pps->Release();
3259 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3261 ASSERT(dialogname.GetLength() < 70);
3262 ASSERT(urlorpath.GetLength() < MAX_PATH);
3263 WCHAR pathbuf[MAX_PATH] = {0};
3265 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3267 wcscat_s(pathbuf, L" - ");
3268 wcscat_s(pathbuf, dialogname);
3269 wcscat_s(pathbuf, L" - ");
3270 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3271 SetWindowText(hWnd, pathbuf);
3274 bool CAppUtils::BisectStart(CString lastGood, CString firstBad, bool bIsMainWnd)
3276 if (!g_Git.CheckCleanWorkTree())
3278 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3280 CSysProgressDlg sysProgressDlg;
3281 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3282 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3283 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3284 sysProgressDlg.SetShowProgressBar(false);
3285 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3286 sysProgressDlg.ShowModeless((HWND)NULL, true);
3288 CString cmd, out;
3289 cmd = _T("git.exe stash");
3290 if (g_Git.Run(cmd, &out, CP_UTF8))
3292 sysProgressDlg.Stop();
3293 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3294 return false;
3296 sysProgressDlg.Stop();
3298 else
3299 return false;
3302 CBisectStartDlg bisectStartDlg;
3304 if (!lastGood.IsEmpty())
3305 bisectStartDlg.m_sLastGood = lastGood;
3306 if (!firstBad.IsEmpty())
3307 bisectStartDlg.m_sFirstBad = firstBad;
3309 if (bisectStartDlg.DoModal() == IDOK)
3311 CProgressDlg progress;
3312 if (bIsMainWnd)
3313 theApp.m_pMainWnd = &progress;
3314 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3315 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3316 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3318 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3320 if (status)
3321 return;
3323 CTGitPath path(g_Git.m_CurrentDir);
3324 if (path.HasSubmodules())
3326 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3328 CString sCmd;
3329 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3330 CAppUtils::RunTortoiseGitProc(sCmd);
3331 }));
3337 INT_PTR ret = progress.DoModal();
3338 return ret == IDOK;
3341 return false;
3344 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3346 CUserPassword dlg;
3347 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3348 if (username_from_url)
3349 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3351 CStringA username, password;
3352 if (dlg.DoModal() == IDOK)
3354 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3355 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3356 return git_cred_userpass_plaintext_new(out, username, password);
3358 giterr_set_str(GITERR_NONE, "User cancelled.");
3359 return GIT_EUSER;
3362 int CAppUtils::Git2CertificateCheck(git_cert* base_cert, int /*valid*/, const char* host, void* /*payload*/)
3364 if (base_cert->cert_type == GIT_CERT_X509)
3366 git_cert_x509* cert = (git_cert_x509*)base_cert;
3368 if (last_accepted_cert.cmp(cert))
3369 return 0;
3371 PCCERT_CONTEXT pServerCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, (BYTE*)cert->data, (DWORD)cert->len);
3373 DWORD verificationError = VerifyServerCertificate(pServerCert, CUnicodeUtils::GetUnicode(host).GetBuffer(), 0);
3374 if (!verificationError)
3376 last_accepted_cert.set(cert);
3377 CertFreeCertificateContext(pServerCert);
3378 return 0;
3381 CString servernameInCert;
3382 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, 0, nullptr, servernameInCert.GetBuffer(128), 128);
3383 servernameInCert.ReleaseBuffer();
3385 CString issuer;
3386 CertGetNameString(pServerCert, CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_ISSUER_FLAG, nullptr, issuer.GetBuffer(128), 128);
3387 issuer.ReleaseBuffer();
3389 CertFreeCertificateContext(pServerCert);
3391 CCheckCertificateDlg dlg;
3392 dlg.cert = cert;
3393 dlg.m_sCertificateCN = servernameInCert;
3394 dlg.m_sCertificateIssuer = issuer;
3395 dlg.m_sHostname = CUnicodeUtils::GetUnicode(host);
3396 dlg.m_sError = CFormatMessageWrapper(verificationError);
3397 if (dlg.DoModal() == IDOK)
3399 last_accepted_cert.set(cert);
3400 return 0;
3403 return GIT_ECERTIFICATE;
3406 void CAppUtils::ExploreTo(HWND hwnd, CString path)
3408 if (PathFileExists(path))
3410 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3411 if (pidl)
3413 SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3414 ILFree(pidl);
3416 return;
3418 // if filepath does not exist any more, navigate to closest matching folder
3421 int pos = path.ReverseFind(_T('\\'));
3422 if (pos <= 3)
3423 break;
3424 path = path.Left(pos);
3425 } while (!PathFileExists(path));
3426 ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW);