Re-use CAppUtils::RebaseAfterFetch() in Sync dialog
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob19aa0884221c0a50ad777840cf7bd08134b57525
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"
71 CAppUtils::CAppUtils(void)
75 CAppUtils::~CAppUtils(void)
79 bool CAppUtils::StashSave(const CString& msg)
81 CStashSaveDlg dlg;
82 dlg.m_sMessage = msg;
83 if (dlg.DoModal() == IDOK)
85 CString cmd;
86 cmd = _T("git.exe stash save");
88 if (CAppUtils::GetMsysgitVersion() >= 0x01070700)
90 if (dlg.m_bIncludeUntracked)
91 cmd += _T(" --include-untracked");
92 else if (dlg.m_bAll)
93 cmd += _T(" --all");
96 if (!dlg.m_sMessage.IsEmpty())
98 CString message = dlg.m_sMessage;
99 message.Replace(_T("\""), _T("\"\""));
100 cmd += _T(" -- \"") + message + _T("\"");
103 CProgressDlg progress;
104 progress.m_GitCmd = cmd;
105 return (progress.DoModal() == IDOK);
107 return false;
110 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
112 CString cmd,out;
113 cmd = _T("git.exe stash apply ");
114 if (ref.Find(_T("refs/")) == 0)
115 ref = ref.Mid(5);
116 if (ref.Find(_T("stash{")) == 0)
117 ref = _T("stash@") + ref.Mid(5);
118 cmd += ref;
120 CSysProgressDlg sysProgressDlg;
121 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
122 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
123 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
124 sysProgressDlg.SetShowProgressBar(false);
125 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
126 sysProgressDlg.ShowModeless((HWND)NULL, true);
128 int ret = g_Git.Run(cmd, &out, CP_UTF8);
130 sysProgressDlg.Stop();
132 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
133 if (ret && !(ret == 1 && hasConflicts))
135 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
137 else
139 CString message;
140 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
141 if (hasConflicts)
142 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
143 if (showChanges)
145 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
146 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
148 CChangedDlg dlg;
149 dlg.m_pathList.AddPath(CTGitPath());
150 dlg.DoModal();
152 return true;
154 else
156 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
157 return true;
160 return false;
163 bool CAppUtils::StashPop(bool showChanges /* true */)
165 CString cmd,out;
166 cmd=_T("git.exe stash pop ");
168 CSysProgressDlg sysProgressDlg;
169 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
170 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
171 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
172 sysProgressDlg.SetShowProgressBar(false);
173 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
174 sysProgressDlg.ShowModeless((HWND)NULL, true);
176 int ret = g_Git.Run(cmd, &out, CP_UTF8);
178 sysProgressDlg.Stop();
180 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
181 if (ret && !(ret == 1 && hasConflicts))
183 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
185 else
187 CString message;
188 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
189 if (hasConflicts)
190 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
191 if (showChanges)
193 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
194 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
196 CChangedDlg dlg;
197 dlg.m_pathList.AddPath(CTGitPath());
198 dlg.DoModal();
200 return true;
202 else
204 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
205 return true;
208 return false;
211 BOOL CAppUtils::StartExtMerge(
212 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
213 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly,
214 HWND resolveMsgHwnd)
217 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
218 CString ext = mergedfile.GetFileExtension();
219 CString com = regCom;
220 bool bInternal = false;
222 if (!ext.IsEmpty())
224 // is there an extension specific merge tool?
225 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
226 if (!CString(mergetool).IsEmpty())
228 com = mergetool;
231 // is there a filename specific merge tool?
232 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
233 if (!CString(mergetool).IsEmpty())
235 com = mergetool;
238 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
240 // Maybe we should use TortoiseIDiff?
241 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
242 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
243 (ext == _T(".png")) || (ext == _T(".ico")) ||
244 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
245 (ext == _T(".dib")) || (ext == _T(".emf")) ||
246 (ext == _T(".cur")))
248 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
249 com = _T("\"") + com + _T("\"");
250 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
251 com = com + _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
253 else
255 // use TortoiseGitMerge
256 bInternal = true;
257 com = CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
258 com = _T("\"") + com + _T("\"");
259 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
260 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
261 com += _T(" /saverequired");
262 if (resolveMsgHwnd)
264 CString s;
265 s.Format(L" /resolvemsghwnd:%I64d", (__int64)resolveMsgHwnd);
266 com += s;
269 if (!g_sGroupingUUID.IsEmpty())
271 com += L" /groupuuid:\"";
272 com += g_sGroupingUUID;
273 com += L"\"";
276 // check if the params are set. If not, just add the files to the command line
277 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
279 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
280 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
281 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
282 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
284 if (basefile.IsEmpty())
286 com.Replace(_T("/base:%base"), _T(""));
287 com.Replace(_T("%base"), _T(""));
289 else
290 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
291 if (theirfile.IsEmpty())
293 com.Replace(_T("/theirs:%theirs"), _T(""));
294 com.Replace(_T("%theirs"), _T(""));
296 else
297 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
298 if (yourfile.IsEmpty())
300 com.Replace(_T("/mine:%mine"), _T(""));
301 com.Replace(_T("%mine"), _T(""));
303 else
304 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
305 if (mergedfile.IsEmpty())
307 com.Replace(_T("/merged:%merged"), _T(""));
308 com.Replace(_T("%merged"), _T(""));
310 else
311 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
312 if (basename.IsEmpty())
314 if (basefile.IsEmpty())
316 com.Replace(_T("/basename:%bname"), _T(""));
317 com.Replace(_T("%bname"), _T(""));
319 else
321 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
324 else
325 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
326 if (theirname.IsEmpty())
328 if (theirfile.IsEmpty())
330 com.Replace(_T("/theirsname:%tname"), _T(""));
331 com.Replace(_T("%tname"), _T(""));
333 else
335 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
338 else
339 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
340 if (yourname.IsEmpty())
342 if (yourfile.IsEmpty())
344 com.Replace(_T("/minename:%yname"), _T(""));
345 com.Replace(_T("%yname"), _T(""));
347 else
349 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
352 else
353 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
354 if (mergedname.IsEmpty())
356 if (mergedfile.IsEmpty())
358 com.Replace(_T("/mergedname:%mname"), _T(""));
359 com.Replace(_T("%mname"), _T(""));
361 else
363 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
366 else
367 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
369 if ((bReadOnly)&&(bInternal))
370 com += _T(" /readonly");
372 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
374 return FALSE;
377 return TRUE;
380 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
382 CString viewer;
383 // use TortoiseGitMerge
384 viewer = CPathUtils::GetAppDirectory();
385 viewer += _T("TortoiseGitMerge.exe");
387 viewer = _T("\"") + viewer + _T("\"");
388 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
389 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
390 if (bReversed)
391 viewer += _T(" /reversedpatch");
392 if (!sOriginalDescription.IsEmpty())
393 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
394 if (!sPatchedDescription.IsEmpty())
395 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
396 if (!g_sGroupingUUID.IsEmpty())
398 viewer += L" /groupuuid:\"";
399 viewer += g_sGroupingUUID;
400 viewer += L"\"";
402 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
404 return FALSE;
406 return TRUE;
409 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
411 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file2.GetFilename().MakeLower());
412 if (!difftool.IsEmpty())
413 return difftool;
414 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file1.GetFilename().MakeLower());
415 if (!difftool.IsEmpty())
416 return difftool;
418 // Is there an extension specific diff tool?
419 CString ext = file2.GetFileExtension().MakeLower();
420 if (!ext.IsEmpty())
422 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
423 if (!difftool.IsEmpty())
424 return difftool;
425 // Maybe we should use TortoiseIDiff?
426 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
427 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
428 (ext == _T(".png")) || (ext == _T(".ico")) ||
429 (ext == _T(".tif")) || (ext == _T(".tiff")) ||
430 (ext == _T(".dib")) || (ext == _T(".emf")) ||
431 (ext == _T(".cur")))
433 return
434 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
435 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
436 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
440 // Finally, pick a generic external diff tool
441 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
442 return difftool;
445 bool CAppUtils::StartExtDiff(
446 const CString& file1, const CString& file2,
447 const CString& sName1, const CString& sName2,
448 const CString& originalFile1, const CString& originalFile2,
449 const git_revnum_t& hash1, const git_revnum_t& hash2,
450 const DiffFlags& flags, int jumpToLine)
452 CString viewer;
454 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
455 if (!flags.bBlame || !(DWORD)blamediff)
457 viewer = PickDiffTool(file1, file2);
458 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
459 bool bCommentedOut = viewer.Left(1) == _T("#");
460 if (flags.bAlternativeTool)
462 // Invert external vs. internal diff tool selection.
463 if (bCommentedOut)
464 viewer.Delete(0); // uncomment
465 else
466 viewer = "";
468 else if (bCommentedOut)
469 viewer = "";
472 bool bInternal = viewer.IsEmpty();
473 if (bInternal)
475 viewer =
476 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
477 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
478 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
479 if (!g_sGroupingUUID.IsEmpty())
481 viewer += L" /groupuuid:\"";
482 viewer += g_sGroupingUUID;
483 viewer += L"\"";
485 if (flags.bBlame)
486 viewer += _T(" /blame");
488 // check if the params are set. If not, just add the files to the command line
489 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
491 viewer += _T(" \"")+file1+_T("\"");
492 viewer += _T(" \"")+file2+_T("\"");
494 if (viewer.Find(_T("%base")) >= 0)
496 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
498 if (viewer.Find(_T("%mine")) >= 0)
500 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
503 if (sName1.IsEmpty())
504 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
505 else
506 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
508 if (sName2.IsEmpty())
509 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
510 else
511 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
513 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
514 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
516 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
517 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
519 if (flags.bReadOnly && bInternal)
520 viewer += _T(" /readonly");
522 if (jumpToLine > 0)
524 CString temp;
525 temp.Format(_T(" /line:%d"), jumpToLine);
526 viewer += temp;
529 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
532 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
534 CString viewer;
535 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
536 viewer = v;
537 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
539 // use TortoiseGitUDiff
540 viewer = CPathUtils::GetAppDirectory();
541 viewer += _T("TortoiseGitUDiff.exe");
542 // enquote the path to TortoiseGitUDiff
543 viewer = _T("\"") + viewer + _T("\"");
544 // add the params
545 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
546 if (!g_sGroupingUUID.IsEmpty())
548 viewer += L" /groupuuid:\"";
549 viewer += g_sGroupingUUID;
550 viewer += L"\"";
553 if (viewer.Find(_T("%1"))>=0)
555 if (viewer.Find(_T("\"%1\"")) >= 0)
556 viewer.Replace(_T("%1"), patchfile);
557 else
558 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
560 else
561 viewer += _T(" \"") + patchfile + _T("\"");
562 if (viewer.Find(_T("%title")) >= 0)
564 viewer.Replace(_T("%title"), title);
567 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
569 return FALSE;
571 return TRUE;
574 BOOL CAppUtils::StartTextViewer(CString file)
576 CString viewer;
577 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
578 viewer = txt;
579 viewer = viewer + _T("\\Shell\\Open\\Command\\");
580 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
581 viewer = txtexe;
583 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
584 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 1]);
585 ExpandEnvironmentStrings(viewer, buf.get(), len);
586 viewer = buf.get();
587 len = ExpandEnvironmentStrings(file, NULL, 0);
588 std::unique_ptr<TCHAR[]> buf2(new TCHAR[len + 1]);
589 ExpandEnvironmentStrings(file, buf2.get(), len);
590 file = buf2.get();
591 file = _T("\"")+file+_T("\"");
592 if (viewer.IsEmpty())
594 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
596 if (viewer.Find(_T("\"%1\"")) >= 0)
598 viewer.Replace(_T("\"%1\""), file);
600 else if (viewer.Find(_T("%1")) >= 0)
602 viewer.Replace(_T("%1"), file);
604 else
606 viewer += _T(" ");
607 viewer += file;
610 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
612 return FALSE;
614 return TRUE;
617 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
619 DWORD length = 0;
620 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
621 if (!hFile)
622 return TRUE;
623 length = ::GetFileSize(hFile, NULL);
624 if (length < 4)
625 return TRUE;
626 return FALSE;
630 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
632 LOGFONT logFont;
633 HDC hScreenDC = ::GetDC(NULL);
634 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
635 ::ReleaseDC(NULL, hScreenDC);
636 logFont.lfWidth = 0;
637 logFont.lfEscapement = 0;
638 logFont.lfOrientation = 0;
639 logFont.lfWeight = FW_NORMAL;
640 logFont.lfItalic = 0;
641 logFont.lfUnderline = 0;
642 logFont.lfStrikeOut = 0;
643 logFont.lfCharSet = DEFAULT_CHARSET;
644 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
645 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
646 logFont.lfQuality = DRAFT_QUALITY;
647 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
648 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
649 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
652 bool CAppUtils::LaunchPAgent(const CString* keyfile, const CString* pRemote)
654 CString key,remote;
655 CString cmd,out;
656 if( pRemote == NULL)
658 remote=_T("origin");
660 else
662 remote=*pRemote;
664 if(keyfile == NULL)
666 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
667 key = g_Git.GetConfigValue(cmd);
669 else
670 key=*keyfile;
672 if(key.IsEmpty())
673 return false;
675 CString proc=CPathUtils::GetAppDirectory();
676 proc += _T("pageant.exe \"");
677 proc += key;
678 proc += _T("\"");
680 CString tempfile = GetTempFile();
681 ::DeleteFile(tempfile);
683 proc += _T(" -c \"");
684 proc += CPathUtils::GetAppDirectory();
685 proc += _T("tgittouch.exe\"");
686 proc += _T(" \"");
687 proc += tempfile;
688 proc += _T("\"");
690 CString appDir = CPathUtils::GetAppDirectory();
691 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
692 if(!b)
693 return b;
695 int i=0;
696 while(!::PathFileExists(tempfile))
698 Sleep(100);
699 ++i;
700 if(i>10*60*5)
701 break; //timeout 5 minutes
704 if( i== 10*60*5)
706 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
708 ::DeleteFile(tempfile);
709 return true;
711 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
713 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
714 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
715 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
718 CString sCmd;
719 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
721 LaunchApplication(sCmd, NULL, false, NULL, uac);
722 return true;
724 bool CAppUtils::LaunchRemoteSetting()
726 CTGitPath path(g_Git.m_CurrentDir);
727 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
728 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
729 dlg.SetTreeWidth(220);
730 dlg.m_DefaultPage = _T("gitremote");
732 dlg.DoModal();
733 dlg.HandleRestart();
734 return true;
737 * Launch the external blame viewer
739 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
741 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
742 viewer += _T("TortoiseGitBlame.exe");
743 viewer += _T("\" \"") + sBlameFile + _T("\"");
744 //viewer += _T(" \"") + sLogFile + _T("\"");
745 //viewer += _T(" \"") + sOriginalFile + _T("\"");
746 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
747 viewer += CString(_T(" /rev:"))+Rev;
748 if (!g_sGroupingUUID.IsEmpty())
750 viewer += L" /groupuuid:\"";
751 viewer += g_sGroupingUUID;
752 viewer += L"\"";
754 viewer += _T(" ")+sParams;
756 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
759 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
761 CString sText;
762 if (pWnd == NULL)
763 return false;
764 bool bStyled = false;
765 pWnd->GetWindowText(sText);
766 // the rich edit control doesn't count the CR char!
767 // to be exact: CRLF is treated as one char.
768 sText.Remove(_T('\r'));
770 // style each line separately
771 int offset = 0;
772 int nNewlinePos;
775 nNewlinePos = sText.Find('\n', offset);
776 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
778 int start = 0;
779 int end = 0;
780 while (FindStyleChars(sLine, '*', start, end))
782 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
783 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
784 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
785 bStyled = true;
786 start = end;
788 start = 0;
789 end = 0;
790 while (FindStyleChars(sLine, '^', start, end))
792 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
793 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
794 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
795 bStyled = true;
796 start = end;
798 start = 0;
799 end = 0;
800 while (FindStyleChars(sLine, '_', start, end))
802 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
803 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
804 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
805 bStyled = true;
806 start = end;
808 offset = nNewlinePos+1;
809 } while(nNewlinePos>=0);
810 return bStyled;
813 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
815 int i=start;
816 int last = sText.GetLength() - 1;
817 bool bFoundMarker = false;
818 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
819 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
821 // find a starting marker
822 while (i < last)
824 TCHAR prevChar = c;
825 c = nextChar;
826 nextChar = sText[i + 1];
828 // IsCharAlphaNumeric can be somewhat expensive.
829 // Long lines of "*****" or "----" will be pre-empted efficiently
830 // by the (c != nextChar) condition.
832 if ((c == stylechar) && (c != nextChar))
834 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
836 start = ++i;
837 bFoundMarker = true;
838 break;
841 ++i;
843 if (!bFoundMarker)
844 return false;
846 // find ending marker
847 // c == sText[i - 1]
849 bFoundMarker = false;
850 while (i <= last)
852 TCHAR prevChar = c;
853 c = sText[i];
854 if (c == stylechar)
856 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
858 end = i;
859 ++i;
860 bFoundMarker = true;
861 break;
864 ++i;
866 return bFoundMarker;
869 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
870 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
871 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
872 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
873 bool /* blame = false */,
874 bool bMerge,
875 bool bCombine)
877 int diffContext = 0;
878 if (GetMsysgitVersion() > 0x01080100)
879 diffContext = g_Git.GetConfigValueInt32(_T("diff.context"), -1);
880 CString tempfile=GetTempFile();
881 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext))
883 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
884 return false;
886 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
888 #if 0
889 CString sCmd;
890 sCmd.Format(_T("%s /command:showcompare /unified"),
891 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
892 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
893 if (rev1.IsValid())
894 sCmd += _T(" /revision1:") + rev1.ToString();
895 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
896 if (rev2.IsValid())
897 sCmd += _T(" /revision2:") + rev2.ToString();
898 if (peg.IsValid())
899 sCmd += _T(" /pegrevision:") + peg.ToString();
900 if (headpeg.IsValid())
901 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
903 if (bAlternateDiff)
904 sCmd += _T(" /alternatediff");
906 if (bIgnoreAncestry)
907 sCmd += _T(" /ignoreancestry");
909 if (hWnd)
911 sCmd += _T(" /hwnd:");
912 TCHAR buf[30];
913 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
914 sCmd += buf;
917 return CAppUtils::LaunchApplication(sCmd, NULL, false);
918 #endif
919 return TRUE;
922 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
924 CString scriptsdir = CPathUtils::GetAppParentDirectory();
925 scriptsdir += _T("Diff-Scripts");
926 CSimpleFileFind files(scriptsdir);
927 while (files.FindNextFileNoDirectories())
929 CString file = files.GetFilePath();
930 CString filename = files.GetFileName();
931 CString ext = file.Mid(file.ReverseFind('-') + 1);
932 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
933 std::set<CString> extensions;
934 extensions.insert(ext);
935 CString kind;
936 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
938 kind = _T(" //E:vbscript");
940 if (file.Right(2).CompareNoCase(_T("js"))==0)
942 kind = _T(" //E:javascript");
944 // open the file, read the first line and find possible extensions
945 // this script can handle
948 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
949 CString extline;
950 if (f.ReadString(extline))
952 if ((extline.GetLength() > 15 ) &&
953 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
954 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
956 if (extline[0] == '/')
957 extline = extline.Mid(15);
958 else
959 extline = extline.Mid(14);
960 CString sToken;
961 int curPos = 0;
962 sToken = extline.Tokenize(_T(";"), curPos);
963 while (!sToken.IsEmpty())
965 if (!sToken.IsEmpty())
967 if (sToken[0] != '.')
968 sToken = _T(".") + sToken;
969 extensions.insert(sToken);
971 sToken = extline.Tokenize(_T(";"), curPos);
975 f.Close();
977 catch (CFileException* e)
979 e->Delete();
982 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
984 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
986 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
988 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
989 CString diffregstring = diffreg;
990 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
991 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
994 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
996 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
998 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
999 CString diffregstring = diffreg;
1000 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1001 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1007 return true;
1010 bool CAppUtils::Export(CString *BashHash, const CTGitPath *orgPath)
1012 // ask from where the export has to be done
1013 CExportDlg dlg;
1014 if(BashHash)
1015 dlg.m_initialRefName=*BashHash;
1016 if (orgPath)
1018 if (PathIsRelative(orgPath->GetWinPath()))
1019 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1020 else
1021 dlg.m_orgPath = *orgPath;
1024 if (dlg.DoModal() == IDOK)
1026 CString cmd;
1027 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1028 dlg.m_strFile, g_Git.FixBranchName(dlg.m_VersionName));
1030 CProgressDlg pro;
1031 pro.m_GitCmd=cmd;
1032 pro.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1034 if (status)
1035 return;
1036 postCmdList.push_back(PostCmd(IDI_EXPLORER, IDS_STATUSLIST_CONTEXT_EXPLORE, [&]{ CAppUtils::ExploreTo(hWndExplorer, dlg.m_strFile); }));
1039 CGit git;
1040 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1042 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1043 pro.m_Git = &git;
1045 return (pro.DoModal() == IDOK);
1047 return false;
1050 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1052 CCreateBranchTagDlg dlg;
1053 dlg.m_bIsTag=IsTag;
1054 dlg.m_bSwitch=switch_new_brach;
1056 if(CommitHash)
1057 dlg.m_initialRefName = *CommitHash;
1059 if(dlg.DoModal()==IDOK)
1061 CString cmd;
1062 CString force;
1063 CString track;
1064 if(dlg.m_bTrack == TRUE)
1065 track=_T(" --track ");
1066 else if(dlg.m_bTrack == FALSE)
1067 track=_T(" --no-track");
1069 if(dlg.m_bForce)
1070 force=_T(" -f ");
1072 if(IsTag)
1074 CString sign;
1075 if(dlg.m_bSign)
1076 sign=_T("-s");
1078 cmd.Format(_T("git.exe tag %s %s %s %s"),
1079 force,
1080 sign,
1081 dlg.m_BranchTagName,
1082 g_Git.FixBranchName(dlg.m_VersionName)
1085 if(!dlg.m_Message.Trim().IsEmpty())
1087 CString tempfile = ::GetTempFile();
1088 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_Message))
1090 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1091 return FALSE;
1093 cmd += _T(" -F ")+tempfile;
1096 else
1098 cmd.Format(_T("git.exe branch %s %s %s %s"),
1099 track,
1100 force,
1101 dlg.m_BranchTagName,
1102 g_Git.FixBranchName(dlg.m_VersionName)
1105 CString out;
1106 if(g_Git.Run(cmd,&out,CP_UTF8))
1108 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1109 return FALSE;
1111 if( !IsTag && dlg.m_bSwitch )
1113 // it is a new branch and the user has requested to switch to it
1114 PerformSwitch(dlg.m_BranchTagName);
1117 return TRUE;
1119 return FALSE;
1122 bool CAppUtils::Switch(CString initialRefName)
1124 CGitSwitchDlg dlg;
1125 if(!initialRefName.IsEmpty())
1126 dlg.m_initialRefName = initialRefName;
1128 if (dlg.DoModal() == IDOK)
1130 CString branch;
1131 if (dlg.m_bBranch)
1132 branch = dlg.m_NewBranch;
1134 // if refs/heads/ is not stripped, checkout will detach HEAD
1135 // checkout prefers branches on name clashes (with tags)
1136 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1137 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1139 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1141 return FALSE;
1144 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1146 CString cmd;
1147 CString track;
1148 CString force;
1149 CString branch;
1150 CString merge;
1152 if(!sNewBranch.IsEmpty()){
1153 if (bBranchOverride)
1155 branch.Format(_T("-B %s"), sNewBranch);
1157 else
1159 branch.Format(_T("-b %s"), sNewBranch);
1161 if (bTrack == TRUE)
1162 track = _T("--track");
1163 else if (bTrack == FALSE)
1164 track = _T("--no-track");
1166 if (bForce)
1167 force = _T("-f");
1168 if (bMerge)
1169 merge = _T("--merge");
1171 cmd.Format(_T("git.exe checkout %s %s %s %s %s --"),
1172 force,
1173 track,
1174 merge,
1175 branch,
1176 g_Git.FixBranchName(ref));
1178 CProgressDlg progress;
1179 progress.m_GitCmd = cmd;
1181 CString currentBranch;
1182 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1183 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1185 if (!status)
1187 CTGitPath gitPath = g_Git.m_CurrentDir;
1188 if (gitPath.HasSubmodules())
1190 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1192 CString sCmd;
1193 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1194 RunTortoiseGitProc(sCmd);
1195 }));
1197 if (hasBranch)
1198 postCmdList.push_back(PostCmd(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); }));
1201 CString newBranch;
1202 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1203 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
1205 else
1207 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); }));
1208 if (!bMerge)
1209 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); }));
1213 INT_PTR ret = progress.DoModal();
1215 return ret == IDOK;
1218 class CIgnoreFile : public CStdioFile
1220 public:
1221 STRING_VECTOR m_Items;
1222 CString m_eol;
1224 virtual BOOL ReadString(CString& rString)
1226 if (GetPosition() == 0)
1228 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1229 char buf[3] = { 0, 0, 0 };
1230 Read(buf, 3);
1231 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1233 SeekToBegin();
1237 CStringA strA;
1238 char lastChar = '\0';
1239 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1241 if (c == '\r')
1242 continue;
1243 if (c == '\n')
1245 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1246 break;
1248 strA.AppendChar(c);
1250 if (strA.IsEmpty())
1251 return FALSE;
1253 rString = CUnicodeUtils::GetUnicode(strA);
1254 return TRUE;
1257 void ResetState()
1259 m_Items.clear();
1260 m_eol = _T("");
1264 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1266 file.ResetState();
1267 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1269 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1270 return false;
1273 if (file.GetLength() > 0)
1275 CString fileText;
1276 while (file.ReadString(fileText))
1277 file.m_Items.push_back(fileText);
1278 file.Seek(file.GetLength() - 1, 0);
1279 char lastchar[1] = { 0 };
1280 file.Read(lastchar, 1);
1281 file.SeekToEnd();
1282 if (lastchar[0] != '\n')
1284 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1285 file.Write(eol, eol.GetLength());
1288 else
1289 file.SeekToEnd();
1291 return true;
1294 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1296 CIgnoreDlg ignoreDlg;
1297 if (ignoreDlg.DoModal() == IDOK)
1299 CString ignorefile;
1300 ignorefile = g_Git.m_CurrentDir + _T("\\");
1302 switch (ignoreDlg.m_IgnoreFile)
1304 case 0:
1305 ignorefile += _T(".gitignore");
1306 break;
1307 case 2:
1308 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1309 ignorefile += _T("info/exclude");
1310 break;
1313 CIgnoreFile file;
1316 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1317 return false;
1319 for (int i = 0; i < path.GetCount(); ++i)
1321 if (ignoreDlg.m_IgnoreFile == 1)
1323 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1324 if (!OpenIgnoreFile(file, ignorefile))
1325 return false;
1328 CString ignorePattern;
1329 if (ignoreDlg.m_IgnoreType == 0)
1331 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1332 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1334 ignorePattern += _T("/");
1336 if (IsMask)
1338 ignorePattern += _T("*") + path[i].GetFileExtension();
1340 else
1342 ignorePattern += path[i].GetFileOrDirectoryName();
1345 // escape [ and ] so that files get ignored correctly
1346 ignorePattern.Replace(_T("["), _T("\\["));
1347 ignorePattern.Replace(_T("]"), _T("\\]"));
1349 bool found = false;
1350 for (size_t j = 0; j < file.m_Items.size(); ++j)
1352 if (file.m_Items[j] == ignorePattern)
1354 found = true;
1355 break;
1358 if (!found)
1360 file.m_Items.push_back(ignorePattern);
1361 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1362 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1363 file.Write(ignorePatternA, ignorePatternA.GetLength());
1366 if (ignoreDlg.m_IgnoreFile == 1)
1367 file.Close();
1370 if (ignoreDlg.m_IgnoreFile != 1)
1371 file.Close();
1373 catch(...)
1375 file.Abort();
1376 return false;
1379 return true;
1381 return false;
1384 static bool Reset(const CString& resetTo, int resetType)
1386 CString cmd;
1387 CString type;
1388 switch (resetType)
1390 case 0:
1391 type = _T("--soft");
1392 break;
1393 case 1:
1394 type = _T("--mixed");
1395 break;
1396 case 2:
1397 type = _T("--hard");
1398 break;
1399 default:
1400 resetType = 1;
1401 type = _T("--mixed");
1402 break;
1404 cmd.Format(_T("git.exe reset %s %s --"), type, resetTo);
1406 CProgressDlg progress;
1407 progress.m_GitCmd = cmd;
1409 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1411 if (status)
1413 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); }));
1414 return;
1417 CTGitPath gitPath = g_Git.m_CurrentDir;
1418 if (gitPath.HasSubmodules() && resetType == 2)
1420 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1422 CString sCmd;
1423 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1424 CAppUtils::RunTortoiseGitProc(sCmd);
1425 }));
1429 INT_PTR ret;
1430 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1432 CGitProgressDlg gitdlg;
1433 ResetProgressCommand resetProgressCommand;
1434 gitdlg.SetCommand(&resetProgressCommand);
1435 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1436 resetProgressCommand.SetRevision(resetTo);
1437 resetProgressCommand.SetResetType(resetType);
1438 ret = gitdlg.DoModal();
1440 else
1441 ret = progress.DoModal();
1443 return ret == IDOK;
1446 bool CAppUtils::GitReset(CString *CommitHash,int type)
1448 CResetDlg dlg;
1449 dlg.m_ResetType=type;
1450 dlg.m_ResetToVersion=*CommitHash;
1451 dlg.m_initialRefName = *CommitHash;
1452 if (dlg.DoModal() == IDOK)
1453 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1455 return false;
1458 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1460 if(mode == FALSE)
1462 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1463 return;
1465 if(base)
1467 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1468 return;
1470 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1471 return;
1474 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1476 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1477 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1478 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1480 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1482 CString file;
1483 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1485 return file;
1488 bool ParseHashesFromLsFile(BYTE_VECTOR &out, CString &hash1, CString &hash2, CString &hash3)
1490 unsigned int pos = 0;
1491 CString one;
1492 CString part;
1494 while (pos >= 0 && pos < out.size())
1496 one.Empty();
1498 g_Git.StringAppend(&one, &out[pos], CP_UTF8);
1499 int tabstart = 0;
1500 one.Tokenize(_T("\t"), tabstart);
1502 tabstart = 0;
1503 part = one.Tokenize(_T(" "), tabstart); //Tag
1504 part = one.Tokenize(_T(" "), tabstart); //Mode
1505 part = one.Tokenize(_T(" "), tabstart); //Hash
1506 CString hash = part;
1507 part = one.Tokenize(_T("\t"), tabstart); //Stage
1508 int stage = _ttol(part);
1509 if (stage == 1)
1510 hash1 = hash;
1511 else if (stage == 2)
1512 hash2 = hash;
1513 else if (stage == 3)
1515 hash3 = hash;
1516 return true;
1519 pos = out.findNextString(pos);
1522 return false;
1525 bool CAppUtils::ConflictEdit(CTGitPath& path, bool /*bAlternativeTool = false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1527 bool bRet = false;
1529 CTGitPath merge=path;
1530 CTGitPath directory = merge.GetDirectory();
1532 // we have the conflicted file (%merged)
1533 // now look for the other required files
1534 //GitStatus stat;
1535 //stat.GetStatus(merge);
1536 //if (stat.status == NULL)
1537 // return false;
1539 BYTE_VECTOR vector;
1541 CString cmd;
1542 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1544 if (g_Git.Run(cmd, &vector))
1546 return FALSE;
1549 if (merge.IsDirectory())
1551 CString baseHash, localHash, remoteHash;
1552 if (!ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash))
1553 return FALSE;
1555 CString msg;
1556 msg.Format(_T("BASE: %s\nLOCAL: %s\nREMOTE: %s"), baseHash, localHash, remoteHash);
1557 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK);
1558 return TRUE;
1561 CTGitPathList list;
1562 if (list.ParserFromLsFile(vector))
1564 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1565 return FALSE;
1568 if (list.IsEmpty())
1569 return FALSE;
1571 CTGitPath theirs;
1572 CTGitPath mine;
1573 CTGitPath base;
1575 if (revertTheirMy)
1577 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1578 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1580 else
1582 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1583 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1585 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1587 CString format;
1589 //format=_T("git.exe cat-file blob \":%d:%s\"");
1590 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1591 CFile tempfile;
1592 //create a empty file, incase stage is not three
1593 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1594 tempfile.Close();
1595 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1596 tempfile.Close();
1597 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1598 tempfile.Close();
1600 bool b_base=false, b_local=false, b_remote=false;
1602 for (int i = 0; i< list.GetCount(); ++i)
1604 CString cmd;
1605 CString outfile;
1606 cmd.Empty();
1607 outfile.Empty();
1609 if( list[i].m_Stage == 1)
1611 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1612 b_base = true;
1613 outfile = base.GetWinPathString();
1616 if( list[i].m_Stage == 2 )
1618 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1619 b_local = true;
1620 outfile = mine.GetWinPathString();
1623 if( list[i].m_Stage == 3 )
1625 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1626 b_remote = true;
1627 outfile = theirs.GetWinPathString();
1629 CString output, err;
1630 if(!outfile.IsEmpty())
1631 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1633 CString file;
1634 int start =0 ;
1635 file = output.Tokenize(_T("\t"), start);
1636 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1638 else
1640 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1644 if(b_local && b_remote )
1646 merge.SetFromWin(g_Git.CombinePath(merge));
1647 if( revertTheirMy )
1648 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1649 else
1650 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1653 else
1655 ::DeleteFile(mine.GetWinPathString());
1656 ::DeleteFile(theirs.GetWinPathString());
1657 ::DeleteFile(base.GetWinPathString());
1659 CDeleteConflictDlg dlg;
1660 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1661 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1662 CGitHash localHash, remoteHash;
1663 if (!g_Git.GetHash(localHash, _T("HEAD")))
1664 dlg.m_LocalHash = localHash.ToString();
1665 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1666 dlg.m_RemoteHash = remoteHash.ToString();
1667 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1668 dlg.m_RemoteHash = remoteHash.ToString();
1669 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1670 dlg.m_RemoteHash = remoteHash.ToString();
1671 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1672 dlg.m_RemoteHash = remoteHash.ToString();
1673 dlg.m_bShowModifiedButton=b_base;
1674 dlg.m_File=merge.GetGitPathString();
1675 if(dlg.DoModal() == IDOK)
1677 CString cmd,out;
1678 if(dlg.m_bIsDelete)
1680 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1682 else
1683 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1685 if (g_Git.Run(cmd, &out, CP_UTF8))
1687 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1688 return FALSE;
1690 return TRUE;
1692 else
1693 return FALSE;
1696 #if 0
1697 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1698 base, theirs, mine, merge);
1699 #endif
1700 #if 0
1701 if (stat.status->text_status == svn_wc_status_conflicted)
1703 // we have a text conflict, use our merge tool to resolve the conflict
1705 CTSVNPath theirs(directory);
1706 CTSVNPath mine(directory);
1707 CTSVNPath base(directory);
1708 bool bConflictData = false;
1710 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1712 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1713 bConflictData = true;
1715 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1717 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1718 bConflictData = true;
1720 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1722 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1723 bConflictData = true;
1725 else
1727 mine = merge;
1729 if (bConflictData)
1730 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1731 base, theirs, mine, merge);
1734 if (stat.status->prop_status == svn_wc_status_conflicted)
1736 // we have a property conflict
1737 CTSVNPath prej(directory);
1738 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1740 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1741 // there's a problem: the prej file contains a _description_ of the conflict, and
1742 // that description string might be translated. That means we have no way of parsing
1743 // the file to find out the conflicting values.
1744 // The only thing we can do: show a dialog with the conflict description, then
1745 // let the user either accept the existing property or open the property edit dialog
1746 // to manually change the properties and values. And a button to mark the conflict as
1747 // resolved.
1748 CEditPropConflictDlg dlg;
1749 dlg.SetPrejFile(prej);
1750 dlg.SetConflictedItem(merge);
1751 bRet = (dlg.DoModal() != IDCANCEL);
1755 if (stat.status->tree_conflict)
1757 // we have a tree conflict
1758 SVNInfo info;
1759 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1760 if (pInfoData)
1762 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1764 CTSVNPath theirs(directory);
1765 CTSVNPath mine(directory);
1766 CTSVNPath base(directory);
1767 bool bConflictData = false;
1769 if (pInfoData->treeconflict_theirfile)
1771 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1772 bConflictData = true;
1774 if (pInfoData->treeconflict_basefile)
1776 base.AppendPathString(pInfoData->treeconflict_basefile);
1777 bConflictData = true;
1779 if (pInfoData->treeconflict_myfile)
1781 mine.AppendPathString(pInfoData->treeconflict_myfile);
1782 bConflictData = true;
1784 else
1786 mine = merge;
1788 if (bConflictData)
1789 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1790 base, theirs, mine, merge);
1792 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1794 CString sConflictAction;
1795 CString sConflictReason;
1796 CString sResolveTheirs;
1797 CString sResolveMine;
1798 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1799 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1801 if (pInfoData->treeconflict_nodekind == svn_node_file)
1803 switch (pInfoData->treeconflict_operation)
1805 case svn_wc_operation_update:
1806 switch (pInfoData->treeconflict_action)
1808 case svn_wc_conflict_action_edit:
1809 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1810 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1811 break;
1812 case svn_wc_conflict_action_add:
1813 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1814 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1815 break;
1816 case svn_wc_conflict_action_delete:
1817 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1818 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1819 break;
1821 break;
1822 case svn_wc_operation_switch:
1823 switch (pInfoData->treeconflict_action)
1825 case svn_wc_conflict_action_edit:
1826 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1827 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1828 break;
1829 case svn_wc_conflict_action_add:
1830 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1831 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1832 break;
1833 case svn_wc_conflict_action_delete:
1834 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1835 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1836 break;
1838 break;
1839 case svn_wc_operation_merge:
1840 switch (pInfoData->treeconflict_action)
1842 case svn_wc_conflict_action_edit:
1843 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1844 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1845 break;
1846 case svn_wc_conflict_action_add:
1847 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1848 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1849 break;
1850 case svn_wc_conflict_action_delete:
1851 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1852 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1853 break;
1855 break;
1858 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1860 switch (pInfoData->treeconflict_operation)
1862 case svn_wc_operation_update:
1863 switch (pInfoData->treeconflict_action)
1865 case svn_wc_conflict_action_edit:
1866 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1867 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1868 break;
1869 case svn_wc_conflict_action_add:
1870 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1871 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1872 break;
1873 case svn_wc_conflict_action_delete:
1874 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1875 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1876 break;
1878 break;
1879 case svn_wc_operation_switch:
1880 switch (pInfoData->treeconflict_action)
1882 case svn_wc_conflict_action_edit:
1883 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1884 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1885 break;
1886 case svn_wc_conflict_action_add:
1887 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1888 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1889 break;
1890 case svn_wc_conflict_action_delete:
1891 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1892 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1893 break;
1895 break;
1896 case svn_wc_operation_merge:
1897 switch (pInfoData->treeconflict_action)
1899 case svn_wc_conflict_action_edit:
1900 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1901 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1902 break;
1903 case svn_wc_conflict_action_add:
1904 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1905 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1906 break;
1907 case svn_wc_conflict_action_delete:
1908 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1909 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1910 break;
1912 break;
1916 UINT uReasonID = 0;
1917 switch (pInfoData->treeconflict_reason)
1919 case svn_wc_conflict_reason_edited:
1920 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1921 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1922 break;
1923 case svn_wc_conflict_reason_obstructed:
1924 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1925 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1926 break;
1927 case svn_wc_conflict_reason_deleted:
1928 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1929 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1930 break;
1931 case svn_wc_conflict_reason_added:
1932 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1933 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1934 break;
1935 case svn_wc_conflict_reason_missing:
1936 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1937 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1938 break;
1939 case svn_wc_conflict_reason_unversioned:
1940 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1941 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1942 break;
1944 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1946 CTreeConflictEditorDlg dlg;
1947 dlg.SetConflictInfoText(sConflictReason);
1948 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1949 dlg.SetPath(treeConflictPath);
1950 INT_PTR dlgRet = dlg.DoModal();
1951 bRet = (dlgRet != IDCANCEL);
1955 #endif
1956 return bRet;
1959 bool CAppUtils::IsSSHPutty()
1961 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1962 sshclient=sshclient.MakeLower();
1963 if(sshclient.Find(_T("plink.exe"),0)>=0)
1965 return true;
1967 return false;
1970 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
1972 if (!OpenClipboard(NULL))
1973 return CString();
1975 CString sClipboardText;
1976 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1977 if (hglb)
1979 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1980 sClipboardText = CString(lpstr);
1981 GlobalUnlock(hglb);
1983 hglb = GetClipboardData(CF_UNICODETEXT);
1984 if (hglb)
1986 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1987 sClipboardText = lpstr;
1988 GlobalUnlock(hglb);
1990 CloseClipboard();
1992 if(!sClipboardText.IsEmpty())
1994 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1995 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1997 if(sClipboardText.Find( _T("http://")) == 0)
1998 return sClipboardText;
2000 if(sClipboardText.Find( _T("https://")) == 0)
2001 return sClipboardText;
2003 if(sClipboardText.Find( _T("git://")) == 0)
2004 return sClipboardText;
2006 if(sClipboardText.Find( _T("ssh://")) == 0)
2007 return sClipboardText;
2009 if (sClipboardText.Find(_T("git@")) == 0)
2010 return sClipboardText;
2012 if(sClipboardText.GetLength()>=2)
2013 if( sClipboardText[1] == _T(':') )
2014 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2015 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2016 return sClipboardText;
2018 // trim prefixes like "git clone "
2019 if (!skipGitPrefix.IsEmpty() && sClipboardText.Find(skipGitPrefix) == 0)
2021 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2022 int spacePos = -1;
2023 while (paramsCount >= 0)
2025 --paramsCount;
2026 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2027 if (spacePos == -1)
2028 break;
2030 if (spacePos > 0 && paramsCount < 0)
2031 sClipboardText = sClipboardText.Left(spacePos);
2032 return sClipboardText;
2036 return CString(_T(""));
2039 CString CAppUtils::ChooseRepository(CString *path)
2041 CBrowseFolder browseFolder;
2042 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2044 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2045 CString strCloneDirectory;
2046 if(path)
2047 strCloneDirectory=*path;
2048 else
2050 strCloneDirectory = regLastResopitory;
2053 CString title;
2054 title.LoadString(IDS_CHOOSE_REPOSITORY);
2056 browseFolder.SetInfo(title);
2058 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2060 regLastResopitory = strCloneDirectory;
2061 return strCloneDirectory;
2063 else
2065 return CString();
2069 bool CAppUtils::SendPatchMail(CTGitPathList& list, bool bIsMainWnd)
2071 CSendMailDlg dlg;
2073 dlg.m_PathList = list;
2075 if(dlg.DoModal()==IDOK)
2077 if (dlg.m_PathList.IsEmpty())
2078 return FALSE;
2080 CGitProgressDlg progDlg;
2081 if (bIsMainWnd)
2082 theApp.m_pMainWnd = &progDlg;
2083 SendMailProgressCommand sendMailProgressCommand;
2084 progDlg.SetCommand(&sendMailProgressCommand);
2086 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2087 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2089 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2090 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2092 progDlg.DoModal();
2094 return true;
2096 return false;
2099 bool CAppUtils::SendPatchMail(CString &cmd, CString &formatpatchoutput, bool bIsMainWnd)
2101 CTGitPathList list;
2102 CString log=formatpatchoutput;
2103 int start=log.Find(cmd);
2104 if(start >=0)
2105 CString one=log.Tokenize(_T("\n"),start);
2106 else
2107 start = 0;
2109 while(start>=0)
2111 CString one=log.Tokenize(_T("\n"),start);
2112 one=one.Trim();
2113 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2114 continue;
2115 one.Replace(_T('/'),_T('\\'));
2116 CTGitPath path;
2117 path.SetFromWin(one);
2118 list.AddPath(path);
2120 if (!list.IsEmpty())
2122 return SendPatchMail(list, bIsMainWnd);
2124 else
2126 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2127 return true;
2132 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2134 CString output;
2135 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2136 if(output.IsEmpty())
2137 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2138 else
2140 return CUnicodeUtils::GetCPCode(output);
2143 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2147 CFile file(filename, CFile::modeReadWrite | CFile::modeCreate);
2148 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2150 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2152 if (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE)
2153 message.TrimRight(L" \r\n");
2155 int len = message.GetLength();
2156 int start = 0;
2157 while (start >= 0 && start < len)
2159 int oldStart = start;
2160 start = message.Find(L"\n", oldStart);
2161 CString line = message.Mid(oldStart);
2162 if (start != -1)
2164 line = line.Left(start - oldStart);
2165 ++start; // move forward so we don't find the same char again
2167 if (stripComments && (line.GetLength() >= 1 && line.GetAt(0) == '#') || (start < 0 && line.IsEmpty()))
2168 continue;
2169 line.TrimRight(L" \r");
2170 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2171 file.Write(lineA.GetBuffer(), lineA.GetLength());
2173 file.Close();
2174 return 0;
2176 catch (CFileException *e)
2178 e->Delete();
2179 return -1;
2183 bool CAppUtils::Pull(bool showPush)
2185 CPullFetchDlg dlg;
2186 dlg.m_IsPull = TRUE;
2187 if (dlg.DoModal() == IDOK)
2189 CString url = dlg.m_RemoteURL;
2191 if (dlg.m_bAutoLoad)
2193 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2196 CString cmd;
2197 CGitHash hashOld;
2198 if (g_Git.GetHash(hashOld, _T("HEAD")))
2200 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
2201 return false;
2204 CString cmdRebase;
2205 CString noff;
2206 CString ffonly;
2207 CString squash;
2208 CString nocommit;
2209 CString depth;
2210 CString notags;
2211 CString prune;
2213 if (dlg.m_bRebase)
2214 cmdRebase = "--rebase ";
2216 if (!dlg.m_bFetchTags)
2217 notags = _T("--no-tags");
2219 if (dlg.m_bNoFF)
2220 noff=_T("--no-ff");
2222 if (dlg.m_bFFonly)
2223 ffonly = _T("--ff-only");
2225 if (dlg.m_bSquash)
2226 squash = _T("--squash");
2228 if (dlg.m_bNoCommit)
2229 nocommit = _T("--no-commit");
2231 if (dlg.m_bDepth)
2232 depth.Format(_T("--depth %d "), dlg.m_nDepth);
2234 int ver = CAppUtils::GetMsysgitVersion();
2236 if (dlg.m_bPrune == TRUE)
2237 prune = _T("--prune ");
2238 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2239 prune = _T("--no-prune ");
2241 if(ver >= 0x01070203) //above 1.7.0.2
2242 cmdRebase += _T("--progress ");
2244 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);
2245 CProgressDlg progress;
2246 progress.m_GitCmd = cmd;
2248 CGitHash hashNew; // declare outside lambda, because it is captured by reference
2249 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2251 if (status)
2253 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
2254 return;
2257 if (g_Git.GetHash(hashNew, _T("HEAD")))
2258 MessageBox(nullptr, g_Git.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR);
2259 else
2261 postCmdList.push_back(PostCmd(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2263 CFileDiffDlg dlg;
2264 dlg.SetDiff(NULL, hashNew.ToString(), hashOld.ToString());
2265 dlg.DoModal();
2266 }));
2267 postCmdList.push_back(PostCmd(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2269 CLogDlg dlg;
2270 dlg.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld.ToString() + _T("..") + hashNew.ToString(), 0);
2271 dlg.DoModal();
2272 }));
2275 if (showPush)
2276 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(_T("")); }));
2278 CTGitPath gitPath = g_Git.m_CurrentDir;
2279 if (gitPath.HasSubmodules())
2281 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2283 CString sCmd;
2284 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2285 CAppUtils::RunTortoiseGitProc(sCmd);
2286 }));
2290 INT_PTR ret = progress.DoModal();
2292 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)
2294 CChangedDlg dlg;
2295 dlg.m_pathList.AddPath(CTGitPath());
2296 dlg.DoModal();
2298 return true;
2301 return ret == IDOK;
2304 return false;
2307 bool CAppUtils::RebaseAfterFetch(const CString& upstream)
2309 while (true)
2311 CRebaseDlg dlg;
2312 if (!upstream.IsEmpty())
2313 dlg.m_Upstream = upstream;
2314 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2315 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2316 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2317 INT_PTR response = dlg.DoModal();
2318 if (response == IDOK)
2320 return true;
2322 else if (response == IDC_REBASE_POST_BUTTON)
2324 CString cmd = _T("/command:log");
2325 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2326 CAppUtils::RunTortoiseGitProc(cmd);
2327 return true;
2329 else if (response == IDC_REBASE_POST_BUTTON + 1)
2331 CString cmd, out, err;
2332 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2333 g_Git.m_CurrentDir,
2334 g_Git.FixBranchName(dlg.m_Upstream),
2335 g_Git.FixBranchName(dlg.m_Branch));
2336 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2338 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2339 return false;
2341 CAppUtils::SendPatchMail(cmd, out);
2342 return true;
2344 else if (response == IDC_REBASE_POST_BUTTON + 2)
2345 continue;
2346 else if (response == IDCANCEL)
2347 return false;
2348 return false;
2352 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)
2354 if (loadPuttyAgent)
2356 if (fetchAllRemotes)
2358 STRING_VECTOR list;
2359 g_Git.GetRemoteList(list);
2361 STRING_VECTOR::const_iterator it = list.begin();
2362 while (it != list.end())
2364 CString remote(*it);
2365 CAppUtils::LaunchPAgent(NULL, &remote);
2366 ++it;
2369 else
2370 CAppUtils::LaunchPAgent(NULL, &url);
2373 CString cmd, arg;
2374 int ver = CAppUtils::GetMsysgitVersion();
2376 if (bDepth)
2377 arg.AppendFormat(_T(" --depth %d"), nDepth);
2379 if (prune == TRUE)
2380 arg += _T(" --prune");
2381 else if (prune == FALSE && ver >= 0x01080500)
2382 arg += _T(" --no-prune");
2384 if (fetchTags == 1)
2385 arg += _T(" --tags");
2386 else if (fetchTags == 0)
2387 arg += _T(" --no-tags");
2389 if (fetchAllRemotes)
2390 cmd.Format(_T("git.exe fetch --all -v%s"), arg);
2391 else
2392 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), arg, url, remoteBranch);
2394 CProgressDlg progress;
2395 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2397 if (status)
2399 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase); }));
2400 return;
2403 postCmdList.push_back(PostCmd(IDI_LOG, IDS_MENULOG, []
2405 CString cmd = _T("/command:log");
2406 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2407 CAppUtils::RunTortoiseGitProc(cmd);
2408 }));
2410 postCmdList.push_back(PostCmd(IDI_REVERT, IDS_PROC_RESET, []
2412 CString pullRemote, pullBranch;
2413 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2414 CString defaultUpstream;
2415 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2416 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2417 CAppUtils::GitReset(&defaultUpstream, 2);
2418 }));
2420 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); }));
2422 if (!runRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2423 postCmdList.push_back(PostCmd(IDI_REBASE, IDS_MENUREBASE, []{ CAppUtils::RebaseAfterFetch(); }));
2426 progress.m_GitCmd = cmd;
2427 INT_PTR userResponse;
2429 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2431 CGitProgressDlg gitdlg;
2432 FetchProgressCommand fetchProgressCommand;
2433 if (!fetchAllRemotes)
2434 fetchProgressCommand.SetUrl(url);
2435 gitdlg.SetCommand(&fetchProgressCommand);
2436 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2437 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2438 if (!fetchAllRemotes)
2439 fetchProgressCommand.SetRefSpec(remoteBranch);
2440 userResponse = gitdlg.DoModal();
2441 return userResponse == IDOK;
2444 userResponse = progress.DoModal();
2445 if (!progress.m_GitStatus)
2447 if (runRebase)
2448 return CAppUtils::RebaseAfterFetch();
2451 return userResponse == IDOK;
2454 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool allRemotes)
2456 CPullFetchDlg dlg;
2457 dlg.m_PreSelectRemote = remoteName;
2458 dlg.m_bAllowRebase = allowRebase;
2459 dlg.m_IsPull=FALSE;
2460 dlg.m_bAllRemotes = allRemotes;
2462 if(dlg.DoModal()==IDOK)
2463 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);
2465 return false;
2468 bool CAppUtils::Push(CString selectLocalBranch)
2470 CPushDlg dlg;
2471 dlg.m_BranchSourceName = selectLocalBranch;
2473 if (dlg.DoModal() == IDOK)
2475 CString error;
2476 DWORD exitcode = 0xFFFFFFFF;
2477 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2479 if (exitcode)
2481 CString temp;
2482 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2483 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2484 return false;
2488 CString arg;
2490 if(dlg.m_bPack)
2491 arg += _T("--thin ");
2492 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2493 arg += _T("--tags ");
2494 if(dlg.m_bForce)
2495 arg += _T("--force ");
2496 if (dlg.m_bForceWithLease)
2497 arg += _T("--force-with-lease ");
2498 if (dlg.m_bSetUpstream)
2499 arg += _T("--set-upstream ");
2500 if (dlg.m_RecurseSubmodules == 1)
2501 arg += _T("--recurse-submodules=check ");
2502 if (dlg.m_RecurseSubmodules == 2)
2503 arg += _T("--recurse-submodules=on-demand ");
2505 int ver = CAppUtils::GetMsysgitVersion();
2507 if(ver >= 0x01070203) //above 1.7.0.2
2508 arg += _T("--progress ");
2510 CProgressDlg progress;
2512 STRING_VECTOR remotesList;
2513 if (dlg.m_bPushAllRemotes)
2514 g_Git.GetRemoteList(remotesList);
2515 else
2516 remotesList.push_back(dlg.m_URL);
2518 for (unsigned int i = 0; i < remotesList.size(); ++i)
2520 if (dlg.m_bAutoLoad)
2521 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2523 CString cmd;
2524 if (dlg.m_bPushAllBranches)
2526 cmd.Format(_T("git.exe push --all %s \"%s\""),
2527 arg,
2528 remotesList[i]);
2530 if (dlg.m_bTags)
2532 progress.m_GitCmdList.push_back(cmd);
2533 cmd.Format(_T("git.exe push --tags %s \"%s\""), arg, remotesList[i]);
2536 else
2538 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2539 arg,
2540 remotesList[i],
2541 dlg.m_BranchSourceName);
2542 if (!dlg.m_BranchRemoteName.IsEmpty())
2544 cmd += _T(":") + dlg.m_BranchRemoteName;
2547 progress.m_GitCmdList.push_back(cmd);
2550 CString superprojectRoot;
2551 g_GitAdminDir.HasAdminDir(g_Git.m_CurrentDir, false, &superprojectRoot);
2552 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2554 // need to execute hooks as those might be needed by post action commands
2555 DWORD exitcode = 0xFFFFFFFF;
2556 CString error;
2557 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2559 if (exitcode)
2561 CString temp;
2562 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2563 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2567 if (status)
2569 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2570 if (rejected)
2572 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, []{ Pull(true); }));
2573 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(dlg.m_bPushAllRemotes ? _T("") : dlg.m_URL, true, !!dlg.m_bPushAllRemotes); }));
2575 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2576 return;
2579 postCmdList.push_back(PostCmd(IDS_PROC_REQUESTPULL, [&]{ RequestPull(dlg.m_BranchRemoteName); }));
2580 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2581 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); }));
2582 if (!superprojectRoot.IsEmpty())
2584 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_PROC_COMMIT_SUPERPROJECT, [&]
2586 CString sCmd;
2587 sCmd.Format(_T("/command:commit /path:\"%s\""), superprojectRoot);
2588 RunTortoiseGitProc(sCmd);
2589 }));
2593 INT_PTR ret = progress.DoModal();
2594 return ret == IDOK;
2596 return FALSE;
2599 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl, bool bIsMainWnd)
2601 CRequestPullDlg dlg;
2602 dlg.m_RepositoryURL = repositoryUrl;
2603 dlg.m_EndRevision = endrevision;
2604 if (dlg.DoModal()==IDOK)
2606 CString cmd;
2607 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2609 CSysProgressDlg sysProgressDlg;
2610 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2611 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2612 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2613 sysProgressDlg.SetShowProgressBar(false);
2614 sysProgressDlg.ShowModeless((HWND)NULL, true);
2616 CString tempFileName = GetTempFile();
2617 CString err;
2618 DeleteFile(tempFileName);
2619 CreateDirectory(tempFileName, NULL);
2620 tempFileName += _T("\\pullrequest.txt");
2621 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2623 CString msg;
2624 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2625 CMessageBox::Show(NULL, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK);
2626 return false;
2629 if (sysProgressDlg.HasUserCancelled())
2631 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2632 ::DeleteFile(tempFileName);
2633 return false;
2636 sysProgressDlg.Stop();
2638 if (dlg.m_bSendMail)
2640 CSendMailDlg dlg;
2641 dlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2642 dlg.m_bCustomSubject = true;
2644 if (dlg.DoModal() == IDOK)
2646 if (dlg.m_PathList.IsEmpty())
2647 return FALSE;
2649 CGitProgressDlg progDlg;
2650 if (bIsMainWnd)
2651 theApp.m_pMainWnd = &progDlg;
2652 SendMailProgressCommand sendMailProgressCommand;
2653 progDlg.SetCommand(&sendMailProgressCommand);
2655 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2656 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2658 CSendMailCombineable sendMailCombineable(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2659 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2661 progDlg.DoModal();
2663 return true;
2665 return false;
2668 CAppUtils::LaunchAlternativeEditor(tempFileName);
2670 return true;
2673 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2675 CString strDir(szPath);
2676 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2678 strDir.AppendChar(_T('\\'));
2680 std::vector<CString> vPath;
2681 CString strTemp;
2682 bool bSuccess = false;
2684 for (int i=0;i<strDir.GetLength();++i)
2686 if (strDir.GetAt(i) != _T('\\'))
2688 strTemp.AppendChar(strDir.GetAt(i));
2690 else
2692 vPath.push_back(strTemp);
2693 strTemp.AppendChar(_T('\\'));
2697 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2699 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2702 return bSuccess;
2705 void CAppUtils::RemoveTrailSlash(CString &path)
2707 if(path.IsEmpty())
2708 return ;
2710 // For URL, do not trim the slash just after the host name component.
2711 int index = path.Find(_T("://"));
2712 if (index >= 0)
2714 index += 4;
2715 index = path.Find(_T('/'), index);
2716 if (index == path.GetLength() - 1)
2717 return;
2720 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2722 path=path.Left(path.GetLength()-1);
2723 if(path.IsEmpty())
2724 return;
2728 bool CAppUtils::CheckUserData()
2730 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2732 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2734 CTGitPath path(g_Git.m_CurrentDir);
2735 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2736 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2737 dlg.SetTreeWidth(220);
2738 dlg.m_DefaultPage = _T("gitconfig");
2740 dlg.DoModal();
2741 dlg.HandleRestart();
2744 else
2745 return false;
2748 return true;
2751 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2752 CTGitPathList &pathList,
2753 CTGitPathList &selectedList,
2754 bool bSelectFilesForCommit)
2756 bool bFailed = true;
2758 if (!CheckUserData())
2759 return false;
2761 while (bFailed)
2763 bFailed = false;
2764 CCommitDlg dlg;
2765 dlg.m_sBugID = bugid;
2767 dlg.m_bWholeProject = bWholeProject;
2769 dlg.m_sLogMessage = sLogMsg;
2770 dlg.m_pathList = pathList;
2771 dlg.m_checkedPathList = selectedList;
2772 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2773 if (dlg.DoModal() == IDOK)
2775 if (dlg.m_pathList.IsEmpty())
2776 return false;
2777 // if the user hasn't changed the list of selected items
2778 // we don't use that list. Because if we would use the list
2779 // of pre-checked items, the dialog would show different
2780 // checked items on the next startup: it would only try
2781 // to check the parent folder (which might not even show)
2782 // instead, we simply use an empty list and let the
2783 // default checking do its job.
2784 if (!dlg.m_pathList.IsEqual(pathList))
2785 selectedList = dlg.m_pathList;
2786 pathList = dlg.m_updatedPathList;
2787 sLogMsg = dlg.m_sLogMessage;
2788 bSelectFilesForCommit = true;
2790 switch (dlg.m_PostCmd)
2792 case GIT_POSTCOMMIT_CMD_DCOMMIT:
2793 CAppUtils::SVNDCommit();
2794 break;
2795 case GIT_POSTCOMMIT_CMD_PUSH:
2796 CAppUtils::Push();
2797 break;
2798 case GIT_POSTCOMMIT_CMD_CREATETAG:
2799 CAppUtils::CreateBranchTag(TRUE);
2800 break;
2801 case GIT_POSTCOMMIT_CMD_PULL:
2802 CAppUtils::Pull(true);
2803 break;
2804 default:
2805 break;
2808 // CGitProgressDlg progDlg;
2809 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2810 // if (parser.HasVal(_T("closeonend")))
2811 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2812 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2813 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2814 // progDlg.SetPathList(dlg.m_pathList);
2815 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2816 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2817 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2818 // progDlg.SetItemCount(dlg.m_itemsCount);
2819 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2820 // progDlg.DoModal();
2821 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2822 // err = (DWORD)progDlg.DidErrorsOccur();
2823 // bFailed = progDlg.DidErrorsOccur();
2824 // bRet = progDlg.DidErrorsOccur();
2825 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2826 // if (DWORD(bFailRepeat)==0)
2827 // bFailed = false; // do not repeat if the user chose not to in the settings.
2830 return true;
2834 BOOL CAppUtils::SVNDCommit()
2836 CSVNDCommitDlg dcommitdlg;
2837 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2838 if (gitSetting == _T("")) {
2839 if (dcommitdlg.DoModal() != IDOK)
2841 return false;
2843 else
2845 if (dcommitdlg.m_remember)
2847 if (dcommitdlg.m_rmdir)
2849 gitSetting = _T("true");
2851 else
2853 gitSetting = _T("false");
2855 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2857 CString msg;
2858 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2859 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2865 BOOL IsStash = false;
2866 if(!g_Git.CheckCleanWorkTree())
2868 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2870 CSysProgressDlg sysProgressDlg;
2871 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2872 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2873 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2874 sysProgressDlg.SetShowProgressBar(false);
2875 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2876 sysProgressDlg.ShowModeless((HWND)NULL, true);
2878 CString cmd,out;
2879 cmd=_T("git.exe stash");
2880 if (g_Git.Run(cmd, &out, CP_UTF8))
2882 sysProgressDlg.Stop();
2883 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2884 return false;
2886 sysProgressDlg.Stop();
2888 IsStash =true;
2890 else
2892 return false;
2896 CProgressDlg progress;
2897 if (dcommitdlg.m_rmdir)
2899 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2901 else
2903 progress.m_GitCmd=_T("git.exe svn dcommit");
2905 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2907 ::DeleteFile(g_Git.m_CurrentDir + _T("\\sys$command"));
2908 if( IsStash)
2910 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2912 CSysProgressDlg sysProgressDlg;
2913 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2914 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2915 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2916 sysProgressDlg.SetShowProgressBar(false);
2917 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2918 sysProgressDlg.ShowModeless((HWND)NULL, true);
2920 CString cmd,out;
2921 cmd=_T("git.exe stash pop");
2922 if (g_Git.Run(cmd, &out, CP_UTF8))
2924 sysProgressDlg.Stop();
2925 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2926 return false;
2928 sysProgressDlg.Stop();
2930 else
2932 return false;
2935 return TRUE;
2937 return FALSE;
2940 BOOL CAppUtils::Merge(CString *commit)
2942 if (!CheckUserData())
2943 return FALSE;
2945 CMergeDlg dlg;
2946 if(commit)
2947 dlg.m_initialRefName = *commit;
2949 if(dlg.DoModal()==IDOK)
2951 CString cmd;
2952 CString args;
2954 if(dlg.m_bNoFF)
2955 args += _T(" --no-ff");
2957 if(dlg.m_bSquash)
2958 args += _T(" --squash");
2960 if(dlg.m_bNoCommit)
2961 args += _T(" --no-commit");
2963 if (dlg.m_bLog)
2965 CString fmt;
2966 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
2967 args += fmt;
2970 if (!dlg.m_MergeStrategy.IsEmpty())
2972 args += _T(" --strategy=") + dlg.m_MergeStrategy;
2973 if (!dlg.m_StrategyOption.IsEmpty())
2975 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
2976 if (!dlg.m_StrategyParam.IsEmpty())
2977 args += _T("=") + dlg.m_StrategyParam;
2981 if(!dlg.m_strLogMesage.IsEmpty())
2983 CString logmsg = dlg.m_strLogMesage;
2984 logmsg.Replace(_T("\""), _T("\\\""));
2985 args += _T(" -m \"") + logmsg + _T("\"");
2987 cmd.Format(_T("git.exe merge %s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
2989 CProgressDlg Prodlg;
2990 Prodlg.m_GitCmd = cmd;
2992 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2994 if (status)
2996 CTGitPathList list;
2997 if (!g_Git.ListConflictFile(list) && !list.IsEmpty())
2999 // there are conflict files
3001 postCmdList.push_back(PostCmd(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
3003 CString sCmd;
3004 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3005 CAppUtils::RunTortoiseGitProc(sCmd);
3006 }));
3008 return;
3011 if (dlg.m_bNoCommit)
3013 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []
3015 CString sCmd;
3016 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
3017 CAppUtils::RunTortoiseGitProc(sCmd);
3018 }));
3019 return;
3022 if (dlg.m_bIsBranch && dlg.m_VersionName.Find(L"remotes/") == -1) // do not ask to remove remote branches
3024 postCmdList.push_back(PostCmd(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
3026 CString msg;
3027 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
3028 if (CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3030 CString cmd, out;
3031 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
3032 if (g_Git.Run(cmd, &out, CP_UTF8))
3033 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
3035 }));
3037 if (dlg.m_bIsBranch)
3038 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(); }));
3040 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3041 if (hasGitSVN)
3042 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ SVNDCommit(); }));
3045 Prodlg.DoModal();
3046 return !Prodlg.m_GitStatus;
3048 return false;
3051 BOOL CAppUtils::MergeAbort()
3053 CMergeAbortDlg dlg;
3054 if (dlg.DoModal() == IDOK)
3055 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3057 return FALSE;
3060 void CAppUtils::EditNote(GitRev *rev)
3062 if (!CheckUserData())
3063 return;
3065 CInputDlg dlg;
3066 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3067 dlg.m_sInputText = rev->m_Notes;
3068 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3069 //dlg.m_pProjectProperties = &m_ProjectProperties;
3070 dlg.m_bUseLogWidth = true;
3071 if(dlg.DoModal() == IDOK)
3073 CString cmd,output;
3074 cmd=_T("notes add -f -F \"");
3076 CString tempfile=::GetTempFile();
3077 if (CAppUtils::SaveCommitUnicodeFile(tempfile, dlg.m_sInputText))
3079 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3080 return;
3082 cmd += tempfile;
3083 cmd += _T("\" ");
3084 cmd += rev->m_CommitHash.ToString();
3088 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3090 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3093 else
3095 rev->m_Notes = dlg.m_sInputText;
3097 }catch(...)
3099 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3101 ::DeleteFile(tempfile);
3106 int CAppUtils::GetMsysgitVersion()
3108 if (g_Git.ms_LastMsysGitVersion)
3109 return g_Git.ms_LastMsysGitVersion;
3111 CString cmd;
3112 CString versiondebug;
3113 CString version;
3115 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3116 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3118 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3120 __int64 time=0;
3121 if (!g_Git.GetFileModifyTime(gitpath, &time))
3123 if((DWORD)time == regTime)
3125 g_Git.ms_LastMsysGitVersion = regVersion;
3126 return regVersion;
3130 CString err;
3131 cmd = _T("git.exe --version");
3132 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
3134 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);
3135 return -1;
3138 int start=0;
3139 int ver = 0;
3141 versiondebug = version;
3145 CString str=version.Tokenize(_T("."), start);
3146 int space = str.ReverseFind(_T(' '));
3147 str = str.Mid(space+1,start);
3148 ver = _ttol(str);
3149 ver <<=24;
3151 version = version.Mid(start);
3152 start = 0;
3154 str = version.Tokenize(_T("."), start);
3156 ver |= (_ttol(str) & 0xFF) << 16;
3158 str = version.Tokenize(_T("."), start);
3159 ver |= (_ttol(str) & 0xFF) << 8;
3161 str = version.Tokenize(_T("."), start);
3162 ver |= (_ttol(str) & 0xFF);
3164 catch(...)
3166 if (!ver)
3168 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3169 return -1;
3173 regTime = time&0xFFFFFFFF;
3174 regVersion = ver;
3175 g_Git.ms_LastMsysGitVersion = ver;
3177 return ver;
3180 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3182 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3184 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3186 if (hShell.IsValid()) {
3187 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3188 if (pfnSHGPSFW) {
3189 IPropertyStore *pps;
3190 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3191 if (SUCCEEDED(hr)) {
3192 PROPVARIANT var;
3193 var.vt = VT_BOOL;
3194 var.boolVal = VARIANT_TRUE;
3195 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3196 pps->Release();
3202 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3204 ASSERT(dialogname.GetLength() < 70);
3205 ASSERT(urlorpath.GetLength() < MAX_PATH);
3206 WCHAR pathbuf[MAX_PATH] = {0};
3208 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3210 wcscat_s(pathbuf, L" - ");
3211 wcscat_s(pathbuf, dialogname);
3212 wcscat_s(pathbuf, L" - ");
3213 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3214 SetWindowText(hWnd, pathbuf);
3217 bool CAppUtils::BisectStart(CString lastGood, CString firstBad, bool bIsMainWnd)
3219 if (!g_Git.CheckCleanWorkTree())
3221 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3223 CSysProgressDlg sysProgressDlg;
3224 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3225 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3226 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3227 sysProgressDlg.SetShowProgressBar(false);
3228 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3229 sysProgressDlg.ShowModeless((HWND)NULL, true);
3231 CString cmd, out;
3232 cmd = _T("git.exe stash");
3233 if (g_Git.Run(cmd, &out, CP_UTF8))
3235 sysProgressDlg.Stop();
3236 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3237 return false;
3239 sysProgressDlg.Stop();
3241 else
3242 return false;
3245 CBisectStartDlg bisectStartDlg;
3247 if (!lastGood.IsEmpty())
3248 bisectStartDlg.m_sLastGood = lastGood;
3249 if (!firstBad.IsEmpty())
3250 bisectStartDlg.m_sFirstBad = firstBad;
3252 if (bisectStartDlg.DoModal() == IDOK)
3254 CProgressDlg progress;
3255 if (bIsMainWnd)
3256 theApp.m_pMainWnd = &progress;
3257 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3258 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3259 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3261 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3263 if (status)
3264 return;
3266 CTGitPath path(g_Git.m_CurrentDir);
3267 if (path.HasSubmodules())
3269 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3271 CString sCmd;
3272 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3273 CAppUtils::RunTortoiseGitProc(sCmd);
3274 }));
3280 INT_PTR ret = progress.DoModal();
3281 return ret == IDOK;
3284 return false;
3287 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3289 CUserPassword dlg;
3290 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3291 if (username_from_url)
3292 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3294 CStringA username, password;
3295 if (dlg.DoModal() == IDOK)
3297 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3298 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3299 return git_cred_userpass_plaintext_new(out, username, password);
3301 giterr_set_str(GITERR_NONE, "User cancelled.");
3302 return GIT_EUSER;
3305 void CAppUtils::ExploreTo(HWND hwnd, CString path)
3307 if (PathFileExists(path))
3309 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3310 if (pidl)
3312 SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3313 ILFree(pidl);
3315 return;
3317 // if filepath does not exist any more, navigate to closest matching folder
3320 int pos = path.ReverseFind(_T('\\'));
3321 if (pos <= 3)
3322 break;
3323 path = path.Left(pos);
3324 } while (!PathFileExists(path));
3325 ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW);