Fix crash when clicking merge after switch
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobfe5fc2d7f0e0343b94b6602ff839bb71722e4d9d
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()
81 CStashSaveDlg dlg;
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_Revision=*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 CGit git;
1033 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1035 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1036 pro.m_Git = &git;
1038 return (pro.DoModal() == IDOK);
1040 return false;
1043 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1045 CCreateBranchTagDlg dlg;
1046 dlg.m_bIsTag=IsTag;
1047 dlg.m_bSwitch=switch_new_brach;
1049 if(CommitHash)
1050 dlg.m_initialRefName = *CommitHash;
1052 if(dlg.DoModal()==IDOK)
1054 CString cmd;
1055 CString force;
1056 CString track;
1057 if(dlg.m_bTrack == TRUE)
1058 track=_T(" --track ");
1059 else if(dlg.m_bTrack == FALSE)
1060 track=_T(" --no-track");
1062 if(dlg.m_bForce)
1063 force=_T(" -f ");
1065 if(IsTag)
1067 CString sign;
1068 if(dlg.m_bSign)
1069 sign=_T("-s");
1071 cmd.Format(_T("git.exe tag %s %s %s %s"),
1072 force,
1073 sign,
1074 dlg.m_BranchTagName,
1075 g_Git.FixBranchName(dlg.m_VersionName)
1078 CString tempfile=::GetTempFile();
1079 if(!dlg.m_Message.Trim().IsEmpty())
1081 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1082 cmd += _T(" -F ")+tempfile;
1085 else
1087 cmd.Format(_T("git.exe branch %s %s %s %s"),
1088 track,
1089 force,
1090 dlg.m_BranchTagName,
1091 g_Git.FixBranchName(dlg.m_VersionName)
1094 CString out;
1095 if(g_Git.Run(cmd,&out,CP_UTF8))
1097 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1098 return FALSE;
1100 if( !IsTag && dlg.m_bSwitch )
1102 // it is a new branch and the user has requested to switch to it
1103 PerformSwitch(dlg.m_BranchTagName);
1106 return TRUE;
1108 return FALSE;
1111 bool CAppUtils::Switch(CString initialRefName)
1113 CGitSwitchDlg dlg;
1114 if(!initialRefName.IsEmpty())
1115 dlg.m_initialRefName = initialRefName;
1117 if (dlg.DoModal() == IDOK)
1119 CString branch;
1120 if (dlg.m_bBranch)
1121 branch = dlg.m_NewBranch;
1123 // if refs/heads/ is not stripped, checkout will detach HEAD
1124 // checkout prefers branches on name clashes (with tags)
1125 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1126 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1128 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1130 return FALSE;
1133 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1135 CString cmd;
1136 CString track;
1137 CString force;
1138 CString branch;
1139 CString merge;
1141 if(!sNewBranch.IsEmpty()){
1142 if (bBranchOverride)
1144 branch.Format(_T("-B %s"), sNewBranch);
1146 else
1148 branch.Format(_T("-b %s"), sNewBranch);
1150 if (bTrack == TRUE)
1151 track = _T("--track");
1152 else if (bTrack == FALSE)
1153 track = _T("--no-track");
1155 if (bForce)
1156 force = _T("-f");
1157 if (bMerge)
1158 merge = _T("--merge");
1160 cmd.Format(_T("git.exe checkout %s %s %s %s %s --"),
1161 force,
1162 track,
1163 merge,
1164 branch,
1165 g_Git.FixBranchName(ref));
1167 CProgressDlg progress;
1168 progress.m_GitCmd = cmd;
1170 CString currentBranch;
1171 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1172 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1174 if (!status)
1176 CTGitPath gitPath = g_Git.m_CurrentDir;
1177 if (gitPath.HasSubmodules())
1179 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1181 CString sCmd;
1182 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1183 RunTortoiseGitProc(sCmd);
1184 }));
1186 if (hasBranch)
1187 postCmdList.push_back(PostCmd(IDI_MERGE, IDS_MENUMERGE, [&]{ Merge(&currentBranch); }));
1190 CString newBranch;
1191 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1192 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
1194 else
1196 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, bMerge); }));
1197 if (!bMerge)
1198 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_SWITCH_WITH_MERGE, [&]{ PerformSwitch(ref, bForce, sNewBranch, bBranchOverride, bTrack, true); }));
1202 INT_PTR ret = progress.DoModal();
1204 return ret == IDOK;
1207 class CIgnoreFile : public CStdioFile
1209 public:
1210 STRING_VECTOR m_Items;
1211 CString m_eol;
1213 virtual BOOL ReadString(CString& rString)
1215 if (GetPosition() == 0)
1217 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1218 char buf[3] = { 0, 0, 0 };
1219 Read(buf, 3);
1220 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1222 SeekToBegin();
1226 CStringA strA;
1227 char lastChar = '\0';
1228 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1230 if (c == '\r')
1231 continue;
1232 if (c == '\n')
1234 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1235 break;
1237 strA.AppendChar(c);
1239 if (strA.IsEmpty())
1240 return FALSE;
1242 rString = CUnicodeUtils::GetUnicode(strA);
1243 return TRUE;
1246 void ResetState()
1248 m_Items.clear();
1249 m_eol = _T("");
1253 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1255 file.ResetState();
1256 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1258 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1259 return false;
1262 if (file.GetLength() > 0)
1264 CString fileText;
1265 while (file.ReadString(fileText))
1266 file.m_Items.push_back(fileText);
1267 file.Seek(file.GetLength() - 1, 0);
1268 char lastchar[1] = { 0 };
1269 file.Read(lastchar, 1);
1270 file.SeekToEnd();
1271 if (lastchar[0] != '\n')
1273 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1274 file.Write(eol, eol.GetLength());
1277 else
1278 file.SeekToEnd();
1280 return true;
1283 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1285 CIgnoreDlg ignoreDlg;
1286 if (ignoreDlg.DoModal() == IDOK)
1288 CString ignorefile;
1289 ignorefile = g_Git.m_CurrentDir + _T("\\");
1291 switch (ignoreDlg.m_IgnoreFile)
1293 case 0:
1294 ignorefile += _T(".gitignore");
1295 break;
1296 case 2:
1297 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1298 ignorefile += _T("info/exclude");
1299 break;
1302 CIgnoreFile file;
1305 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1306 return false;
1308 for (int i = 0; i < path.GetCount(); ++i)
1310 if (ignoreDlg.m_IgnoreFile == 1)
1312 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1313 if (!OpenIgnoreFile(file, ignorefile))
1314 return false;
1317 CString ignorePattern;
1318 if (ignoreDlg.m_IgnoreType == 0)
1320 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1321 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1323 ignorePattern += _T("/");
1325 if (IsMask)
1327 ignorePattern += _T("*") + path[i].GetFileExtension();
1329 else
1331 ignorePattern += path[i].GetFileOrDirectoryName();
1334 // escape [ and ] so that files get ignored correctly
1335 ignorePattern.Replace(_T("["), _T("\\["));
1336 ignorePattern.Replace(_T("]"), _T("\\]"));
1338 bool found = false;
1339 for (size_t j = 0; j < file.m_Items.size(); ++j)
1341 if (file.m_Items[j] == ignorePattern)
1343 found = true;
1344 break;
1347 if (!found)
1349 file.m_Items.push_back(ignorePattern);
1350 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1351 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1352 file.Write(ignorePatternA, ignorePatternA.GetLength());
1355 if (ignoreDlg.m_IgnoreFile == 1)
1356 file.Close();
1359 if (ignoreDlg.m_IgnoreFile != 1)
1360 file.Close();
1362 catch(...)
1364 file.Abort();
1365 return false;
1368 return true;
1370 return false;
1373 static bool Reset(const CString& resetTo, int resetType)
1375 CString cmd;
1376 CString type;
1377 switch (resetType)
1379 case 0:
1380 type = _T("--soft");
1381 break;
1382 case 1:
1383 type = _T("--mixed");
1384 break;
1385 case 2:
1386 type = _T("--hard");
1387 break;
1388 default:
1389 resetType = 1;
1390 type = _T("--mixed");
1391 break;
1393 cmd.Format(_T("git.exe reset %s %s --"), type, resetTo);
1395 CProgressDlg progress;
1396 progress.m_GitCmd = cmd;
1398 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
1400 if (status)
1402 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ Reset(resetTo, resetType); }));
1403 return;
1406 CTGitPath gitPath = g_Git.m_CurrentDir;
1407 if (gitPath.HasSubmodules() && resetType == 2)
1409 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, [&]
1411 CString sCmd;
1412 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1413 CAppUtils::RunTortoiseGitProc(sCmd);
1414 }));
1418 INT_PTR ret;
1419 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1421 CGitProgressDlg gitdlg;
1422 ResetProgressCommand resetProgressCommand;
1423 gitdlg.SetCommand(&resetProgressCommand);
1424 resetProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
1425 resetProgressCommand.SetRevision(resetTo);
1426 resetProgressCommand.SetResetType(resetType);
1427 ret = gitdlg.DoModal();
1429 else
1430 ret = progress.DoModal();
1432 return ret == IDOK;
1435 bool CAppUtils::GitReset(CString *CommitHash,int type)
1437 CResetDlg dlg;
1438 dlg.m_ResetType=type;
1439 dlg.m_ResetToVersion=*CommitHash;
1440 dlg.m_initialRefName = *CommitHash;
1441 if (dlg.DoModal() == IDOK)
1442 return Reset(dlg.m_ResetToVersion, dlg.m_ResetType);
1444 return false;
1447 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1449 if(mode == FALSE)
1451 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1452 return;
1454 if(base)
1456 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1457 return;
1459 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1460 return;
1463 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1465 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1466 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1467 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1469 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1471 CString file;
1472 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1474 return file;
1477 bool ParseHashesFromLsFile(BYTE_VECTOR &out, CString &hash1, CString &hash2, CString &hash3)
1479 unsigned int pos = 0;
1480 CString one;
1481 CString part;
1483 while (pos >= 0 && pos < out.size())
1485 one.Empty();
1487 g_Git.StringAppend(&one, &out[pos], CP_UTF8);
1488 int tabstart = 0;
1489 one.Tokenize(_T("\t"), tabstart);
1491 tabstart = 0;
1492 part = one.Tokenize(_T(" "), tabstart); //Tag
1493 part = one.Tokenize(_T(" "), tabstart); //Mode
1494 part = one.Tokenize(_T(" "), tabstart); //Hash
1495 CString hash = part;
1496 part = one.Tokenize(_T("\t"), tabstart); //Stage
1497 int stage = _ttol(part);
1498 if (stage == 1)
1499 hash1 = hash;
1500 else if (stage == 2)
1501 hash2 = hash;
1502 else if (stage == 3)
1504 hash3 = hash;
1505 return true;
1508 pos = out.findNextString(pos);
1511 return false;
1514 bool CAppUtils::ConflictEdit(CTGitPath& path, bool /*bAlternativeTool = false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1516 bool bRet = false;
1518 CTGitPath merge=path;
1519 CTGitPath directory = merge.GetDirectory();
1521 // we have the conflicted file (%merged)
1522 // now look for the other required files
1523 //GitStatus stat;
1524 //stat.GetStatus(merge);
1525 //if (stat.status == NULL)
1526 // return false;
1528 BYTE_VECTOR vector;
1530 CString cmd;
1531 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1533 if (g_Git.Run(cmd, &vector))
1535 return FALSE;
1538 if (merge.IsDirectory())
1540 CString baseHash, localHash, remoteHash;
1541 if (!ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash))
1542 return FALSE;
1544 CString msg;
1545 msg.Format(_T("BASE: %s\nLOCAL: %s\nREMOTE: %s"), baseHash, localHash, remoteHash);
1546 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK);
1547 return TRUE;
1550 CTGitPathList list;
1551 if (list.ParserFromLsFile(vector))
1553 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1554 return FALSE;
1557 if (list.IsEmpty())
1558 return FALSE;
1560 CTGitPath theirs;
1561 CTGitPath mine;
1562 CTGitPath base;
1564 if (revertTheirMy)
1566 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1567 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1569 else
1571 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1572 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1574 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1576 CString format;
1578 //format=_T("git.exe cat-file blob \":%d:%s\"");
1579 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1580 CFile tempfile;
1581 //create a empty file, incase stage is not three
1582 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1583 tempfile.Close();
1584 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1585 tempfile.Close();
1586 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1587 tempfile.Close();
1589 bool b_base=false, b_local=false, b_remote=false;
1591 for (int i = 0; i< list.GetCount(); ++i)
1593 CString cmd;
1594 CString outfile;
1595 cmd.Empty();
1596 outfile.Empty();
1598 if( list[i].m_Stage == 1)
1600 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1601 b_base = true;
1602 outfile = base.GetWinPathString();
1605 if( list[i].m_Stage == 2 )
1607 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1608 b_local = true;
1609 outfile = mine.GetWinPathString();
1612 if( list[i].m_Stage == 3 )
1614 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1615 b_remote = true;
1616 outfile = theirs.GetWinPathString();
1618 CString output, err;
1619 if(!outfile.IsEmpty())
1620 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1622 CString file;
1623 int start =0 ;
1624 file = output.Tokenize(_T("\t"), start);
1625 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1627 else
1629 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1633 if(b_local && b_remote )
1635 merge.SetFromWin(g_Git.CombinePath(merge));
1636 if( revertTheirMy )
1637 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1638 else
1639 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1642 else
1644 ::DeleteFile(mine.GetWinPathString());
1645 ::DeleteFile(theirs.GetWinPathString());
1646 ::DeleteFile(base.GetWinPathString());
1648 CDeleteConflictDlg dlg;
1649 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1650 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1651 CGitHash localHash, remoteHash;
1652 if (!g_Git.GetHash(localHash, _T("HEAD")))
1653 dlg.m_LocalHash = localHash.ToString();
1654 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1655 dlg.m_RemoteHash = remoteHash.ToString();
1656 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1657 dlg.m_RemoteHash = remoteHash.ToString();
1658 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1659 dlg.m_RemoteHash = remoteHash.ToString();
1660 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1661 dlg.m_RemoteHash = remoteHash.ToString();
1662 dlg.m_bShowModifiedButton=b_base;
1663 dlg.m_File=merge.GetGitPathString();
1664 if(dlg.DoModal() == IDOK)
1666 CString cmd,out;
1667 if(dlg.m_bIsDelete)
1669 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1671 else
1672 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1674 if (g_Git.Run(cmd, &out, CP_UTF8))
1676 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1677 return FALSE;
1679 return TRUE;
1681 else
1682 return FALSE;
1685 #if 0
1686 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1687 base, theirs, mine, merge);
1688 #endif
1689 #if 0
1690 if (stat.status->text_status == svn_wc_status_conflicted)
1692 // we have a text conflict, use our merge tool to resolve the conflict
1694 CTSVNPath theirs(directory);
1695 CTSVNPath mine(directory);
1696 CTSVNPath base(directory);
1697 bool bConflictData = false;
1699 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1701 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1702 bConflictData = true;
1704 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1706 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1707 bConflictData = true;
1709 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1711 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1712 bConflictData = true;
1714 else
1716 mine = merge;
1718 if (bConflictData)
1719 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1720 base, theirs, mine, merge);
1723 if (stat.status->prop_status == svn_wc_status_conflicted)
1725 // we have a property conflict
1726 CTSVNPath prej(directory);
1727 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1729 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1730 // there's a problem: the prej file contains a _description_ of the conflict, and
1731 // that description string might be translated. That means we have no way of parsing
1732 // the file to find out the conflicting values.
1733 // The only thing we can do: show a dialog with the conflict description, then
1734 // let the user either accept the existing property or open the property edit dialog
1735 // to manually change the properties and values. And a button to mark the conflict as
1736 // resolved.
1737 CEditPropConflictDlg dlg;
1738 dlg.SetPrejFile(prej);
1739 dlg.SetConflictedItem(merge);
1740 bRet = (dlg.DoModal() != IDCANCEL);
1744 if (stat.status->tree_conflict)
1746 // we have a tree conflict
1747 SVNInfo info;
1748 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1749 if (pInfoData)
1751 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1753 CTSVNPath theirs(directory);
1754 CTSVNPath mine(directory);
1755 CTSVNPath base(directory);
1756 bool bConflictData = false;
1758 if (pInfoData->treeconflict_theirfile)
1760 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1761 bConflictData = true;
1763 if (pInfoData->treeconflict_basefile)
1765 base.AppendPathString(pInfoData->treeconflict_basefile);
1766 bConflictData = true;
1768 if (pInfoData->treeconflict_myfile)
1770 mine.AppendPathString(pInfoData->treeconflict_myfile);
1771 bConflictData = true;
1773 else
1775 mine = merge;
1777 if (bConflictData)
1778 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1779 base, theirs, mine, merge);
1781 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1783 CString sConflictAction;
1784 CString sConflictReason;
1785 CString sResolveTheirs;
1786 CString sResolveMine;
1787 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1788 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1790 if (pInfoData->treeconflict_nodekind == svn_node_file)
1792 switch (pInfoData->treeconflict_operation)
1794 case svn_wc_operation_update:
1795 switch (pInfoData->treeconflict_action)
1797 case svn_wc_conflict_action_edit:
1798 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1799 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1800 break;
1801 case svn_wc_conflict_action_add:
1802 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1803 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1804 break;
1805 case svn_wc_conflict_action_delete:
1806 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1807 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1808 break;
1810 break;
1811 case svn_wc_operation_switch:
1812 switch (pInfoData->treeconflict_action)
1814 case svn_wc_conflict_action_edit:
1815 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1816 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1817 break;
1818 case svn_wc_conflict_action_add:
1819 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1820 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1821 break;
1822 case svn_wc_conflict_action_delete:
1823 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1824 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1825 break;
1827 break;
1828 case svn_wc_operation_merge:
1829 switch (pInfoData->treeconflict_action)
1831 case svn_wc_conflict_action_edit:
1832 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1833 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1834 break;
1835 case svn_wc_conflict_action_add:
1836 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1837 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1838 break;
1839 case svn_wc_conflict_action_delete:
1840 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1841 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1842 break;
1844 break;
1847 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1849 switch (pInfoData->treeconflict_operation)
1851 case svn_wc_operation_update:
1852 switch (pInfoData->treeconflict_action)
1854 case svn_wc_conflict_action_edit:
1855 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1856 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1857 break;
1858 case svn_wc_conflict_action_add:
1859 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1860 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1861 break;
1862 case svn_wc_conflict_action_delete:
1863 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1864 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1865 break;
1867 break;
1868 case svn_wc_operation_switch:
1869 switch (pInfoData->treeconflict_action)
1871 case svn_wc_conflict_action_edit:
1872 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1873 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1874 break;
1875 case svn_wc_conflict_action_add:
1876 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1877 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1878 break;
1879 case svn_wc_conflict_action_delete:
1880 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1881 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1882 break;
1884 break;
1885 case svn_wc_operation_merge:
1886 switch (pInfoData->treeconflict_action)
1888 case svn_wc_conflict_action_edit:
1889 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1890 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1891 break;
1892 case svn_wc_conflict_action_add:
1893 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1894 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1895 break;
1896 case svn_wc_conflict_action_delete:
1897 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1898 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1899 break;
1901 break;
1905 UINT uReasonID = 0;
1906 switch (pInfoData->treeconflict_reason)
1908 case svn_wc_conflict_reason_edited:
1909 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1910 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1911 break;
1912 case svn_wc_conflict_reason_obstructed:
1913 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1914 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1915 break;
1916 case svn_wc_conflict_reason_deleted:
1917 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1918 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1919 break;
1920 case svn_wc_conflict_reason_added:
1921 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1922 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1923 break;
1924 case svn_wc_conflict_reason_missing:
1925 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1926 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1927 break;
1928 case svn_wc_conflict_reason_unversioned:
1929 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1930 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1931 break;
1933 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1935 CTreeConflictEditorDlg dlg;
1936 dlg.SetConflictInfoText(sConflictReason);
1937 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1938 dlg.SetPath(treeConflictPath);
1939 INT_PTR dlgRet = dlg.DoModal();
1940 bRet = (dlgRet != IDCANCEL);
1944 #endif
1945 return bRet;
1948 bool CAppUtils::IsSSHPutty()
1950 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1951 sshclient=sshclient.MakeLower();
1952 if(sshclient.Find(_T("plink.exe"),0)>=0)
1954 return true;
1956 return false;
1959 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
1961 if (!OpenClipboard(NULL))
1962 return CString();
1964 CString sClipboardText;
1965 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1966 if (hglb)
1968 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1969 sClipboardText = CString(lpstr);
1970 GlobalUnlock(hglb);
1972 hglb = GetClipboardData(CF_UNICODETEXT);
1973 if (hglb)
1975 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1976 sClipboardText = lpstr;
1977 GlobalUnlock(hglb);
1979 CloseClipboard();
1981 if(!sClipboardText.IsEmpty())
1983 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1984 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1986 if(sClipboardText.Find( _T("http://")) == 0)
1987 return sClipboardText;
1989 if(sClipboardText.Find( _T("https://")) == 0)
1990 return sClipboardText;
1992 if(sClipboardText.Find( _T("git://")) == 0)
1993 return sClipboardText;
1995 if(sClipboardText.Find( _T("ssh://")) == 0)
1996 return sClipboardText;
1998 if(sClipboardText.GetLength()>=2)
1999 if( sClipboardText[1] == _T(':') )
2000 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2001 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2002 return sClipboardText;
2004 // trim prefixes like "git clone "
2005 if (!skipGitPrefix.IsEmpty() && sClipboardText.Find(skipGitPrefix) == 0)
2007 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2008 int spacePos = -1;
2009 while (paramsCount >= 0)
2011 --paramsCount;
2012 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2013 if (spacePos == -1)
2014 break;
2016 if (spacePos > 0 && paramsCount < 0)
2017 sClipboardText = sClipboardText.Left(spacePos);
2018 return sClipboardText;
2022 return CString(_T(""));
2025 CString CAppUtils::ChooseRepository(CString *path)
2027 CBrowseFolder browseFolder;
2028 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2030 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2031 CString strCloneDirectory;
2032 if(path)
2033 strCloneDirectory=*path;
2034 else
2036 strCloneDirectory = regLastResopitory;
2039 CString title;
2040 title.LoadString(IDS_CHOOSE_REPOSITORY);
2042 browseFolder.SetInfo(title);
2044 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2046 regLastResopitory = strCloneDirectory;
2047 return strCloneDirectory;
2049 else
2051 return CString();
2055 bool CAppUtils::SendPatchMail(CTGitPathList& list)
2057 CSendMailDlg dlg;
2059 dlg.m_PathList = list;
2061 if(dlg.DoModal()==IDOK)
2063 if (dlg.m_PathList.IsEmpty())
2064 return FALSE;
2066 CGitProgressDlg progDlg;
2068 theApp.m_pMainWnd = &progDlg;
2069 SendMailProgressCommand sendMailProgressCommand;
2070 progDlg.SetCommand(&sendMailProgressCommand);
2072 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2073 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2075 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2076 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2078 progDlg.DoModal();
2080 return true;
2082 return false;
2085 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput)
2087 CTGitPathList list;
2088 CString log=formatpatchoutput;
2089 int start=log.Find(cmd);
2090 if(start >=0)
2091 CString one=log.Tokenize(_T("\n"),start);
2092 else
2093 start = 0;
2095 while(start>=0)
2097 CString one=log.Tokenize(_T("\n"),start);
2098 one=one.Trim();
2099 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2100 continue;
2101 one.Replace(_T('/'),_T('\\'));
2102 CTGitPath path;
2103 path.SetFromWin(one);
2104 list.AddPath(path);
2106 if (!list.IsEmpty())
2108 return SendPatchMail(list);
2110 else
2112 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2113 return true;
2118 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2120 CString output;
2121 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2122 if(output.IsEmpty())
2123 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2124 else
2126 return CUnicodeUtils::GetCPCode(output);
2129 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2131 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2132 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2134 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2136 if (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE)
2137 message.TrimRight(L" \r\n");
2139 int len = message.GetLength();
2140 int start = 0;
2141 while (start >= 0 && start < len)
2143 int oldStart = start;
2144 start = message.Find(L"\n", oldStart);
2145 CString line = message.Mid(oldStart);
2146 if (start != -1)
2148 line = line.Left(start - oldStart);
2149 ++start; // move forward so we don't find the same char again
2151 if (stripComments && (line.GetLength() >= 1 && line.GetAt(0) == '#') || (start < 0 && line.IsEmpty()))
2152 continue;
2153 line.TrimRight(L" \r");
2154 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2155 file.Write(lineA.GetBuffer(), lineA.GetLength());
2157 file.Close();
2158 return 0;
2161 bool CAppUtils::Pull(bool showPush)
2163 CPullFetchDlg dlg;
2164 dlg.m_IsPull = TRUE;
2165 if (dlg.DoModal() == IDOK)
2167 CString url = dlg.m_RemoteURL;
2169 if (dlg.m_bAutoLoad)
2171 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2174 CString cmd;
2175 CGitHash hashOld;
2176 if (g_Git.GetHash(hashOld, _T("HEAD")))
2178 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
2179 return false;
2182 CString cmdRebase;
2183 CString noff;
2184 CString ffonly;
2185 CString squash;
2186 CString nocommit;
2187 CString depth;
2188 CString notags;
2189 CString prune;
2191 if (dlg.m_bRebase)
2192 cmdRebase = "--rebase ";
2194 if (!dlg.m_bFetchTags)
2195 notags = _T("--no-tags");
2197 if (dlg.m_bNoFF)
2198 noff=_T("--no-ff");
2200 if (dlg.m_bFFonly)
2201 ffonly = _T("--ff-only");
2203 if (dlg.m_bSquash)
2204 squash = _T("--squash");
2206 if (dlg.m_bNoCommit)
2207 nocommit = _T("--no-commit");
2209 if (dlg.m_bDepth)
2210 depth.Format(_T("--depth %d "), dlg.m_nDepth);
2212 int ver = CAppUtils::GetMsysgitVersion();
2214 if (dlg.m_bPrune == TRUE)
2215 prune = _T("--prune ");
2216 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2217 prune = _T("--no-prune ");
2219 if(ver >= 0x01070203) //above 1.7.0.2
2220 cmdRebase += _T("--progress ");
2222 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);
2223 CProgressDlg progress;
2224 progress.m_GitCmd = cmd;
2226 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2228 if (status)
2230 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, [&]{ Pull(); }));
2231 return;
2234 CGitHash hashNew;
2235 if (g_Git.GetHash(hashNew, _T("HEAD")))
2236 MessageBox(nullptr, g_Git.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR);
2237 else
2239 postCmdList.push_back(PostCmd(IDI_DIFF, IDS_PROC_PULL_DIFFS, [&]
2241 CFileDiffDlg dlg;
2242 dlg.SetDiff(NULL, hashNew.ToString(), hashOld.ToString());
2243 dlg.DoModal();
2244 }));
2245 postCmdList.push_back(PostCmd(IDI_LOG, IDS_PROC_PULL_LOG, [&]
2247 CLogDlg dlg;
2248 dlg.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld.ToString() + _T("..") + hashNew.ToString(), 0);
2249 dlg.DoModal();
2250 }));
2253 if (showPush)
2254 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(_T("")); }));
2256 CTGitPath gitPath = g_Git.m_CurrentDir;
2257 if (gitPath.HasSubmodules())
2259 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
2261 CString sCmd;
2262 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2263 CAppUtils::RunTortoiseGitProc(sCmd);
2264 }));
2268 INT_PTR ret = progress.DoModal();
2270 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)
2272 CChangedDlg dlg;
2273 dlg.m_pathList.AddPath(CTGitPath());
2274 dlg.DoModal();
2276 return true;
2279 return ret == IDOK;
2282 return false;
2285 static bool RebaseAfterFetch()
2287 while (true)
2289 CRebaseDlg dlg;
2290 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2291 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2292 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2293 INT_PTR response = dlg.DoModal();
2294 if (response == IDOK)
2296 return true;
2298 else if (response == IDC_REBASE_POST_BUTTON)
2300 CString cmd = _T("/command:log");
2301 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2302 CAppUtils::RunTortoiseGitProc(cmd);
2303 return true;
2305 else if (response == IDC_REBASE_POST_BUTTON + 1)
2307 CString cmd, out, err;
2308 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2309 g_Git.m_CurrentDir,
2310 g_Git.FixBranchName(dlg.m_Upstream),
2311 g_Git.FixBranchName(dlg.m_Branch));
2312 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2314 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2315 return false;
2317 CAppUtils::SendPatchMail(cmd, out);
2318 return true;
2320 else if (response == IDC_REBASE_POST_BUTTON + 2)
2321 continue;
2322 else if (response == IDCANCEL)
2323 return false;
2324 return false;
2328 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)
2330 if (loadPuttyAgent)
2332 if (fetchAllRemotes)
2334 STRING_VECTOR list;
2335 g_Git.GetRemoteList(list);
2337 STRING_VECTOR::const_iterator it = list.begin();
2338 while (it != list.end())
2340 CString remote(*it);
2341 CAppUtils::LaunchPAgent(NULL, &remote);
2342 ++it;
2345 else
2346 CAppUtils::LaunchPAgent(NULL, &url);
2349 CString cmd, arg;
2350 int ver = CAppUtils::GetMsysgitVersion();
2352 if (bDepth)
2353 arg.AppendFormat(_T(" --depth %d"), nDepth);
2355 if (prune == TRUE)
2356 arg += _T(" --prune");
2357 else if (prune == FALSE && ver >= 0x01080500)
2358 arg += _T(" --no-prune");
2360 if (fetchTags == 1)
2361 arg += _T(" --tags");
2362 else if (fetchTags == 0)
2363 arg += _T(" --no-tags");
2365 if (fetchAllRemotes)
2366 cmd.Format(_T("git.exe fetch --all -v%s"), arg);
2367 else
2368 cmd.Format(_T("git.exe fetch -v%s \"%s\" %s"), arg, url, remoteBranch);
2370 CProgressDlg progress;
2371 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2373 if (status)
2375 postCmdList.push_back(PostCmd(IDI_REFRESH, IDS_MSGBOX_RETRY, [&]{ DoFetch(url, fetchAllRemotes, loadPuttyAgent, prune, bDepth, nDepth, fetchTags, remoteBranch, runRebase); }));
2376 return;
2379 postCmdList.push_back(PostCmd(IDI_LOG, IDS_MENULOG, []
2381 CString cmd = _T("/command:log");
2382 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2383 CAppUtils::RunTortoiseGitProc(cmd);
2384 }));
2386 postCmdList.push_back(PostCmd(IDS_PROC_RESET, []
2388 CString pullRemote, pullBranch;
2389 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2390 CString defaultUpstream;
2391 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2392 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2393 CAppUtils::GitReset(&defaultUpstream, 2);
2394 }));
2396 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, []{ CAppUtils::Fetch(); }));
2398 if (!runRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2399 postCmdList.push_back(PostCmd(IDI_REBASE, IDS_MENUREBASE, []{ RebaseAfterFetch(); }));
2402 progress.m_GitCmd = cmd;
2403 INT_PTR userResponse;
2405 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2407 CGitProgressDlg gitdlg;
2408 FetchProgressCommand fetchProgressCommand;
2409 if (!fetchAllRemotes)
2410 fetchProgressCommand.SetUrl(url);
2411 gitdlg.SetCommand(&fetchProgressCommand);
2412 fetchProgressCommand.m_PostCmdCallback = progress.m_PostCmdCallback;
2413 fetchProgressCommand.SetAutoTag(fetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : fetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2414 if (!fetchAllRemotes)
2415 fetchProgressCommand.SetRefSpec(remoteBranch);
2416 userResponse = gitdlg.DoModal();
2417 return userResponse == IDOK;
2420 userResponse = progress.DoModal();
2421 if (!progress.m_GitStatus)
2423 if (runRebase)
2424 return RebaseAfterFetch();
2427 return userResponse == IDOK;
2430 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool allRemotes)
2432 CPullFetchDlg dlg;
2433 dlg.m_PreSelectRemote = remoteName;
2434 dlg.m_bAllowRebase = allowRebase;
2435 dlg.m_IsPull=FALSE;
2436 dlg.m_bAllRemotes = allRemotes;
2438 if(dlg.DoModal()==IDOK)
2439 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);
2441 return false;
2444 bool CAppUtils::Push(CString selectLocalBranch)
2446 CPushDlg dlg;
2447 dlg.m_BranchSourceName = selectLocalBranch;
2449 if (dlg.DoModal() == IDOK)
2451 CString error;
2452 DWORD exitcode = 0xFFFFFFFF;
2453 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2455 if (exitcode)
2457 CString temp;
2458 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2459 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2460 return false;
2464 CString arg;
2466 if(dlg.m_bPack)
2467 arg += _T("--thin ");
2468 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2469 arg += _T("--tags ");
2470 if(dlg.m_bForce)
2471 arg += _T("--force ");
2472 if (dlg.m_bSetUpstream)
2473 arg += _T("--set-upstream ");
2474 if (dlg.m_RecurseSubmodules == 1)
2475 arg += _T("--recurse-submodules=check ");
2476 if (dlg.m_RecurseSubmodules == 2)
2477 arg += _T("--recurse-submodules=on-demand ");
2479 int ver = CAppUtils::GetMsysgitVersion();
2481 if(ver >= 0x01070203) //above 1.7.0.2
2482 arg += _T("--progress ");
2484 CProgressDlg progress;
2486 STRING_VECTOR remotesList;
2487 if (dlg.m_bPushAllRemotes)
2488 g_Git.GetRemoteList(remotesList);
2489 else
2490 remotesList.push_back(dlg.m_URL);
2492 for (unsigned int i = 0; i < remotesList.size(); ++i)
2494 if (dlg.m_bAutoLoad)
2495 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2497 CString cmd;
2498 if (dlg.m_bPushAllBranches)
2500 cmd.Format(_T("git.exe push --all %s \"%s\""),
2501 arg,
2502 remotesList[i]);
2504 if (dlg.m_bTags)
2506 progress.m_GitCmdList.push_back(cmd);
2507 cmd.Format(_T("git.exe push --tags %s \"%s\""), arg, remotesList[i]);
2510 else
2512 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2513 arg,
2514 remotesList[i],
2515 dlg.m_BranchSourceName);
2516 if (!dlg.m_BranchRemoteName.IsEmpty())
2518 cmd += _T(":") + dlg.m_BranchRemoteName;
2521 progress.m_GitCmdList.push_back(cmd);
2524 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2526 // need to execute hooks as those might be needed by post action commands
2527 DWORD exitcode = 0xFFFFFFFF;
2528 CString error;
2529 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2531 if (exitcode)
2533 CString temp;
2534 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2535 MessageBox(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2539 if (status)
2541 bool rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2542 if (rejected)
2544 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUPULL, []{ Pull(true); }));
2545 postCmdList.push_back(PostCmd(IDI_PULL, IDS_MENUFETCH, [&]{ Fetch(dlg.m_bPushAllRemotes ? _T("") : dlg.m_URL, true, !!dlg.m_bPushAllRemotes); }));
2547 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2548 return;
2551 postCmdList.push_back(PostCmd(IDS_PROC_REQUESTPULL, [&]{ RequestPull(dlg.m_BranchRemoteName); }));
2552 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, [&]{ Push(selectLocalBranch); }));
2553 postCmdList.push_back(PostCmd(IDI_SWITCH, IDS_MENUSWITCH, [&]{ Switch(); }));
2556 INT_PTR ret = progress.DoModal();
2557 return ret == IDOK;
2559 return FALSE;
2562 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2564 CRequestPullDlg dlg;
2565 dlg.m_RepositoryURL = repositoryUrl;
2566 dlg.m_EndRevision = endrevision;
2567 if (dlg.DoModal()==IDOK)
2569 CString cmd;
2570 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2572 CSysProgressDlg sysProgressDlg;
2573 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2574 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2575 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2576 sysProgressDlg.SetShowProgressBar(false);
2577 sysProgressDlg.ShowModeless((HWND)NULL, true);
2579 CString tempFileName = GetTempFile();
2580 CString err;
2581 DeleteFile(tempFileName);
2582 CreateDirectory(tempFileName, NULL);
2583 tempFileName += _T("\\pullrequest.txt");
2584 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2586 CString msg;
2587 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2588 CMessageBox::Show(NULL, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK);
2589 return false;
2592 if (sysProgressDlg.HasUserCancelled())
2594 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2595 ::DeleteFile(tempFileName);
2596 return false;
2599 sysProgressDlg.Stop();
2601 if (dlg.m_bSendMail)
2603 CSendMailDlg dlg;
2604 dlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2605 dlg.m_bCustomSubject = true;
2607 if (dlg.DoModal() == IDOK)
2609 if (dlg.m_PathList.IsEmpty())
2610 return FALSE;
2612 CGitProgressDlg progDlg;
2614 theApp.m_pMainWnd = &progDlg;
2615 SendMailProgressCommand sendMailProgressCommand;
2616 progDlg.SetCommand(&sendMailProgressCommand);
2618 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2619 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2621 CSendMailCombineable sendMailCombineable(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2622 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2624 progDlg.DoModal();
2626 return true;
2628 return false;
2631 CAppUtils::LaunchAlternativeEditor(tempFileName);
2633 return true;
2636 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2638 CString strDir(szPath);
2639 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2641 strDir.AppendChar(_T('\\'));
2643 std::vector<CString> vPath;
2644 CString strTemp;
2645 bool bSuccess = false;
2647 for (int i=0;i<strDir.GetLength();++i)
2649 if (strDir.GetAt(i) != _T('\\'))
2651 strTemp.AppendChar(strDir.GetAt(i));
2653 else
2655 vPath.push_back(strTemp);
2656 strTemp.AppendChar(_T('\\'));
2660 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2662 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2665 return bSuccess;
2668 void CAppUtils::RemoveTrailSlash(CString &path)
2670 if(path.IsEmpty())
2671 return ;
2673 // For URL, do not trim the slash just after the host name component.
2674 int index = path.Find(_T("://"));
2675 if (index >= 0)
2677 index += 4;
2678 index = path.Find(_T('/'), index);
2679 if (index == path.GetLength() - 1)
2680 return;
2683 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2685 path=path.Left(path.GetLength()-1);
2686 if(path.IsEmpty())
2687 return;
2691 bool CAppUtils::CheckUserData()
2693 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2695 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2697 CTGitPath path(g_Git.m_CurrentDir);
2698 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2699 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2700 dlg.SetTreeWidth(220);
2701 dlg.m_DefaultPage = _T("gitconfig");
2703 dlg.DoModal();
2704 dlg.HandleRestart();
2707 else
2708 return false;
2711 return true;
2714 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2715 CTGitPathList &pathList,
2716 CTGitPathList &selectedList,
2717 bool bSelectFilesForCommit)
2719 bool bFailed = true;
2721 if (!CheckUserData())
2722 return false;
2724 while (bFailed)
2726 bFailed = false;
2727 CCommitDlg dlg;
2728 dlg.m_sBugID = bugid;
2730 dlg.m_bWholeProject = bWholeProject;
2732 dlg.m_sLogMessage = sLogMsg;
2733 dlg.m_pathList = pathList;
2734 dlg.m_checkedPathList = selectedList;
2735 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2736 if (dlg.DoModal() == IDOK)
2738 if (dlg.m_pathList.IsEmpty())
2739 return false;
2740 // if the user hasn't changed the list of selected items
2741 // we don't use that list. Because if we would use the list
2742 // of pre-checked items, the dialog would show different
2743 // checked items on the next startup: it would only try
2744 // to check the parent folder (which might not even show)
2745 // instead, we simply use an empty list and let the
2746 // default checking do its job.
2747 if (!dlg.m_pathList.IsEqual(pathList))
2748 selectedList = dlg.m_pathList;
2749 pathList = dlg.m_updatedPathList;
2750 sLogMsg = dlg.m_sLogMessage;
2751 bSelectFilesForCommit = true;
2753 switch (dlg.m_PostCmd)
2755 case GIT_POSTCOMMIT_CMD_DCOMMIT:
2756 CAppUtils::SVNDCommit();
2757 break;
2758 case GIT_POSTCOMMIT_CMD_PUSH:
2759 CAppUtils::Push();
2760 break;
2761 case GIT_POSTCOMMIT_CMD_CREATETAG:
2762 CAppUtils::CreateBranchTag(TRUE);
2763 break;
2764 case GIT_POSTCOMMIT_CMD_PULL:
2765 CAppUtils::Pull(true);
2766 break;
2767 default:
2768 break;
2771 // CGitProgressDlg progDlg;
2772 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2773 // if (parser.HasVal(_T("closeonend")))
2774 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2775 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2776 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2777 // progDlg.SetPathList(dlg.m_pathList);
2778 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2779 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2780 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2781 // progDlg.SetItemCount(dlg.m_itemsCount);
2782 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2783 // progDlg.DoModal();
2784 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2785 // err = (DWORD)progDlg.DidErrorsOccur();
2786 // bFailed = progDlg.DidErrorsOccur();
2787 // bRet = progDlg.DidErrorsOccur();
2788 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2789 // if (DWORD(bFailRepeat)==0)
2790 // bFailed = false; // do not repeat if the user chose not to in the settings.
2793 return true;
2797 BOOL CAppUtils::SVNDCommit()
2799 CSVNDCommitDlg dcommitdlg;
2800 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2801 if (gitSetting == _T("")) {
2802 if (dcommitdlg.DoModal() != IDOK)
2804 return false;
2806 else
2808 if (dcommitdlg.m_remember)
2810 if (dcommitdlg.m_rmdir)
2812 gitSetting = _T("true");
2814 else
2816 gitSetting = _T("false");
2818 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2820 CString msg;
2821 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2822 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2828 BOOL IsStash = false;
2829 if(!g_Git.CheckCleanWorkTree())
2831 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2833 CSysProgressDlg sysProgressDlg;
2834 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2835 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2836 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2837 sysProgressDlg.SetShowProgressBar(false);
2838 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2839 sysProgressDlg.ShowModeless((HWND)NULL, true);
2841 CString cmd,out;
2842 cmd=_T("git.exe stash");
2843 if (g_Git.Run(cmd, &out, CP_UTF8))
2845 sysProgressDlg.Stop();
2846 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2847 return false;
2849 sysProgressDlg.Stop();
2851 IsStash =true;
2853 else
2855 return false;
2859 CProgressDlg progress;
2860 if (dcommitdlg.m_rmdir)
2862 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2864 else
2866 progress.m_GitCmd=_T("git.exe svn dcommit");
2868 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2870 ::DeleteFile(g_Git.m_CurrentDir + _T("\\sys$command"));
2871 if( IsStash)
2873 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2875 CSysProgressDlg sysProgressDlg;
2876 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2877 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2878 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2879 sysProgressDlg.SetShowProgressBar(false);
2880 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2881 sysProgressDlg.ShowModeless((HWND)NULL, true);
2883 CString cmd,out;
2884 cmd=_T("git.exe stash pop");
2885 if (g_Git.Run(cmd, &out, CP_UTF8))
2887 sysProgressDlg.Stop();
2888 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2889 return false;
2891 sysProgressDlg.Stop();
2893 else
2895 return false;
2898 return TRUE;
2900 return FALSE;
2903 BOOL CAppUtils::Merge(CString *commit)
2905 if (!CheckUserData())
2906 return FALSE;
2908 CMergeDlg dlg;
2909 if(commit)
2910 dlg.m_initialRefName = *commit;
2912 if(dlg.DoModal()==IDOK)
2914 CString cmd;
2915 CString args;
2917 if(dlg.m_bNoFF)
2918 args += _T(" --no-ff");
2920 if(dlg.m_bSquash)
2921 args += _T(" --squash");
2923 if(dlg.m_bNoCommit)
2924 args += _T(" --no-commit");
2926 if (dlg.m_bLog)
2928 CString fmt;
2929 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
2930 args += fmt;
2933 if (!dlg.m_MergeStrategy.IsEmpty())
2935 args += _T(" --strategy=") + dlg.m_MergeStrategy;
2936 if (!dlg.m_StrategyOption.IsEmpty())
2938 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
2939 if (!dlg.m_StrategyParam.IsEmpty())
2940 args += _T("=") + dlg.m_StrategyParam;
2944 if(!dlg.m_strLogMesage.IsEmpty())
2946 CString logmsg = dlg.m_strLogMesage;
2947 logmsg.Replace(_T("\""), _T("\\\""));
2948 args += _T(" -m \"") + logmsg + _T("\"");
2950 cmd.Format(_T("git.exe merge %s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
2952 CProgressDlg Prodlg;
2953 Prodlg.m_GitCmd = cmd;
2955 Prodlg.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
2957 if (status)
2959 CTGitPathList list;
2960 if (!g_Git.ListConflictFile(list) && !list.IsEmpty())
2962 // there are conflict files
2964 postCmdList.push_back(PostCmd(IDI_RESOLVE, IDS_PROGRS_CMD_RESOLVE, []
2966 CString sCmd;
2967 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
2968 CAppUtils::RunTortoiseGitProc(sCmd);
2969 }));
2971 return;
2974 if (dlg.m_bNoCommit)
2976 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUCOMMIT, []
2978 CString sCmd;
2979 sCmd.Format(_T("/command:commit /path:\"%s\""), g_Git.m_CurrentDir);
2980 CAppUtils::RunTortoiseGitProc(sCmd);
2981 }));
2982 return;
2985 if (dlg.m_bIsBranch && dlg.m_VersionName.Find(L"remotes/") == -1) // do not ask to remove remote branches
2987 postCmdList.push_back(PostCmd(IDI_DELETE, IDS_PROC_REMOVEBRANCH, [&]
2989 CString msg;
2990 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2991 if (CMessageBox::Show(nullptr, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2993 CString cmd, out;
2994 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2995 if (g_Git.Run(cmd, &out, CP_UTF8))
2996 MessageBox(nullptr, out, _T("TortoiseGit"), MB_OK);
2998 }));
3000 if (dlg.m_bIsBranch)
3001 postCmdList.push_back(PostCmd(IDI_PUSH, IDS_MENUPUSH, []{ Push(); }));
3003 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3004 if (hasGitSVN)
3005 postCmdList.push_back(PostCmd(IDI_COMMIT, IDS_MENUSVNDCOMMIT, []{ SVNDCommit(); }));
3008 Prodlg.DoModal();
3009 return !Prodlg.m_GitStatus;
3011 return false;
3014 BOOL CAppUtils::MergeAbort()
3016 CMergeAbortDlg dlg;
3017 if (dlg.DoModal() == IDOK)
3018 return Reset(_T("HEAD"), dlg.m_ResetType + 1);
3020 return FALSE;
3023 void CAppUtils::EditNote(GitRev *rev)
3025 if (!CheckUserData())
3026 return;
3028 CInputDlg dlg;
3029 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3030 dlg.m_sInputText = rev->m_Notes;
3031 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3032 //dlg.m_pProjectProperties = &m_ProjectProperties;
3033 dlg.m_bUseLogWidth = true;
3034 if(dlg.DoModal() == IDOK)
3036 CString cmd,output;
3037 cmd=_T("notes add -f -F \"");
3039 CString tempfile=::GetTempFile();
3040 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
3041 cmd += tempfile;
3042 cmd += _T("\" ");
3043 cmd += rev->m_CommitHash.ToString();
3047 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3049 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3052 else
3054 rev->m_Notes = dlg.m_sInputText;
3056 }catch(...)
3058 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3060 ::DeleteFile(tempfile);
3065 int CAppUtils::GetMsysgitVersion()
3067 if (g_Git.ms_LastMsysGitVersion)
3068 return g_Git.ms_LastMsysGitVersion;
3070 CString cmd;
3071 CString versiondebug;
3072 CString version;
3074 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3075 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3077 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3079 __int64 time=0;
3080 if (!g_Git.GetFileModifyTime(gitpath, &time))
3082 if((DWORD)time == regTime)
3084 g_Git.ms_LastMsysGitVersion = regVersion;
3085 return regVersion;
3089 CString err;
3090 cmd = _T("git.exe --version");
3091 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
3093 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);
3094 return -1;
3097 int start=0;
3098 int ver = 0;
3100 versiondebug = version;
3104 CString str=version.Tokenize(_T("."), start);
3105 int space = str.ReverseFind(_T(' '));
3106 str = str.Mid(space+1,start);
3107 ver = _ttol(str);
3108 ver <<=24;
3110 version = version.Mid(start);
3111 start = 0;
3113 str = version.Tokenize(_T("."), start);
3115 ver |= (_ttol(str) & 0xFF) << 16;
3117 str = version.Tokenize(_T("."), start);
3118 ver |= (_ttol(str) & 0xFF) << 8;
3120 str = version.Tokenize(_T("."), start);
3121 ver |= (_ttol(str) & 0xFF);
3123 catch(...)
3125 if (!ver)
3127 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3128 return -1;
3132 regTime = time&0xFFFFFFFF;
3133 regVersion = ver;
3134 g_Git.ms_LastMsysGitVersion = ver;
3136 return ver;
3139 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3141 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3143 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3145 if (hShell.IsValid()) {
3146 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3147 if (pfnSHGPSFW) {
3148 IPropertyStore *pps;
3149 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3150 if (SUCCEEDED(hr)) {
3151 PROPVARIANT var;
3152 var.vt = VT_BOOL;
3153 var.boolVal = VARIANT_TRUE;
3154 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3155 pps->Release();
3161 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3163 ASSERT(dialogname.GetLength() < 70);
3164 ASSERT(urlorpath.GetLength() < MAX_PATH);
3165 WCHAR pathbuf[MAX_PATH] = {0};
3167 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3169 wcscat_s(pathbuf, L" - ");
3170 wcscat_s(pathbuf, dialogname);
3171 wcscat_s(pathbuf, L" - ");
3172 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3173 SetWindowText(hWnd, pathbuf);
3176 bool CAppUtils::BisectStart(CString lastGood, CString firstBad)
3178 if (!g_Git.CheckCleanWorkTree())
3180 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3182 CSysProgressDlg sysProgressDlg;
3183 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3184 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3185 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3186 sysProgressDlg.SetShowProgressBar(false);
3187 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3188 sysProgressDlg.ShowModeless((HWND)NULL, true);
3190 CString cmd, out;
3191 cmd = _T("git.exe stash");
3192 if (g_Git.Run(cmd, &out, CP_UTF8))
3194 sysProgressDlg.Stop();
3195 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3196 return false;
3198 sysProgressDlg.Stop();
3200 else
3201 return false;
3204 CBisectStartDlg bisectStartDlg;
3206 if (!lastGood.IsEmpty())
3207 bisectStartDlg.m_sLastGood = lastGood;
3208 if (!firstBad.IsEmpty())
3209 bisectStartDlg.m_sFirstBad = firstBad;
3211 if (bisectStartDlg.DoModal() == IDOK)
3213 CProgressDlg progress;
3214 theApp.m_pMainWnd = &progress;
3215 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3216 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3217 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3219 progress.m_PostCmdCallback = [&](DWORD status, PostCmdList& postCmdList)
3221 if (status)
3222 return;
3224 CTGitPath path(g_Git.m_CurrentDir);
3225 if (path.HasSubmodules())
3227 postCmdList.push_back(PostCmd(IDI_UPDATE, IDS_PROC_SUBMODULESUPDATE, []
3229 CString sCmd;
3230 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3231 CAppUtils::RunTortoiseGitProc(sCmd);
3232 }));
3238 INT_PTR ret = progress.DoModal();
3239 return ret == IDOK;
3242 return false;
3245 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3247 CUserPassword dlg;
3248 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3249 if (username_from_url)
3250 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3252 CStringA username, password;
3253 if (dlg.DoModal() == IDOK)
3255 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3256 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3257 return git_cred_userpass_plaintext_new(out, username, password);
3259 return -1;
3262 void CAppUtils::ExploreTo(HWND hwnd, CString path)
3264 if (PathFileExists(path))
3266 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3267 if (pidl)
3269 SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3270 ILFree(pidl);
3272 return;
3274 // if filepath does not exist any more, navigate to closest matching folder
3277 int pos = path.ReverseFind(_T('\\'));
3278 if (pos <= 3)
3279 break;
3280 path = path.Left(pos);
3281 } while (!PathFileExists(path));
3282 ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW);