Fix broken build by moving implementations to cpp files
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob115ac9d54c3d78bcfa897807472edd1b96da0d5d
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(".dib")) || (ext == _T(".emf")) ||
430 (ext == _T(".cur")))
432 return
433 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
434 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
435 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
439 // Finally, pick a generic external diff tool
440 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
441 return difftool;
444 bool CAppUtils::StartExtDiff(
445 const CString& file1, const CString& file2,
446 const CString& sName1, const CString& sName2,
447 const CString& originalFile1, const CString& originalFile2,
448 const git_revnum_t& hash1, const git_revnum_t& hash2,
449 const DiffFlags& flags, int jumpToLine)
451 CString viewer;
453 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
454 if (!flags.bBlame || !(DWORD)blamediff)
456 viewer = PickDiffTool(file1, file2);
457 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
458 bool bCommentedOut = viewer.Left(1) == _T("#");
459 if (flags.bAlternativeTool)
461 // Invert external vs. internal diff tool selection.
462 if (bCommentedOut)
463 viewer.Delete(0); // uncomment
464 else
465 viewer = "";
467 else if (bCommentedOut)
468 viewer = "";
471 bool bInternal = viewer.IsEmpty();
472 if (bInternal)
474 viewer =
475 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
476 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
477 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
478 if (!g_sGroupingUUID.IsEmpty())
480 viewer += L" /groupuuid:\"";
481 viewer += g_sGroupingUUID;
482 viewer += L"\"";
484 if (flags.bBlame)
485 viewer += _T(" /blame");
487 // check if the params are set. If not, just add the files to the command line
488 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
490 viewer += _T(" \"")+file1+_T("\"");
491 viewer += _T(" \"")+file2+_T("\"");
493 if (viewer.Find(_T("%base")) >= 0)
495 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
497 if (viewer.Find(_T("%mine")) >= 0)
499 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
502 if (sName1.IsEmpty())
503 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
504 else
505 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
507 if (sName2.IsEmpty())
508 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
509 else
510 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
512 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
513 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
515 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
516 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
518 if (flags.bReadOnly && bInternal)
519 viewer += _T(" /readonly");
521 if (jumpToLine > 0)
523 CString temp;
524 temp.Format(_T(" /line:%d"), jumpToLine);
525 viewer += temp;
528 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
531 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
533 CString viewer;
534 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
535 viewer = v;
536 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
538 // use TortoiseGitUDiff
539 viewer = CPathUtils::GetAppDirectory();
540 viewer += _T("TortoiseGitUDiff.exe");
541 // enquote the path to TortoiseGitUDiff
542 viewer = _T("\"") + viewer + _T("\"");
543 // add the params
544 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
545 if (!g_sGroupingUUID.IsEmpty())
547 viewer += L" /groupuuid:\"";
548 viewer += g_sGroupingUUID;
549 viewer += L"\"";
552 if (viewer.Find(_T("%1"))>=0)
554 if (viewer.Find(_T("\"%1\"")) >= 0)
555 viewer.Replace(_T("%1"), patchfile);
556 else
557 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
559 else
560 viewer += _T(" \"") + patchfile + _T("\"");
561 if (viewer.Find(_T("%title")) >= 0)
563 viewer.Replace(_T("%title"), title);
566 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
568 return FALSE;
570 return TRUE;
573 BOOL CAppUtils::StartTextViewer(CString file)
575 CString viewer;
576 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
577 viewer = txt;
578 viewer = viewer + _T("\\Shell\\Open\\Command\\");
579 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
580 viewer = txtexe;
582 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
583 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 1]);
584 ExpandEnvironmentStrings(viewer, buf.get(), len);
585 viewer = buf.get();
586 len = ExpandEnvironmentStrings(file, NULL, 0);
587 std::unique_ptr<TCHAR[]> buf2(new TCHAR[len + 1]);
588 ExpandEnvironmentStrings(file, buf2.get(), len);
589 file = buf2.get();
590 file = _T("\"")+file+_T("\"");
591 if (viewer.IsEmpty())
593 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
595 if (viewer.Find(_T("\"%1\"")) >= 0)
597 viewer.Replace(_T("\"%1\""), file);
599 else if (viewer.Find(_T("%1")) >= 0)
601 viewer.Replace(_T("%1"), file);
603 else
605 viewer += _T(" ");
606 viewer += file;
609 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
611 return FALSE;
613 return TRUE;
616 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
618 DWORD length = 0;
619 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
620 if (!hFile)
621 return TRUE;
622 length = ::GetFileSize(hFile, NULL);
623 if (length < 4)
624 return TRUE;
625 return FALSE;
629 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
631 LOGFONT logFont;
632 HDC hScreenDC = ::GetDC(NULL);
633 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
634 ::ReleaseDC(NULL, hScreenDC);
635 logFont.lfWidth = 0;
636 logFont.lfEscapement = 0;
637 logFont.lfOrientation = 0;
638 logFont.lfWeight = FW_NORMAL;
639 logFont.lfItalic = 0;
640 logFont.lfUnderline = 0;
641 logFont.lfStrikeOut = 0;
642 logFont.lfCharSet = DEFAULT_CHARSET;
643 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
644 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
645 logFont.lfQuality = DRAFT_QUALITY;
646 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
647 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
648 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
651 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
653 CString key,remote;
654 CString cmd,out;
655 if( pRemote == NULL)
657 remote=_T("origin");
659 else
661 remote=*pRemote;
663 if(keyfile == NULL)
665 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
666 key = g_Git.GetConfigValue(cmd);
668 else
669 key=*keyfile;
671 if(key.IsEmpty())
672 return false;
674 CString proc=CPathUtils::GetAppDirectory();
675 proc += _T("pageant.exe \"");
676 proc += key;
677 proc += _T("\"");
679 CString tempfile = GetTempFile();
680 ::DeleteFile(tempfile);
682 proc += _T(" -c \"");
683 proc += CPathUtils::GetAppDirectory();
684 proc += _T("tgittouch.exe\"");
685 proc += _T(" \"");
686 proc += tempfile;
687 proc += _T("\"");
689 CString appDir = CPathUtils::GetAppDirectory();
690 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
691 if(!b)
692 return b;
694 int i=0;
695 while(!::PathFileExists(tempfile))
697 Sleep(100);
698 ++i;
699 if(i>10*60*5)
700 break; //timeout 5 minutes
703 if( i== 10*60*5)
705 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
707 ::DeleteFile(tempfile);
708 return true;
710 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
712 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
713 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
714 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
717 CString sCmd;
718 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
720 LaunchApplication(sCmd, NULL, false, NULL, uac);
721 return true;
723 bool CAppUtils::LaunchRemoteSetting()
725 CTGitPath path(g_Git.m_CurrentDir);
726 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
727 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
728 dlg.SetTreeWidth(220);
729 dlg.m_DefaultPage = _T("gitremote");
731 dlg.DoModal();
732 dlg.HandleRestart();
733 return true;
736 * Launch the external blame viewer
738 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
740 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
741 viewer += _T("TortoiseGitBlame.exe");
742 viewer += _T("\" \"") + sBlameFile + _T("\"");
743 //viewer += _T(" \"") + sLogFile + _T("\"");
744 //viewer += _T(" \"") + sOriginalFile + _T("\"");
745 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
746 viewer += CString(_T(" /rev:"))+Rev;
747 if (!g_sGroupingUUID.IsEmpty())
749 viewer += L" /groupuuid:\"";
750 viewer += g_sGroupingUUID;
751 viewer += L"\"";
753 viewer += _T(" ")+sParams;
755 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
758 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
760 CString sText;
761 if (pWnd == NULL)
762 return false;
763 bool bStyled = false;
764 pWnd->GetWindowText(sText);
765 // the rich edit control doesn't count the CR char!
766 // to be exact: CRLF is treated as one char.
767 sText.Remove(_T('\r'));
769 // style each line separately
770 int offset = 0;
771 int nNewlinePos;
774 nNewlinePos = sText.Find('\n', offset);
775 CString sLine = nNewlinePos >= 0 ? sText.Mid(offset, nNewlinePos - offset) : sText.Mid(offset);
777 int start = 0;
778 int end = 0;
779 while (FindStyleChars(sLine, '*', start, end))
781 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
782 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
783 SetCharFormat(pWnd, CFM_BOLD, CFE_BOLD);
784 bStyled = true;
785 start = end;
787 start = 0;
788 end = 0;
789 while (FindStyleChars(sLine, '^', start, end))
791 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
792 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
793 SetCharFormat(pWnd, CFM_ITALIC, CFE_ITALIC);
794 bStyled = true;
795 start = end;
797 start = 0;
798 end = 0;
799 while (FindStyleChars(sLine, '_', start, end))
801 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
802 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
803 SetCharFormat(pWnd, CFM_UNDERLINE, CFE_UNDERLINE);
804 bStyled = true;
805 start = end;
807 offset = nNewlinePos+1;
808 } while(nNewlinePos>=0);
809 return bStyled;
812 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
814 int i=start;
815 int last = sText.GetLength() - 1;
816 bool bFoundMarker = false;
817 TCHAR c = i == 0 ? _T('\0') : sText[i - 1];
818 TCHAR nextChar = i >= last ? _T('\0') : sText[i + 1];
820 // find a starting marker
821 while (i < last)
823 TCHAR prevChar = c;
824 c = nextChar;
825 nextChar = sText[i + 1];
827 // IsCharAlphaNumeric can be somewhat expensive.
828 // Long lines of "*****" or "----" will be pre-empted efficiently
829 // by the (c != nextChar) condition.
831 if ((c == stylechar) && (c != nextChar))
833 if (IsCharAlphaNumeric(nextChar) && !IsCharAlphaNumeric(prevChar))
835 start = ++i;
836 bFoundMarker = true;
837 break;
840 ++i;
842 if (!bFoundMarker)
843 return false;
845 // find ending marker
846 // c == sText[i - 1]
848 bFoundMarker = false;
849 while (i <= last)
851 TCHAR prevChar = c;
852 c = sText[i];
853 if (c == stylechar)
855 if ((i == last) || (!IsCharAlphaNumeric(sText[i + 1]) && IsCharAlphaNumeric(prevChar)))
857 end = i;
858 ++i;
859 bFoundMarker = true;
860 break;
863 ++i;
865 return bFoundMarker;
868 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
869 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
870 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
871 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */,
872 bool /* blame = false */,
873 bool bMerge,
874 bool bCombine)
876 int diffContext = 0;
877 if (GetMsysgitVersion() > 0x01080100)
878 diffContext = g_Git.GetConfigValueInt32(_T("diff.context"), -1);
879 CString tempfile=GetTempFile();
880 if (g_Git.GetUnifiedDiff(url1, rev1, rev2, tempfile, bMerge, bCombine, diffContext))
882 CMessageBox::Show(hWnd, g_Git.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF), _T("TortoiseGit"), MB_OK);
883 return false;
885 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
887 #if 0
888 CString sCmd;
889 sCmd.Format(_T("%s /command:showcompare /unified"),
890 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
891 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
892 if (rev1.IsValid())
893 sCmd += _T(" /revision1:") + rev1.ToString();
894 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
895 if (rev2.IsValid())
896 sCmd += _T(" /revision2:") + rev2.ToString();
897 if (peg.IsValid())
898 sCmd += _T(" /pegrevision:") + peg.ToString();
899 if (headpeg.IsValid())
900 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
902 if (bAlternateDiff)
903 sCmd += _T(" /alternatediff");
905 if (bIgnoreAncestry)
906 sCmd += _T(" /ignoreancestry");
908 if (hWnd)
910 sCmd += _T(" /hwnd:");
911 TCHAR buf[30];
912 _stprintf_s(buf, 30, _T("%p"), (void*)hWnd);
913 sCmd += buf;
916 return CAppUtils::LaunchApplication(sCmd, NULL, false);
917 #endif
918 return TRUE;
921 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
923 CString scriptsdir = CPathUtils::GetAppParentDirectory();
924 scriptsdir += _T("Diff-Scripts");
925 CSimpleFileFind files(scriptsdir);
926 while (files.FindNextFileNoDirectories())
928 CString file = files.GetFilePath();
929 CString filename = files.GetFileName();
930 CString ext = file.Mid(file.ReverseFind('-') + 1);
931 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
932 std::set<CString> extensions;
933 extensions.insert(ext);
934 CString kind;
935 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
937 kind = _T(" //E:vbscript");
939 if (file.Right(2).CompareNoCase(_T("js"))==0)
941 kind = _T(" //E:javascript");
943 // open the file, read the first line and find possible extensions
944 // this script can handle
947 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
948 CString extline;
949 if (f.ReadString(extline))
951 if ((extline.GetLength() > 15 ) &&
952 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
953 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
955 if (extline[0] == '/')
956 extline = extline.Mid(15);
957 else
958 extline = extline.Mid(14);
959 CString sToken;
960 int curPos = 0;
961 sToken = extline.Tokenize(_T(";"), curPos);
962 while (!sToken.IsEmpty())
964 if (!sToken.IsEmpty())
966 if (sToken[0] != '.')
967 sToken = _T(".") + sToken;
968 extensions.insert(sToken);
970 sToken = extline.Tokenize(_T(";"), curPos);
974 f.Close();
976 catch (CFileException* e)
978 e->Delete();
981 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
983 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
985 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
987 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
988 CString diffregstring = diffreg;
989 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
990 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
993 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
995 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
997 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
998 CString diffregstring = diffreg;
999 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1000 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1006 return true;
1009 bool CAppUtils::Export(CString *BashHash, const CTGitPath *orgPath)
1011 // ask from where the export has to be done
1012 CExportDlg dlg;
1013 if(BashHash)
1014 dlg.m_Revision=*BashHash;
1015 if (orgPath)
1017 if (PathIsRelative(orgPath->GetWinPath()))
1018 dlg.m_orgPath = g_Git.CombinePath(orgPath);
1019 else
1020 dlg.m_orgPath = *orgPath;
1023 if (dlg.DoModal() == IDOK)
1025 CString cmd;
1026 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1027 dlg.m_strFile, g_Git.FixBranchName(dlg.m_VersionName));
1029 CProgressDlg pro;
1030 pro.m_GitCmd=cmd;
1031 CGit git;
1032 if (!dlg.m_bWholeProject && !dlg.m_orgPath.IsEmpty() && PathIsDirectory(dlg.m_orgPath.GetWinPathString()))
1034 git.m_CurrentDir = dlg.m_orgPath.GetWinPathString();
1035 pro.m_Git = &git;
1037 return (pro.DoModal() == IDOK);
1039 return false;
1042 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1044 CCreateBranchTagDlg dlg;
1045 dlg.m_bIsTag=IsTag;
1046 dlg.m_bSwitch=switch_new_brach;
1048 if(CommitHash)
1049 dlg.m_initialRefName = *CommitHash;
1051 if(dlg.DoModal()==IDOK)
1053 CString cmd;
1054 CString force;
1055 CString track;
1056 if(dlg.m_bTrack == TRUE)
1057 track=_T(" --track ");
1058 else if(dlg.m_bTrack == FALSE)
1059 track=_T(" --no-track");
1061 if(dlg.m_bForce)
1062 force=_T(" -f ");
1064 if(IsTag)
1066 CString sign;
1067 if(dlg.m_bSign)
1068 sign=_T("-s");
1070 cmd.Format(_T("git.exe tag %s %s %s %s"),
1071 force,
1072 sign,
1073 dlg.m_BranchTagName,
1074 g_Git.FixBranchName(dlg.m_VersionName)
1077 CString tempfile=::GetTempFile();
1078 if(!dlg.m_Message.Trim().IsEmpty())
1080 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1081 cmd += _T(" -F ")+tempfile;
1084 else
1086 cmd.Format(_T("git.exe branch %s %s %s %s"),
1087 track,
1088 force,
1089 dlg.m_BranchTagName,
1090 g_Git.FixBranchName(dlg.m_VersionName)
1093 CString out;
1094 if(g_Git.Run(cmd,&out,CP_UTF8))
1096 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1097 return FALSE;
1099 if( !IsTag && dlg.m_bSwitch )
1101 // it is a new branch and the user has requested to switch to it
1102 PerformSwitch(dlg.m_BranchTagName);
1105 return TRUE;
1107 return FALSE;
1110 bool CAppUtils::Switch(CString initialRefName)
1112 CGitSwitchDlg dlg;
1113 if(!initialRefName.IsEmpty())
1114 dlg.m_initialRefName = initialRefName;
1116 if (dlg.DoModal() == IDOK)
1118 CString branch;
1119 if (dlg.m_bBranch)
1120 branch = dlg.m_NewBranch;
1122 // if refs/heads/ is not stripped, checkout will detach HEAD
1123 // checkout prefers branches on name clashes (with tags)
1124 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1125 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1127 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, dlg.m_bMerge == TRUE);
1129 return FALSE;
1132 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool bMerge /* false */)
1134 CString cmd;
1135 CString track;
1136 CString force;
1137 CString branch;
1138 CString merge;
1140 if(!sNewBranch.IsEmpty()){
1141 if (bBranchOverride)
1143 branch.Format(_T("-B %s"), sNewBranch);
1145 else
1147 branch.Format(_T("-b %s"), sNewBranch);
1149 if (bTrack == TRUE)
1150 track = _T("--track");
1151 else if (bTrack == FALSE)
1152 track = _T("--no-track");
1154 if (bForce)
1155 force = _T("-f");
1156 if (bMerge)
1157 merge = _T("--merge");
1159 cmd.Format(_T("git.exe checkout %s %s %s %s %s --"),
1160 force,
1161 track,
1162 merge,
1163 branch,
1164 g_Git.FixBranchName(ref));
1166 while (true)
1168 CProgressDlg progress;
1169 progress.m_GitCmd = cmd;
1171 INT_PTR idPull = -1;
1172 INT_PTR idSubmoduleUpdate = -1;
1173 INT_PTR idMerge = -1;
1175 CTGitPath gitPath = g_Git.m_CurrentDir;
1176 if (gitPath.HasSubmodules())
1177 idSubmoduleUpdate = progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1178 CString currentBranch;
1179 bool hasBranch = CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentBranch) == 0;
1180 if (hasBranch)
1181 idMerge = progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUMERGE)));
1183 progress.m_PostCmdCallback = [&] ()
1185 if (!progress.m_GitStatus)
1187 CString newBranch;
1188 if (!CGit::GetCurrentBranchFromFile(g_Git.m_CurrentDir, newBranch))
1189 idPull = progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPULL)));
1191 else
1193 progress.m_PostCmdList.RemoveAll();
1194 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
1195 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_SWITCH_WITH_MERGE)));
1199 INT_PTR ret = progress.DoModal();
1200 if (progress.m_GitStatus == 0)
1202 if (idSubmoduleUpdate >= 0 && ret == IDC_PROGRESS_BUTTON1 + idSubmoduleUpdate)
1204 CString sCmd;
1205 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1207 RunTortoiseGitProc(sCmd);
1208 return TRUE;
1210 else if (ret == IDC_PROGRESS_BUTTON1 + idPull)
1212 Pull();
1213 return TRUE;
1215 else if (ret == IDC_PROGRESS_BUTTON1 + idMerge)
1217 Merge(&currentBranch);
1218 return TRUE;
1220 else if (ret == IDOK)
1221 return TRUE;
1223 else if (ret == IDC_PROGRESS_BUTTON1)
1224 continue; // retry
1225 else if (ret == IDC_PROGRESS_BUTTON1 + 1)
1227 merge = _T("--merge");
1228 cmd.Format(_T("git.exe checkout %s %s %s %s %s --"),
1229 force, track, merge, branch, g_Git.FixBranchName(ref));
1230 continue; // retry
1233 return FALSE;
1237 class CIgnoreFile : public CStdioFile
1239 public:
1240 STRING_VECTOR m_Items;
1241 CString m_eol;
1243 virtual BOOL ReadString(CString& rString)
1245 if (GetPosition() == 0)
1247 unsigned char utf8bom[] = { 0xEF, 0xBB, 0xBF };
1248 char buf[3] = { 0, 0, 0 };
1249 Read(buf, 3);
1250 if (memcpy(buf, utf8bom, sizeof(utf8bom)))
1252 SeekToBegin();
1256 CStringA strA;
1257 char lastChar = '\0';
1258 for (char c = '\0'; Read(&c, 1) == 1; lastChar = c)
1260 if (c == '\r')
1261 continue;
1262 if (c == '\n')
1264 m_eol = lastChar == '\r' ? _T("\r\n") : _T("\n");
1265 break;
1267 strA.AppendChar(c);
1269 if (strA.IsEmpty())
1270 return FALSE;
1272 rString = CUnicodeUtils::GetUnicode(strA);
1273 return TRUE;
1276 void ResetState()
1278 m_Items.clear();
1279 m_eol = _T("");
1283 bool CAppUtils::OpenIgnoreFile(CIgnoreFile &file, const CString& filename)
1285 file.ResetState();
1286 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate | CFile::typeBinary))
1288 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1289 return false;
1292 if (file.GetLength() > 0)
1294 CString fileText;
1295 while (file.ReadString(fileText))
1296 file.m_Items.push_back(fileText);
1297 file.Seek(file.GetLength() - 1, 0);
1298 char lastchar[1] = { 0 };
1299 file.Read(lastchar, 1);
1300 file.SeekToEnd();
1301 if (lastchar[0] != '\n')
1303 CStringA eol = CStringA(file.m_eol.IsEmpty() ? _T("\n") : file.m_eol);
1304 file.Write(eol, eol.GetLength());
1307 else
1308 file.SeekToEnd();
1310 return true;
1313 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1315 CIgnoreDlg ignoreDlg;
1316 if (ignoreDlg.DoModal() == IDOK)
1318 CString ignorefile;
1319 ignorefile = g_Git.m_CurrentDir + _T("\\");
1321 switch (ignoreDlg.m_IgnoreFile)
1323 case 0:
1324 ignorefile += _T(".gitignore");
1325 break;
1326 case 2:
1327 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1328 ignorefile += _T("info/exclude");
1329 break;
1332 CIgnoreFile file;
1335 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1336 return false;
1338 for (int i = 0; i < path.GetCount(); ++i)
1340 if (ignoreDlg.m_IgnoreFile == 1)
1342 ignorefile = g_Git.CombinePath(path[i].GetContainingDirectory()) + _T("\\.gitignore");
1343 if (!OpenIgnoreFile(file, ignorefile))
1344 return false;
1347 CString ignorePattern;
1348 if (ignoreDlg.m_IgnoreType == 0)
1350 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1351 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1353 ignorePattern += _T("/");
1355 if (IsMask)
1357 ignorePattern += _T("*") + path[i].GetFileExtension();
1359 else
1361 ignorePattern += path[i].GetFileOrDirectoryName();
1364 // escape [ and ] so that files get ignored correctly
1365 ignorePattern.Replace(_T("["), _T("\\["));
1366 ignorePattern.Replace(_T("]"), _T("\\]"));
1368 bool found = false;
1369 for (size_t j = 0; j < file.m_Items.size(); ++j)
1371 if (file.m_Items[j] == ignorePattern)
1373 found = true;
1374 break;
1377 if (!found)
1379 file.m_Items.push_back(ignorePattern);
1380 ignorePattern += file.m_eol.IsEmpty() ? _T("\n") : file.m_eol;
1381 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1382 file.Write(ignorePatternA, ignorePatternA.GetLength());
1385 if (ignoreDlg.m_IgnoreFile == 1)
1386 file.Close();
1389 if (ignoreDlg.m_IgnoreFile != 1)
1390 file.Close();
1392 catch(...)
1394 file.Abort();
1395 return false;
1398 return true;
1400 return false;
1404 bool CAppUtils::GitReset(CString *CommitHash,int type)
1406 CResetDlg dlg;
1407 dlg.m_ResetType=type;
1408 dlg.m_ResetToVersion=*CommitHash;
1409 dlg.m_initialRefName = *CommitHash;
1410 if (dlg.DoModal() == IDOK)
1412 CString cmd;
1413 CString type;
1414 switch(dlg.m_ResetType)
1416 case 0:
1417 type=_T("--soft");
1418 break;
1419 case 1:
1420 type=_T("--mixed");
1421 break;
1422 case 2:
1423 type=_T("--hard");
1424 break;
1425 default:
1426 dlg.m_ResetType = 1;
1427 type=_T("--mixed");
1428 break;
1430 cmd.Format(_T("git.exe reset %s %s --"),type, dlg.m_ResetToVersion);
1432 while (true)
1434 CProgressDlg progress;
1435 progress.m_GitCmd=cmd;
1437 CTGitPath gitPath = g_Git.m_CurrentDir;
1438 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1439 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1441 progress.m_PostFailCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
1443 INT_PTR ret;
1444 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
1446 CGitProgressDlg gitdlg;
1447 ResetProgressCommand resetProgressCommand;
1448 gitdlg.SetCommand(&resetProgressCommand);
1449 resetProgressCommand.SetRevision(dlg.m_ResetToVersion);
1450 resetProgressCommand.SetResetType(dlg.m_ResetType);
1451 ret = gitdlg.DoModal();
1453 else
1454 ret = progress.DoModal();
1456 if (progress.m_GitStatus == 0 && gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1458 CString sCmd;
1459 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1461 RunTortoiseGitProc(sCmd);
1462 return TRUE;
1464 else if (progress.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
1465 continue; // retry
1466 else if (ret == IDOK)
1467 return TRUE;
1468 else
1469 break;
1472 return FALSE;
1475 void CAppUtils::DescribeConflictFile(bool mode, bool base,CString &descript)
1477 if(mode == FALSE)
1479 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1480 return;
1482 if(base)
1484 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1485 return;
1487 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1488 return;
1491 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1493 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path));
1494 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path));
1495 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path));
1497 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1499 CString file;
1500 file = g_Git.CombinePath(merge.GetWinPathString() + _T(".") + type + merge.GetFileExtension());
1502 return file;
1505 bool ParseHashesFromLsFile(BYTE_VECTOR &out, CString &hash1, CString &hash2, CString &hash3)
1507 unsigned int pos = 0;
1508 CString one;
1509 CString part;
1511 while (pos >= 0 && pos < out.size())
1513 one.Empty();
1515 g_Git.StringAppend(&one, &out[pos], CP_UTF8);
1516 int tabstart = 0;
1517 one.Tokenize(_T("\t"), tabstart);
1519 tabstart = 0;
1520 part = one.Tokenize(_T(" "), tabstart); //Tag
1521 part = one.Tokenize(_T(" "), tabstart); //Mode
1522 part = one.Tokenize(_T(" "), tabstart); //Hash
1523 CString hash = part;
1524 part = one.Tokenize(_T("\t"), tabstart); //Stage
1525 int stage = _ttol(part);
1526 if (stage == 1)
1527 hash1 = hash;
1528 else if (stage == 2)
1529 hash2 = hash;
1530 else if (stage == 3)
1532 hash3 = hash;
1533 return true;
1536 pos = out.findNextString(pos);
1539 return false;
1542 bool CAppUtils::ConflictEdit(CTGitPath& path, bool /*bAlternativeTool = false*/, bool revertTheirMy /*= false*/, HWND resolveMsgHwnd /*= nullptr*/)
1544 bool bRet = false;
1546 CTGitPath merge=path;
1547 CTGitPath directory = merge.GetDirectory();
1549 // we have the conflicted file (%merged)
1550 // now look for the other required files
1551 //GitStatus stat;
1552 //stat.GetStatus(merge);
1553 //if (stat.status == NULL)
1554 // return false;
1556 BYTE_VECTOR vector;
1558 CString cmd;
1559 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1561 if (g_Git.Run(cmd, &vector))
1563 return FALSE;
1566 if (merge.IsDirectory())
1568 CString baseHash, localHash, remoteHash;
1569 if (!ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash))
1570 return FALSE;
1572 CString msg;
1573 msg.Format(_T("BASE: %s\nLOCAL: %s\nREMOTE: %s"), baseHash, localHash, remoteHash);
1574 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK);
1575 return TRUE;
1578 CTGitPathList list;
1579 if (list.ParserFromLsFile(vector))
1581 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1582 return FALSE;
1585 if (list.IsEmpty())
1586 return FALSE;
1588 CTGitPath theirs;
1589 CTGitPath mine;
1590 CTGitPath base;
1592 if (revertTheirMy)
1594 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1595 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1597 else
1599 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1600 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1602 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1604 CString format;
1606 //format=_T("git.exe cat-file blob \":%d:%s\"");
1607 format = _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1608 CFile tempfile;
1609 //create a empty file, incase stage is not three
1610 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1611 tempfile.Close();
1612 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1613 tempfile.Close();
1614 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1615 tempfile.Close();
1617 bool b_base=false, b_local=false, b_remote=false;
1619 for (int i = 0; i< list.GetCount(); ++i)
1621 CString cmd;
1622 CString outfile;
1623 cmd.Empty();
1624 outfile.Empty();
1626 if( list[i].m_Stage == 1)
1628 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1629 b_base = true;
1630 outfile = base.GetWinPathString();
1633 if( list[i].m_Stage == 2 )
1635 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1636 b_local = true;
1637 outfile = mine.GetWinPathString();
1640 if( list[i].m_Stage == 3 )
1642 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1643 b_remote = true;
1644 outfile = theirs.GetWinPathString();
1646 CString output, err;
1647 if(!outfile.IsEmpty())
1648 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1650 CString file;
1651 int start =0 ;
1652 file = output.Tokenize(_T("\t"), start);
1653 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1655 else
1657 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1661 if(b_local && b_remote )
1663 merge.SetFromWin(g_Git.CombinePath(merge));
1664 if( revertTheirMy )
1665 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1666 else
1667 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd);
1670 else
1672 ::DeleteFile(mine.GetWinPathString());
1673 ::DeleteFile(theirs.GetWinPathString());
1674 ::DeleteFile(base.GetWinPathString());
1676 CDeleteConflictDlg dlg;
1677 DescribeConflictFile(b_local, b_base,dlg.m_LocalStatus);
1678 DescribeConflictFile(b_remote,b_base,dlg.m_RemoteStatus);
1679 CGitHash localHash, remoteHash;
1680 if (!g_Git.GetHash(localHash, _T("HEAD")))
1681 dlg.m_LocalHash = localHash.ToString();
1682 if (!g_Git.GetHash(remoteHash, _T("MERGE_HEAD")))
1683 dlg.m_RemoteHash = remoteHash.ToString();
1684 else if (!g_Git.GetHash(remoteHash, _T("rebase-apply/original-commit")))
1685 dlg.m_RemoteHash = remoteHash.ToString();
1686 else if (!g_Git.GetHash(remoteHash, _T("CHERRY_PICK_HEAD")))
1687 dlg.m_RemoteHash = remoteHash.ToString();
1688 else if (!g_Git.GetHash(remoteHash, _T("REVERT_HEAD")))
1689 dlg.m_RemoteHash = remoteHash.ToString();
1690 dlg.m_bShowModifiedButton=b_base;
1691 dlg.m_File=merge.GetGitPathString();
1692 if(dlg.DoModal() == IDOK)
1694 CString cmd,out;
1695 if(dlg.m_bIsDelete)
1697 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1699 else
1700 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1702 if (g_Git.Run(cmd, &out, CP_UTF8))
1704 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1705 return FALSE;
1707 return TRUE;
1709 else
1710 return FALSE;
1713 #if 0
1714 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1715 base, theirs, mine, merge);
1716 #endif
1717 #if 0
1718 if (stat.status->text_status == svn_wc_status_conflicted)
1720 // we have a text conflict, use our merge tool to resolve the conflict
1722 CTSVNPath theirs(directory);
1723 CTSVNPath mine(directory);
1724 CTSVNPath base(directory);
1725 bool bConflictData = false;
1727 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1729 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1730 bConflictData = true;
1732 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1734 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1735 bConflictData = true;
1737 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1739 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1740 bConflictData = true;
1742 else
1744 mine = merge;
1746 if (bConflictData)
1747 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1748 base, theirs, mine, merge);
1751 if (stat.status->prop_status == svn_wc_status_conflicted)
1753 // we have a property conflict
1754 CTSVNPath prej(directory);
1755 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1757 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1758 // there's a problem: the prej file contains a _description_ of the conflict, and
1759 // that description string might be translated. That means we have no way of parsing
1760 // the file to find out the conflicting values.
1761 // The only thing we can do: show a dialog with the conflict description, then
1762 // let the user either accept the existing property or open the property edit dialog
1763 // to manually change the properties and values. And a button to mark the conflict as
1764 // resolved.
1765 CEditPropConflictDlg dlg;
1766 dlg.SetPrejFile(prej);
1767 dlg.SetConflictedItem(merge);
1768 bRet = (dlg.DoModal() != IDCANCEL);
1772 if (stat.status->tree_conflict)
1774 // we have a tree conflict
1775 SVNInfo info;
1776 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1777 if (pInfoData)
1779 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1781 CTSVNPath theirs(directory);
1782 CTSVNPath mine(directory);
1783 CTSVNPath base(directory);
1784 bool bConflictData = false;
1786 if (pInfoData->treeconflict_theirfile)
1788 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1789 bConflictData = true;
1791 if (pInfoData->treeconflict_basefile)
1793 base.AppendPathString(pInfoData->treeconflict_basefile);
1794 bConflictData = true;
1796 if (pInfoData->treeconflict_myfile)
1798 mine.AppendPathString(pInfoData->treeconflict_myfile);
1799 bConflictData = true;
1801 else
1803 mine = merge;
1805 if (bConflictData)
1806 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1807 base, theirs, mine, merge);
1809 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1811 CString sConflictAction;
1812 CString sConflictReason;
1813 CString sResolveTheirs;
1814 CString sResolveMine;
1815 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1816 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1818 if (pInfoData->treeconflict_nodekind == svn_node_file)
1820 switch (pInfoData->treeconflict_operation)
1822 case svn_wc_operation_update:
1823 switch (pInfoData->treeconflict_action)
1825 case svn_wc_conflict_action_edit:
1826 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1827 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1828 break;
1829 case svn_wc_conflict_action_add:
1830 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1831 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1832 break;
1833 case svn_wc_conflict_action_delete:
1834 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1835 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1836 break;
1838 break;
1839 case svn_wc_operation_switch:
1840 switch (pInfoData->treeconflict_action)
1842 case svn_wc_conflict_action_edit:
1843 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1844 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1845 break;
1846 case svn_wc_conflict_action_add:
1847 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1848 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1849 break;
1850 case svn_wc_conflict_action_delete:
1851 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1852 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1853 break;
1855 break;
1856 case svn_wc_operation_merge:
1857 switch (pInfoData->treeconflict_action)
1859 case svn_wc_conflict_action_edit:
1860 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1861 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1862 break;
1863 case svn_wc_conflict_action_add:
1864 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1865 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1866 break;
1867 case svn_wc_conflict_action_delete:
1868 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1869 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1870 break;
1872 break;
1875 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1877 switch (pInfoData->treeconflict_operation)
1879 case svn_wc_operation_update:
1880 switch (pInfoData->treeconflict_action)
1882 case svn_wc_conflict_action_edit:
1883 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1884 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1885 break;
1886 case svn_wc_conflict_action_add:
1887 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1888 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1889 break;
1890 case svn_wc_conflict_action_delete:
1891 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1892 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1893 break;
1895 break;
1896 case svn_wc_operation_switch:
1897 switch (pInfoData->treeconflict_action)
1899 case svn_wc_conflict_action_edit:
1900 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1901 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1902 break;
1903 case svn_wc_conflict_action_add:
1904 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1905 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1906 break;
1907 case svn_wc_conflict_action_delete:
1908 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1909 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1910 break;
1912 break;
1913 case svn_wc_operation_merge:
1914 switch (pInfoData->treeconflict_action)
1916 case svn_wc_conflict_action_edit:
1917 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1918 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1919 break;
1920 case svn_wc_conflict_action_add:
1921 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1922 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1923 break;
1924 case svn_wc_conflict_action_delete:
1925 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1926 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1927 break;
1929 break;
1933 UINT uReasonID = 0;
1934 switch (pInfoData->treeconflict_reason)
1936 case svn_wc_conflict_reason_edited:
1937 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1938 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1939 break;
1940 case svn_wc_conflict_reason_obstructed:
1941 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1942 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1943 break;
1944 case svn_wc_conflict_reason_deleted:
1945 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1946 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1947 break;
1948 case svn_wc_conflict_reason_added:
1949 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1950 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1951 break;
1952 case svn_wc_conflict_reason_missing:
1953 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1954 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1955 break;
1956 case svn_wc_conflict_reason_unversioned:
1957 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1958 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1959 break;
1961 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1963 CTreeConflictEditorDlg dlg;
1964 dlg.SetConflictInfoText(sConflictReason);
1965 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1966 dlg.SetPath(treeConflictPath);
1967 INT_PTR dlgRet = dlg.DoModal();
1968 bRet = (dlgRet != IDCANCEL);
1972 #endif
1973 return bRet;
1976 bool CAppUtils::IsSSHPutty()
1978 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1979 sshclient=sshclient.MakeLower();
1980 if(sshclient.Find(_T("plink.exe"),0)>=0)
1982 return true;
1984 return false;
1987 CString CAppUtils::GetClipboardLink(const CString &skipGitPrefix, int paramsCount)
1989 if (!OpenClipboard(NULL))
1990 return CString();
1992 CString sClipboardText;
1993 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1994 if (hglb)
1996 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1997 sClipboardText = CString(lpstr);
1998 GlobalUnlock(hglb);
2000 hglb = GetClipboardData(CF_UNICODETEXT);
2001 if (hglb)
2003 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2004 sClipboardText = lpstr;
2005 GlobalUnlock(hglb);
2007 CloseClipboard();
2009 if(!sClipboardText.IsEmpty())
2011 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2012 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2014 if(sClipboardText.Find( _T("http://")) == 0)
2015 return sClipboardText;
2017 if(sClipboardText.Find( _T("https://")) == 0)
2018 return sClipboardText;
2020 if(sClipboardText.Find( _T("git://")) == 0)
2021 return sClipboardText;
2023 if(sClipboardText.Find( _T("ssh://")) == 0)
2024 return sClipboardText;
2026 if(sClipboardText.GetLength()>=2)
2027 if( sClipboardText[1] == _T(':') )
2028 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2029 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2030 return sClipboardText;
2032 // trim prefixes like "git clone "
2033 if (!skipGitPrefix.IsEmpty() && sClipboardText.Find(skipGitPrefix) == 0)
2035 sClipboardText = sClipboardText.Mid(skipGitPrefix.GetLength()).Trim();
2036 int spacePos = -1;
2037 while (paramsCount >= 0)
2039 --paramsCount;
2040 spacePos = sClipboardText.Find(_T(' '), spacePos + 1);
2041 if (spacePos == -1)
2042 break;
2044 if (spacePos > 0 && paramsCount < 0)
2045 sClipboardText = sClipboardText.Left(spacePos);
2046 return sClipboardText;
2050 return CString(_T(""));
2053 CString CAppUtils::ChooseRepository(CString *path)
2055 CBrowseFolder browseFolder;
2056 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2058 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2059 CString strCloneDirectory;
2060 if(path)
2061 strCloneDirectory=*path;
2062 else
2064 strCloneDirectory = regLastResopitory;
2067 CString title;
2068 title.LoadString(IDS_CHOOSE_REPOSITORY);
2070 browseFolder.SetInfo(title);
2072 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2074 regLastResopitory = strCloneDirectory;
2075 return strCloneDirectory;
2077 else
2079 return CString();
2083 bool CAppUtils::SendPatchMail(CTGitPathList& list)
2085 CSendMailDlg dlg;
2087 dlg.m_PathList = list;
2089 if(dlg.DoModal()==IDOK)
2091 if (dlg.m_PathList.IsEmpty())
2092 return FALSE;
2094 CGitProgressDlg progDlg;
2096 theApp.m_pMainWnd = &progDlg;
2097 SendMailProgressCommand sendMailProgressCommand;
2098 progDlg.SetCommand(&sendMailProgressCommand);
2100 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2101 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2103 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2104 sendMailProgressCommand.SetSendMailOption(&sendMailPatch);
2106 progDlg.DoModal();
2108 return true;
2110 return false;
2113 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput)
2115 CTGitPathList list;
2116 CString log=formatpatchoutput;
2117 int start=log.Find(cmd);
2118 if(start >=0)
2119 CString one=log.Tokenize(_T("\n"),start);
2120 else
2121 start = 0;
2123 while(start>=0)
2125 CString one=log.Tokenize(_T("\n"),start);
2126 one=one.Trim();
2127 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2128 continue;
2129 one.Replace(_T('/'),_T('\\'));
2130 CTGitPath path;
2131 path.SetFromWin(one);
2132 list.AddPath(path);
2134 if (!list.IsEmpty())
2136 return SendPatchMail(list);
2138 else
2140 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2141 return true;
2146 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2148 CString output;
2149 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2150 if(output.IsEmpty())
2151 return CUnicodeUtils::GetCPCode(pGit->GetConfigValue(_T("i18n.commitencoding")));
2152 else
2154 return CUnicodeUtils::GetCPCode(output);
2157 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2159 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2160 int cp = CUnicodeUtils::GetCPCode(g_Git.GetConfigValue(_T("i18n.commitencoding")));
2162 bool stripComments = (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE) == TRUE);
2164 if (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE) == TRUE)
2165 message.TrimRight(L" \r\n");
2167 int len = message.GetLength();
2168 int start = 0;
2169 while (start >= 0 && start < len)
2171 int oldStart = start;
2172 start = message.Find(L"\n", oldStart);
2173 CString line = message.Mid(oldStart);
2174 if (start != -1)
2176 line = line.Left(start - oldStart);
2177 ++start; // move forward so we don't find the same char again
2179 if (stripComments && (line.GetLength() >= 1 && line.GetAt(0) == '#') || (start < 0 && line.IsEmpty()))
2180 continue;
2181 line.TrimRight(L" \r");
2182 CStringA lineA = CUnicodeUtils::GetMulti(line + L"\n", cp);
2183 file.Write(lineA.GetBuffer(), lineA.GetLength());
2185 file.Close();
2186 return 0;
2189 bool CAppUtils::Pull(bool showPush)
2191 CPullFetchDlg dlg;
2192 dlg.m_IsPull = TRUE;
2193 if (dlg.DoModal() == IDOK)
2195 CString url = dlg.m_RemoteURL;
2197 if (dlg.m_bAutoLoad)
2199 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2202 CString cmd;
2203 CGitHash hashOld;
2204 if (g_Git.GetHash(hashOld, _T("HEAD")))
2206 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR);
2207 return false;
2210 CString cmdRebase;
2211 CString noff;
2212 CString ffonly;
2213 CString squash;
2214 CString nocommit;
2215 CString depth;
2216 CString notags;
2217 CString prune;
2219 if (dlg.m_bRebase)
2220 cmdRebase = "--rebase ";
2222 if (!dlg.m_bFetchTags)
2223 notags = _T("--no-tags");
2225 if (dlg.m_bNoFF)
2226 noff=_T("--no-ff");
2228 if (dlg.m_bFFonly)
2229 ffonly = _T("--ff-only");
2231 if (dlg.m_bSquash)
2232 squash = _T("--squash");
2234 if (dlg.m_bNoCommit)
2235 nocommit = _T("--no-commit");
2237 if (dlg.m_bDepth)
2238 depth.Format(_T("--depth %d "), dlg.m_nDepth);
2240 int ver = CAppUtils::GetMsysgitVersion();
2242 if (dlg.m_bPrune == TRUE)
2243 prune = _T("--prune ");
2244 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2245 prune = _T("--no-prune ");
2247 if(ver >= 0x01070203) //above 1.7.0.2
2248 cmdRebase += _T("--progress ");
2250 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);
2251 CProgressDlg progress;
2252 progress.m_GitCmd = cmd;
2253 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_PULL_DIFFS)));
2254 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_PULL_LOG)));
2255 INT_PTR pushButton = showPush ? progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH))) + IDC_PROGRESS_BUTTON1 : -1;
2257 CTGitPath gitPath = g_Git.m_CurrentDir;
2258 INT_PTR smUpdateButton = gitPath.HasSubmodules() ? progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE))) + IDC_PROGRESS_BUTTON1 : -1;
2260 INT_PTR ret = progress.DoModal();
2262 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)
2264 CChangedDlg dlg;
2265 dlg.m_pathList.AddPath(CTGitPath());
2266 dlg.DoModal();
2268 return true;
2271 CGitHash hashNew;
2272 if (g_Git.GetHash(hashNew, _T("HEAD")))
2274 MessageBox(NULL, g_Git.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR);
2275 return FALSE;
2278 if( ret == IDC_PROGRESS_BUTTON1)
2280 if(hashOld == hashNew)
2282 if(progress.m_GitStatus == 0)
2283 CMessageBox::Show(NULL, IDS_UPTODATE, IDS_APPNAME, MB_OK | MB_ICONINFORMATION);
2284 return TRUE;
2287 CFileDiffDlg dlg;
2288 dlg.SetDiff(NULL, hashNew.ToString(), hashOld.ToString());
2289 dlg.DoModal();
2291 return true;
2293 else if ( ret == IDC_PROGRESS_BUTTON1 +1 )
2295 if(hashOld == hashNew)
2297 if(progress.m_GitStatus == 0)
2298 CMessageBox::Show(NULL, IDS_UPTODATE, IDS_APPNAME, MB_OK | MB_ICONINFORMATION);
2299 return true;
2302 CLogDlg dlg;
2303 dlg.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld.ToString() + _T("..") + hashNew.ToString(), 0);
2304 dlg.DoModal();
2306 else if (ret == pushButton)
2308 Push(_T(""));
2309 return true;
2311 else if (ret == smUpdateButton)
2313 CString sCmd;
2314 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2316 CAppUtils::RunTortoiseGitProc(sCmd);
2317 return true;
2321 return true;
2324 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool allRemotes)
2326 CPullFetchDlg dlg;
2327 dlg.m_PreSelectRemote = remoteName;
2328 dlg.m_bAllowRebase = allowRebase;
2329 dlg.m_IsPull=FALSE;
2330 dlg.m_bAllRemotes = allRemotes;
2332 if(dlg.DoModal()==IDOK)
2334 if(dlg.m_bAutoLoad)
2336 if (dlg.m_bAllRemotes)
2338 STRING_VECTOR list;
2339 g_Git.GetRemoteList(list);
2341 STRING_VECTOR::const_iterator it = list.begin();
2342 while (it != list.end())
2344 CString remote(*it);
2345 CAppUtils::LaunchPAgent(NULL, &remote);
2346 ++it;
2349 else
2350 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2353 CString url;
2354 url=dlg.m_RemoteURL;
2355 CString cmd;
2356 CString arg;
2358 int ver = CAppUtils::GetMsysgitVersion();
2360 if(ver >= 0x01070203) //above 1.7.0.2
2361 arg = _T("--progress ");
2363 if (dlg.m_bDepth)
2364 arg.AppendFormat(_T("--depth %d "), dlg.m_nDepth);
2366 if (dlg.m_bPrune == TRUE)
2367 arg += _T("--prune ");
2368 else if (dlg.m_bPrune == FALSE && ver >= 0x01080500)
2369 arg += _T("--no-prune ");
2371 if (dlg.m_bFetchTags == 1)
2373 arg += _T("--tags ");
2375 else if (dlg.m_bFetchTags == 0)
2377 arg += _T("--no-tags ");
2380 if (dlg.m_bAllRemotes)
2381 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
2382 else
2383 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
2385 while (true)
2387 CProgressDlg progress;
2389 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2390 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_RESET)));
2392 if (!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2393 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2395 progress.m_PostFailCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
2397 progress.m_GitCmd=cmd;
2398 INT_PTR userResponse;
2400 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2402 CGitProgressDlg gitdlg;
2403 FetchProgressCommand fetchProgressCommand;
2404 if (!dlg.m_bAllRemotes)
2405 fetchProgressCommand.SetUrl(url);
2406 gitdlg.SetCommand(&fetchProgressCommand);
2407 fetchProgressCommand.SetAutoTag(dlg.m_bFetchTags == 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : dlg.m_bFetchTags == 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2408 if (!dlg.m_bAllRemotes)
2409 fetchProgressCommand.SetRefSpec(dlg.m_RemoteBranchName);
2410 userResponse = gitdlg.DoModal();
2412 else
2413 userResponse = progress.DoModal();
2415 if (!progress.m_GitStatus)
2417 if (userResponse == IDC_PROGRESS_BUTTON1)
2419 CString cmd = _T("/command:log");
2420 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2421 RunTortoiseGitProc(cmd);
2422 return TRUE;
2424 else if (userResponse == IDC_PROGRESS_BUTTON1 + 1)
2426 CString pullRemote, pullBranch;
2427 g_Git.GetRemoteTrackedBranchForHEAD(pullRemote, pullBranch);
2429 CString defaultUpstream;
2430 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2431 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2432 GitReset(&defaultUpstream, 2);
2433 return TRUE;
2435 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 2) || dlg.m_bRebase)
2437 while(1)
2439 CRebaseDlg dlg;
2440 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2441 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2442 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2443 INT_PTR response = dlg.DoModal();
2444 if(response == IDOK)
2446 return TRUE;
2448 else if (response == IDC_REBASE_POST_BUTTON)
2450 CString cmd = _T("/command:log");
2451 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2452 RunTortoiseGitProc(cmd);
2453 return TRUE;
2455 else if (response == IDC_REBASE_POST_BUTTON + 1)
2457 CString cmd, out, err;
2458 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2459 g_Git.m_CurrentDir,
2460 g_Git.FixBranchName(dlg.m_Upstream),
2461 g_Git.FixBranchName(dlg.m_Branch));
2462 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2464 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2465 return FALSE;
2468 CAppUtils::SendPatchMail(cmd,out);
2469 return TRUE;
2471 else if (response == IDC_REBASE_POST_BUTTON + 2)
2472 continue;
2473 else if(response == IDCANCEL)
2474 return FALSE;
2476 return TRUE;
2478 else if (userResponse != IDCANCEL)
2479 return TRUE;
2480 return FALSE;
2482 else
2484 if (userResponse == IDC_PROGRESS_BUTTON1)
2485 continue;
2486 return FALSE;
2490 return FALSE;
2493 bool CAppUtils::Push(CString selectLocalBranch)
2495 CPushDlg dlg;
2496 dlg.m_BranchSourceName = selectLocalBranch;
2498 if (dlg.DoModal() == IDOK)
2500 CString error;
2501 DWORD exitcode = 0xFFFFFFFF;
2502 if (CHooks::Instance().PrePush(g_Git.m_CurrentDir, exitcode, error))
2504 if (exitcode)
2506 CString temp;
2507 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2508 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2509 return false;
2513 CString arg;
2515 if(dlg.m_bPack)
2516 arg += _T("--thin ");
2517 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2518 arg += _T("--tags ");
2519 if(dlg.m_bForce)
2520 arg += _T("--force ");
2521 if (dlg.m_bSetUpstream)
2522 arg += _T("--set-upstream ");
2523 if (dlg.m_RecurseSubmodules == 1)
2524 arg += _T("--recurse-submodules=check ");
2525 if (dlg.m_RecurseSubmodules == 2)
2526 arg += _T("--recurse-submodules=on-demand ");
2528 int ver = CAppUtils::GetMsysgitVersion();
2530 if(ver >= 0x01070203) //above 1.7.0.2
2531 arg += _T("--progress ");
2533 CProgressDlg progress;
2535 STRING_VECTOR remotesList;
2536 if (dlg.m_bPushAllRemotes)
2537 g_Git.GetRemoteList(remotesList);
2538 else
2539 remotesList.push_back(dlg.m_URL);
2541 for (unsigned int i = 0; i < remotesList.size(); ++i)
2543 if (dlg.m_bAutoLoad)
2544 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2546 CString cmd;
2547 if (dlg.m_bPushAllBranches)
2549 cmd.Format(_T("git.exe push --all %s \"%s\""),
2550 arg,
2551 remotesList[i]);
2553 if (dlg.m_bTags)
2555 progress.m_GitCmdList.push_back(cmd);
2556 cmd.Format(_T("git.exe push --tags %s \"%s\""), arg, remotesList[i]);
2559 else
2561 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2562 arg,
2563 remotesList[i],
2564 dlg.m_BranchSourceName);
2565 if (!dlg.m_BranchRemoteName.IsEmpty())
2567 cmd += _T(":") + dlg.m_BranchRemoteName;
2570 progress.m_GitCmdList.push_back(cmd);
2573 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2574 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2575 bool rejected = false;
2576 progress.m_PostCmdCallback = [&] ()
2578 if (progress.m_GitStatus)
2580 progress.m_PostCmdList.RemoveAll();
2581 rejected = progress.GetLogText().Find(_T("! [rejected]")) > 0;
2582 if (rejected)
2584 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPULL)));
2585 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUFETCH)));
2587 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2591 INT_PTR ret = progress.DoModal();
2593 exitcode = 0xFFFFFFFF;
2594 error.Empty();
2595 if (CHooks::Instance().PostPush(g_Git.m_CurrentDir, exitcode, error))
2597 if (exitcode)
2599 CString temp;
2600 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2601 CMessageBox::Show(nullptr, temp, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2602 return false;
2606 if (!progress.m_GitStatus)
2608 if(ret == IDC_PROGRESS_BUTTON1)
2610 RequestPull(dlg.m_BranchRemoteName);
2612 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2614 Push(selectLocalBranch);
2616 return TRUE;
2618 else
2620 if (rejected)
2622 // failed, pull first
2623 if (ret == IDC_PROGRESS_BUTTON1)
2625 Pull(true);
2627 else if (ret == IDC_PROGRESS_BUTTON1 + 1)
2629 Fetch(dlg.m_bPushAllRemotes ? _T("") : dlg.m_URL, true, !!dlg.m_bPushAllRemotes);
2631 else if (ret == IDC_PROGRESS_BUTTON1 + 2)
2633 Push(selectLocalBranch);
2636 else
2638 if (ret == IDC_PROGRESS_BUTTON1)
2640 Push(selectLocalBranch);
2645 return FALSE;
2648 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2650 CRequestPullDlg dlg;
2651 dlg.m_RepositoryURL = repositoryUrl;
2652 dlg.m_EndRevision = endrevision;
2653 if (dlg.DoModal()==IDOK)
2655 CString cmd;
2656 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2658 CSysProgressDlg sysProgressDlg;
2659 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2660 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2661 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2662 sysProgressDlg.SetShowProgressBar(false);
2663 sysProgressDlg.ShowModeless((HWND)NULL, true);
2665 CString tempFileName = GetTempFile();
2666 CString err;
2667 DeleteFile(tempFileName);
2668 CreateDirectory(tempFileName, NULL);
2669 tempFileName += _T("\\pullrequest.txt");
2670 if (g_Git.RunLogFile(cmd, tempFileName, &err))
2672 CString msg;
2673 msg.LoadString(IDS_ERR_PULLREUQESTFAILED);
2674 CMessageBox::Show(NULL, msg + _T("\n") + err, _T("TortoiseGit"), MB_OK);
2675 return false;
2678 if (sysProgressDlg.HasUserCancelled())
2680 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2681 ::DeleteFile(tempFileName);
2682 return false;
2685 sysProgressDlg.Stop();
2687 if (dlg.m_bSendMail)
2689 CSendMailDlg dlg;
2690 dlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2691 dlg.m_bCustomSubject = true;
2693 if (dlg.DoModal() == IDOK)
2695 if (dlg.m_PathList.IsEmpty())
2696 return FALSE;
2698 CGitProgressDlg progDlg;
2700 theApp.m_pMainWnd = &progDlg;
2701 SendMailProgressCommand sendMailProgressCommand;
2702 progDlg.SetCommand(&sendMailProgressCommand);
2704 sendMailProgressCommand.SetPathList(dlg.m_PathList);
2705 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2707 CSendMailCombineable sendMailCombineable(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine);
2708 sendMailProgressCommand.SetSendMailOption(&sendMailCombineable);
2710 progDlg.DoModal();
2712 return true;
2714 return false;
2717 CAppUtils::LaunchAlternativeEditor(tempFileName);
2719 return true;
2722 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2724 CString strDir(szPath);
2725 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2727 strDir.AppendChar(_T('\\'));
2729 std::vector<CString> vPath;
2730 CString strTemp;
2731 bool bSuccess = false;
2733 for (int i=0;i<strDir.GetLength();++i)
2735 if (strDir.GetAt(i) != _T('\\'))
2737 strTemp.AppendChar(strDir.GetAt(i));
2739 else
2741 vPath.push_back(strTemp);
2742 strTemp.AppendChar(_T('\\'));
2746 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2748 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2751 return bSuccess;
2754 void CAppUtils::RemoveTrailSlash(CString &path)
2756 if(path.IsEmpty())
2757 return ;
2759 // For URL, do not trim the slash just after the host name component.
2760 int index = path.Find(_T("://"));
2761 if (index >= 0)
2763 index += 4;
2764 index = path.Find(_T('/'), index);
2765 if (index == path.GetLength() - 1)
2766 return;
2769 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2771 path=path.Left(path.GetLength()-1);
2772 if(path.IsEmpty())
2773 return;
2777 bool CAppUtils::CheckUserData()
2779 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2781 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2783 CTGitPath path(g_Git.m_CurrentDir);
2784 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2785 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2786 dlg.SetTreeWidth(220);
2787 dlg.m_DefaultPage = _T("gitconfig");
2789 dlg.DoModal();
2790 dlg.HandleRestart();
2793 else
2794 return false;
2797 return true;
2800 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2801 CTGitPathList &pathList,
2802 CTGitPathList &selectedList,
2803 bool bSelectFilesForCommit)
2805 bool bFailed = true;
2807 if (!CheckUserData())
2808 return false;
2810 while (bFailed)
2812 bFailed = false;
2813 CCommitDlg dlg;
2814 dlg.m_sBugID = bugid;
2816 dlg.m_bWholeProject = bWholeProject;
2818 dlg.m_sLogMessage = sLogMsg;
2819 dlg.m_pathList = pathList;
2820 dlg.m_checkedPathList = selectedList;
2821 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2822 if (dlg.DoModal() == IDOK)
2824 if (dlg.m_pathList.IsEmpty())
2825 return false;
2826 // if the user hasn't changed the list of selected items
2827 // we don't use that list. Because if we would use the list
2828 // of pre-checked items, the dialog would show different
2829 // checked items on the next startup: it would only try
2830 // to check the parent folder (which might not even show)
2831 // instead, we simply use an empty list and let the
2832 // default checking do its job.
2833 if (!dlg.m_pathList.IsEqual(pathList))
2834 selectedList = dlg.m_pathList;
2835 pathList = dlg.m_updatedPathList;
2836 sLogMsg = dlg.m_sLogMessage;
2837 bSelectFilesForCommit = true;
2839 switch (dlg.m_PostCmd)
2841 case GIT_POSTCOMMIT_CMD_DCOMMIT:
2842 CAppUtils::SVNDCommit();
2843 break;
2844 case GIT_POSTCOMMIT_CMD_PUSH:
2845 CAppUtils::Push();
2846 break;
2847 case GIT_POSTCOMMIT_CMD_CREATETAG:
2848 CAppUtils::CreateBranchTag(TRUE);
2849 break;
2850 case GIT_POSTCOMMIT_CMD_PULL:
2851 CAppUtils::Pull(true);
2852 break;
2853 default:
2854 break;
2857 // CGitProgressDlg progDlg;
2858 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2859 // if (parser.HasVal(_T("closeonend")))
2860 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2861 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2862 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2863 // progDlg.SetPathList(dlg.m_pathList);
2864 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2865 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2866 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2867 // progDlg.SetItemCount(dlg.m_itemsCount);
2868 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2869 // progDlg.DoModal();
2870 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2871 // err = (DWORD)progDlg.DidErrorsOccur();
2872 // bFailed = progDlg.DidErrorsOccur();
2873 // bRet = progDlg.DidErrorsOccur();
2874 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2875 // if (DWORD(bFailRepeat)==0)
2876 // bFailed = false; // do not repeat if the user chose not to in the settings.
2879 return true;
2883 BOOL CAppUtils::SVNDCommit()
2885 CSVNDCommitDlg dcommitdlg;
2886 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2887 if (gitSetting == _T("")) {
2888 if (dcommitdlg.DoModal() != IDOK)
2890 return false;
2892 else
2894 if (dcommitdlg.m_remember)
2896 if (dcommitdlg.m_rmdir)
2898 gitSetting = _T("true");
2900 else
2902 gitSetting = _T("false");
2904 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2906 CString msg;
2907 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2908 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2914 BOOL IsStash = false;
2915 if(!g_Git.CheckCleanWorkTree())
2917 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2919 CSysProgressDlg sysProgressDlg;
2920 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2921 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2922 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2923 sysProgressDlg.SetShowProgressBar(false);
2924 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2925 sysProgressDlg.ShowModeless((HWND)NULL, true);
2927 CString cmd,out;
2928 cmd=_T("git.exe stash");
2929 if (g_Git.Run(cmd, &out, CP_UTF8))
2931 sysProgressDlg.Stop();
2932 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2933 return false;
2935 sysProgressDlg.Stop();
2937 IsStash =true;
2939 else
2941 return false;
2945 CProgressDlg progress;
2946 if (dcommitdlg.m_rmdir)
2948 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2950 else
2952 progress.m_GitCmd=_T("git.exe svn dcommit");
2954 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2956 ::DeleteFile(g_Git.m_CurrentDir + _T("\\sys$command"));
2957 if( IsStash)
2959 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2961 CSysProgressDlg sysProgressDlg;
2962 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2963 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2964 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2965 sysProgressDlg.SetShowProgressBar(false);
2966 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2967 sysProgressDlg.ShowModeless((HWND)NULL, true);
2969 CString cmd,out;
2970 cmd=_T("git.exe stash pop");
2971 if (g_Git.Run(cmd, &out, CP_UTF8))
2973 sysProgressDlg.Stop();
2974 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2975 return false;
2977 sysProgressDlg.Stop();
2979 else
2981 return false;
2984 return TRUE;
2986 return FALSE;
2989 BOOL CAppUtils::Merge(CString *commit)
2991 if (!CheckUserData())
2992 return FALSE;
2994 CMergeDlg dlg;
2995 if(commit)
2996 dlg.m_initialRefName = *commit;
2998 if(dlg.DoModal()==IDOK)
3000 CString cmd;
3001 CString args;
3003 if(dlg.m_bNoFF)
3004 args += _T(" --no-ff");
3006 if(dlg.m_bSquash)
3007 args += _T(" --squash");
3009 if(dlg.m_bNoCommit)
3010 args += _T(" --no-commit");
3012 if (dlg.m_bLog)
3014 CString fmt;
3015 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
3016 args += fmt;
3019 if (!dlg.m_MergeStrategy.IsEmpty())
3021 args += _T(" --strategy=") + dlg.m_MergeStrategy;
3022 if (!dlg.m_StrategyOption.IsEmpty())
3024 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
3025 if (!dlg.m_StrategyParam.IsEmpty())
3026 args += _T("=") + dlg.m_StrategyParam;
3030 if(!dlg.m_strLogMesage.IsEmpty())
3032 CString logmsg = dlg.m_strLogMesage;
3033 logmsg.Replace(_T("\""), _T("\\\""));
3034 args += _T(" -m \"") + logmsg + _T("\"");
3036 cmd.Format(_T("git.exe merge %s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
3038 CProgressDlg Prodlg;
3039 Prodlg.m_GitCmd = cmd;
3041 INT_PTR idCommit = -1;
3042 INT_PTR idRemoveBranch = -1;
3043 INT_PTR idPush = -1;
3044 INT_PTR idSVNDCommit = -1;
3045 INT_PTR idResolve = -1;
3046 BOOL hasGitSVN = CTGitPath(g_Git.m_CurrentDir).GetAdminDirMask() & ITEMIS_GITSVN;
3047 if (dlg.m_bNoCommit)
3048 idCommit = Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
3049 else
3051 if (dlg.m_bIsBranch)
3053 idRemoveBranch = Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
3054 idPush = Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
3057 if (hasGitSVN)
3058 idSVNDCommit = Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUSVNDCOMMIT)));
3061 Prodlg.m_PostCmdCallback = [&] ()
3063 if (Prodlg.m_GitStatus)
3065 Prodlg.m_PostCmdList.RemoveAll();
3067 CTGitPathList list;
3068 if (!g_Git.ListConflictFile(list) && !list.IsEmpty())
3070 // there are conflict files
3071 idResolve = Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROGRS_CMD_RESOLVE)));
3076 INT_PTR ret = Prodlg.DoModal();
3077 if (Prodlg.m_GitStatus && (ret == IDC_PROGRESS_BUTTON1 + idResolve))
3079 CTGitPathList pathlist;
3080 CTGitPathList selectedlist;
3081 pathlist.AddPath(g_Git.m_CurrentDir);
3082 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
3083 CString str;
3084 CAppUtils::Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
3086 else if (!Prodlg.m_GitStatus)
3088 if (ret == IDC_PROGRESS_BUTTON1 + idCommit)
3090 CString sLogMsg;
3091 CTGitPathList pathList;
3092 CTGitPathList selectedList;
3093 return Commit(_T(""), TRUE, sLogMsg, pathList, selectedList, true);
3095 else if (ret == IDC_PROGRESS_BUTTON1 + idRemoveBranch)
3097 CString msg;
3098 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
3099 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
3101 CString cmd, out;
3102 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
3103 if (g_Git.Run(cmd, &out, CP_UTF8))
3104 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
3107 else if (ret == IDC_PROGRESS_BUTTON1 + idPush)
3108 CAppUtils::Push();
3109 else if (ret == IDC_PROGRESS_BUTTON1 + idSVNDCommit)
3110 CAppUtils::SVNDCommit();
3113 return !Prodlg.m_GitStatus;
3115 return false;
3118 BOOL CAppUtils::MergeAbort()
3120 CMergeAbortDlg dlg;
3121 if (dlg.DoModal() == IDOK)
3123 CString cmd;
3124 CString type;
3125 switch (dlg.m_ResetType)
3127 case 0:
3128 type = _T("--mixed");
3129 break;
3130 case 1:
3131 type = _T("--hard");
3132 break;
3133 default:
3134 dlg.m_ResetType = 0;
3135 type = _T("--mixed");
3136 break;
3138 cmd.Format(_T("git.exe reset %s HEAD --"), type);
3140 while (true)
3142 CProgressDlg progress;
3143 progress.m_GitCmd = cmd;
3145 CTGitPath gitPath = g_Git.m_CurrentDir;
3146 if (gitPath.HasSubmodules() && dlg.m_ResetType == 1)
3147 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
3149 progress.m_PostFailCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
3151 INT_PTR ret;
3152 if (g_Git.UsingLibGit2(CGit::GIT_CMD_RESET))
3154 CGitProgressDlg gitdlg;
3155 ResetProgressCommand resetProgressCommand;
3156 gitdlg.SetCommand(&resetProgressCommand);
3157 resetProgressCommand.SetRevision(_T("HEAD"));
3158 resetProgressCommand.SetResetType(dlg.m_ResetType + 1);
3159 ret = gitdlg.DoModal();
3161 else
3162 ret = progress.DoModal();
3164 if (progress.m_GitStatus == 0 && gitPath.HasSubmodules() && dlg.m_ResetType == 1 && ret == IDC_PROGRESS_BUTTON1)
3166 CString sCmd;
3167 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3169 CCommonAppUtils::RunTortoiseGitProc(sCmd);
3170 return TRUE;
3172 else if (progress.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
3173 continue; // retry
3174 else if (ret == IDOK)
3175 return TRUE;
3176 else
3177 break;
3180 return FALSE;
3183 void CAppUtils::EditNote(GitRev *rev)
3185 if (!CheckUserData())
3186 return;
3188 CInputDlg dlg;
3189 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3190 dlg.m_sInputText = rev->m_Notes;
3191 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
3192 //dlg.m_pProjectProperties = &m_ProjectProperties;
3193 dlg.m_bUseLogWidth = true;
3194 if(dlg.DoModal() == IDOK)
3196 CString cmd,output;
3197 cmd=_T("notes add -f -F \"");
3199 CString tempfile=::GetTempFile();
3200 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
3201 cmd += tempfile;
3202 cmd += _T("\" ");
3203 cmd += rev->m_CommitHash.ToString();
3207 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
3209 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3212 else
3214 rev->m_Notes = dlg.m_sInputText;
3216 }catch(...)
3218 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
3220 ::DeleteFile(tempfile);
3225 int CAppUtils::GetMsysgitVersion()
3227 if (g_Git.ms_LastMsysGitVersion)
3228 return g_Git.ms_LastMsysGitVersion;
3230 CString cmd;
3231 CString versiondebug;
3232 CString version;
3234 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3235 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3237 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
3239 __int64 time=0;
3240 if (!g_Git.GetFileModifyTime(gitpath, &time))
3242 if((DWORD)time == regTime)
3244 g_Git.ms_LastMsysGitVersion = regVersion;
3245 return regVersion;
3249 CString err;
3250 cmd = _T("git.exe --version");
3251 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
3253 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);
3254 return -1;
3257 int start=0;
3258 int ver = 0;
3260 versiondebug = version;
3264 CString str=version.Tokenize(_T("."), start);
3265 int space = str.ReverseFind(_T(' '));
3266 str = str.Mid(space+1,start);
3267 ver = _ttol(str);
3268 ver <<=24;
3270 version = version.Mid(start);
3271 start = 0;
3273 str = version.Tokenize(_T("."), start);
3275 ver |= (_ttol(str) & 0xFF) << 16;
3277 str = version.Tokenize(_T("."), start);
3278 ver |= (_ttol(str) & 0xFF) << 8;
3280 str = version.Tokenize(_T("."), start);
3281 ver |= (_ttol(str) & 0xFF);
3283 catch(...)
3285 if (!ver)
3287 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3288 return -1;
3292 regTime = time&0xFFFFFFFF;
3293 regVersion = ver;
3294 g_Git.ms_LastMsysGitVersion = ver;
3296 return ver;
3299 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3301 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3303 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3305 if (hShell.IsValid()) {
3306 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3307 if (pfnSHGPSFW) {
3308 IPropertyStore *pps;
3309 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3310 if (SUCCEEDED(hr)) {
3311 PROPVARIANT var;
3312 var.vt = VT_BOOL;
3313 var.boolVal = VARIANT_TRUE;
3314 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3315 pps->Release();
3321 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3323 ASSERT(dialogname.GetLength() < 70);
3324 ASSERT(urlorpath.GetLength() < MAX_PATH);
3325 WCHAR pathbuf[MAX_PATH] = {0};
3327 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3329 wcscat_s(pathbuf, L" - ");
3330 wcscat_s(pathbuf, dialogname);
3331 wcscat_s(pathbuf, L" - ");
3332 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3333 SetWindowText(hWnd, pathbuf);
3336 bool CAppUtils::BisectStart(CString lastGood, CString firstBad)
3338 if (!g_Git.CheckCleanWorkTree())
3340 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3342 CSysProgressDlg sysProgressDlg;
3343 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3344 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3345 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3346 sysProgressDlg.SetShowProgressBar(false);
3347 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3348 sysProgressDlg.ShowModeless((HWND)NULL, true);
3350 CString cmd, out;
3351 cmd = _T("git.exe stash");
3352 if (g_Git.Run(cmd, &out, CP_UTF8))
3354 sysProgressDlg.Stop();
3355 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3356 return false;
3358 sysProgressDlg.Stop();
3360 else
3361 return false;
3364 CBisectStartDlg bisectStartDlg;
3366 if (!lastGood.IsEmpty())
3367 bisectStartDlg.m_sLastGood = lastGood;
3368 if (!firstBad.IsEmpty())
3369 bisectStartDlg.m_sFirstBad = firstBad;
3371 if (bisectStartDlg.DoModal() == IDOK)
3373 CProgressDlg progress;
3374 theApp.m_pMainWnd = &progress;
3375 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3376 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3377 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3379 CTGitPath path(g_Git.m_CurrentDir);
3381 if (path.HasSubmodules())
3382 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
3384 INT_PTR ret = progress.DoModal();
3385 if (path.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
3387 CString sCmd;
3388 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3390 CAppUtils::RunTortoiseGitProc(sCmd);
3391 return true;
3393 else if (ret == IDOK)
3394 return true;
3397 return false;
3400 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3402 CUserPassword dlg;
3403 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3404 if (username_from_url)
3405 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3407 CStringA username, password;
3408 if (dlg.DoModal() == IDOK)
3410 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3411 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3412 return git_cred_userpass_plaintext_new(out, username, password);
3414 return -1;
3417 void CAppUtils::ExploreTo(HWND hwnd, CString path)
3419 if (PathFileExists(path))
3421 ITEMIDLIST __unaligned * pidl = ILCreateFromPath(path);
3422 if (pidl)
3424 SHOpenFolderAndSelectItems(pidl, 0, 0, 0);
3425 ILFree(pidl);
3427 return;
3429 // if filepath does not exist any more, navigate to closest matching folder
3432 int pos = path.ReverseFind(_T('\\'));
3433 if (pos <= 3)
3434 break;
3435 path = path.Left(pos);
3436 } while (!PathFileExists(path));
3437 ShellExecute(hwnd, _T("explore"), path, nullptr, nullptr, SW_SHOW);