Moved bisect start logic to AppUtils
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobf886a996694e9b35e9dfce9adfab0d82e9d8f8f2
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - TortoiseGit
4 // Copyright (C) 2003-2011 - 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 "resource.h"
22 #include "TortoiseProc.h"
23 #include "PathUtils.h"
24 #include "AppUtils.h"
25 //#include "GitProperties.h"
26 #include "StringUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "TGitPath.h"
30 #include "Git.h"
31 //#include "RepositoryBrowser.h"
32 //#include "BrowseFolder.h"
33 #include "UnicodeUtils.h"
34 #include "ExportDlg.h"
35 #include "ProgressDlg.h"
36 #include "GitAdminDir.h"
37 #include "ProgressDlg.h"
38 #include "BrowseFolder.h"
39 #include "DirFileEnum.h"
40 #include "MessageBox.h"
41 #include "GitStatus.h"
42 #include "CreateBranchTagDlg.h"
43 #include "GitSwitchDlg.h"
44 #include "ResetDlg.h"
45 #include "DeleteConflictDlg.h"
46 #include "ChangedDlg.h"
47 #include "SendMailDlg.h"
48 #include "GITProgressDlg.h"
49 #include "PushDlg.h"
50 #include "CommitDlg.h"
51 #include "MergeDlg.h"
52 #include "hooks.h"
53 #include "..\Settings\Settings.h"
54 #include "InputDlg.h"
55 #include "SVNDCommitDlg.h"
56 #include "requestpulldlg.h"
57 #include "PullFetchDlg.h"
58 #include "RebaseDlg.h"
59 #include "PropKey.h"
60 #include "StashSave.h"
61 #include "IgnoreDlg.h"
62 #include "FormatMessageWrapper.h"
63 #include "SmartHandle.h"
64 #include "BisectStartDlg.h"
66 CAppUtils::CAppUtils(void)
70 CAppUtils::~CAppUtils(void)
74 bool CAppUtils::StashSave()
76 CStashSaveDlg dlg;
78 if (dlg.DoModal() == IDOK)
80 CString cmd, out;
81 cmd = _T("git.exe stash save");
83 if (dlg.m_bIncludeUntracked && CAppUtils::GetMsysgitVersion() >= 0x01070700)
84 cmd += _T(" --include-untracked");
86 if (!dlg.m_sMessage.IsEmpty())
88 CString message = dlg.m_sMessage;
89 message.Replace(_T("\""), _T("\"\""));
90 cmd += _T(" \"") + message + _T("\"");
93 if (g_Git.Run(cmd, &out, CP_UTF8))
95 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
97 else
99 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHSUCCESS)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
100 return true;
103 return false;
106 int CAppUtils::StashApply(CString ref, bool showChanges /* true */)
108 CString cmd,out;
109 cmd = _T("git.exe stash apply ");
110 if (ref.Find(_T("refs/")) == 0)
111 ref = ref.Mid(5);
112 if (ref.Find(_T("stash{")) == 0)
113 ref = _T("stash@") + ref.Mid(5);
114 cmd += ref;
116 int ret = g_Git.Run(cmd, &out, CP_UTF8);
117 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
118 if (ret && !(ret == 1 && hasConflicts))
120 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
122 else
124 CString message;
125 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
126 if (hasConflicts)
127 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
128 if (showChanges)
130 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
131 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
133 CChangedDlg dlg;
134 dlg.m_pathList.AddPath(CTGitPath());
135 dlg.DoModal();
137 return 0;
139 else
141 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
142 return 0;
145 return -1;
148 int CAppUtils::StashPop(bool showChanges /* true */)
150 CString cmd,out;
151 cmd=_T("git.exe stash pop ");
153 int ret = g_Git.Run(cmd, &out, CP_UTF8);
154 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
155 if (ret && !(ret == 1 && hasConflicts))
157 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
159 else
161 CString message;
162 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
163 if (hasConflicts)
164 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
165 if (showChanges)
167 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
168 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
170 CChangedDlg dlg;
171 dlg.m_pathList.AddPath(CTGitPath());
172 dlg.DoModal();
174 return 0;
176 else
178 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
179 return 0;
182 return -1;
185 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
187 #if 0
188 GitProperties props(file, GitRev::REV_WC, false);
189 for (int i = 0; i < props.GetCount(); ++i)
191 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
193 mimetype = props.GetItemValue(i).c_str();
194 return true;
197 #endif
198 return false;
201 BOOL CAppUtils::StartExtMerge(
202 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
203 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
206 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
207 CString ext = mergedfile.GetFileExtension();
208 CString com = regCom;
209 bool bInternal = false;
211 CString mimetype;
212 if (ext != "")
214 // is there an extension specific merge tool?
215 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
216 if (CString(mergetool) != "")
218 com = mergetool;
221 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
223 // is there a mime type specific merge tool?
224 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
225 if (CString(mergetool) != "")
227 com = mergetool;
231 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
233 // use TortoiseMerge
234 bInternal = true;
235 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
236 com = tortoiseMergePath;
237 if (com.IsEmpty())
239 com = CPathUtils::GetAppDirectory();
240 com += _T("TortoiseMerge.exe");
242 com = _T("\"") + com + _T("\"");
243 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
244 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
246 // check if the params are set. If not, just add the files to the command line
247 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
249 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
250 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
251 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
252 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
254 if (basefile.IsEmpty())
256 com.Replace(_T("/base:%base"), _T(""));
257 com.Replace(_T("%base"), _T(""));
259 else
260 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
261 if (theirfile.IsEmpty())
263 com.Replace(_T("/theirs:%theirs"), _T(""));
264 com.Replace(_T("%theirs"), _T(""));
266 else
267 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
268 if (yourfile.IsEmpty())
270 com.Replace(_T("/mine:%mine"), _T(""));
271 com.Replace(_T("%mine"), _T(""));
273 else
274 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
275 if (mergedfile.IsEmpty())
277 com.Replace(_T("/merged:%merged"), _T(""));
278 com.Replace(_T("%merged"), _T(""));
280 else
281 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
282 if (basename.IsEmpty())
284 if (basefile.IsEmpty())
286 com.Replace(_T("/basename:%bname"), _T(""));
287 com.Replace(_T("%bname"), _T(""));
289 else
291 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
294 else
295 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
296 if (theirname.IsEmpty())
298 if (theirfile.IsEmpty())
300 com.Replace(_T("/theirsname:%tname"), _T(""));
301 com.Replace(_T("%tname"), _T(""));
303 else
305 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
308 else
309 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
310 if (yourname.IsEmpty())
312 if (yourfile.IsEmpty())
314 com.Replace(_T("/minename:%yname"), _T(""));
315 com.Replace(_T("%yname"), _T(""));
317 else
319 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
322 else
323 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
324 if (mergedname.IsEmpty())
326 if (mergedfile.IsEmpty())
328 com.Replace(_T("/mergedname:%mname"), _T(""));
329 com.Replace(_T("%mname"), _T(""));
331 else
333 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
336 else
337 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
339 if ((bReadOnly)&&(bInternal))
340 com += _T(" /readonly");
342 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
344 return FALSE;
347 return TRUE;
350 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
352 CString viewer;
353 // use TortoiseMerge
354 viewer = CPathUtils::GetAppDirectory();
355 viewer += _T("TortoiseMerge.exe");
357 viewer = _T("\"") + viewer + _T("\"");
358 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
359 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
360 if (bReversed)
361 viewer += _T(" /reversedpatch");
362 if (!sOriginalDescription.IsEmpty())
363 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
364 if (!sPatchedDescription.IsEmpty())
365 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
366 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
368 return FALSE;
370 return TRUE;
373 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
375 // Is there a mime type specific diff tool?
376 CString mimetype;
377 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
379 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
380 if (!difftool.IsEmpty())
381 return difftool;
384 // Is there an extension specific diff tool?
385 CString ext = file2.GetFileExtension().MakeLower();
386 if (!ext.IsEmpty())
388 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
389 if (!difftool.IsEmpty())
390 return difftool;
391 // Maybe we should use TortoiseIDiff?
392 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
393 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
394 (ext == _T(".png")) || (ext == _T(".ico")) ||
395 (ext == _T(".dib")) || (ext == _T(".emf")))
397 return
398 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
399 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
403 // Finally, pick a generic external diff tool
404 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
405 return difftool;
408 bool CAppUtils::StartExtDiff(
409 const CString& file1, const CString& file2,
410 const CString& sName1, const CString& sName2,
411 const DiffFlags& flags)
413 CString viewer;
415 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
416 if (!flags.bBlame || !(DWORD)blamediff)
418 viewer = PickDiffTool(file1, file2);
419 // If registry entry for a diff program is commented out, use TortoiseMerge.
420 bool bCommentedOut = viewer.Left(1) == _T("#");
421 if (flags.bAlternativeTool)
423 // Invert external vs. internal diff tool selection.
424 if (bCommentedOut)
425 viewer.Delete(0); // uncomment
426 else
427 viewer = "";
429 else if (bCommentedOut)
430 viewer = "";
433 bool bInternal = viewer.IsEmpty();
434 if (bInternal)
436 viewer =
437 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
438 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
439 if (flags.bBlame)
440 viewer += _T(" /blame");
442 // check if the params are set. If not, just add the files to the command line
443 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
445 viewer += _T(" \"")+file1+_T("\"");
446 viewer += _T(" \"")+file2+_T("\"");
448 if (viewer.Find(_T("%base")) >= 0)
450 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
452 if (viewer.Find(_T("%mine")) >= 0)
454 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
457 if (sName1.IsEmpty())
458 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
459 else
460 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
462 if (sName2.IsEmpty())
463 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
464 else
465 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
467 if (flags.bReadOnly && bInternal)
468 viewer += _T(" /readonly");
470 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
473 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
475 CString viewer;
476 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
477 viewer = v;
478 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
480 // use TortoiseUDiff
481 viewer = CPathUtils::GetAppDirectory();
482 viewer += _T("TortoiseUDiff.exe");
483 // enquote the path to TortoiseUDiff
484 viewer = _T("\"") + viewer + _T("\"");
485 // add the params
486 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
489 if (viewer.Find(_T("%1"))>=0)
491 if (viewer.Find(_T("\"%1\"")) >= 0)
492 viewer.Replace(_T("%1"), patchfile);
493 else
494 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
496 else
497 viewer += _T(" \"") + patchfile + _T("\"");
498 if (viewer.Find(_T("%title")) >= 0)
500 viewer.Replace(_T("%title"), title);
503 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
505 return FALSE;
507 return TRUE;
510 BOOL CAppUtils::StartTextViewer(CString file)
512 CString viewer;
513 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
514 viewer = txt;
515 viewer = viewer + _T("\\Shell\\Open\\Command\\");
516 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
517 viewer = txtexe;
519 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
520 TCHAR * buf = new TCHAR[len+1];
521 ExpandEnvironmentStrings(viewer, buf, len);
522 viewer = buf;
523 delete [] buf;
524 len = ExpandEnvironmentStrings(file, NULL, 0);
525 buf = new TCHAR[len+1];
526 ExpandEnvironmentStrings(file, buf, len);
527 file = buf;
528 delete [] buf;
529 file = _T("\"")+file+_T("\"");
530 if (viewer.IsEmpty())
532 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
534 if (viewer.Find(_T("\"%1\"")) >= 0)
536 viewer.Replace(_T("\"%1\""), file);
538 else if (viewer.Find(_T("%1")) >= 0)
540 viewer.Replace(_T("%1"), file);
542 else
544 viewer += _T(" ");
545 viewer += file;
548 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
550 return FALSE;
552 return TRUE;
555 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
557 DWORD length = 0;
558 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
559 if (!hFile)
560 return TRUE;
561 length = ::GetFileSize(hFile, NULL);
562 if (length < 4)
563 return TRUE;
564 return FALSE;
568 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
570 LOGFONT logFont;
571 HDC hScreenDC = ::GetDC(NULL);
572 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
573 ::ReleaseDC(NULL, hScreenDC);
574 logFont.lfWidth = 0;
575 logFont.lfEscapement = 0;
576 logFont.lfOrientation = 0;
577 logFont.lfWeight = FW_NORMAL;
578 logFont.lfItalic = 0;
579 logFont.lfUnderline = 0;
580 logFont.lfStrikeOut = 0;
581 logFont.lfCharSet = DEFAULT_CHARSET;
582 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
583 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
584 logFont.lfQuality = DRAFT_QUALITY;
585 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
586 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
587 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
590 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
592 CString key,remote;
593 CString cmd,out;
594 if( pRemote == NULL)
596 remote=_T("origin");
598 else
600 remote=*pRemote;
602 if(keyfile == NULL)
604 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
605 key = g_Git.GetConfigValue(cmd);
606 int start=0;
607 key = key.Tokenize(_T("\n"),start);
609 else
610 key=*keyfile;
612 if(key.IsEmpty())
613 return false;
615 CString proc=CPathUtils::GetAppDirectory();
616 proc += _T("pageant.exe \"");
617 proc += key;
618 proc += _T("\"");
620 CString tempfile = GetTempFile();
621 ::DeleteFile(tempfile);
623 proc += _T(" -c \"");
624 proc += CPathUtils::GetAppDirectory();
625 proc += _T("touch.exe\"");
626 proc += _T(" \"");
627 proc += tempfile;
628 proc += _T("\"");
630 CString appDir = CPathUtils::GetAppDirectory();
631 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
632 if(!b)
633 return b;
635 int i=0;
636 while(!::PathFileExists(tempfile))
638 Sleep(100);
639 i++;
640 if(i>10*60*5)
641 break; //timeout 5 minutes
644 if( i== 10*60*5)
646 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
648 ::DeleteFile(tempfile);
649 return true;
651 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
653 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
654 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
655 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
658 CString sCmd;
659 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
661 LaunchApplication(sCmd, NULL, false);
662 return true;
664 bool CAppUtils::LaunchRemoteSetting()
666 CTGitPath path(g_Git.m_CurrentDir);
667 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
668 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
669 //dlg.SetTreeWidth(220);
670 dlg.m_DefaultPage = _T("gitremote");
672 dlg.DoModal();
673 dlg.HandleRestart();
674 return true;
677 * Launch the external blame viewer
679 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
681 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
682 viewer += _T("TortoiseGitBlame.exe");
683 viewer += _T("\" \"") + sBlameFile + _T("\"");
684 //viewer += _T(" \"") + sLogFile + _T("\"");
685 //viewer += _T(" \"") + sOriginalFile + _T("\"");
686 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
687 viewer += CString(_T(" /rev:"))+Rev;
688 viewer += _T(" ")+sParams;
690 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
693 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
695 CString sText;
696 if (pWnd == NULL)
697 return false;
698 bool bStyled = false;
699 pWnd->GetWindowText(sText);
700 // the rich edit control doesn't count the CR char!
701 // to be exact: CRLF is treated as one char.
702 sText.Remove('\r');
704 // style each line separately
705 int offset = 0;
706 int nNewlinePos;
709 nNewlinePos = sText.Find('\n', offset);
710 CString sLine = sText.Mid(offset);
711 if (nNewlinePos>=0)
712 sLine = sLine.Left(nNewlinePos-offset);
713 int start = 0;
714 int end = 0;
715 while (FindStyleChars(sLine, '*', start, end))
717 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
718 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
719 CHARFORMAT2 format;
720 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
721 format.cbSize = sizeof(CHARFORMAT2);
722 format.dwMask = CFM_BOLD;
723 format.dwEffects = CFE_BOLD;
724 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
725 bStyled = true;
726 start = end;
728 start = 0;
729 end = 0;
730 while (FindStyleChars(sLine, '^', start, end))
732 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
733 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
734 CHARFORMAT2 format;
735 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
736 format.cbSize = sizeof(CHARFORMAT2);
737 format.dwMask = CFM_ITALIC;
738 format.dwEffects = CFE_ITALIC;
739 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
740 bStyled = true;
741 start = end;
743 start = 0;
744 end = 0;
745 while (FindStyleChars(sLine, '_', start, end))
747 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
748 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
749 CHARFORMAT2 format;
750 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
751 format.cbSize = sizeof(CHARFORMAT2);
752 format.dwMask = CFM_UNDERLINE;
753 format.dwEffects = CFE_UNDERLINE;
754 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
755 bStyled = true;
756 start = end;
758 offset = nNewlinePos+1;
759 } while(nNewlinePos>=0);
760 return bStyled;
763 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
765 int i=start;
766 bool bFoundMarker = false;
767 // find a starting marker
768 while (sText[i] != 0)
770 if (sText[i] == stylechar)
772 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
773 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
775 start = i+1;
776 i++;
777 bFoundMarker = true;
778 break;
781 i++;
783 if (!bFoundMarker)
784 return false;
785 // find ending marker
786 bFoundMarker = false;
787 while (sText[i] != 0)
789 if (sText[i] == stylechar)
791 if ((IsCharAlphaNumeric(sText[i-1])) &&
792 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
794 end = i;
795 i++;
796 bFoundMarker = true;
797 break;
800 i++;
802 return bFoundMarker;
805 CString CAppUtils::GetProjectNameFromURL(CString url)
807 CString name;
808 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
809 (name.CompareNoCase(_T("tags"))==0) ||
810 (name.CompareNoCase(_T("trunk"))==0))
812 name = url.Mid(url.ReverseFind('/')+1);
813 url = url.Left(url.ReverseFind('/'));
815 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
817 // a name of svn or svnroot indicates that it's not really the project name. In that
818 // case, we try the first part of the URL
819 // of course, this won't work in all cases (but it works for Google project hosting)
820 url.Replace(_T("http://"), _T(""));
821 url.Replace(_T("https://"), _T(""));
822 url.Replace(_T("svn://"), _T(""));
823 url.Replace(_T("svn+ssh://"), _T(""));
824 url.TrimLeft(_T("/"));
825 name = url.Left(url.Find('.'));
827 return name;
830 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
831 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
832 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
833 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
836 CString tempfile=GetTempFile();
837 CString cmd;
838 if(rev2 == GitRev::GetWorkingCopy())
840 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
842 else if (rev1 == GitRev::GetWorkingCopy())
844 cmd.Format(_T("git.exe diff -R --stat -p %s "), rev2);
846 else
848 CString merge;
849 if(bMerge)
850 merge = _T("-c");
852 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
855 if( !url1.IsEmpty() )
857 cmd += _T(" -- \"");
858 cmd += url1.GetGitPathString();
859 cmd += _T("\" ");
861 g_Git.RunLogFile(cmd,tempfile);
862 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
865 #if 0
866 CString sCmd;
867 sCmd.Format(_T("%s /command:showcompare /unified"),
868 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
869 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
870 if (rev1.IsValid())
871 sCmd += _T(" /revision1:") + rev1.ToString();
872 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
873 if (rev2.IsValid())
874 sCmd += _T(" /revision2:") + rev2.ToString();
875 if (peg.IsValid())
876 sCmd += _T(" /pegrevision:") + peg.ToString();
877 if (headpeg.IsValid())
878 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
880 if (bAlternateDiff)
881 sCmd += _T(" /alternatediff");
883 if (bIgnoreAncestry)
884 sCmd += _T(" /ignoreancestry");
886 if (hWnd)
888 sCmd += _T(" /hwnd:");
889 TCHAR buf[30];
890 _stprintf_s(buf, 30, _T("%d"), hWnd);
891 sCmd += buf;
894 return CAppUtils::LaunchApplication(sCmd, NULL, false);
895 #endif
896 return TRUE;
900 bool CAppUtils::Export(CString *BashHash)
902 bool bRet = false;
904 // ask from where the export has to be done
905 CExportDlg dlg;
906 if(BashHash)
907 dlg.m_Revision=*BashHash;
909 if (dlg.DoModal() == IDOK)
911 CString cmd;
912 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
913 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
915 CProgressDlg pro;
916 pro.m_GitCmd=cmd;
917 pro.DoModal();
918 return TRUE;
920 return bRet;
923 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
925 CCreateBranchTagDlg dlg;
926 dlg.m_bIsTag=IsTag;
927 dlg.m_bSwitch=switch_new_brach;
929 if(CommitHash)
930 dlg.m_initialRefName = *CommitHash;
932 if(dlg.DoModal()==IDOK)
934 CString cmd;
935 CString force;
936 CString track;
937 if(dlg.m_bTrack == TRUE)
938 track=_T(" --track ");
939 else if(dlg.m_bTrack == FALSE)
940 track=_T(" --no-track");
942 if(dlg.m_bForce)
943 force=_T(" -f ");
945 if(IsTag)
947 CString sign;
948 if(dlg.m_bSign)
949 sign=_T("-s");
951 cmd.Format(_T("git.exe tag %s %s %s %s"),
952 force,
953 sign,
954 dlg.m_BranchTagName,
955 g_Git.FixBranchName(dlg.m_VersionName)
958 CString tempfile=::GetTempFile();
959 if(!dlg.m_Message.Trim().IsEmpty())
961 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
962 cmd += _T(" -F ")+tempfile;
965 else
967 cmd.Format(_T("git.exe branch %s %s %s %s"),
968 track,
969 force,
970 dlg.m_BranchTagName,
971 g_Git.FixBranchName(dlg.m_VersionName)
974 CString out;
975 if(g_Git.Run(cmd,&out,CP_UTF8))
977 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
978 return FALSE;
980 if( !IsTag && dlg.m_bSwitch )
982 // it is a new branch and the user has requested to switch to it
983 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
984 g_Git.Run(cmd,&out,CP_UTF8);
985 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
988 return TRUE;
990 return FALSE;
993 bool CAppUtils::Switch(CString initialRefName, bool autoclose)
995 CGitSwitchDlg dlg;
996 if(!initialRefName.IsEmpty())
997 dlg.m_initialRefName = initialRefName;
999 if (dlg.DoModal() == IDOK)
1001 CString branch;
1002 if (dlg.m_bBranch)
1003 branch = dlg.m_NewBranch;
1005 // if refs/heads/ is not stripped, checkout will detach HEAD
1006 // checkout prefers branches on name clashes (with tags)
1007 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1008 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1010 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1012 return FALSE;
1015 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1017 CString cmd;
1018 CString track;
1019 CString force;
1020 CString branch;
1022 if(!sNewBranch.IsEmpty()){
1023 if (bBranchOverride)
1025 branch.Format(_T("-B %s"), sNewBranch);
1027 else
1029 branch.Format(_T("-b %s"), sNewBranch);
1031 if (bTrack)
1032 track = _T("--track");
1034 if (bForce)
1035 force = _T("-f");
1037 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1038 force,
1039 track,
1040 branch,
1041 g_Git.FixBranchName(ref));
1043 CProgressDlg progress;
1044 progress.m_bAutoCloseOnSuccess = autoClose;
1045 progress.m_GitCmd = cmd;
1047 CTGitPath gitPath = g_Git.m_CurrentDir;
1048 if (gitPath.HasSubmodules())
1049 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1051 INT_PTR ret = progress.DoModal();
1052 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1054 CString sCmd;
1055 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1057 RunTortoiseProc(sCmd);
1058 return TRUE;
1060 else if (ret == IDOK)
1061 return TRUE;
1063 return FALSE;
1066 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1068 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1070 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1071 return false;
1074 if (file.GetLength() > 0)
1076 file.Seek(file.GetLength() - 1, 0);
1077 auto_buffer<TCHAR> buf(1);
1078 file.Read(buf, 1);
1079 file.SeekToEnd();
1080 if (buf[0] != _T('\n'))
1081 file.WriteString(_T("\n"));
1083 else
1084 file.SeekToEnd();
1086 return true;
1089 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1091 CIgnoreDlg ignoreDlg;
1092 if (ignoreDlg.DoModal() == IDOK)
1094 CString ignorefile;
1095 ignorefile = g_Git.m_CurrentDir + _T("\\");
1097 switch (ignoreDlg.m_IgnoreFile)
1099 case 0:
1100 ignorefile += _T(".gitignore");
1101 break;
1102 case 2:
1103 ignorefile += _T(".git/info/exclude");
1104 break;
1107 CStdioFile file;
1110 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1111 return false;
1113 for (int i = 0; i < path.GetCount(); i++)
1115 if (ignoreDlg.m_IgnoreFile == 1)
1117 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1118 if (!OpenIgnoreFile(file, ignorefile))
1119 return false;
1122 CString ignorePattern;
1123 if (ignoreDlg.m_IgnoreType == 0)
1125 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1126 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1128 ignorePattern += _T("/");
1130 if (IsMask)
1132 ignorePattern += _T("*") + path[i].GetFileExtension();
1134 else
1136 ignorePattern += path[i].GetFileOrDirectoryName();
1139 // escape [ and ] so that files get ignored correctly
1140 ignorePattern.Replace(_T("["), _T("\\["));
1141 ignorePattern.Replace(_T("]"), _T("\\]"));
1143 ignorePattern += _T("\n");
1144 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1145 file.Write(ignorePatternA.GetBuffer(), ignorePatternA.GetLength());
1146 ignorePatternA.ReleaseBuffer();
1148 if (ignoreDlg.m_IgnoreFile == 1)
1149 file.Close();
1152 if (ignoreDlg.m_IgnoreFile != 1)
1153 file.Close();
1155 catch(...)
1157 file.Abort();
1158 return false;
1161 return true;
1163 return false;
1167 bool CAppUtils::GitReset(CString *CommitHash,int type)
1169 CResetDlg dlg;
1170 dlg.m_ResetType=type;
1171 dlg.m_ResetToVersion=*CommitHash;
1172 if (dlg.DoModal() == IDOK)
1174 CString cmd;
1175 CString type;
1176 switch(dlg.m_ResetType)
1178 case 0:
1179 type=_T("--soft");
1180 break;
1181 case 1:
1182 type=_T("--mixed");
1183 break;
1184 case 2:
1185 type=_T("--hard");
1186 break;
1187 default:
1188 type=_T("--mixed");
1189 break;
1191 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1193 CProgressDlg progress;
1194 progress.m_GitCmd=cmd;
1196 CTGitPath gitPath = g_Git.m_CurrentDir;
1197 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1198 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1200 INT_PTR ret = progress.DoModal();
1201 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1203 CString sCmd;
1204 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1206 RunTortoiseProc(sCmd);
1207 return TRUE;
1209 else if (ret == IDOK)
1210 return TRUE;
1213 return FALSE;
1216 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1218 if(mode == FALSE)
1220 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1221 return;
1223 if(base)
1225 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1226 return;
1228 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1229 return;
1232 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1234 CString tempmergefile;
1237 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1238 CFile::Remove(tempmergefile);
1239 }catch(...)
1245 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1246 CFile::Remove(tempmergefile);
1247 }catch(...)
1253 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1254 CFile::Remove(tempmergefile);
1255 }catch(...)
1259 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1261 CString file;
1262 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1264 return file;
1267 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1269 bool bRet = false;
1271 CTGitPath merge=path;
1272 CTGitPath directory = merge.GetDirectory();
1274 // we have the conflicted file (%merged)
1275 // now look for the other required files
1276 //GitStatus stat;
1277 //stat.GetStatus(merge);
1278 //if (stat.status == NULL)
1279 // return false;
1281 BYTE_VECTOR vector;
1283 CString cmd;
1284 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1286 if (g_Git.Run(cmd, &vector))
1288 return FALSE;
1291 CTGitPathList list;
1292 list.ParserFromLsFile(vector);
1294 if(list.GetCount() == 0)
1295 return FALSE;
1297 CTGitPath theirs;
1298 CTGitPath mine;
1299 CTGitPath base;
1301 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1302 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1303 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1305 CString format;
1307 //format=_T("git.exe cat-file blob \":%d:%s\"");
1308 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1309 CFile tempfile;
1310 //create a empty file, incase stage is not three
1311 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1312 tempfile.Close();
1313 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1314 tempfile.Close();
1315 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1316 tempfile.Close();
1318 bool b_base=false, b_local=false, b_remote=false;
1320 for(int i=0;i<list.GetCount();i++)
1322 CString cmd;
1323 CString outfile;
1324 cmd.Empty();
1325 outfile.Empty();
1327 if( list[i].m_Stage == 1)
1329 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1330 b_base = true;
1331 outfile = base.GetWinPathString();
1334 if( list[i].m_Stage == 2 )
1336 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1337 b_local = true;
1338 outfile = mine.GetWinPathString();
1341 if( list[i].m_Stage == 3 )
1343 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1344 b_remote = true;
1345 outfile = theirs.GetWinPathString();
1347 CString output, err;
1348 if(!outfile.IsEmpty())
1349 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1351 CString file;
1352 int start =0 ;
1353 file = output.Tokenize(_T("\t"), start);
1354 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1356 else
1358 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1362 if(b_local && b_remote )
1364 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1365 if( revertTheirMy )
1366 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1367 else
1368 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1371 else
1373 CFile::Remove(mine.GetWinPathString());
1374 CFile::Remove(theirs.GetWinPathString());
1375 CFile::Remove(base.GetWinPathString());
1377 CDeleteConflictDlg dlg;
1378 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1379 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1380 dlg.m_bShowModifiedButton=b_base;
1381 dlg.m_File=merge.GetGitPathString();
1382 if(dlg.DoModal() == IDOK)
1384 CString cmd,out;
1385 if(dlg.m_bIsDelete)
1387 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1389 else
1390 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1392 if (g_Git.Run(cmd, &out, CP_UTF8))
1394 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1395 return FALSE;
1397 return TRUE;
1399 else
1400 return FALSE;
1403 #if 0
1404 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1405 base, theirs, mine, merge);
1406 #endif
1407 #if 0
1408 if (stat.status->text_status == svn_wc_status_conflicted)
1410 // we have a text conflict, use our merge tool to resolve the conflict
1412 CTSVNPath theirs(directory);
1413 CTSVNPath mine(directory);
1414 CTSVNPath base(directory);
1415 bool bConflictData = false;
1417 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1419 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1420 bConflictData = true;
1422 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1424 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1425 bConflictData = true;
1427 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1429 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1430 bConflictData = true;
1432 else
1434 mine = merge;
1436 if (bConflictData)
1437 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1438 base, theirs, mine, merge);
1441 if (stat.status->prop_status == svn_wc_status_conflicted)
1443 // we have a property conflict
1444 CTSVNPath prej(directory);
1445 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1447 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1448 // there's a problem: the prej file contains a _description_ of the conflict, and
1449 // that description string might be translated. That means we have no way of parsing
1450 // the file to find out the conflicting values.
1451 // The only thing we can do: show a dialog with the conflict description, then
1452 // let the user either accept the existing property or open the property edit dialog
1453 // to manually change the properties and values. And a button to mark the conflict as
1454 // resolved.
1455 CEditPropConflictDlg dlg;
1456 dlg.SetPrejFile(prej);
1457 dlg.SetConflictedItem(merge);
1458 bRet = (dlg.DoModal() != IDCANCEL);
1462 if (stat.status->tree_conflict)
1464 // we have a tree conflict
1465 SVNInfo info;
1466 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1467 if (pInfoData)
1469 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1471 CTSVNPath theirs(directory);
1472 CTSVNPath mine(directory);
1473 CTSVNPath base(directory);
1474 bool bConflictData = false;
1476 if (pInfoData->treeconflict_theirfile)
1478 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1479 bConflictData = true;
1481 if (pInfoData->treeconflict_basefile)
1483 base.AppendPathString(pInfoData->treeconflict_basefile);
1484 bConflictData = true;
1486 if (pInfoData->treeconflict_myfile)
1488 mine.AppendPathString(pInfoData->treeconflict_myfile);
1489 bConflictData = true;
1491 else
1493 mine = merge;
1495 if (bConflictData)
1496 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1497 base, theirs, mine, merge);
1499 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1501 CString sConflictAction;
1502 CString sConflictReason;
1503 CString sResolveTheirs;
1504 CString sResolveMine;
1505 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1506 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1508 if (pInfoData->treeconflict_nodekind == svn_node_file)
1510 switch (pInfoData->treeconflict_operation)
1512 case svn_wc_operation_update:
1513 switch (pInfoData->treeconflict_action)
1515 case svn_wc_conflict_action_edit:
1516 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1517 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1518 break;
1519 case svn_wc_conflict_action_add:
1520 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1521 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1522 break;
1523 case svn_wc_conflict_action_delete:
1524 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1525 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1526 break;
1528 break;
1529 case svn_wc_operation_switch:
1530 switch (pInfoData->treeconflict_action)
1532 case svn_wc_conflict_action_edit:
1533 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1534 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1535 break;
1536 case svn_wc_conflict_action_add:
1537 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1538 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1539 break;
1540 case svn_wc_conflict_action_delete:
1541 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1542 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1543 break;
1545 break;
1546 case svn_wc_operation_merge:
1547 switch (pInfoData->treeconflict_action)
1549 case svn_wc_conflict_action_edit:
1550 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1551 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1552 break;
1553 case svn_wc_conflict_action_add:
1554 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1555 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1556 break;
1557 case svn_wc_conflict_action_delete:
1558 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1559 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1560 break;
1562 break;
1565 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1567 switch (pInfoData->treeconflict_operation)
1569 case svn_wc_operation_update:
1570 switch (pInfoData->treeconflict_action)
1572 case svn_wc_conflict_action_edit:
1573 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1574 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1575 break;
1576 case svn_wc_conflict_action_add:
1577 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1578 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1579 break;
1580 case svn_wc_conflict_action_delete:
1581 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1582 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1583 break;
1585 break;
1586 case svn_wc_operation_switch:
1587 switch (pInfoData->treeconflict_action)
1589 case svn_wc_conflict_action_edit:
1590 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1591 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1592 break;
1593 case svn_wc_conflict_action_add:
1594 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1595 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1596 break;
1597 case svn_wc_conflict_action_delete:
1598 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1599 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1600 break;
1602 break;
1603 case svn_wc_operation_merge:
1604 switch (pInfoData->treeconflict_action)
1606 case svn_wc_conflict_action_edit:
1607 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1608 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1609 break;
1610 case svn_wc_conflict_action_add:
1611 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1612 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1613 break;
1614 case svn_wc_conflict_action_delete:
1615 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1616 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1617 break;
1619 break;
1623 UINT uReasonID = 0;
1624 switch (pInfoData->treeconflict_reason)
1626 case svn_wc_conflict_reason_edited:
1627 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1628 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1629 break;
1630 case svn_wc_conflict_reason_obstructed:
1631 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1632 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1633 break;
1634 case svn_wc_conflict_reason_deleted:
1635 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1636 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1637 break;
1638 case svn_wc_conflict_reason_added:
1639 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1640 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1641 break;
1642 case svn_wc_conflict_reason_missing:
1643 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1644 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1645 break;
1646 case svn_wc_conflict_reason_unversioned:
1647 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1648 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1649 break;
1651 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1653 CTreeConflictEditorDlg dlg;
1654 dlg.SetConflictInfoText(sConflictReason);
1655 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1656 dlg.SetPath(treeConflictPath);
1657 INT_PTR dlgRet = dlg.DoModal();
1658 bRet = (dlgRet != IDCANCEL);
1662 #endif
1663 return bRet;
1666 bool CAppUtils::IsSSHPutty()
1668 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1669 sshclient=sshclient.MakeLower();
1670 if(sshclient.Find(_T("plink.exe"),0)>=0)
1672 return true;
1674 return false;
1677 CString CAppUtils::GetClipboardLink()
1679 if (!OpenClipboard(NULL))
1680 return CString();
1682 CString sClipboardText;
1683 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1684 if (hglb)
1686 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1687 sClipboardText = CString(lpstr);
1688 GlobalUnlock(hglb);
1690 hglb = GetClipboardData(CF_UNICODETEXT);
1691 if (hglb)
1693 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1694 sClipboardText = lpstr;
1695 GlobalUnlock(hglb);
1697 CloseClipboard();
1699 if(!sClipboardText.IsEmpty())
1701 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1702 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1704 if(sClipboardText.Find( _T("http://")) == 0)
1705 return sClipboardText;
1707 if(sClipboardText.Find( _T("https://")) == 0)
1708 return sClipboardText;
1710 if(sClipboardText.Find( _T("git://")) == 0)
1711 return sClipboardText;
1713 if(sClipboardText.Find( _T("ssh://")) == 0)
1714 return sClipboardText;
1716 if(sClipboardText.GetLength()>=2)
1717 if( sClipboardText[1] == _T(':') )
1718 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1719 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1720 return sClipboardText;
1723 return CString(_T(""));
1726 CString CAppUtils::ChooseRepository(CString *path)
1728 CBrowseFolder browseFolder;
1729 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1731 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1732 CString strCloneDirectory;
1733 if(path)
1734 strCloneDirectory=*path;
1735 else
1737 strCloneDirectory = regLastResopitory;
1740 CString title;
1741 title.LoadString(IDS_CHOOSE_REPOSITORY);
1743 browseFolder.SetInfo(title);
1745 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1747 regLastResopitory = strCloneDirectory;
1748 return strCloneDirectory;
1750 else
1752 return CString();
1756 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1758 CSendMailDlg dlg;
1760 dlg.m_PathList = list;
1762 if(dlg.DoModal()==IDOK)
1764 if(dlg.m_PathList.GetCount() == 0)
1765 return FALSE;
1767 CGitProgressDlg progDlg;
1769 theApp.m_pMainWnd = &progDlg;
1770 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1772 progDlg.SetAutoClose(autoclose);
1774 progDlg.SetPathList(dlg.m_PathList);
1775 //ProjectProperties props;
1776 //props.ReadPropsPathList(dlg.m_pathList);
1777 //progDlg.SetProjectProperties(props);
1778 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1780 DWORD flags =0;
1781 if(dlg.m_bAttachment)
1782 flags |= SENDMAIL_ATTACHMENT;
1783 if(dlg.m_bCombine)
1784 flags |= SENDMAIL_COMBINED;
1785 if(dlg.m_bUseMAPI)
1786 flags |= SENDMAIL_MAPI;
1788 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1790 progDlg.DoModal();
1792 return true;
1794 return false;
1797 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1799 CTGitPathList list;
1800 CString log=formatpatchoutput;
1801 int start=log.Find(cmd);
1802 if(start >=0)
1803 CString one=log.Tokenize(_T("\n"),start);
1804 else
1805 start = 0;
1807 while(start>=0)
1809 CString one=log.Tokenize(_T("\n"),start);
1810 one=one.Trim();
1811 if(one.IsEmpty() || one == _T("Success"))
1812 continue;
1813 one.Replace(_T('/'),_T('\\'));
1814 CTGitPath path;
1815 path.SetFromWin(one);
1816 list.AddPath(path);
1818 if (list.GetCount() > 0)
1820 return SendPatchMail(list, autoclose);
1822 else
1824 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1825 return true;
1830 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1832 CString cmd,output;
1833 int start=0;
1835 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1836 if(output.IsEmpty())
1838 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1839 if(output.IsEmpty())
1840 return CP_UTF8;
1842 int start=0;
1843 output=output.Tokenize(_T("\n"),start);
1844 return CUnicodeUtils::GetCPCode(output);
1847 else
1849 output=output.Tokenize(_T("\n"),start);
1850 return CUnicodeUtils::GetCPCode(output);
1853 int CAppUtils::GetCommitTemplate(CString &temp)
1855 CString cmd,output;
1857 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
1858 if( output.IsEmpty() )
1859 return -1;
1861 if( output.GetLength()<1)
1862 return -1;
1864 if( output[0] == _T('/'))
1866 if(output.GetLength()>=3)
1867 if(output[2] == _T('/'))
1869 output.GetBuffer()[0] = output[1];
1870 output.GetBuffer()[1] = _T(':');
1874 int start=0;
1875 output=output.Tokenize(_T("\n"),start);
1877 output.Replace(_T('/'),_T('\\'));
1881 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1882 CString str;
1883 while(file.ReadString(str))
1885 temp+=str+_T("\n");
1888 }catch(...)
1890 return -1;
1892 return 0;
1894 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1896 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1897 CString cmd,output;
1898 int cp=CP_UTF8;
1900 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1901 if(output.IsEmpty())
1902 cp=CP_UTF8;
1904 int start=0;
1905 output=output.Tokenize(_T("\n"),start);
1906 cp=CUnicodeUtils::GetCPCode(output);
1908 int len=message.GetLength();
1910 char * buf;
1911 buf = new char[len*4 + 4];
1912 SecureZeroMemory(buf, (len*4 + 4));
1914 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1916 file.Write(buf,lengthIncTerminator-1);
1917 file.Close();
1918 delete buf;
1919 return 0;
1922 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1924 CPullFetchDlg dlg;
1925 dlg.m_PreSelectRemote = remoteName;
1926 dlg.m_bAllowRebase = allowRebase;
1927 dlg.m_IsPull=FALSE;
1929 if(dlg.DoModal()==IDOK)
1931 if(dlg.m_bAutoLoad)
1933 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1936 CString url;
1937 url=dlg.m_RemoteURL;
1938 CString cmd;
1939 CString arg;
1941 int ver = CAppUtils::GetMsysgitVersion();
1943 if(ver >= 0x01070203) //above 1.7.0.2
1944 arg = _T("--progress ");
1946 if (dlg.m_bPrune) {
1947 arg += _T("--prune ");
1950 if (dlg.m_bFetchTags == 1)
1952 arg += _T("--tags ");
1954 else if (dlg.m_bFetchTags == 0)
1956 arg += _T("--no-tags ");
1959 if (dlg.m_bAllRemotes)
1960 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
1961 else
1962 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
1964 CProgressDlg progress;
1966 progress.m_bAutoCloseOnSuccess = autoClose;
1968 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
1970 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1972 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1975 progress.m_GitCmd=cmd;
1976 INT_PTR userResponse = progress.DoModal();
1978 if (userResponse == IDC_PROGRESS_BUTTON1)
1980 CString cmd = _T("/command:log");
1981 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1982 RunTortoiseProc(cmd);
1983 return TRUE;
1985 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1987 while(1)
1989 CRebaseDlg dlg;
1990 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
1991 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1992 INT_PTR response = dlg.DoModal();
1993 if(response == IDOK)
1995 return TRUE;
1997 if(response == IDC_REBASE_POST_BUTTON )
1999 CString cmd, out, err;
2000 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2001 g_Git.m_CurrentDir,
2002 g_Git.FixBranchName(dlg.m_Upstream),
2003 g_Git.FixBranchName(dlg.m_Branch));
2004 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2006 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2007 return FALSE;
2010 CAppUtils::SendPatchMail(cmd,out);
2011 return TRUE;
2014 if(response == IDC_REBASE_POST_BUTTON +1 )
2015 continue;
2017 if(response == IDCANCEL)
2018 return FALSE;
2020 return TRUE;
2022 else if (userResponse != IDCANCEL)
2023 return TRUE;
2025 return FALSE;
2028 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2030 CPushDlg dlg;
2031 dlg.m_BranchSourceName = selectLocalBranch;
2032 CString error;
2033 DWORD exitcode = 0xFFFFFFFF;
2034 CTGitPathList list;
2035 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2036 if (CHooks::Instance().PrePush(list,exitcode, error))
2038 if (exitcode)
2040 CString temp;
2041 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2042 //ReportError(temp);
2043 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2044 return false;
2048 if(dlg.DoModal()==IDOK)
2050 CString arg;
2052 if(dlg.m_bAutoLoad)
2054 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2057 if(dlg.m_bPack)
2058 arg += _T("--thin ");
2059 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2060 arg += _T("--tags ");
2061 if(dlg.m_bForce)
2062 arg += _T("--force ");
2063 if (dlg.m_bSetUpstream)
2064 arg += _T("--set-upstream ");
2066 int ver = CAppUtils::GetMsysgitVersion();
2068 if(ver >= 0x01070203) //above 1.7.0.2
2069 arg += _T("--progress ");
2071 CProgressDlg progress;
2072 progress.m_bAutoCloseOnSuccess=autoClose;
2074 STRING_VECTOR remotesList;
2075 if (dlg.m_bPushAllRemotes)
2076 g_Git.GetRemoteList(remotesList);
2077 else
2078 remotesList.push_back(dlg.m_URL);
2080 for (unsigned int i = 0; i < remotesList.size(); i++)
2082 CString cmd;
2083 if (dlg.m_bPushAllBranches)
2085 cmd.Format(_T("git.exe push --all %s \"%s\""),
2086 arg,
2087 remotesList[i]);
2089 else
2091 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2092 arg,
2093 remotesList[i],
2094 dlg.m_BranchSourceName);
2095 if (!dlg.m_BranchRemoteName.IsEmpty())
2097 cmd += _T(":") + dlg.m_BranchRemoteName;
2100 progress.m_GitCmdList.push_back(cmd);
2103 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2104 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2105 INT_PTR ret = progress.DoModal();
2107 if(!progress.m_GitStatus)
2109 if (CHooks::Instance().PostPush(list,exitcode, error))
2111 if (exitcode)
2113 CString temp;
2114 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2115 //ReportError(temp);
2116 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2117 return false;
2120 if(ret == IDC_PROGRESS_BUTTON1)
2122 RequestPull(dlg.m_BranchRemoteName);
2124 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2126 Push();
2128 return TRUE;
2132 return FALSE;
2135 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2137 CRequestPullDlg dlg;
2138 dlg.m_RepositoryURL = repositoryUrl;
2139 dlg.m_EndRevision = endrevision;
2140 if (dlg.DoModal()==IDOK)
2142 CString cmd;
2143 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2145 CString tempFileName = GetTempFile();
2146 if (g_Git.RunLogFile(cmd, tempFileName))
2148 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2149 return false;
2151 CAppUtils::LaunchAlternativeEditor(tempFileName);
2153 return true;
2156 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2158 CString strDir(szPath);
2159 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2161 strDir.AppendChar(_T('\\'));
2163 std::vector<CString> vPath;
2164 CString strTemp;
2165 bool bSuccess = false;
2167 for (int i=0;i<strDir.GetLength();++i)
2169 if (strDir.GetAt(i) != _T('\\'))
2171 strTemp.AppendChar(strDir.GetAt(i));
2173 else
2175 vPath.push_back(strTemp);
2176 strTemp.AppendChar(_T('\\'));
2180 std::vector<CString>::const_iterator vIter;
2181 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2183 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2186 return bSuccess;
2189 void CAppUtils::RemoveTrailSlash(CString &path)
2191 if(path.IsEmpty())
2192 return ;
2194 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2196 path=path.Left(path.GetLength()-1);
2197 if(path.IsEmpty())
2198 return;
2202 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2203 CTGitPathList &pathList,
2204 CTGitPathList &selectedList,
2205 bool bSelectFilesForCommit,
2206 bool autoClose)
2208 bool bFailed = true;
2210 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2212 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2214 CTGitPath path(g_Git.m_CurrentDir);
2215 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2216 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2217 dlg.SetTreeWidth(220);
2218 dlg.m_DefaultPage = _T("gitconfig");
2220 dlg.DoModal();
2221 dlg.HandleRestart();
2224 else
2225 return false;
2228 while (bFailed)
2230 bFailed = false;
2231 CCommitDlg dlg;
2232 dlg.m_sBugID = bugid;
2234 dlg.m_bWholeProject = bWholeProject;
2236 dlg.m_sLogMessage = sLogMsg;
2237 dlg.m_pathList = pathList;
2238 dlg.m_checkedPathList = selectedList;
2239 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2240 dlg.m_bAutoClose = autoClose;
2241 if (dlg.DoModal() == IDOK)
2243 if (dlg.m_pathList.GetCount()==0)
2244 return false;
2245 // if the user hasn't changed the list of selected items
2246 // we don't use that list. Because if we would use the list
2247 // of pre-checked items, the dialog would show different
2248 // checked items on the next startup: it would only try
2249 // to check the parent folder (which might not even show)
2250 // instead, we simply use an empty list and let the
2251 // default checking do its job.
2252 if (!dlg.m_pathList.IsEqual(pathList))
2253 selectedList = dlg.m_pathList;
2254 pathList = dlg.m_updatedPathList;
2255 sLogMsg = dlg.m_sLogMessage;
2256 bSelectFilesForCommit = true;
2258 if( dlg.m_bPushAfterCommit )
2260 switch(dlg.m_PostCmd)
2262 case GIT_POST_CMD_DCOMMIT:
2263 CAppUtils::SVNDCommit();
2264 break;
2265 default:
2266 CAppUtils::Push();
2269 else if (dlg.m_bCreateTagAfterCommit)
2271 CAppUtils::CreateBranchTag(TRUE);
2274 // CGitProgressDlg progDlg;
2275 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2276 // if (parser.HasVal(_T("closeonend")))
2277 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2278 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2279 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2280 // progDlg.SetPathList(dlg.m_pathList);
2281 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2282 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2283 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2284 // progDlg.SetItemCount(dlg.m_itemsCount);
2285 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2286 // progDlg.DoModal();
2287 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2288 // err = (DWORD)progDlg.DidErrorsOccur();
2289 // bFailed = progDlg.DidErrorsOccur();
2290 // bRet = progDlg.DidErrorsOccur();
2291 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2292 // if (DWORD(bFailRepeat)==0)
2293 // bFailed = false; // do not repeat if the user chose not to in the settings.
2296 return true;
2300 BOOL CAppUtils::SVNDCommit()
2302 CSVNDCommitDlg dcommitdlg;
2303 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2304 if (gitSetting == _T("")) {
2305 if (dcommitdlg.DoModal() != IDOK)
2307 return false;
2309 else
2311 if (dcommitdlg.m_remember)
2313 if (dcommitdlg.m_rmdir)
2315 gitSetting = _T("true");
2317 else
2319 gitSetting = _T("false");
2321 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2323 CString msg;
2324 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2325 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2331 BOOL IsStash = false;
2332 if(!g_Git.CheckCleanWorkTree())
2334 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2336 CString cmd,out;
2337 cmd=_T("git.exe stash");
2338 if (g_Git.Run(cmd, &out, CP_UTF8))
2340 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2341 return false;
2343 IsStash =true;
2346 else
2348 return false;
2352 CProgressDlg progress;
2353 if (dcommitdlg.m_rmdir)
2355 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2357 else
2359 progress.m_GitCmd=_T("git.exe svn dcommit");
2361 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2363 if( IsStash)
2365 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2367 CString cmd,out;
2368 cmd=_T("git.exe stash pop");
2369 if (g_Git.Run(cmd, &out, CP_UTF8))
2371 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2372 return false;
2376 else
2378 return false;
2381 return TRUE;
2383 return FALSE;
2386 BOOL CAppUtils::Merge(CString *commit)
2388 CMergeDlg dlg;
2389 if(commit)
2390 dlg.m_initialRefName = *commit;
2392 if(dlg.DoModal()==IDOK)
2394 CString cmd;
2395 CString noff;
2396 CString squash;
2397 CString nocommit;
2398 CString msg;
2400 if(dlg.m_bNoFF)
2401 noff=_T("--no-ff");
2403 if(dlg.m_bSquash)
2404 squash=_T("--squash");
2406 if(dlg.m_bNoCommit)
2407 nocommit=_T("--no-commit");
2409 if(!dlg.m_strLogMesage.IsEmpty())
2411 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2413 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2414 msg,
2415 noff,
2416 squash,
2417 nocommit,
2418 g_Git.FixBranchName(dlg.m_VersionName));
2420 CProgressDlg Prodlg;
2421 Prodlg.m_GitCmd = cmd;
2423 if (dlg.m_bNoCommit)
2424 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2425 else if (dlg.m_bIsBranch)
2426 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2428 INT_PTR ret = Prodlg.DoModal();
2430 if (ret == IDC_PROGRESS_BUTTON1)
2431 if (dlg.m_bNoCommit)
2433 CString sLogMsg;
2434 CTGitPathList pathList;
2435 CTGitPathList selectedList;
2436 return Commit(_T(""), TRUE, sLogMsg, pathList, selectedList, true);
2438 else if (dlg.m_bIsBranch)
2440 CString msg;
2441 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2442 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2444 CString cmd, out;
2445 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2446 if (g_Git.Run(cmd, &out, CP_UTF8))
2447 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2451 return !Prodlg.m_GitStatus;
2453 return false;
2456 void CAppUtils::EditNote(GitRev *rev)
2458 CInputDlg dlg;
2459 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2460 dlg.m_sInputText = rev->m_Notes;
2461 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2462 //dlg.m_pProjectProperties = &m_ProjectProperties;
2463 dlg.m_bUseLogWidth = true;
2464 if(dlg.DoModal() == IDOK)
2466 CString cmd,output;
2467 cmd=_T("notes add -f -F \"");
2469 CString tempfile=::GetTempFile();
2470 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2471 cmd += tempfile;
2472 cmd += _T("\" ");
2473 cmd += rev->m_CommitHash.ToString();
2477 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2479 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2482 else
2484 rev->m_Notes = dlg.m_sInputText;
2486 }catch(...)
2488 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2490 CFile::Remove(tempfile);
2495 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2497 CString cmd;
2498 CString progressarg;
2499 CString version;
2501 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2502 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2504 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2506 __int64 time=0;
2507 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2509 if((DWORD)time == regTime)
2511 return regVersion;
2515 if(versionstr)
2516 version = *versionstr;
2517 else
2519 CString err;
2520 cmd = _T("git.exe --version");
2521 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2523 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2524 return false;
2528 int start=0;
2529 int ver = 0;
2533 CString str=version.Tokenize(_T("."), start);
2534 int space = str.ReverseFind(_T(' '));
2535 str = str.Mid(space+1,start);
2536 ver = _ttol(str);
2537 ver <<=24;
2539 version = version.Mid(start);
2540 start = 0;
2542 str = version.Tokenize(_T("."), start);
2544 ver |= (_ttol(str) & 0xFF) << 16;
2546 str = version.Tokenize(_T("."), start);
2547 ver |= (_ttol(str) & 0xFF) << 8;
2549 str = version.Tokenize(_T("."), start);
2550 ver |= (_ttol(str) & 0xFF);
2552 catch(...)
2554 if (!ver)
2556 CMessageBox::Show(NULL, _T("Could not parse git.exe version number."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2557 return false;
2561 regTime = time&0xFFFFFFFF;
2562 regVersion = ver;
2564 return ver;
2567 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2569 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2571 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2573 if (hShell.IsValid()) {
2574 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2575 if (pfnSHGPSFW) {
2576 IPropertyStore *pps;
2577 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2578 if (SUCCEEDED(hr)) {
2579 PROPVARIANT var;
2580 var.vt = VT_BOOL;
2581 var.boolVal = VARIANT_TRUE;
2582 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2583 pps->Release();
2589 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2591 ASSERT(dialogname.GetLength() < 70);
2592 ASSERT(urlorpath.GetLength() < MAX_PATH);
2593 WCHAR pathbuf[MAX_PATH] = {0};
2595 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2597 wcscat_s(pathbuf, L" - ");
2598 wcscat_s(pathbuf, dialogname);
2599 wcscat_s(pathbuf, L" - ");
2600 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2601 SetWindowText(hWnd, pathbuf);
2604 bool CAppUtils::BisectStart(CString lastGood, CString firstBad, bool autoClose)
2606 if (!g_Git.CheckCleanWorkTree())
2608 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, MB_YESNO|MB_ICONINFORMATION) == IDYES)
2610 CString cmd, out;
2611 cmd = _T("git.exe stash");
2612 if (g_Git.Run(cmd, &out, CP_UTF8))
2614 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
2615 return false;
2618 else
2619 return false;
2622 CBisectStartDlg bisectStartDlg;
2624 if (!lastGood.IsEmpty())
2625 bisectStartDlg.m_sLastGood = lastGood;
2626 if (!firstBad.IsEmpty())
2627 bisectStartDlg.m_sFirstBad = firstBad;
2629 if (bisectStartDlg.DoModal() == IDOK)
2631 CProgressDlg progress;
2632 theApp.m_pMainWnd = &progress;
2633 progress.m_bAutoCloseOnSuccess = autoClose;
2634 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
2635 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
2636 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
2638 CTGitPath path(g_Git.m_CurrentDir);
2640 if (path.HasSubmodules())
2641 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
2643 INT_PTR ret = progress.DoModal();
2644 if (path.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
2646 CString sCmd;
2647 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2649 CAppUtils::RunTortoiseProc(sCmd);
2650 return true;
2652 else if (ret == IDOK)
2653 return true;
2656 return false;