Fixed issue #1262: TortoiseProc might crash if git.exe version is not parseable
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob4ca4e77164660c57b4b51ffe162dd20c2e559638
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"
65 CAppUtils::CAppUtils(void)
69 CAppUtils::~CAppUtils(void)
73 bool CAppUtils::StashSave()
75 CStashSaveDlg dlg;
77 if (dlg.DoModal() == IDOK)
79 CString cmd, out;
80 cmd = _T("git.exe stash save");
82 if (dlg.m_bIncludeUntracked && CAppUtils::GetMsysgitVersion() >= 0x01070700)
83 cmd += _T(" --include-untracked");
85 if (!dlg.m_sMessage.IsEmpty())
87 CString message = dlg.m_sMessage;
88 message.Replace(_T("\""), _T("\"\""));
89 cmd += _T(" \"") + message + _T("\"");
92 if (g_Git.Run(cmd, &out, CP_UTF8))
94 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
96 else
98 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHSUCCESS)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
99 return true;
102 return false;
105 int CAppUtils::StashApply(CString ref, bool showChanges /* true */)
107 CString cmd,out;
108 cmd = _T("git.exe stash apply ");
109 if (ref.Find(_T("refs/")) == 0)
110 ref = ref.Mid(5);
111 if (ref.Find(_T("stash{")) == 0)
112 ref = _T("stash@") + ref.Mid(5);
113 cmd += ref;
115 int ret = g_Git.Run(cmd, &out, CP_UTF8);
116 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
117 if (ret && !(ret == 1 && hasConflicts))
119 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
121 else
123 CString message;
124 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
125 if (hasConflicts)
126 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
127 if (showChanges)
129 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
130 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
132 CChangedDlg dlg;
133 dlg.m_pathList.AddPath(CTGitPath());
134 dlg.DoModal();
136 return 0;
138 else
140 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
141 return 0;
144 return -1;
147 int CAppUtils::StashPop(bool showChanges /* true */)
149 CString cmd,out;
150 cmd=_T("git.exe stash pop ");
152 int ret = g_Git.Run(cmd, &out, CP_UTF8);
153 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
154 if (ret && !(ret == 1 && hasConflicts))
156 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
158 else
160 CString message;
161 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
162 if (hasConflicts)
163 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
164 if (showChanges)
166 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
167 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
169 CChangedDlg dlg;
170 dlg.m_pathList.AddPath(CTGitPath());
171 dlg.DoModal();
173 return 0;
175 else
177 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
178 return 0;
181 return -1;
184 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
186 #if 0
187 GitProperties props(file, GitRev::REV_WC, false);
188 for (int i = 0; i < props.GetCount(); ++i)
190 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
192 mimetype = props.GetItemValue(i).c_str();
193 return true;
196 #endif
197 return false;
200 BOOL CAppUtils::StartExtMerge(
201 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
202 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
205 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
206 CString ext = mergedfile.GetFileExtension();
207 CString com = regCom;
208 bool bInternal = false;
210 CString mimetype;
211 if (ext != "")
213 // is there an extension specific merge tool?
214 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
215 if (CString(mergetool) != "")
217 com = mergetool;
220 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
222 // is there a mime type specific merge tool?
223 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
224 if (CString(mergetool) != "")
226 com = mergetool;
230 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
232 // use TortoiseMerge
233 bInternal = true;
234 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
235 com = tortoiseMergePath;
236 if (com.IsEmpty())
238 com = CPathUtils::GetAppDirectory();
239 com += _T("TortoiseMerge.exe");
241 com = _T("\"") + com + _T("\"");
242 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
243 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
245 // check if the params are set. If not, just add the files to the command line
246 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
248 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
249 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
250 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
251 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
253 if (basefile.IsEmpty())
255 com.Replace(_T("/base:%base"), _T(""));
256 com.Replace(_T("%base"), _T(""));
258 else
259 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
260 if (theirfile.IsEmpty())
262 com.Replace(_T("/theirs:%theirs"), _T(""));
263 com.Replace(_T("%theirs"), _T(""));
265 else
266 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
267 if (yourfile.IsEmpty())
269 com.Replace(_T("/mine:%mine"), _T(""));
270 com.Replace(_T("%mine"), _T(""));
272 else
273 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
274 if (mergedfile.IsEmpty())
276 com.Replace(_T("/merged:%merged"), _T(""));
277 com.Replace(_T("%merged"), _T(""));
279 else
280 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
281 if (basename.IsEmpty())
283 if (basefile.IsEmpty())
285 com.Replace(_T("/basename:%bname"), _T(""));
286 com.Replace(_T("%bname"), _T(""));
288 else
290 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
293 else
294 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
295 if (theirname.IsEmpty())
297 if (theirfile.IsEmpty())
299 com.Replace(_T("/theirsname:%tname"), _T(""));
300 com.Replace(_T("%tname"), _T(""));
302 else
304 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
307 else
308 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
309 if (yourname.IsEmpty())
311 if (yourfile.IsEmpty())
313 com.Replace(_T("/minename:%yname"), _T(""));
314 com.Replace(_T("%yname"), _T(""));
316 else
318 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
321 else
322 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
323 if (mergedname.IsEmpty())
325 if (mergedfile.IsEmpty())
327 com.Replace(_T("/mergedname:%mname"), _T(""));
328 com.Replace(_T("%mname"), _T(""));
330 else
332 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
335 else
336 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
338 if ((bReadOnly)&&(bInternal))
339 com += _T(" /readonly");
341 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
343 return FALSE;
346 return TRUE;
349 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
351 CString viewer;
352 // use TortoiseMerge
353 viewer = CPathUtils::GetAppDirectory();
354 viewer += _T("TortoiseMerge.exe");
356 viewer = _T("\"") + viewer + _T("\"");
357 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
358 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
359 if (bReversed)
360 viewer += _T(" /reversedpatch");
361 if (!sOriginalDescription.IsEmpty())
362 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
363 if (!sPatchedDescription.IsEmpty())
364 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
365 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
367 return FALSE;
369 return TRUE;
372 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
374 // Is there a mime type specific diff tool?
375 CString mimetype;
376 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
378 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
379 if (!difftool.IsEmpty())
380 return difftool;
383 // Is there an extension specific diff tool?
384 CString ext = file2.GetFileExtension().MakeLower();
385 if (!ext.IsEmpty())
387 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
388 if (!difftool.IsEmpty())
389 return difftool;
390 // Maybe we should use TortoiseIDiff?
391 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
392 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
393 (ext == _T(".png")) || (ext == _T(".ico")) ||
394 (ext == _T(".dib")) || (ext == _T(".emf")))
396 return
397 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
398 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
402 // Finally, pick a generic external diff tool
403 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
404 return difftool;
407 bool CAppUtils::StartExtDiff(
408 const CString& file1, const CString& file2,
409 const CString& sName1, const CString& sName2,
410 const DiffFlags& flags)
412 CString viewer;
414 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
415 if (!flags.bBlame || !(DWORD)blamediff)
417 viewer = PickDiffTool(file1, file2);
418 // If registry entry for a diff program is commented out, use TortoiseMerge.
419 bool bCommentedOut = viewer.Left(1) == _T("#");
420 if (flags.bAlternativeTool)
422 // Invert external vs. internal diff tool selection.
423 if (bCommentedOut)
424 viewer.Delete(0); // uncomment
425 else
426 viewer = "";
428 else if (bCommentedOut)
429 viewer = "";
432 bool bInternal = viewer.IsEmpty();
433 if (bInternal)
435 viewer =
436 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
437 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
438 if (flags.bBlame)
439 viewer += _T(" /blame");
441 // check if the params are set. If not, just add the files to the command line
442 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
444 viewer += _T(" \"")+file1+_T("\"");
445 viewer += _T(" \"")+file2+_T("\"");
447 if (viewer.Find(_T("%base")) >= 0)
449 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
451 if (viewer.Find(_T("%mine")) >= 0)
453 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
456 if (sName1.IsEmpty())
457 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
458 else
459 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
461 if (sName2.IsEmpty())
462 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
463 else
464 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
466 if (flags.bReadOnly && bInternal)
467 viewer += _T(" /readonly");
469 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
472 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
474 CString viewer;
475 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
476 viewer = v;
477 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
479 // use TortoiseUDiff
480 viewer = CPathUtils::GetAppDirectory();
481 viewer += _T("TortoiseUDiff.exe");
482 // enquote the path to TortoiseUDiff
483 viewer = _T("\"") + viewer + _T("\"");
484 // add the params
485 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
488 if (viewer.Find(_T("%1"))>=0)
490 if (viewer.Find(_T("\"%1\"")) >= 0)
491 viewer.Replace(_T("%1"), patchfile);
492 else
493 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
495 else
496 viewer += _T(" \"") + patchfile + _T("\"");
497 if (viewer.Find(_T("%title")) >= 0)
499 viewer.Replace(_T("%title"), title);
502 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
504 return FALSE;
506 return TRUE;
509 BOOL CAppUtils::StartTextViewer(CString file)
511 CString viewer;
512 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
513 viewer = txt;
514 viewer = viewer + _T("\\Shell\\Open\\Command\\");
515 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
516 viewer = txtexe;
518 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
519 TCHAR * buf = new TCHAR[len+1];
520 ExpandEnvironmentStrings(viewer, buf, len);
521 viewer = buf;
522 delete [] buf;
523 len = ExpandEnvironmentStrings(file, NULL, 0);
524 buf = new TCHAR[len+1];
525 ExpandEnvironmentStrings(file, buf, len);
526 file = buf;
527 delete [] buf;
528 file = _T("\"")+file+_T("\"");
529 if (viewer.IsEmpty())
531 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
533 if (viewer.Find(_T("\"%1\"")) >= 0)
535 viewer.Replace(_T("\"%1\""), file);
537 else if (viewer.Find(_T("%1")) >= 0)
539 viewer.Replace(_T("%1"), file);
541 else
543 viewer += _T(" ");
544 viewer += file;
547 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
549 return FALSE;
551 return TRUE;
554 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
556 DWORD length = 0;
557 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
558 if (!hFile)
559 return TRUE;
560 length = ::GetFileSize(hFile, NULL);
561 if (length < 4)
562 return TRUE;
563 return FALSE;
567 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
569 LOGFONT logFont;
570 HDC hScreenDC = ::GetDC(NULL);
571 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
572 ::ReleaseDC(NULL, hScreenDC);
573 logFont.lfWidth = 0;
574 logFont.lfEscapement = 0;
575 logFont.lfOrientation = 0;
576 logFont.lfWeight = FW_NORMAL;
577 logFont.lfItalic = 0;
578 logFont.lfUnderline = 0;
579 logFont.lfStrikeOut = 0;
580 logFont.lfCharSet = DEFAULT_CHARSET;
581 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
582 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
583 logFont.lfQuality = DRAFT_QUALITY;
584 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
585 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
586 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
589 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
591 CString key,remote;
592 CString cmd,out;
593 if( pRemote == NULL)
595 remote=_T("origin");
597 else
599 remote=*pRemote;
601 if(keyfile == NULL)
603 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
604 key = g_Git.GetConfigValue(cmd);
605 int start=0;
606 key = key.Tokenize(_T("\n"),start);
608 else
609 key=*keyfile;
611 if(key.IsEmpty())
612 return false;
614 CString proc=CPathUtils::GetAppDirectory();
615 proc += _T("pageant.exe \"");
616 proc += key;
617 proc += _T("\"");
619 CString tempfile = GetTempFile();
620 ::DeleteFile(tempfile);
622 proc += _T(" -c \"");
623 proc += CPathUtils::GetAppDirectory();
624 proc += _T("touch.exe\"");
625 proc += _T(" \"");
626 proc += tempfile;
627 proc += _T("\"");
629 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &CPathUtils::GetAppDirectory());
630 if(!b)
631 return b;
633 int i=0;
634 while(!::PathFileExists(tempfile))
636 Sleep(100);
637 i++;
638 if(i>10*60*5)
639 break; //timeout 5 minutes
642 if( i== 10*60*5)
644 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
646 ::DeleteFile(tempfile);
647 return true;
649 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
651 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
652 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
653 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
656 CString sCmd;
657 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
659 LaunchApplication(sCmd, NULL, false);
660 return true;
662 bool CAppUtils::LaunchRemoteSetting()
664 CTGitPath path(g_Git.m_CurrentDir);
665 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
666 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
667 //dlg.SetTreeWidth(220);
668 dlg.m_DefaultPage = _T("gitremote");
670 dlg.DoModal();
671 dlg.HandleRestart();
672 return true;
675 * Launch the external blame viewer
677 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
679 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
680 viewer += _T("TortoiseGitBlame.exe");
681 viewer += _T("\" \"") + sBlameFile + _T("\"");
682 //viewer += _T(" \"") + sLogFile + _T("\"");
683 //viewer += _T(" \"") + sOriginalFile + _T("\"");
684 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
685 viewer += CString(_T(" /rev:"))+Rev;
686 viewer += _T(" ")+sParams;
688 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
691 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
693 CString sText;
694 if (pWnd == NULL)
695 return false;
696 bool bStyled = false;
697 pWnd->GetWindowText(sText);
698 // the rich edit control doesn't count the CR char!
699 // to be exact: CRLF is treated as one char.
700 sText.Remove('\r');
702 // style each line separately
703 int offset = 0;
704 int nNewlinePos;
707 nNewlinePos = sText.Find('\n', offset);
708 CString sLine = sText.Mid(offset);
709 if (nNewlinePos>=0)
710 sLine = sLine.Left(nNewlinePos-offset);
711 int start = 0;
712 int end = 0;
713 while (FindStyleChars(sLine, '*', start, end))
715 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
716 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
717 CHARFORMAT2 format;
718 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
719 format.cbSize = sizeof(CHARFORMAT2);
720 format.dwMask = CFM_BOLD;
721 format.dwEffects = CFE_BOLD;
722 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
723 bStyled = true;
724 start = end;
726 start = 0;
727 end = 0;
728 while (FindStyleChars(sLine, '^', start, end))
730 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
731 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
732 CHARFORMAT2 format;
733 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
734 format.cbSize = sizeof(CHARFORMAT2);
735 format.dwMask = CFM_ITALIC;
736 format.dwEffects = CFE_ITALIC;
737 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
738 bStyled = true;
739 start = end;
741 start = 0;
742 end = 0;
743 while (FindStyleChars(sLine, '_', start, end))
745 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
746 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
747 CHARFORMAT2 format;
748 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
749 format.cbSize = sizeof(CHARFORMAT2);
750 format.dwMask = CFM_UNDERLINE;
751 format.dwEffects = CFE_UNDERLINE;
752 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
753 bStyled = true;
754 start = end;
756 offset = nNewlinePos+1;
757 } while(nNewlinePos>=0);
758 return bStyled;
761 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
763 int i=start;
764 bool bFoundMarker = false;
765 // find a starting marker
766 while (sText[i] != 0)
768 if (sText[i] == stylechar)
770 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
771 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
773 start = i+1;
774 i++;
775 bFoundMarker = true;
776 break;
779 i++;
781 if (!bFoundMarker)
782 return false;
783 // find ending marker
784 bFoundMarker = false;
785 while (sText[i] != 0)
787 if (sText[i] == stylechar)
789 if ((IsCharAlphaNumeric(sText[i-1])) &&
790 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
792 end = i;
793 i++;
794 bFoundMarker = true;
795 break;
798 i++;
800 return bFoundMarker;
803 CString CAppUtils::GetProjectNameFromURL(CString url)
805 CString name;
806 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
807 (name.CompareNoCase(_T("tags"))==0) ||
808 (name.CompareNoCase(_T("trunk"))==0))
810 name = url.Mid(url.ReverseFind('/')+1);
811 url = url.Left(url.ReverseFind('/'));
813 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
815 // a name of svn or svnroot indicates that it's not really the project name. In that
816 // case, we try the first part of the URL
817 // of course, this won't work in all cases (but it works for Google project hosting)
818 url.Replace(_T("http://"), _T(""));
819 url.Replace(_T("https://"), _T(""));
820 url.Replace(_T("svn://"), _T(""));
821 url.Replace(_T("svn+ssh://"), _T(""));
822 url.TrimLeft(_T("/"));
823 name = url.Left(url.Find('.'));
825 return name;
828 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
829 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
830 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
831 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
834 CString tempfile=GetTempFile();
835 CString cmd;
836 if(rev2 == GitRev::GetWorkingCopy())
838 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
840 else
842 CString merge;
843 if(bMerge)
844 merge = _T("-c");
846 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
849 if( !url1.IsEmpty() )
851 cmd += _T(" -- \"");
852 cmd += url1.GetGitPathString();
853 cmd += _T("\" ");
855 g_Git.RunLogFile(cmd,tempfile);
856 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
859 #if 0
860 CString sCmd;
861 sCmd.Format(_T("%s /command:showcompare /unified"),
862 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
863 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
864 if (rev1.IsValid())
865 sCmd += _T(" /revision1:") + rev1.ToString();
866 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
867 if (rev2.IsValid())
868 sCmd += _T(" /revision2:") + rev2.ToString();
869 if (peg.IsValid())
870 sCmd += _T(" /pegrevision:") + peg.ToString();
871 if (headpeg.IsValid())
872 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
874 if (bAlternateDiff)
875 sCmd += _T(" /alternatediff");
877 if (bIgnoreAncestry)
878 sCmd += _T(" /ignoreancestry");
880 if (hWnd)
882 sCmd += _T(" /hwnd:");
883 TCHAR buf[30];
884 _stprintf_s(buf, 30, _T("%d"), hWnd);
885 sCmd += buf;
888 return CAppUtils::LaunchApplication(sCmd, NULL, false);
889 #endif
890 return TRUE;
894 bool CAppUtils::Export(CString *BashHash)
896 bool bRet = false;
898 // ask from where the export has to be done
899 CExportDlg dlg;
900 if(BashHash)
901 dlg.m_Revision=*BashHash;
903 if (dlg.DoModal() == IDOK)
905 CString cmd;
906 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
907 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
909 CProgressDlg pro;
910 pro.m_GitCmd=cmd;
911 pro.DoModal();
912 return TRUE;
914 return bRet;
917 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
919 CCreateBranchTagDlg dlg;
920 dlg.m_bIsTag=IsTag;
921 dlg.m_bSwitch=switch_new_brach;
923 if(CommitHash)
924 dlg.m_Base = *CommitHash;
926 if(dlg.DoModal()==IDOK)
928 CString cmd;
929 CString force;
930 CString track;
931 if(dlg.m_bTrack == TRUE)
932 track=_T(" --track ");
933 else if(dlg.m_bTrack == FALSE)
934 track=_T(" --no-track");
936 if(dlg.m_bForce)
937 force=_T(" -f ");
939 if(IsTag)
941 CString sign;
942 if(dlg.m_bSign)
943 sign=_T("-s");
945 cmd.Format(_T("git.exe tag %s %s %s %s"),
946 force,
947 sign,
948 dlg.m_BranchTagName,
949 g_Git.FixBranchName(dlg.m_VersionName)
952 CString tempfile=::GetTempFile();
953 if(!dlg.m_Message.Trim().IsEmpty())
955 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
956 cmd += _T(" -F ")+tempfile;
959 else
961 cmd.Format(_T("git.exe branch %s %s %s %s"),
962 track,
963 force,
964 dlg.m_BranchTagName,
965 g_Git.FixBranchName(dlg.m_VersionName)
968 CString out;
969 if(g_Git.Run(cmd,&out,CP_UTF8))
971 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
973 if( !IsTag && dlg.m_bSwitch )
975 // it is a new branch and the user has requested to switch to it
976 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
977 g_Git.Run(cmd,&out,CP_UTF8);
978 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
981 return TRUE;
983 return FALSE;
986 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
988 CGitSwitchDlg dlg;
989 if(CommitHash)
990 dlg.m_Base=*CommitHash;
991 if(!initialRefName.IsEmpty())
992 dlg.m_initialRefName = initialRefName;
994 if (dlg.DoModal() == IDOK)
996 CString branch;
997 if (dlg.m_bBranch)
998 branch = dlg.m_NewBranch;
1000 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1002 return FALSE;
1005 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1007 CString cmd;
1008 CString track;
1009 CString force;
1010 CString branch;
1012 if(!sNewBranch.IsEmpty()){
1013 if (bBranchOverride)
1015 branch.Format(_T("-B %s"), sNewBranch);
1017 else
1019 branch.Format(_T("-b %s"), sNewBranch);
1021 if (bTrack)
1022 track = _T("--track");
1024 if (bForce)
1025 force = _T("-f");
1027 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1028 force,
1029 track,
1030 branch,
1031 g_Git.FixBranchName(ref));
1033 CProgressDlg progress;
1034 progress.m_bAutoCloseOnSuccess = autoClose;
1035 progress.m_GitCmd = cmd;
1037 CTGitPath gitPath = g_Git.m_CurrentDir;
1038 if (gitPath.HasSubmodules())
1039 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1041 int ret = progress.DoModal();
1042 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1044 CString sCmd;
1045 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1047 RunTortoiseProc(sCmd);
1048 return TRUE;
1050 else if (ret == IDOK)
1051 return TRUE;
1053 return FALSE;
1056 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1058 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1060 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1061 return false;
1064 if (file.GetLength() > 0)
1066 file.Seek(file.GetLength() - 1, 0);
1067 auto_buffer<TCHAR> buf(1);
1068 file.Read(buf, 1);
1069 file.SeekToEnd();
1070 if (buf[0] != _T('\n'))
1071 file.WriteString(_T("\n"));
1073 else
1074 file.SeekToEnd();
1076 return true;
1079 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1081 CIgnoreDlg ignoreDlg;
1082 if (ignoreDlg.DoModal() == IDOK)
1084 CString ignorefile;
1085 ignorefile = g_Git.m_CurrentDir + _T("\\");
1087 switch (ignoreDlg.m_IgnoreFile)
1089 case 0:
1090 ignorefile += _T(".gitignore");
1091 break;
1092 case 2:
1093 ignorefile += _T(".git/info/exclude");
1094 break;
1097 CStdioFile file;
1100 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1101 return false;
1103 for (int i = 0; i < path.GetCount(); i++)
1105 if (ignoreDlg.m_IgnoreFile == 1)
1107 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1108 if (!OpenIgnoreFile(file, ignorefile))
1109 return false;
1112 CString ignorePattern;
1113 if (ignoreDlg.m_IgnoreType == 0)
1115 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetWinPathString().IsEmpty())
1116 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetWinPathString();
1118 ignorePattern += _T("/");
1120 if (IsMask)
1122 ignorePattern += _T("*") + path[i].GetFileExtension();
1124 else
1126 ignorePattern += path[i].GetFileOrDirectoryName();
1128 file.WriteString(ignorePattern + _T("\n"));
1130 if (ignoreDlg.m_IgnoreFile == 1)
1131 file.Close();
1134 if (ignoreDlg.m_IgnoreFile != 1)
1135 file.Close();
1137 catch(...)
1139 file.Abort();
1140 return false;
1143 return true;
1145 return false;
1149 bool CAppUtils::GitReset(CString *CommitHash,int type)
1151 CResetDlg dlg;
1152 dlg.m_ResetType=type;
1153 dlg.m_ResetToVersion=*CommitHash;
1154 if (dlg.DoModal() == IDOK)
1156 CString cmd;
1157 CString type;
1158 switch(dlg.m_ResetType)
1160 case 0:
1161 type=_T("--soft");
1162 break;
1163 case 1:
1164 type=_T("--mixed");
1165 break;
1166 case 2:
1167 type=_T("--hard");
1168 break;
1169 default:
1170 type=_T("--mixed");
1171 break;
1173 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1175 CProgressDlg progress;
1176 progress.m_GitCmd=cmd;
1178 CTGitPath gitPath = g_Git.m_CurrentDir;
1179 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1180 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1182 int ret = progress.DoModal();
1183 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1185 CString sCmd;
1186 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1188 RunTortoiseProc(sCmd);
1189 return TRUE;
1191 else if (ret == IDOK)
1192 return TRUE;
1195 return FALSE;
1198 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1200 if(mode == FALSE)
1202 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1203 return;
1205 if(base)
1207 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1208 return;
1210 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1211 return;
1214 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1216 CString tempmergefile;
1219 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1220 CFile::Remove(tempmergefile);
1221 }catch(...)
1227 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1228 CFile::Remove(tempmergefile);
1229 }catch(...)
1235 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1236 CFile::Remove(tempmergefile);
1237 }catch(...)
1241 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1243 CString file;
1244 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1246 return file;
1249 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1251 bool bRet = false;
1253 CTGitPath merge=path;
1254 CTGitPath directory = merge.GetDirectory();
1256 // we have the conflicted file (%merged)
1257 // now look for the other required files
1258 //GitStatus stat;
1259 //stat.GetStatus(merge);
1260 //if (stat.status == NULL)
1261 // return false;
1263 BYTE_VECTOR vector;
1265 CString cmd;
1266 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1268 if (g_Git.Run(cmd, &vector))
1270 return FALSE;
1273 CTGitPathList list;
1274 list.ParserFromLsFile(vector);
1276 if(list.GetCount() == 0)
1277 return FALSE;
1279 CTGitPath theirs;
1280 CTGitPath mine;
1281 CTGitPath base;
1283 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1284 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1285 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1287 CString format;
1289 //format=_T("git.exe cat-file blob \":%d:%s\"");
1290 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1291 CFile tempfile;
1292 //create a empty file, incase stage is not three
1293 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1294 tempfile.Close();
1295 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1296 tempfile.Close();
1297 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1298 tempfile.Close();
1300 bool b_base=false, b_local=false, b_remote=false;
1302 for(int i=0;i<list.GetCount();i++)
1304 CString cmd;
1305 CString outfile;
1306 cmd.Empty();
1307 outfile.Empty();
1309 if( list[i].m_Stage == 1)
1311 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1312 b_base = true;
1313 outfile = base.GetWinPathString();
1316 if( list[i].m_Stage == 2 )
1318 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1319 b_local = true;
1320 outfile = mine.GetWinPathString();
1323 if( list[i].m_Stage == 3 )
1325 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1326 b_remote = true;
1327 outfile = theirs.GetWinPathString();
1329 CString output, err;
1330 if(!outfile.IsEmpty())
1331 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1333 CString file;
1334 int start =0 ;
1335 file = output.Tokenize(_T("\t"), start);
1336 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1338 else
1340 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1344 if(b_local && b_remote )
1346 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1347 if( revertTheirMy )
1348 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1349 else
1350 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1353 else
1355 CFile::Remove(mine.GetWinPathString());
1356 CFile::Remove(theirs.GetWinPathString());
1357 CFile::Remove(base.GetWinPathString());
1359 CDeleteConflictDlg dlg;
1360 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1361 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1362 dlg.m_bShowModifiedButton=b_base;
1363 dlg.m_File=merge.GetGitPathString();
1364 if(dlg.DoModal() == IDOK)
1366 CString cmd,out;
1367 if(dlg.m_bIsDelete)
1369 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1371 else
1372 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1374 if (g_Git.Run(cmd, &out, CP_UTF8))
1376 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1377 return FALSE;
1379 return TRUE;
1381 else
1382 return FALSE;
1385 #if 0
1386 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1387 base, theirs, mine, merge);
1388 #endif
1389 #if 0
1390 if (stat.status->text_status == svn_wc_status_conflicted)
1392 // we have a text conflict, use our merge tool to resolve the conflict
1394 CTSVNPath theirs(directory);
1395 CTSVNPath mine(directory);
1396 CTSVNPath base(directory);
1397 bool bConflictData = false;
1399 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1401 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1402 bConflictData = true;
1404 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1406 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1407 bConflictData = true;
1409 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1411 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1412 bConflictData = true;
1414 else
1416 mine = merge;
1418 if (bConflictData)
1419 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1420 base, theirs, mine, merge);
1423 if (stat.status->prop_status == svn_wc_status_conflicted)
1425 // we have a property conflict
1426 CTSVNPath prej(directory);
1427 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1429 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1430 // there's a problem: the prej file contains a _description_ of the conflict, and
1431 // that description string might be translated. That means we have no way of parsing
1432 // the file to find out the conflicting values.
1433 // The only thing we can do: show a dialog with the conflict description, then
1434 // let the user either accept the existing property or open the property edit dialog
1435 // to manually change the properties and values. And a button to mark the conflict as
1436 // resolved.
1437 CEditPropConflictDlg dlg;
1438 dlg.SetPrejFile(prej);
1439 dlg.SetConflictedItem(merge);
1440 bRet = (dlg.DoModal() != IDCANCEL);
1444 if (stat.status->tree_conflict)
1446 // we have a tree conflict
1447 SVNInfo info;
1448 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1449 if (pInfoData)
1451 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1453 CTSVNPath theirs(directory);
1454 CTSVNPath mine(directory);
1455 CTSVNPath base(directory);
1456 bool bConflictData = false;
1458 if (pInfoData->treeconflict_theirfile)
1460 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1461 bConflictData = true;
1463 if (pInfoData->treeconflict_basefile)
1465 base.AppendPathString(pInfoData->treeconflict_basefile);
1466 bConflictData = true;
1468 if (pInfoData->treeconflict_myfile)
1470 mine.AppendPathString(pInfoData->treeconflict_myfile);
1471 bConflictData = true;
1473 else
1475 mine = merge;
1477 if (bConflictData)
1478 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1479 base, theirs, mine, merge);
1481 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1483 CString sConflictAction;
1484 CString sConflictReason;
1485 CString sResolveTheirs;
1486 CString sResolveMine;
1487 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1488 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1490 if (pInfoData->treeconflict_nodekind == svn_node_file)
1492 switch (pInfoData->treeconflict_operation)
1494 case svn_wc_operation_update:
1495 switch (pInfoData->treeconflict_action)
1497 case svn_wc_conflict_action_edit:
1498 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1499 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1500 break;
1501 case svn_wc_conflict_action_add:
1502 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1503 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1504 break;
1505 case svn_wc_conflict_action_delete:
1506 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1507 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1508 break;
1510 break;
1511 case svn_wc_operation_switch:
1512 switch (pInfoData->treeconflict_action)
1514 case svn_wc_conflict_action_edit:
1515 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1516 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1517 break;
1518 case svn_wc_conflict_action_add:
1519 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1520 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1521 break;
1522 case svn_wc_conflict_action_delete:
1523 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1524 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1525 break;
1527 break;
1528 case svn_wc_operation_merge:
1529 switch (pInfoData->treeconflict_action)
1531 case svn_wc_conflict_action_edit:
1532 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1533 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1534 break;
1535 case svn_wc_conflict_action_add:
1536 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1537 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1538 break;
1539 case svn_wc_conflict_action_delete:
1540 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1541 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1542 break;
1544 break;
1547 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1549 switch (pInfoData->treeconflict_operation)
1551 case svn_wc_operation_update:
1552 switch (pInfoData->treeconflict_action)
1554 case svn_wc_conflict_action_edit:
1555 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1556 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1557 break;
1558 case svn_wc_conflict_action_add:
1559 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1560 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1561 break;
1562 case svn_wc_conflict_action_delete:
1563 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1564 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1565 break;
1567 break;
1568 case svn_wc_operation_switch:
1569 switch (pInfoData->treeconflict_action)
1571 case svn_wc_conflict_action_edit:
1572 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1573 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1574 break;
1575 case svn_wc_conflict_action_add:
1576 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1577 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1578 break;
1579 case svn_wc_conflict_action_delete:
1580 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1581 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1582 break;
1584 break;
1585 case svn_wc_operation_merge:
1586 switch (pInfoData->treeconflict_action)
1588 case svn_wc_conflict_action_edit:
1589 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1590 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1591 break;
1592 case svn_wc_conflict_action_add:
1593 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1594 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1595 break;
1596 case svn_wc_conflict_action_delete:
1597 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1598 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1599 break;
1601 break;
1605 UINT uReasonID = 0;
1606 switch (pInfoData->treeconflict_reason)
1608 case svn_wc_conflict_reason_edited:
1609 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1610 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1611 break;
1612 case svn_wc_conflict_reason_obstructed:
1613 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1614 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1615 break;
1616 case svn_wc_conflict_reason_deleted:
1617 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1618 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1619 break;
1620 case svn_wc_conflict_reason_added:
1621 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1622 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1623 break;
1624 case svn_wc_conflict_reason_missing:
1625 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1626 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1627 break;
1628 case svn_wc_conflict_reason_unversioned:
1629 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1630 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1631 break;
1633 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1635 CTreeConflictEditorDlg dlg;
1636 dlg.SetConflictInfoText(sConflictReason);
1637 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1638 dlg.SetPath(treeConflictPath);
1639 INT_PTR dlgRet = dlg.DoModal();
1640 bRet = (dlgRet != IDCANCEL);
1644 #endif
1645 return bRet;
1648 bool CAppUtils::IsSSHPutty()
1650 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1651 sshclient=sshclient.MakeLower();
1652 if(sshclient.Find(_T("plink.exe"),0)>=0)
1654 return true;
1656 return false;
1659 CString CAppUtils::GetClipboardLink()
1661 if (!OpenClipboard(NULL))
1662 return CString();
1664 CString sClipboardText;
1665 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1666 if (hglb)
1668 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1669 sClipboardText = CString(lpstr);
1670 GlobalUnlock(hglb);
1672 hglb = GetClipboardData(CF_UNICODETEXT);
1673 if (hglb)
1675 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1676 sClipboardText = lpstr;
1677 GlobalUnlock(hglb);
1679 CloseClipboard();
1681 if(!sClipboardText.IsEmpty())
1683 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1684 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1686 if(sClipboardText.Find( _T("http://")) == 0)
1687 return sClipboardText;
1689 if(sClipboardText.Find( _T("https://")) == 0)
1690 return sClipboardText;
1692 if(sClipboardText.Find( _T("git://")) == 0)
1693 return sClipboardText;
1695 if(sClipboardText.Find( _T("ssh://")) == 0)
1696 return sClipboardText;
1698 if(sClipboardText.GetLength()>=2)
1699 if( sClipboardText[1] == _T(':') )
1700 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1701 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1702 return sClipboardText;
1705 return CString(_T(""));
1708 CString CAppUtils::ChooseRepository(CString *path)
1710 CBrowseFolder browseFolder;
1711 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1713 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1714 CString strCloneDirectory;
1715 if(path)
1716 strCloneDirectory=*path;
1717 else
1719 strCloneDirectory = regLastResopitory;
1722 CString title;
1723 title.LoadString(IDS_CHOOSE_REPOSITORY);
1725 browseFolder.SetInfo(title);
1727 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1729 regLastResopitory = strCloneDirectory;
1730 return strCloneDirectory;
1732 else
1734 return CString();
1738 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1740 CSendMailDlg dlg;
1742 dlg.m_PathList = list;
1744 if(dlg.DoModal()==IDOK)
1746 if(dlg.m_PathList.GetCount() == 0)
1747 return FALSE;
1749 CGitProgressDlg progDlg;
1751 theApp.m_pMainWnd = &progDlg;
1752 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1754 progDlg.SetAutoClose(autoclose);
1756 progDlg.SetPathList(dlg.m_PathList);
1757 //ProjectProperties props;
1758 //props.ReadPropsPathList(dlg.m_pathList);
1759 //progDlg.SetProjectProperties(props);
1760 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1762 DWORD flags =0;
1763 if(dlg.m_bAttachment)
1764 flags |= SENDMAIL_ATTACHMENT;
1765 if(dlg.m_bCombine)
1766 flags |= SENDMAIL_COMBINED;
1767 if(dlg.m_bUseMAPI)
1768 flags |= SENDMAIL_MAPI;
1770 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1772 progDlg.DoModal();
1774 return true;
1776 return false;
1779 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1781 CTGitPathList list;
1782 CString log=formatpatchoutput;
1783 int start=log.Find(cmd);
1784 if(start >=0)
1785 CString one=log.Tokenize(_T("\n"),start);
1786 else
1787 start = 0;
1789 while(start>=0)
1791 CString one=log.Tokenize(_T("\n"),start);
1792 one=one.Trim();
1793 if(one.IsEmpty() || one == _T("Success"))
1794 continue;
1795 one.Replace(_T('/'),_T('\\'));
1796 CTGitPath path;
1797 path.SetFromWin(one);
1798 list.AddPath(path);
1800 if (list.GetCount() > 0)
1802 return SendPatchMail(list, autoclose);
1804 else
1806 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1807 return true;
1812 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1814 CString cmd,output;
1815 int start=0;
1817 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1818 if(output.IsEmpty())
1820 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1821 if(output.IsEmpty())
1822 return CP_UTF8;
1824 int start=0;
1825 output=output.Tokenize(_T("\n"),start);
1826 return CUnicodeUtils::GetCPCode(output);
1829 else
1831 output=output.Tokenize(_T("\n"),start);
1832 return CUnicodeUtils::GetCPCode(output);
1835 int CAppUtils::GetCommitTemplate(CString &temp)
1837 CString cmd,output;
1839 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
1840 if( output.IsEmpty() )
1841 return -1;
1843 if( output.GetLength()<1)
1844 return -1;
1846 if( output[0] == _T('/'))
1848 if(output.GetLength()>=3)
1849 if(output[2] == _T('/'))
1851 output.GetBuffer()[0] = output[1];
1852 output.GetBuffer()[1] = _T(':');
1856 int start=0;
1857 output=output.Tokenize(_T("\n"),start);
1859 output.Replace(_T('/'),_T('\\'));
1863 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1864 CString str;
1865 while(file.ReadString(str))
1867 temp+=str+_T("\n");
1870 }catch(...)
1872 return -1;
1874 return 0;
1876 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1878 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1879 CString cmd,output;
1880 int cp=CP_UTF8;
1882 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1883 if(output.IsEmpty())
1884 cp=CP_UTF8;
1886 int start=0;
1887 output=output.Tokenize(_T("\n"),start);
1888 cp=CUnicodeUtils::GetCPCode(output);
1890 int len=message.GetLength();
1892 char * buf;
1893 buf = new char[len*4 + 4];
1894 SecureZeroMemory(buf, (len*4 + 4));
1896 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1898 file.Write(buf,lengthIncTerminator-1);
1899 file.Close();
1900 delete buf;
1901 return 0;
1904 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1906 CPullFetchDlg dlg;
1907 dlg.m_PreSelectRemote = remoteName;
1908 dlg.m_bAllowRebase = allowRebase;
1909 dlg.m_IsPull=FALSE;
1911 if(dlg.DoModal()==IDOK)
1913 if(dlg.m_bAutoLoad)
1915 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1918 CString url;
1919 url=dlg.m_RemoteURL;
1920 CString cmd;
1921 CString arg;
1923 int ver = CAppUtils::GetMsysgitVersion();
1925 if(ver >= 0x01070203) //above 1.7.0.2
1926 arg = _T("--progress ");
1928 if (dlg.m_bPrune) {
1929 arg += _T("--prune ");
1932 if (dlg.m_bFetchTags == 1)
1934 arg += _T("--tags ");
1936 else if (dlg.m_bFetchTags == 0)
1938 arg += _T("--no-tags ");
1941 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
1942 CProgressDlg progress;
1944 progress.m_bAutoCloseOnSuccess = autoClose;
1946 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
1948 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1950 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1953 progress.m_GitCmd=cmd;
1954 int userResponse=progress.DoModal();
1956 if (userResponse == IDC_PROGRESS_BUTTON1)
1958 CString cmd = _T("/command:log");
1959 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1960 RunTortoiseProc(cmd);
1961 return TRUE;
1963 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1965 while(1)
1967 CRebaseDlg dlg;
1968 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
1969 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1970 int response = dlg.DoModal();
1971 if(response == IDOK)
1973 return TRUE;
1975 if(response == IDC_REBASE_POST_BUTTON )
1977 CString cmd, out, err;
1978 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
1979 g_Git.m_CurrentDir,
1980 g_Git.FixBranchName(dlg.m_Upstream),
1981 g_Git.FixBranchName(dlg.m_Branch));
1982 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
1984 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1985 return FALSE;
1988 CAppUtils::SendPatchMail(cmd,out);
1989 return TRUE;
1992 if(response == IDC_REBASE_POST_BUTTON +1 )
1993 continue;
1995 if(response == IDCANCEL)
1996 return FALSE;
1998 return TRUE;
2000 else if (userResponse != IDCANCEL)
2001 return TRUE;
2003 return FALSE;
2006 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2008 CPushDlg dlg;
2009 dlg.m_BranchSourceName = selectLocalBranch;
2010 CString error;
2011 DWORD exitcode = 0xFFFFFFFF;
2012 CTGitPathList list;
2013 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2014 if (CHooks::Instance().PrePush(list,exitcode, error))
2016 if (exitcode)
2018 CString temp;
2019 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2020 //ReportError(temp);
2021 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2022 return false;
2026 if(dlg.DoModal()==IDOK)
2028 CString cmd;
2029 CString arg;
2031 if(dlg.m_bAutoLoad)
2033 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2036 if(dlg.m_bPack)
2037 arg += _T("--thin ");
2038 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2039 arg += _T("--tags ");
2040 if(dlg.m_bForce)
2041 arg += _T("--force ");
2043 int ver = CAppUtils::GetMsysgitVersion();
2045 if(ver >= 0x01070203) //above 1.7.0.2
2046 arg += _T("--progress ");
2048 if (dlg.m_bPushAllBranches)
2050 cmd.Format(_T("git.exe push --all %s \"%s\""),
2051 arg,
2052 dlg.m_URL);
2054 else
2056 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2057 arg,
2058 dlg.m_URL,
2059 dlg.m_BranchSourceName);
2060 if (!dlg.m_BranchRemoteName.IsEmpty())
2062 cmd += _T(":") + dlg.m_BranchRemoteName;
2066 CProgressDlg progress;
2067 progress.m_bAutoCloseOnSuccess=autoClose;
2068 progress.m_GitCmd=cmd;
2069 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2070 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2071 int ret = progress.DoModal();
2073 if(!progress.m_GitStatus)
2075 if (CHooks::Instance().PostPush(list,exitcode, error))
2077 if (exitcode)
2079 CString temp;
2080 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2081 //ReportError(temp);
2082 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2083 return false;
2086 if(ret == IDC_PROGRESS_BUTTON1)
2088 RequestPull(dlg.m_BranchRemoteName);
2090 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2092 Push();
2094 return TRUE;
2098 return FALSE;
2101 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2103 CRequestPullDlg dlg;
2104 dlg.m_RepositoryURL = repositoryUrl;
2105 dlg.m_EndRevision = endrevision;
2106 if (dlg.DoModal()==IDOK)
2108 CString cmd;
2109 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2111 CString tempFileName = GetTempFile();
2112 if (g_Git.RunLogFile(cmd, tempFileName))
2114 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2115 return false;
2117 CAppUtils::LaunchAlternativeEditor(tempFileName);
2119 return true;
2122 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2124 CString strDir(szPath);
2125 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2127 strDir.AppendChar(_T('\\'));
2129 std::vector<CString> vPath;
2130 CString strTemp;
2131 bool bSuccess = false;
2133 for (int i=0;i<strDir.GetLength();++i)
2135 if (strDir.GetAt(i) != _T('\\'))
2137 strTemp.AppendChar(strDir.GetAt(i));
2139 else
2141 vPath.push_back(strTemp);
2142 strTemp.AppendChar(_T('\\'));
2146 std::vector<CString>::const_iterator vIter;
2147 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2149 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2152 return bSuccess;
2155 void CAppUtils::RemoveTrailSlash(CString &path)
2157 if(path.IsEmpty())
2158 return ;
2160 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2162 path=path.Left(path.GetLength()-1);
2163 if(path.IsEmpty())
2164 return;
2168 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2169 CTGitPathList &pathList,
2170 CTGitPathList &selectedList,
2171 bool bSelectFilesForCommit,
2172 bool autoClose)
2174 bool bFailed = true;
2176 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2178 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2180 CTGitPath path(g_Git.m_CurrentDir);
2181 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2182 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2183 dlg.SetTreeWidth(220);
2184 dlg.m_DefaultPage = _T("gitconfig");
2186 dlg.DoModal();
2187 dlg.HandleRestart();
2190 else
2191 return false;
2194 while (bFailed)
2196 bFailed = false;
2197 CCommitDlg dlg;
2198 dlg.m_sBugID = bugid;
2200 dlg.m_bWholeProject = bWholeProject;
2202 dlg.m_sLogMessage = sLogMsg;
2203 dlg.m_pathList = pathList;
2204 dlg.m_checkedPathList = selectedList;
2205 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2206 dlg.m_bAutoClose = autoClose;
2207 if (dlg.DoModal() == IDOK)
2209 if (dlg.m_pathList.GetCount()==0)
2210 return false;
2211 // if the user hasn't changed the list of selected items
2212 // we don't use that list. Because if we would use the list
2213 // of pre-checked items, the dialog would show different
2214 // checked items on the next startup: it would only try
2215 // to check the parent folder (which might not even show)
2216 // instead, we simply use an empty list and let the
2217 // default checking do its job.
2218 if (!dlg.m_pathList.IsEqual(pathList))
2219 selectedList = dlg.m_pathList;
2220 pathList = dlg.m_updatedPathList;
2221 sLogMsg = dlg.m_sLogMessage;
2222 bSelectFilesForCommit = true;
2224 if( dlg.m_bPushAfterCommit )
2226 switch(dlg.m_PostCmd)
2228 case GIT_POST_CMD_DCOMMIT:
2229 CAppUtils::SVNDCommit();
2230 break;
2231 default:
2232 CAppUtils::Push();
2235 else if (dlg.m_bCreateTagAfterCommit)
2237 CAppUtils::CreateBranchTag(TRUE);
2240 // CGitProgressDlg progDlg;
2241 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2242 // if (parser.HasVal(_T("closeonend")))
2243 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2244 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2245 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2246 // progDlg.SetPathList(dlg.m_pathList);
2247 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2248 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2249 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2250 // progDlg.SetItemCount(dlg.m_itemsCount);
2251 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2252 // progDlg.DoModal();
2253 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2254 // err = (DWORD)progDlg.DidErrorsOccur();
2255 // bFailed = progDlg.DidErrorsOccur();
2256 // bRet = progDlg.DidErrorsOccur();
2257 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2258 // if (DWORD(bFailRepeat)==0)
2259 // bFailed = false; // do not repeat if the user chose not to in the settings.
2262 return true;
2266 BOOL CAppUtils::SVNDCommit()
2268 CSVNDCommitDlg dcommitdlg;
2269 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2270 if (gitSetting == _T("")) {
2271 if (dcommitdlg.DoModal() != IDOK)
2273 return false;
2275 else
2277 if (dcommitdlg.m_remember)
2279 if (dcommitdlg.m_rmdir)
2281 gitSetting = _T("true");
2283 else
2285 gitSetting = _T("false");
2287 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2289 CString msg;
2290 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2291 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2297 BOOL IsStash = false;
2298 if(!g_Git.CheckCleanWorkTree())
2300 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2302 CString cmd,out;
2303 cmd=_T("git.exe stash");
2304 if (g_Git.Run(cmd, &out, CP_UTF8))
2306 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2307 return false;
2309 IsStash =true;
2312 else
2314 return false;
2318 CProgressDlg progress;
2319 if (dcommitdlg.m_rmdir)
2321 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2323 else
2325 progress.m_GitCmd=_T("git.exe svn dcommit");
2327 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2329 if( IsStash)
2331 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2333 CString cmd,out;
2334 cmd=_T("git.exe stash pop");
2335 if (g_Git.Run(cmd, &out, CP_UTF8))
2337 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2338 return false;
2342 else
2344 return false;
2347 return TRUE;
2349 return FALSE;
2352 BOOL CAppUtils::Merge(CString *commit)
2354 CMergeDlg dlg;
2355 if(commit)
2356 dlg.m_initialRefName = *commit;
2358 if(dlg.DoModal()==IDOK)
2360 CString cmd;
2361 CString noff;
2362 CString squash;
2363 CString nocommit;
2364 CString msg;
2366 if(dlg.m_bNoFF)
2367 noff=_T("--no-ff");
2369 if(dlg.m_bSquash)
2370 squash=_T("--squash");
2372 if(dlg.m_bNoCommit)
2373 nocommit=_T("--no-commit");
2375 if(!dlg.m_strLogMesage.IsEmpty())
2377 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2379 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2380 msg,
2381 noff,
2382 squash,
2383 nocommit,
2384 g_Git.FixBranchName(dlg.m_VersionName));
2386 CProgressDlg Prodlg;
2387 Prodlg.m_GitCmd = cmd;
2389 if (dlg.m_bNoCommit)
2390 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2391 else if (dlg.m_bIsBranch)
2392 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2394 int ret = Prodlg.DoModal();
2396 if (ret == IDC_PROGRESS_BUTTON1)
2397 if (dlg.m_bNoCommit)
2398 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2399 else if (dlg.m_bIsBranch)
2401 CString msg;
2402 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2403 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2405 CString cmd, out;
2406 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2407 if (g_Git.Run(cmd, &out, CP_UTF8))
2408 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2412 return !Prodlg.m_GitStatus;
2414 return false;
2417 void CAppUtils::EditNote(GitRev *rev)
2419 CInputDlg dlg;
2420 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2421 dlg.m_sInputText = rev->m_Notes;
2422 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2423 //dlg.m_pProjectProperties = &m_ProjectProperties;
2424 dlg.m_bUseLogWidth = true;
2425 if(dlg.DoModal() == IDOK)
2427 CString cmd,output;
2428 cmd=_T("notes add -f -F \"");
2430 CString tempfile=::GetTempFile();
2431 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2432 cmd += tempfile;
2433 cmd += _T("\" ");
2434 cmd += rev->m_CommitHash.ToString();
2438 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2440 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2443 else
2445 rev->m_Notes = dlg.m_sInputText;
2447 }catch(...)
2449 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2451 CFile::Remove(tempfile);
2456 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2458 CString cmd;
2459 CString progressarg;
2460 CString version;
2462 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2463 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2465 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2467 __int64 time=0;
2468 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2470 if((DWORD)time == regTime)
2472 return regVersion;
2476 if(versionstr)
2477 version = *versionstr;
2478 else
2480 CString err;
2481 cmd = _T("git.exe --version");
2482 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2484 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2485 return false;
2489 int start=0;
2490 int ver = 0;
2494 CString str=version.Tokenize(_T("."), start);
2495 int space = str.ReverseFind(_T(' '));
2496 str = str.Mid(space+1,start);
2497 ver = _ttol(str);
2498 ver <<=24;
2500 version = version.Mid(start);
2501 start = 0;
2503 str = version.Tokenize(_T("."), start);
2505 ver |= (_ttol(str) & 0xFF) << 16;
2507 str = version.Tokenize(_T("."), start);
2508 ver |= (_ttol(str) & 0xFF) << 8;
2510 str = version.Tokenize(_T("."), start);
2511 ver |= (_ttol(str) & 0xFF);
2513 catch(...)
2515 if (!ver)
2517 CMessageBox::Show(NULL, _T("Could not parse git.exe version number."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2518 return false;
2522 regTime = time&0xFFFFFFFF;
2523 regVersion = ver;
2525 return ver;
2528 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2530 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2532 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2534 if (hShell.IsValid()) {
2535 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2536 if (pfnSHGPSFW) {
2537 IPropertyStore *pps;
2538 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2539 if (SUCCEEDED(hr)) {
2540 PROPVARIANT var;
2541 var.vt = VT_BOOL;
2542 var.boolVal = VARIANT_TRUE;
2543 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2544 pps->Release();
2550 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2552 ASSERT(dialogname.GetLength() < 70);
2553 ASSERT(urlorpath.GetLength() < MAX_PATH);
2554 WCHAR pathbuf[MAX_PATH] = {0};
2556 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2558 wcscat_s(pathbuf, L" - ");
2559 wcscat_s(pathbuf, dialogname);
2560 wcscat_s(pathbuf, L" - ");
2561 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2562 SetWindowText(hWnd, pathbuf);