PushDlg: Allow to set upstream
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
bloba0122464ed3a1c777edf82620570fbac550c4859
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 if (rev1 == GitRev::GetWorkingCopy())
842 cmd.Format(_T("git.exe diff -R --stat -p %s "), rev2);
844 else
846 CString merge;
847 if(bMerge)
848 merge = _T("-c");
850 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
853 if( !url1.IsEmpty() )
855 cmd += _T(" -- \"");
856 cmd += url1.GetGitPathString();
857 cmd += _T("\" ");
859 g_Git.RunLogFile(cmd,tempfile);
860 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
863 #if 0
864 CString sCmd;
865 sCmd.Format(_T("%s /command:showcompare /unified"),
866 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
867 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
868 if (rev1.IsValid())
869 sCmd += _T(" /revision1:") + rev1.ToString();
870 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
871 if (rev2.IsValid())
872 sCmd += _T(" /revision2:") + rev2.ToString();
873 if (peg.IsValid())
874 sCmd += _T(" /pegrevision:") + peg.ToString();
875 if (headpeg.IsValid())
876 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
878 if (bAlternateDiff)
879 sCmd += _T(" /alternatediff");
881 if (bIgnoreAncestry)
882 sCmd += _T(" /ignoreancestry");
884 if (hWnd)
886 sCmd += _T(" /hwnd:");
887 TCHAR buf[30];
888 _stprintf_s(buf, 30, _T("%d"), hWnd);
889 sCmd += buf;
892 return CAppUtils::LaunchApplication(sCmd, NULL, false);
893 #endif
894 return TRUE;
898 bool CAppUtils::Export(CString *BashHash)
900 bool bRet = false;
902 // ask from where the export has to be done
903 CExportDlg dlg;
904 if(BashHash)
905 dlg.m_Revision=*BashHash;
907 if (dlg.DoModal() == IDOK)
909 CString cmd;
910 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
911 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
913 CProgressDlg pro;
914 pro.m_GitCmd=cmd;
915 pro.DoModal();
916 return TRUE;
918 return bRet;
921 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
923 CCreateBranchTagDlg dlg;
924 dlg.m_bIsTag=IsTag;
925 dlg.m_bSwitch=switch_new_brach;
927 if(CommitHash)
928 dlg.m_initialRefName = *CommitHash;
930 if(dlg.DoModal()==IDOK)
932 CString cmd;
933 CString force;
934 CString track;
935 if(dlg.m_bTrack == TRUE)
936 track=_T(" --track ");
937 else if(dlg.m_bTrack == FALSE)
938 track=_T(" --no-track");
940 if(dlg.m_bForce)
941 force=_T(" -f ");
943 if(IsTag)
945 CString sign;
946 if(dlg.m_bSign)
947 sign=_T("-s");
949 cmd.Format(_T("git.exe tag %s %s %s %s"),
950 force,
951 sign,
952 dlg.m_BranchTagName,
953 g_Git.FixBranchName(dlg.m_VersionName)
956 CString tempfile=::GetTempFile();
957 if(!dlg.m_Message.Trim().IsEmpty())
959 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
960 cmd += _T(" -F ")+tempfile;
963 else
965 cmd.Format(_T("git.exe branch %s %s %s %s"),
966 track,
967 force,
968 dlg.m_BranchTagName,
969 g_Git.FixBranchName(dlg.m_VersionName)
972 CString out;
973 if(g_Git.Run(cmd,&out,CP_UTF8))
975 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
976 return FALSE;
978 if( !IsTag && dlg.m_bSwitch )
980 // it is a new branch and the user has requested to switch to it
981 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
982 g_Git.Run(cmd,&out,CP_UTF8);
983 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
986 return TRUE;
988 return FALSE;
991 bool CAppUtils::Switch(CString initialRefName, bool autoclose)
993 CGitSwitchDlg dlg;
994 if(!initialRefName.IsEmpty())
995 dlg.m_initialRefName = initialRefName;
997 if (dlg.DoModal() == IDOK)
999 CString branch;
1000 if (dlg.m_bBranch)
1001 branch = dlg.m_NewBranch;
1003 // if refs/heads/ is not stripped, checkout will detach HEAD
1004 // checkout prefers branches on name clashes (with tags)
1005 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1006 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1008 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1010 return FALSE;
1013 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1015 CString cmd;
1016 CString track;
1017 CString force;
1018 CString branch;
1020 if(!sNewBranch.IsEmpty()){
1021 if (bBranchOverride)
1023 branch.Format(_T("-B %s"), sNewBranch);
1025 else
1027 branch.Format(_T("-b %s"), sNewBranch);
1029 if (bTrack)
1030 track = _T("--track");
1032 if (bForce)
1033 force = _T("-f");
1035 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1036 force,
1037 track,
1038 branch,
1039 g_Git.FixBranchName(ref));
1041 CProgressDlg progress;
1042 progress.m_bAutoCloseOnSuccess = autoClose;
1043 progress.m_GitCmd = cmd;
1045 CTGitPath gitPath = g_Git.m_CurrentDir;
1046 if (gitPath.HasSubmodules())
1047 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1049 int ret = progress.DoModal();
1050 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1052 CString sCmd;
1053 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1055 RunTortoiseProc(sCmd);
1056 return TRUE;
1058 else if (ret == IDOK)
1059 return TRUE;
1061 return FALSE;
1064 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1066 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1068 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1069 return false;
1072 if (file.GetLength() > 0)
1074 file.Seek(file.GetLength() - 1, 0);
1075 auto_buffer<TCHAR> buf(1);
1076 file.Read(buf, 1);
1077 file.SeekToEnd();
1078 if (buf[0] != _T('\n'))
1079 file.WriteString(_T("\n"));
1081 else
1082 file.SeekToEnd();
1084 return true;
1087 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1089 CIgnoreDlg ignoreDlg;
1090 if (ignoreDlg.DoModal() == IDOK)
1092 CString ignorefile;
1093 ignorefile = g_Git.m_CurrentDir + _T("\\");
1095 switch (ignoreDlg.m_IgnoreFile)
1097 case 0:
1098 ignorefile += _T(".gitignore");
1099 break;
1100 case 2:
1101 ignorefile += _T(".git/info/exclude");
1102 break;
1105 CStdioFile file;
1108 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1109 return false;
1111 for (int i = 0; i < path.GetCount(); i++)
1113 if (ignoreDlg.m_IgnoreFile == 1)
1115 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1116 if (!OpenIgnoreFile(file, ignorefile))
1117 return false;
1120 CString ignorePattern;
1121 if (ignoreDlg.m_IgnoreType == 0)
1123 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1124 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1126 ignorePattern += _T("/");
1128 if (IsMask)
1130 ignorePattern += _T("*") + path[i].GetFileExtension();
1132 else
1134 ignorePattern += path[i].GetFileOrDirectoryName();
1137 // escape [ and ] so that files get ignored correctly
1138 ignorePattern.Replace(_T("["), _T("\\["));
1139 ignorePattern.Replace(_T("]"), _T("\\]"));
1141 ignorePattern += _T("\n");
1142 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1143 file.Write(ignorePatternA.GetBuffer(), ignorePatternA.GetLength());
1144 ignorePatternA.ReleaseBuffer();
1146 if (ignoreDlg.m_IgnoreFile == 1)
1147 file.Close();
1150 if (ignoreDlg.m_IgnoreFile != 1)
1151 file.Close();
1153 catch(...)
1155 file.Abort();
1156 return false;
1159 return true;
1161 return false;
1165 bool CAppUtils::GitReset(CString *CommitHash,int type)
1167 CResetDlg dlg;
1168 dlg.m_ResetType=type;
1169 dlg.m_ResetToVersion=*CommitHash;
1170 if (dlg.DoModal() == IDOK)
1172 CString cmd;
1173 CString type;
1174 switch(dlg.m_ResetType)
1176 case 0:
1177 type=_T("--soft");
1178 break;
1179 case 1:
1180 type=_T("--mixed");
1181 break;
1182 case 2:
1183 type=_T("--hard");
1184 break;
1185 default:
1186 type=_T("--mixed");
1187 break;
1189 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1191 CProgressDlg progress;
1192 progress.m_GitCmd=cmd;
1194 CTGitPath gitPath = g_Git.m_CurrentDir;
1195 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1196 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1198 int ret = progress.DoModal();
1199 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1201 CString sCmd;
1202 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1204 RunTortoiseProc(sCmd);
1205 return TRUE;
1207 else if (ret == IDOK)
1208 return TRUE;
1211 return FALSE;
1214 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1216 if(mode == FALSE)
1218 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1219 return;
1221 if(base)
1223 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1224 return;
1226 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1227 return;
1230 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1232 CString tempmergefile;
1235 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1236 CFile::Remove(tempmergefile);
1237 }catch(...)
1243 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1244 CFile::Remove(tempmergefile);
1245 }catch(...)
1251 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1252 CFile::Remove(tempmergefile);
1253 }catch(...)
1257 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1259 CString file;
1260 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1262 return file;
1265 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1267 bool bRet = false;
1269 CTGitPath merge=path;
1270 CTGitPath directory = merge.GetDirectory();
1272 // we have the conflicted file (%merged)
1273 // now look for the other required files
1274 //GitStatus stat;
1275 //stat.GetStatus(merge);
1276 //if (stat.status == NULL)
1277 // return false;
1279 BYTE_VECTOR vector;
1281 CString cmd;
1282 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1284 if (g_Git.Run(cmd, &vector))
1286 return FALSE;
1289 CTGitPathList list;
1290 list.ParserFromLsFile(vector);
1292 if(list.GetCount() == 0)
1293 return FALSE;
1295 CTGitPath theirs;
1296 CTGitPath mine;
1297 CTGitPath base;
1299 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1300 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1301 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1303 CString format;
1305 //format=_T("git.exe cat-file blob \":%d:%s\"");
1306 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1307 CFile tempfile;
1308 //create a empty file, incase stage is not three
1309 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1310 tempfile.Close();
1311 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1312 tempfile.Close();
1313 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1314 tempfile.Close();
1316 bool b_base=false, b_local=false, b_remote=false;
1318 for(int i=0;i<list.GetCount();i++)
1320 CString cmd;
1321 CString outfile;
1322 cmd.Empty();
1323 outfile.Empty();
1325 if( list[i].m_Stage == 1)
1327 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1328 b_base = true;
1329 outfile = base.GetWinPathString();
1332 if( list[i].m_Stage == 2 )
1334 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1335 b_local = true;
1336 outfile = mine.GetWinPathString();
1339 if( list[i].m_Stage == 3 )
1341 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1342 b_remote = true;
1343 outfile = theirs.GetWinPathString();
1345 CString output, err;
1346 if(!outfile.IsEmpty())
1347 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1349 CString file;
1350 int start =0 ;
1351 file = output.Tokenize(_T("\t"), start);
1352 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1354 else
1356 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1360 if(b_local && b_remote )
1362 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1363 if( revertTheirMy )
1364 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1365 else
1366 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1369 else
1371 CFile::Remove(mine.GetWinPathString());
1372 CFile::Remove(theirs.GetWinPathString());
1373 CFile::Remove(base.GetWinPathString());
1375 CDeleteConflictDlg dlg;
1376 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1377 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1378 dlg.m_bShowModifiedButton=b_base;
1379 dlg.m_File=merge.GetGitPathString();
1380 if(dlg.DoModal() == IDOK)
1382 CString cmd,out;
1383 if(dlg.m_bIsDelete)
1385 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1387 else
1388 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1390 if (g_Git.Run(cmd, &out, CP_UTF8))
1392 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1393 return FALSE;
1395 return TRUE;
1397 else
1398 return FALSE;
1401 #if 0
1402 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1403 base, theirs, mine, merge);
1404 #endif
1405 #if 0
1406 if (stat.status->text_status == svn_wc_status_conflicted)
1408 // we have a text conflict, use our merge tool to resolve the conflict
1410 CTSVNPath theirs(directory);
1411 CTSVNPath mine(directory);
1412 CTSVNPath base(directory);
1413 bool bConflictData = false;
1415 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1417 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1418 bConflictData = true;
1420 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1422 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1423 bConflictData = true;
1425 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1427 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1428 bConflictData = true;
1430 else
1432 mine = merge;
1434 if (bConflictData)
1435 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1436 base, theirs, mine, merge);
1439 if (stat.status->prop_status == svn_wc_status_conflicted)
1441 // we have a property conflict
1442 CTSVNPath prej(directory);
1443 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1445 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1446 // there's a problem: the prej file contains a _description_ of the conflict, and
1447 // that description string might be translated. That means we have no way of parsing
1448 // the file to find out the conflicting values.
1449 // The only thing we can do: show a dialog with the conflict description, then
1450 // let the user either accept the existing property or open the property edit dialog
1451 // to manually change the properties and values. And a button to mark the conflict as
1452 // resolved.
1453 CEditPropConflictDlg dlg;
1454 dlg.SetPrejFile(prej);
1455 dlg.SetConflictedItem(merge);
1456 bRet = (dlg.DoModal() != IDCANCEL);
1460 if (stat.status->tree_conflict)
1462 // we have a tree conflict
1463 SVNInfo info;
1464 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1465 if (pInfoData)
1467 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1469 CTSVNPath theirs(directory);
1470 CTSVNPath mine(directory);
1471 CTSVNPath base(directory);
1472 bool bConflictData = false;
1474 if (pInfoData->treeconflict_theirfile)
1476 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1477 bConflictData = true;
1479 if (pInfoData->treeconflict_basefile)
1481 base.AppendPathString(pInfoData->treeconflict_basefile);
1482 bConflictData = true;
1484 if (pInfoData->treeconflict_myfile)
1486 mine.AppendPathString(pInfoData->treeconflict_myfile);
1487 bConflictData = true;
1489 else
1491 mine = merge;
1493 if (bConflictData)
1494 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1495 base, theirs, mine, merge);
1497 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1499 CString sConflictAction;
1500 CString sConflictReason;
1501 CString sResolveTheirs;
1502 CString sResolveMine;
1503 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1504 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1506 if (pInfoData->treeconflict_nodekind == svn_node_file)
1508 switch (pInfoData->treeconflict_operation)
1510 case svn_wc_operation_update:
1511 switch (pInfoData->treeconflict_action)
1513 case svn_wc_conflict_action_edit:
1514 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1515 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1516 break;
1517 case svn_wc_conflict_action_add:
1518 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1519 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1520 break;
1521 case svn_wc_conflict_action_delete:
1522 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1523 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1524 break;
1526 break;
1527 case svn_wc_operation_switch:
1528 switch (pInfoData->treeconflict_action)
1530 case svn_wc_conflict_action_edit:
1531 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1532 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1533 break;
1534 case svn_wc_conflict_action_add:
1535 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1536 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1537 break;
1538 case svn_wc_conflict_action_delete:
1539 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1540 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1541 break;
1543 break;
1544 case svn_wc_operation_merge:
1545 switch (pInfoData->treeconflict_action)
1547 case svn_wc_conflict_action_edit:
1548 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1549 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1550 break;
1551 case svn_wc_conflict_action_add:
1552 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1553 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1554 break;
1555 case svn_wc_conflict_action_delete:
1556 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1557 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1558 break;
1560 break;
1563 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1565 switch (pInfoData->treeconflict_operation)
1567 case svn_wc_operation_update:
1568 switch (pInfoData->treeconflict_action)
1570 case svn_wc_conflict_action_edit:
1571 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1572 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1573 break;
1574 case svn_wc_conflict_action_add:
1575 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1576 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1577 break;
1578 case svn_wc_conflict_action_delete:
1579 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1580 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1581 break;
1583 break;
1584 case svn_wc_operation_switch:
1585 switch (pInfoData->treeconflict_action)
1587 case svn_wc_conflict_action_edit:
1588 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1589 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1590 break;
1591 case svn_wc_conflict_action_add:
1592 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1593 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1594 break;
1595 case svn_wc_conflict_action_delete:
1596 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1597 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1598 break;
1600 break;
1601 case svn_wc_operation_merge:
1602 switch (pInfoData->treeconflict_action)
1604 case svn_wc_conflict_action_edit:
1605 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1606 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1607 break;
1608 case svn_wc_conflict_action_add:
1609 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1610 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1611 break;
1612 case svn_wc_conflict_action_delete:
1613 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1614 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1615 break;
1617 break;
1621 UINT uReasonID = 0;
1622 switch (pInfoData->treeconflict_reason)
1624 case svn_wc_conflict_reason_edited:
1625 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1626 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1627 break;
1628 case svn_wc_conflict_reason_obstructed:
1629 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1630 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1631 break;
1632 case svn_wc_conflict_reason_deleted:
1633 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1634 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1635 break;
1636 case svn_wc_conflict_reason_added:
1637 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1638 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1639 break;
1640 case svn_wc_conflict_reason_missing:
1641 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1642 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1643 break;
1644 case svn_wc_conflict_reason_unversioned:
1645 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1646 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1647 break;
1649 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1651 CTreeConflictEditorDlg dlg;
1652 dlg.SetConflictInfoText(sConflictReason);
1653 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1654 dlg.SetPath(treeConflictPath);
1655 INT_PTR dlgRet = dlg.DoModal();
1656 bRet = (dlgRet != IDCANCEL);
1660 #endif
1661 return bRet;
1664 bool CAppUtils::IsSSHPutty()
1666 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1667 sshclient=sshclient.MakeLower();
1668 if(sshclient.Find(_T("plink.exe"),0)>=0)
1670 return true;
1672 return false;
1675 CString CAppUtils::GetClipboardLink()
1677 if (!OpenClipboard(NULL))
1678 return CString();
1680 CString sClipboardText;
1681 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1682 if (hglb)
1684 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1685 sClipboardText = CString(lpstr);
1686 GlobalUnlock(hglb);
1688 hglb = GetClipboardData(CF_UNICODETEXT);
1689 if (hglb)
1691 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1692 sClipboardText = lpstr;
1693 GlobalUnlock(hglb);
1695 CloseClipboard();
1697 if(!sClipboardText.IsEmpty())
1699 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1700 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1702 if(sClipboardText.Find( _T("http://")) == 0)
1703 return sClipboardText;
1705 if(sClipboardText.Find( _T("https://")) == 0)
1706 return sClipboardText;
1708 if(sClipboardText.Find( _T("git://")) == 0)
1709 return sClipboardText;
1711 if(sClipboardText.Find( _T("ssh://")) == 0)
1712 return sClipboardText;
1714 if(sClipboardText.GetLength()>=2)
1715 if( sClipboardText[1] == _T(':') )
1716 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1717 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1718 return sClipboardText;
1721 return CString(_T(""));
1724 CString CAppUtils::ChooseRepository(CString *path)
1726 CBrowseFolder browseFolder;
1727 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1729 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1730 CString strCloneDirectory;
1731 if(path)
1732 strCloneDirectory=*path;
1733 else
1735 strCloneDirectory = regLastResopitory;
1738 CString title;
1739 title.LoadString(IDS_CHOOSE_REPOSITORY);
1741 browseFolder.SetInfo(title);
1743 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1745 regLastResopitory = strCloneDirectory;
1746 return strCloneDirectory;
1748 else
1750 return CString();
1754 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1756 CSendMailDlg dlg;
1758 dlg.m_PathList = list;
1760 if(dlg.DoModal()==IDOK)
1762 if(dlg.m_PathList.GetCount() == 0)
1763 return FALSE;
1765 CGitProgressDlg progDlg;
1767 theApp.m_pMainWnd = &progDlg;
1768 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1770 progDlg.SetAutoClose(autoclose);
1772 progDlg.SetPathList(dlg.m_PathList);
1773 //ProjectProperties props;
1774 //props.ReadPropsPathList(dlg.m_pathList);
1775 //progDlg.SetProjectProperties(props);
1776 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1778 DWORD flags =0;
1779 if(dlg.m_bAttachment)
1780 flags |= SENDMAIL_ATTACHMENT;
1781 if(dlg.m_bCombine)
1782 flags |= SENDMAIL_COMBINED;
1783 if(dlg.m_bUseMAPI)
1784 flags |= SENDMAIL_MAPI;
1786 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1788 progDlg.DoModal();
1790 return true;
1792 return false;
1795 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1797 CTGitPathList list;
1798 CString log=formatpatchoutput;
1799 int start=log.Find(cmd);
1800 if(start >=0)
1801 CString one=log.Tokenize(_T("\n"),start);
1802 else
1803 start = 0;
1805 while(start>=0)
1807 CString one=log.Tokenize(_T("\n"),start);
1808 one=one.Trim();
1809 if(one.IsEmpty() || one == _T("Success"))
1810 continue;
1811 one.Replace(_T('/'),_T('\\'));
1812 CTGitPath path;
1813 path.SetFromWin(one);
1814 list.AddPath(path);
1816 if (list.GetCount() > 0)
1818 return SendPatchMail(list, autoclose);
1820 else
1822 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1823 return true;
1828 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1830 CString cmd,output;
1831 int start=0;
1833 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1834 if(output.IsEmpty())
1836 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1837 if(output.IsEmpty())
1838 return CP_UTF8;
1840 int start=0;
1841 output=output.Tokenize(_T("\n"),start);
1842 return CUnicodeUtils::GetCPCode(output);
1845 else
1847 output=output.Tokenize(_T("\n"),start);
1848 return CUnicodeUtils::GetCPCode(output);
1851 int CAppUtils::GetCommitTemplate(CString &temp)
1853 CString cmd,output;
1855 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
1856 if( output.IsEmpty() )
1857 return -1;
1859 if( output.GetLength()<1)
1860 return -1;
1862 if( output[0] == _T('/'))
1864 if(output.GetLength()>=3)
1865 if(output[2] == _T('/'))
1867 output.GetBuffer()[0] = output[1];
1868 output.GetBuffer()[1] = _T(':');
1872 int start=0;
1873 output=output.Tokenize(_T("\n"),start);
1875 output.Replace(_T('/'),_T('\\'));
1879 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1880 CString str;
1881 while(file.ReadString(str))
1883 temp+=str+_T("\n");
1886 }catch(...)
1888 return -1;
1890 return 0;
1892 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1894 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1895 CString cmd,output;
1896 int cp=CP_UTF8;
1898 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1899 if(output.IsEmpty())
1900 cp=CP_UTF8;
1902 int start=0;
1903 output=output.Tokenize(_T("\n"),start);
1904 cp=CUnicodeUtils::GetCPCode(output);
1906 int len=message.GetLength();
1908 char * buf;
1909 buf = new char[len*4 + 4];
1910 SecureZeroMemory(buf, (len*4 + 4));
1912 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1914 file.Write(buf,lengthIncTerminator-1);
1915 file.Close();
1916 delete buf;
1917 return 0;
1920 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1922 CPullFetchDlg dlg;
1923 dlg.m_PreSelectRemote = remoteName;
1924 dlg.m_bAllowRebase = allowRebase;
1925 dlg.m_IsPull=FALSE;
1927 if(dlg.DoModal()==IDOK)
1929 if(dlg.m_bAutoLoad)
1931 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1934 CString url;
1935 url=dlg.m_RemoteURL;
1936 CString cmd;
1937 CString arg;
1939 int ver = CAppUtils::GetMsysgitVersion();
1941 if(ver >= 0x01070203) //above 1.7.0.2
1942 arg = _T("--progress ");
1944 if (dlg.m_bPrune) {
1945 arg += _T("--prune ");
1948 if (dlg.m_bFetchTags == 1)
1950 arg += _T("--tags ");
1952 else if (dlg.m_bFetchTags == 0)
1954 arg += _T("--no-tags ");
1957 if (dlg.m_bAllRemotes)
1958 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
1959 else
1960 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
1962 CProgressDlg progress;
1964 progress.m_bAutoCloseOnSuccess = autoClose;
1966 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
1968 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1970 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1973 progress.m_GitCmd=cmd;
1974 int userResponse=progress.DoModal();
1976 if (userResponse == IDC_PROGRESS_BUTTON1)
1978 CString cmd = _T("/command:log");
1979 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1980 RunTortoiseProc(cmd);
1981 return TRUE;
1983 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1985 while(1)
1987 CRebaseDlg dlg;
1988 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
1989 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1990 int response = dlg.DoModal();
1991 if(response == IDOK)
1993 return TRUE;
1995 if(response == IDC_REBASE_POST_BUTTON )
1997 CString cmd, out, err;
1998 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
1999 g_Git.m_CurrentDir,
2000 g_Git.FixBranchName(dlg.m_Upstream),
2001 g_Git.FixBranchName(dlg.m_Branch));
2002 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2004 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2005 return FALSE;
2008 CAppUtils::SendPatchMail(cmd,out);
2009 return TRUE;
2012 if(response == IDC_REBASE_POST_BUTTON +1 )
2013 continue;
2015 if(response == IDCANCEL)
2016 return FALSE;
2018 return TRUE;
2020 else if (userResponse != IDCANCEL)
2021 return TRUE;
2023 return FALSE;
2026 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2028 CPushDlg dlg;
2029 dlg.m_BranchSourceName = selectLocalBranch;
2030 CString error;
2031 DWORD exitcode = 0xFFFFFFFF;
2032 CTGitPathList list;
2033 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2034 if (CHooks::Instance().PrePush(list,exitcode, error))
2036 if (exitcode)
2038 CString temp;
2039 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2040 //ReportError(temp);
2041 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2042 return false;
2046 if(dlg.DoModal()==IDOK)
2048 CString arg;
2050 if(dlg.m_bAutoLoad)
2052 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2055 if(dlg.m_bPack)
2056 arg += _T("--thin ");
2057 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2058 arg += _T("--tags ");
2059 if(dlg.m_bForce)
2060 arg += _T("--force ");
2061 if (dlg.m_bSetUpstream)
2062 arg += _T("--set-upstream ");
2064 int ver = CAppUtils::GetMsysgitVersion();
2066 if(ver >= 0x01070203) //above 1.7.0.2
2067 arg += _T("--progress ");
2069 CProgressDlg progress;
2070 progress.m_bAutoCloseOnSuccess=autoClose;
2072 STRING_VECTOR remotesList;
2073 if (dlg.m_bPushAllRemotes)
2074 g_Git.GetRemoteList(remotesList);
2075 else
2076 remotesList.push_back(dlg.m_URL);
2078 for (unsigned int i = 0; i < remotesList.size(); i++)
2080 CString cmd;
2081 if (dlg.m_bPushAllBranches)
2083 cmd.Format(_T("git.exe push --all %s \"%s\""),
2084 arg,
2085 remotesList[i]);
2087 else
2089 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2090 arg,
2091 remotesList[i],
2092 dlg.m_BranchSourceName);
2093 if (!dlg.m_BranchRemoteName.IsEmpty())
2095 cmd += _T(":") + dlg.m_BranchRemoteName;
2098 progress.m_GitCmdList.push_back(cmd);
2101 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2102 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2103 int ret = progress.DoModal();
2105 if(!progress.m_GitStatus)
2107 if (CHooks::Instance().PostPush(list,exitcode, error))
2109 if (exitcode)
2111 CString temp;
2112 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2113 //ReportError(temp);
2114 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2115 return false;
2118 if(ret == IDC_PROGRESS_BUTTON1)
2120 RequestPull(dlg.m_BranchRemoteName);
2122 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2124 Push();
2126 return TRUE;
2130 return FALSE;
2133 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2135 CRequestPullDlg dlg;
2136 dlg.m_RepositoryURL = repositoryUrl;
2137 dlg.m_EndRevision = endrevision;
2138 if (dlg.DoModal()==IDOK)
2140 CString cmd;
2141 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2143 CString tempFileName = GetTempFile();
2144 if (g_Git.RunLogFile(cmd, tempFileName))
2146 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2147 return false;
2149 CAppUtils::LaunchAlternativeEditor(tempFileName);
2151 return true;
2154 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2156 CString strDir(szPath);
2157 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2159 strDir.AppendChar(_T('\\'));
2161 std::vector<CString> vPath;
2162 CString strTemp;
2163 bool bSuccess = false;
2165 for (int i=0;i<strDir.GetLength();++i)
2167 if (strDir.GetAt(i) != _T('\\'))
2169 strTemp.AppendChar(strDir.GetAt(i));
2171 else
2173 vPath.push_back(strTemp);
2174 strTemp.AppendChar(_T('\\'));
2178 std::vector<CString>::const_iterator vIter;
2179 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2181 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2184 return bSuccess;
2187 void CAppUtils::RemoveTrailSlash(CString &path)
2189 if(path.IsEmpty())
2190 return ;
2192 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2194 path=path.Left(path.GetLength()-1);
2195 if(path.IsEmpty())
2196 return;
2200 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2201 CTGitPathList &pathList,
2202 CTGitPathList &selectedList,
2203 bool bSelectFilesForCommit,
2204 bool autoClose)
2206 bool bFailed = true;
2208 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2210 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2212 CTGitPath path(g_Git.m_CurrentDir);
2213 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2214 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2215 dlg.SetTreeWidth(220);
2216 dlg.m_DefaultPage = _T("gitconfig");
2218 dlg.DoModal();
2219 dlg.HandleRestart();
2222 else
2223 return false;
2226 while (bFailed)
2228 bFailed = false;
2229 CCommitDlg dlg;
2230 dlg.m_sBugID = bugid;
2232 dlg.m_bWholeProject = bWholeProject;
2234 dlg.m_sLogMessage = sLogMsg;
2235 dlg.m_pathList = pathList;
2236 dlg.m_checkedPathList = selectedList;
2237 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2238 dlg.m_bAutoClose = autoClose;
2239 if (dlg.DoModal() == IDOK)
2241 if (dlg.m_pathList.GetCount()==0)
2242 return false;
2243 // if the user hasn't changed the list of selected items
2244 // we don't use that list. Because if we would use the list
2245 // of pre-checked items, the dialog would show different
2246 // checked items on the next startup: it would only try
2247 // to check the parent folder (which might not even show)
2248 // instead, we simply use an empty list and let the
2249 // default checking do its job.
2250 if (!dlg.m_pathList.IsEqual(pathList))
2251 selectedList = dlg.m_pathList;
2252 pathList = dlg.m_updatedPathList;
2253 sLogMsg = dlg.m_sLogMessage;
2254 bSelectFilesForCommit = true;
2256 if( dlg.m_bPushAfterCommit )
2258 switch(dlg.m_PostCmd)
2260 case GIT_POST_CMD_DCOMMIT:
2261 CAppUtils::SVNDCommit();
2262 break;
2263 default:
2264 CAppUtils::Push();
2267 else if (dlg.m_bCreateTagAfterCommit)
2269 CAppUtils::CreateBranchTag(TRUE);
2272 // CGitProgressDlg progDlg;
2273 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2274 // if (parser.HasVal(_T("closeonend")))
2275 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2276 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2277 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2278 // progDlg.SetPathList(dlg.m_pathList);
2279 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2280 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2281 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2282 // progDlg.SetItemCount(dlg.m_itemsCount);
2283 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2284 // progDlg.DoModal();
2285 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2286 // err = (DWORD)progDlg.DidErrorsOccur();
2287 // bFailed = progDlg.DidErrorsOccur();
2288 // bRet = progDlg.DidErrorsOccur();
2289 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2290 // if (DWORD(bFailRepeat)==0)
2291 // bFailed = false; // do not repeat if the user chose not to in the settings.
2294 return true;
2298 BOOL CAppUtils::SVNDCommit()
2300 CSVNDCommitDlg dcommitdlg;
2301 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2302 if (gitSetting == _T("")) {
2303 if (dcommitdlg.DoModal() != IDOK)
2305 return false;
2307 else
2309 if (dcommitdlg.m_remember)
2311 if (dcommitdlg.m_rmdir)
2313 gitSetting = _T("true");
2315 else
2317 gitSetting = _T("false");
2319 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2321 CString msg;
2322 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2323 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2329 BOOL IsStash = false;
2330 if(!g_Git.CheckCleanWorkTree())
2332 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2334 CString cmd,out;
2335 cmd=_T("git.exe stash");
2336 if (g_Git.Run(cmd, &out, CP_UTF8))
2338 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2339 return false;
2341 IsStash =true;
2344 else
2346 return false;
2350 CProgressDlg progress;
2351 if (dcommitdlg.m_rmdir)
2353 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2355 else
2357 progress.m_GitCmd=_T("git.exe svn dcommit");
2359 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2361 if( IsStash)
2363 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2365 CString cmd,out;
2366 cmd=_T("git.exe stash pop");
2367 if (g_Git.Run(cmd, &out, CP_UTF8))
2369 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2370 return false;
2374 else
2376 return false;
2379 return TRUE;
2381 return FALSE;
2384 BOOL CAppUtils::Merge(CString *commit)
2386 CMergeDlg dlg;
2387 if(commit)
2388 dlg.m_initialRefName = *commit;
2390 if(dlg.DoModal()==IDOK)
2392 CString cmd;
2393 CString noff;
2394 CString squash;
2395 CString nocommit;
2396 CString msg;
2398 if(dlg.m_bNoFF)
2399 noff=_T("--no-ff");
2401 if(dlg.m_bSquash)
2402 squash=_T("--squash");
2404 if(dlg.m_bNoCommit)
2405 nocommit=_T("--no-commit");
2407 if(!dlg.m_strLogMesage.IsEmpty())
2409 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2411 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2412 msg,
2413 noff,
2414 squash,
2415 nocommit,
2416 g_Git.FixBranchName(dlg.m_VersionName));
2418 CProgressDlg Prodlg;
2419 Prodlg.m_GitCmd = cmd;
2421 if (dlg.m_bNoCommit)
2422 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2423 else if (dlg.m_bIsBranch)
2424 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2426 int ret = Prodlg.DoModal();
2428 if (ret == IDC_PROGRESS_BUTTON1)
2429 if (dlg.m_bNoCommit)
2430 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2431 else if (dlg.m_bIsBranch)
2433 CString msg;
2434 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2435 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2437 CString cmd, out;
2438 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2439 if (g_Git.Run(cmd, &out, CP_UTF8))
2440 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2444 return !Prodlg.m_GitStatus;
2446 return false;
2449 void CAppUtils::EditNote(GitRev *rev)
2451 CInputDlg dlg;
2452 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2453 dlg.m_sInputText = rev->m_Notes;
2454 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2455 //dlg.m_pProjectProperties = &m_ProjectProperties;
2456 dlg.m_bUseLogWidth = true;
2457 if(dlg.DoModal() == IDOK)
2459 CString cmd,output;
2460 cmd=_T("notes add -f -F \"");
2462 CString tempfile=::GetTempFile();
2463 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2464 cmd += tempfile;
2465 cmd += _T("\" ");
2466 cmd += rev->m_CommitHash.ToString();
2470 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2472 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2475 else
2477 rev->m_Notes = dlg.m_sInputText;
2479 }catch(...)
2481 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2483 CFile::Remove(tempfile);
2488 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2490 CString cmd;
2491 CString progressarg;
2492 CString version;
2494 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2495 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2497 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2499 __int64 time=0;
2500 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2502 if((DWORD)time == regTime)
2504 return regVersion;
2508 if(versionstr)
2509 version = *versionstr;
2510 else
2512 CString err;
2513 cmd = _T("git.exe --version");
2514 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2516 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2517 return false;
2521 int start=0;
2522 int ver = 0;
2526 CString str=version.Tokenize(_T("."), start);
2527 int space = str.ReverseFind(_T(' '));
2528 str = str.Mid(space+1,start);
2529 ver = _ttol(str);
2530 ver <<=24;
2532 version = version.Mid(start);
2533 start = 0;
2535 str = version.Tokenize(_T("."), start);
2537 ver |= (_ttol(str) & 0xFF) << 16;
2539 str = version.Tokenize(_T("."), start);
2540 ver |= (_ttol(str) & 0xFF) << 8;
2542 str = version.Tokenize(_T("."), start);
2543 ver |= (_ttol(str) & 0xFF);
2545 catch(...)
2547 if (!ver)
2549 CMessageBox::Show(NULL, _T("Could not parse git.exe version number."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2550 return false;
2554 regTime = time&0xFFFFFFFF;
2555 regVersion = ver;
2557 return ver;
2560 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2562 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2564 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2566 if (hShell.IsValid()) {
2567 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2568 if (pfnSHGPSFW) {
2569 IPropertyStore *pps;
2570 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2571 if (SUCCEEDED(hr)) {
2572 PROPVARIANT var;
2573 var.vt = VT_BOOL;
2574 var.boolVal = VARIANT_TRUE;
2575 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2576 pps->Release();
2582 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2584 ASSERT(dialogname.GetLength() < 70);
2585 ASSERT(urlorpath.GetLength() < MAX_PATH);
2586 WCHAR pathbuf[MAX_PATH] = {0};
2588 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2590 wcscat_s(pathbuf, L" - ");
2591 wcscat_s(pathbuf, dialogname);
2592 wcscat_s(pathbuf, L" - ");
2593 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2594 SetWindowText(hWnd, pathbuf);