Fixed issue #1076: Error trying to delete remote branch named 1.0.0
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob414ab139bf7e1cb2226ff5a84e0557971c931465
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 CString appDir = CPathUtils::GetAppDirectory();
630 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
631 if(!b)
632 return b;
634 int i=0;
635 while(!::PathFileExists(tempfile))
637 Sleep(100);
638 i++;
639 if(i>10*60*5)
640 break; //timeout 5 minutes
643 if( i== 10*60*5)
645 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
647 ::DeleteFile(tempfile);
648 return true;
650 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
652 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
653 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
654 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
657 CString sCmd;
658 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
660 LaunchApplication(sCmd, NULL, false);
661 return true;
663 bool CAppUtils::LaunchRemoteSetting()
665 CTGitPath path(g_Git.m_CurrentDir);
666 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
667 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
668 //dlg.SetTreeWidth(220);
669 dlg.m_DefaultPage = _T("gitremote");
671 dlg.DoModal();
672 dlg.HandleRestart();
673 return true;
676 * Launch the external blame viewer
678 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
680 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
681 viewer += _T("TortoiseGitBlame.exe");
682 viewer += _T("\" \"") + sBlameFile + _T("\"");
683 //viewer += _T(" \"") + sLogFile + _T("\"");
684 //viewer += _T(" \"") + sOriginalFile + _T("\"");
685 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
686 viewer += CString(_T(" /rev:"))+Rev;
687 viewer += _T(" ")+sParams;
689 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
692 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
694 CString sText;
695 if (pWnd == NULL)
696 return false;
697 bool bStyled = false;
698 pWnd->GetWindowText(sText);
699 // the rich edit control doesn't count the CR char!
700 // to be exact: CRLF is treated as one char.
701 sText.Remove('\r');
703 // style each line separately
704 int offset = 0;
705 int nNewlinePos;
708 nNewlinePos = sText.Find('\n', offset);
709 CString sLine = sText.Mid(offset);
710 if (nNewlinePos>=0)
711 sLine = sLine.Left(nNewlinePos-offset);
712 int start = 0;
713 int end = 0;
714 while (FindStyleChars(sLine, '*', start, end))
716 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
717 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
718 CHARFORMAT2 format;
719 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
720 format.cbSize = sizeof(CHARFORMAT2);
721 format.dwMask = CFM_BOLD;
722 format.dwEffects = CFE_BOLD;
723 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
724 bStyled = true;
725 start = end;
727 start = 0;
728 end = 0;
729 while (FindStyleChars(sLine, '^', start, end))
731 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
732 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
733 CHARFORMAT2 format;
734 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
735 format.cbSize = sizeof(CHARFORMAT2);
736 format.dwMask = CFM_ITALIC;
737 format.dwEffects = CFE_ITALIC;
738 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
739 bStyled = true;
740 start = end;
742 start = 0;
743 end = 0;
744 while (FindStyleChars(sLine, '_', start, end))
746 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
747 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
748 CHARFORMAT2 format;
749 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
750 format.cbSize = sizeof(CHARFORMAT2);
751 format.dwMask = CFM_UNDERLINE;
752 format.dwEffects = CFE_UNDERLINE;
753 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
754 bStyled = true;
755 start = end;
757 offset = nNewlinePos+1;
758 } while(nNewlinePos>=0);
759 return bStyled;
762 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
764 int i=start;
765 bool bFoundMarker = false;
766 // find a starting marker
767 while (sText[i] != 0)
769 if (sText[i] == stylechar)
771 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
772 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
774 start = i+1;
775 i++;
776 bFoundMarker = true;
777 break;
780 i++;
782 if (!bFoundMarker)
783 return false;
784 // find ending marker
785 bFoundMarker = false;
786 while (sText[i] != 0)
788 if (sText[i] == stylechar)
790 if ((IsCharAlphaNumeric(sText[i-1])) &&
791 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
793 end = i;
794 i++;
795 bFoundMarker = true;
796 break;
799 i++;
801 return bFoundMarker;
804 CString CAppUtils::GetProjectNameFromURL(CString url)
806 CString name;
807 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
808 (name.CompareNoCase(_T("tags"))==0) ||
809 (name.CompareNoCase(_T("trunk"))==0))
811 name = url.Mid(url.ReverseFind('/')+1);
812 url = url.Left(url.ReverseFind('/'));
814 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
816 // a name of svn or svnroot indicates that it's not really the project name. In that
817 // case, we try the first part of the URL
818 // of course, this won't work in all cases (but it works for Google project hosting)
819 url.Replace(_T("http://"), _T(""));
820 url.Replace(_T("https://"), _T(""));
821 url.Replace(_T("svn://"), _T(""));
822 url.Replace(_T("svn+ssh://"), _T(""));
823 url.TrimLeft(_T("/"));
824 name = url.Left(url.Find('.'));
826 return name;
829 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
830 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
831 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
832 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
835 CString tempfile=GetTempFile();
836 CString cmd;
837 if(rev2 == GitRev::GetWorkingCopy())
839 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
841 else if (rev1 == GitRev::GetWorkingCopy())
843 cmd.Format(_T("git.exe diff -R --stat -p %s "), rev2);
845 else
847 CString merge;
848 if(bMerge)
849 merge = _T("-c");
851 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
854 if( !url1.IsEmpty() )
856 cmd += _T(" -- \"");
857 cmd += url1.GetGitPathString();
858 cmd += _T("\" ");
860 g_Git.RunLogFile(cmd,tempfile);
861 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
864 #if 0
865 CString sCmd;
866 sCmd.Format(_T("%s /command:showcompare /unified"),
867 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
868 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
869 if (rev1.IsValid())
870 sCmd += _T(" /revision1:") + rev1.ToString();
871 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
872 if (rev2.IsValid())
873 sCmd += _T(" /revision2:") + rev2.ToString();
874 if (peg.IsValid())
875 sCmd += _T(" /pegrevision:") + peg.ToString();
876 if (headpeg.IsValid())
877 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
879 if (bAlternateDiff)
880 sCmd += _T(" /alternatediff");
882 if (bIgnoreAncestry)
883 sCmd += _T(" /ignoreancestry");
885 if (hWnd)
887 sCmd += _T(" /hwnd:");
888 TCHAR buf[30];
889 _stprintf_s(buf, 30, _T("%d"), hWnd);
890 sCmd += buf;
893 return CAppUtils::LaunchApplication(sCmd, NULL, false);
894 #endif
895 return TRUE;
899 bool CAppUtils::Export(CString *BashHash)
901 bool bRet = false;
903 // ask from where the export has to be done
904 CExportDlg dlg;
905 if(BashHash)
906 dlg.m_Revision=*BashHash;
908 if (dlg.DoModal() == IDOK)
910 CString cmd;
911 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
912 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
914 CProgressDlg pro;
915 pro.m_GitCmd=cmd;
916 pro.DoModal();
917 return TRUE;
919 return bRet;
922 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
924 CCreateBranchTagDlg dlg;
925 dlg.m_bIsTag=IsTag;
926 dlg.m_bSwitch=switch_new_brach;
928 if(CommitHash)
929 dlg.m_initialRefName = *CommitHash;
931 if(dlg.DoModal()==IDOK)
933 CString cmd;
934 CString force;
935 CString track;
936 if(dlg.m_bTrack == TRUE)
937 track=_T(" --track ");
938 else if(dlg.m_bTrack == FALSE)
939 track=_T(" --no-track");
941 if(dlg.m_bForce)
942 force=_T(" -f ");
944 if(IsTag)
946 CString sign;
947 if(dlg.m_bSign)
948 sign=_T("-s");
950 cmd.Format(_T("git.exe tag %s %s %s %s"),
951 force,
952 sign,
953 dlg.m_BranchTagName,
954 g_Git.FixBranchName(dlg.m_VersionName)
957 CString tempfile=::GetTempFile();
958 if(!dlg.m_Message.Trim().IsEmpty())
960 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
961 cmd += _T(" -F ")+tempfile;
964 else
966 cmd.Format(_T("git.exe branch %s %s %s %s"),
967 track,
968 force,
969 dlg.m_BranchTagName,
970 g_Git.FixBranchName(dlg.m_VersionName)
973 CString out;
974 if(g_Git.Run(cmd,&out,CP_UTF8))
976 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
977 return FALSE;
979 if( !IsTag && dlg.m_bSwitch )
981 // it is a new branch and the user has requested to switch to it
982 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
983 g_Git.Run(cmd,&out,CP_UTF8);
984 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
987 return TRUE;
989 return FALSE;
992 bool CAppUtils::Switch(CString initialRefName, bool autoclose)
994 CGitSwitchDlg dlg;
995 if(!initialRefName.IsEmpty())
996 dlg.m_initialRefName = initialRefName;
998 if (dlg.DoModal() == IDOK)
1000 CString branch;
1001 if (dlg.m_bBranch)
1002 branch = dlg.m_NewBranch;
1004 // if refs/heads/ is not stripped, checkout will detach HEAD
1005 // checkout prefers branches on name clashes (with tags)
1006 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1007 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1009 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1011 return FALSE;
1014 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1016 CString cmd;
1017 CString track;
1018 CString force;
1019 CString branch;
1021 if(!sNewBranch.IsEmpty()){
1022 if (bBranchOverride)
1024 branch.Format(_T("-B %s"), sNewBranch);
1026 else
1028 branch.Format(_T("-b %s"), sNewBranch);
1030 if (bTrack)
1031 track = _T("--track");
1033 if (bForce)
1034 force = _T("-f");
1036 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1037 force,
1038 track,
1039 branch,
1040 g_Git.FixBranchName(ref));
1042 CProgressDlg progress;
1043 progress.m_bAutoCloseOnSuccess = autoClose;
1044 progress.m_GitCmd = cmd;
1046 CTGitPath gitPath = g_Git.m_CurrentDir;
1047 if (gitPath.HasSubmodules())
1048 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1050 INT_PTR ret = progress.DoModal();
1051 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1053 CString sCmd;
1054 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1056 RunTortoiseProc(sCmd);
1057 return TRUE;
1059 else if (ret == IDOK)
1060 return TRUE;
1062 return FALSE;
1065 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1067 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1069 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1070 return false;
1073 if (file.GetLength() > 0)
1075 file.Seek(file.GetLength() - 1, 0);
1076 auto_buffer<TCHAR> buf(1);
1077 file.Read(buf, 1);
1078 file.SeekToEnd();
1079 if (buf[0] != _T('\n'))
1080 file.WriteString(_T("\n"));
1082 else
1083 file.SeekToEnd();
1085 return true;
1088 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1090 CIgnoreDlg ignoreDlg;
1091 if (ignoreDlg.DoModal() == IDOK)
1093 CString ignorefile;
1094 ignorefile = g_Git.m_CurrentDir + _T("\\");
1096 switch (ignoreDlg.m_IgnoreFile)
1098 case 0:
1099 ignorefile += _T(".gitignore");
1100 break;
1101 case 2:
1102 ignorefile += _T(".git/info/exclude");
1103 break;
1106 CStdioFile file;
1109 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1110 return false;
1112 for (int i = 0; i < path.GetCount(); i++)
1114 if (ignoreDlg.m_IgnoreFile == 1)
1116 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1117 if (!OpenIgnoreFile(file, ignorefile))
1118 return false;
1121 CString ignorePattern;
1122 if (ignoreDlg.m_IgnoreType == 0)
1124 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1125 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1127 ignorePattern += _T("/");
1129 if (IsMask)
1131 ignorePattern += _T("*") + path[i].GetFileExtension();
1133 else
1135 ignorePattern += path[i].GetFileOrDirectoryName();
1138 // escape [ and ] so that files get ignored correctly
1139 ignorePattern.Replace(_T("["), _T("\\["));
1140 ignorePattern.Replace(_T("]"), _T("\\]"));
1142 ignorePattern += _T("\n");
1143 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1144 file.Write(ignorePatternA.GetBuffer(), ignorePatternA.GetLength());
1145 ignorePatternA.ReleaseBuffer();
1147 if (ignoreDlg.m_IgnoreFile == 1)
1148 file.Close();
1151 if (ignoreDlg.m_IgnoreFile != 1)
1152 file.Close();
1154 catch(...)
1156 file.Abort();
1157 return false;
1160 return true;
1162 return false;
1166 bool CAppUtils::GitReset(CString *CommitHash,int type)
1168 CResetDlg dlg;
1169 dlg.m_ResetType=type;
1170 dlg.m_ResetToVersion=*CommitHash;
1171 if (dlg.DoModal() == IDOK)
1173 CString cmd;
1174 CString type;
1175 switch(dlg.m_ResetType)
1177 case 0:
1178 type=_T("--soft");
1179 break;
1180 case 1:
1181 type=_T("--mixed");
1182 break;
1183 case 2:
1184 type=_T("--hard");
1185 break;
1186 default:
1187 type=_T("--mixed");
1188 break;
1190 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1192 CProgressDlg progress;
1193 progress.m_GitCmd=cmd;
1195 CTGitPath gitPath = g_Git.m_CurrentDir;
1196 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1197 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1199 INT_PTR ret = progress.DoModal();
1200 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1202 CString sCmd;
1203 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1205 RunTortoiseProc(sCmd);
1206 return TRUE;
1208 else if (ret == IDOK)
1209 return TRUE;
1212 return FALSE;
1215 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1217 if(mode == FALSE)
1219 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1220 return;
1222 if(base)
1224 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1225 return;
1227 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1228 return;
1231 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1233 CString tempmergefile;
1236 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1237 CFile::Remove(tempmergefile);
1238 }catch(...)
1244 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1245 CFile::Remove(tempmergefile);
1246 }catch(...)
1252 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1253 CFile::Remove(tempmergefile);
1254 }catch(...)
1258 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1260 CString file;
1261 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1263 return file;
1266 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1268 bool bRet = false;
1270 CTGitPath merge=path;
1271 CTGitPath directory = merge.GetDirectory();
1273 // we have the conflicted file (%merged)
1274 // now look for the other required files
1275 //GitStatus stat;
1276 //stat.GetStatus(merge);
1277 //if (stat.status == NULL)
1278 // return false;
1280 BYTE_VECTOR vector;
1282 CString cmd;
1283 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1285 if (g_Git.Run(cmd, &vector))
1287 return FALSE;
1290 CTGitPathList list;
1291 list.ParserFromLsFile(vector);
1293 if(list.GetCount() == 0)
1294 return FALSE;
1296 CTGitPath theirs;
1297 CTGitPath mine;
1298 CTGitPath base;
1300 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1301 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1302 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1304 CString format;
1306 //format=_T("git.exe cat-file blob \":%d:%s\"");
1307 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1308 CFile tempfile;
1309 //create a empty file, incase stage is not three
1310 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1311 tempfile.Close();
1312 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1313 tempfile.Close();
1314 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1315 tempfile.Close();
1317 bool b_base=false, b_local=false, b_remote=false;
1319 for(int i=0;i<list.GetCount();i++)
1321 CString cmd;
1322 CString outfile;
1323 cmd.Empty();
1324 outfile.Empty();
1326 if( list[i].m_Stage == 1)
1328 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1329 b_base = true;
1330 outfile = base.GetWinPathString();
1333 if( list[i].m_Stage == 2 )
1335 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1336 b_local = true;
1337 outfile = mine.GetWinPathString();
1340 if( list[i].m_Stage == 3 )
1342 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1343 b_remote = true;
1344 outfile = theirs.GetWinPathString();
1346 CString output, err;
1347 if(!outfile.IsEmpty())
1348 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1350 CString file;
1351 int start =0 ;
1352 file = output.Tokenize(_T("\t"), start);
1353 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1355 else
1357 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1361 if(b_local && b_remote )
1363 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1364 if( revertTheirMy )
1365 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1366 else
1367 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1370 else
1372 CFile::Remove(mine.GetWinPathString());
1373 CFile::Remove(theirs.GetWinPathString());
1374 CFile::Remove(base.GetWinPathString());
1376 CDeleteConflictDlg dlg;
1377 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1378 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1379 dlg.m_bShowModifiedButton=b_base;
1380 dlg.m_File=merge.GetGitPathString();
1381 if(dlg.DoModal() == IDOK)
1383 CString cmd,out;
1384 if(dlg.m_bIsDelete)
1386 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1388 else
1389 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1391 if (g_Git.Run(cmd, &out, CP_UTF8))
1393 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1394 return FALSE;
1396 return TRUE;
1398 else
1399 return FALSE;
1402 #if 0
1403 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1404 base, theirs, mine, merge);
1405 #endif
1406 #if 0
1407 if (stat.status->text_status == svn_wc_status_conflicted)
1409 // we have a text conflict, use our merge tool to resolve the conflict
1411 CTSVNPath theirs(directory);
1412 CTSVNPath mine(directory);
1413 CTSVNPath base(directory);
1414 bool bConflictData = false;
1416 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1418 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1419 bConflictData = true;
1421 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1423 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1424 bConflictData = true;
1426 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1428 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1429 bConflictData = true;
1431 else
1433 mine = merge;
1435 if (bConflictData)
1436 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1437 base, theirs, mine, merge);
1440 if (stat.status->prop_status == svn_wc_status_conflicted)
1442 // we have a property conflict
1443 CTSVNPath prej(directory);
1444 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1446 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1447 // there's a problem: the prej file contains a _description_ of the conflict, and
1448 // that description string might be translated. That means we have no way of parsing
1449 // the file to find out the conflicting values.
1450 // The only thing we can do: show a dialog with the conflict description, then
1451 // let the user either accept the existing property or open the property edit dialog
1452 // to manually change the properties and values. And a button to mark the conflict as
1453 // resolved.
1454 CEditPropConflictDlg dlg;
1455 dlg.SetPrejFile(prej);
1456 dlg.SetConflictedItem(merge);
1457 bRet = (dlg.DoModal() != IDCANCEL);
1461 if (stat.status->tree_conflict)
1463 // we have a tree conflict
1464 SVNInfo info;
1465 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1466 if (pInfoData)
1468 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1470 CTSVNPath theirs(directory);
1471 CTSVNPath mine(directory);
1472 CTSVNPath base(directory);
1473 bool bConflictData = false;
1475 if (pInfoData->treeconflict_theirfile)
1477 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1478 bConflictData = true;
1480 if (pInfoData->treeconflict_basefile)
1482 base.AppendPathString(pInfoData->treeconflict_basefile);
1483 bConflictData = true;
1485 if (pInfoData->treeconflict_myfile)
1487 mine.AppendPathString(pInfoData->treeconflict_myfile);
1488 bConflictData = true;
1490 else
1492 mine = merge;
1494 if (bConflictData)
1495 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1496 base, theirs, mine, merge);
1498 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1500 CString sConflictAction;
1501 CString sConflictReason;
1502 CString sResolveTheirs;
1503 CString sResolveMine;
1504 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1505 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1507 if (pInfoData->treeconflict_nodekind == svn_node_file)
1509 switch (pInfoData->treeconflict_operation)
1511 case svn_wc_operation_update:
1512 switch (pInfoData->treeconflict_action)
1514 case svn_wc_conflict_action_edit:
1515 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1516 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1517 break;
1518 case svn_wc_conflict_action_add:
1519 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1520 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1521 break;
1522 case svn_wc_conflict_action_delete:
1523 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1524 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1525 break;
1527 break;
1528 case svn_wc_operation_switch:
1529 switch (pInfoData->treeconflict_action)
1531 case svn_wc_conflict_action_edit:
1532 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1533 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1534 break;
1535 case svn_wc_conflict_action_add:
1536 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1537 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1538 break;
1539 case svn_wc_conflict_action_delete:
1540 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1541 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1542 break;
1544 break;
1545 case svn_wc_operation_merge:
1546 switch (pInfoData->treeconflict_action)
1548 case svn_wc_conflict_action_edit:
1549 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1550 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1551 break;
1552 case svn_wc_conflict_action_add:
1553 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1554 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1555 break;
1556 case svn_wc_conflict_action_delete:
1557 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1558 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1559 break;
1561 break;
1564 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1566 switch (pInfoData->treeconflict_operation)
1568 case svn_wc_operation_update:
1569 switch (pInfoData->treeconflict_action)
1571 case svn_wc_conflict_action_edit:
1572 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1573 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1574 break;
1575 case svn_wc_conflict_action_add:
1576 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1577 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1578 break;
1579 case svn_wc_conflict_action_delete:
1580 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1581 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1582 break;
1584 break;
1585 case svn_wc_operation_switch:
1586 switch (pInfoData->treeconflict_action)
1588 case svn_wc_conflict_action_edit:
1589 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1590 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1591 break;
1592 case svn_wc_conflict_action_add:
1593 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1594 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1595 break;
1596 case svn_wc_conflict_action_delete:
1597 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1598 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1599 break;
1601 break;
1602 case svn_wc_operation_merge:
1603 switch (pInfoData->treeconflict_action)
1605 case svn_wc_conflict_action_edit:
1606 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1607 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1608 break;
1609 case svn_wc_conflict_action_add:
1610 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1611 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1612 break;
1613 case svn_wc_conflict_action_delete:
1614 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1615 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1616 break;
1618 break;
1622 UINT uReasonID = 0;
1623 switch (pInfoData->treeconflict_reason)
1625 case svn_wc_conflict_reason_edited:
1626 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1627 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1628 break;
1629 case svn_wc_conflict_reason_obstructed:
1630 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1631 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1632 break;
1633 case svn_wc_conflict_reason_deleted:
1634 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1635 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1636 break;
1637 case svn_wc_conflict_reason_added:
1638 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1639 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1640 break;
1641 case svn_wc_conflict_reason_missing:
1642 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1643 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1644 break;
1645 case svn_wc_conflict_reason_unversioned:
1646 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1647 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1648 break;
1650 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1652 CTreeConflictEditorDlg dlg;
1653 dlg.SetConflictInfoText(sConflictReason);
1654 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1655 dlg.SetPath(treeConflictPath);
1656 INT_PTR dlgRet = dlg.DoModal();
1657 bRet = (dlgRet != IDCANCEL);
1661 #endif
1662 return bRet;
1665 bool CAppUtils::IsSSHPutty()
1667 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1668 sshclient=sshclient.MakeLower();
1669 if(sshclient.Find(_T("plink.exe"),0)>=0)
1671 return true;
1673 return false;
1676 CString CAppUtils::GetClipboardLink()
1678 if (!OpenClipboard(NULL))
1679 return CString();
1681 CString sClipboardText;
1682 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1683 if (hglb)
1685 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1686 sClipboardText = CString(lpstr);
1687 GlobalUnlock(hglb);
1689 hglb = GetClipboardData(CF_UNICODETEXT);
1690 if (hglb)
1692 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1693 sClipboardText = lpstr;
1694 GlobalUnlock(hglb);
1696 CloseClipboard();
1698 if(!sClipboardText.IsEmpty())
1700 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1701 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1703 if(sClipboardText.Find( _T("http://")) == 0)
1704 return sClipboardText;
1706 if(sClipboardText.Find( _T("https://")) == 0)
1707 return sClipboardText;
1709 if(sClipboardText.Find( _T("git://")) == 0)
1710 return sClipboardText;
1712 if(sClipboardText.Find( _T("ssh://")) == 0)
1713 return sClipboardText;
1715 if(sClipboardText.GetLength()>=2)
1716 if( sClipboardText[1] == _T(':') )
1717 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1718 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1719 return sClipboardText;
1722 return CString(_T(""));
1725 CString CAppUtils::ChooseRepository(CString *path)
1727 CBrowseFolder browseFolder;
1728 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1730 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1731 CString strCloneDirectory;
1732 if(path)
1733 strCloneDirectory=*path;
1734 else
1736 strCloneDirectory = regLastResopitory;
1739 CString title;
1740 title.LoadString(IDS_CHOOSE_REPOSITORY);
1742 browseFolder.SetInfo(title);
1744 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1746 regLastResopitory = strCloneDirectory;
1747 return strCloneDirectory;
1749 else
1751 return CString();
1755 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1757 CSendMailDlg dlg;
1759 dlg.m_PathList = list;
1761 if(dlg.DoModal()==IDOK)
1763 if(dlg.m_PathList.GetCount() == 0)
1764 return FALSE;
1766 CGitProgressDlg progDlg;
1768 theApp.m_pMainWnd = &progDlg;
1769 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1771 progDlg.SetAutoClose(autoclose);
1773 progDlg.SetPathList(dlg.m_PathList);
1774 //ProjectProperties props;
1775 //props.ReadPropsPathList(dlg.m_pathList);
1776 //progDlg.SetProjectProperties(props);
1777 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1779 DWORD flags =0;
1780 if(dlg.m_bAttachment)
1781 flags |= SENDMAIL_ATTACHMENT;
1782 if(dlg.m_bCombine)
1783 flags |= SENDMAIL_COMBINED;
1784 if(dlg.m_bUseMAPI)
1785 flags |= SENDMAIL_MAPI;
1787 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1789 progDlg.DoModal();
1791 return true;
1793 return false;
1796 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1798 CTGitPathList list;
1799 CString log=formatpatchoutput;
1800 int start=log.Find(cmd);
1801 if(start >=0)
1802 CString one=log.Tokenize(_T("\n"),start);
1803 else
1804 start = 0;
1806 while(start>=0)
1808 CString one=log.Tokenize(_T("\n"),start);
1809 one=one.Trim();
1810 if(one.IsEmpty() || one == _T("Success"))
1811 continue;
1812 one.Replace(_T('/'),_T('\\'));
1813 CTGitPath path;
1814 path.SetFromWin(one);
1815 list.AddPath(path);
1817 if (list.GetCount() > 0)
1819 return SendPatchMail(list, autoclose);
1821 else
1823 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1824 return true;
1829 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1831 CString cmd,output;
1832 int start=0;
1834 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1835 if(output.IsEmpty())
1837 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1838 if(output.IsEmpty())
1839 return CP_UTF8;
1841 int start=0;
1842 output=output.Tokenize(_T("\n"),start);
1843 return CUnicodeUtils::GetCPCode(output);
1846 else
1848 output=output.Tokenize(_T("\n"),start);
1849 return CUnicodeUtils::GetCPCode(output);
1852 int CAppUtils::GetCommitTemplate(CString &temp)
1854 CString cmd,output;
1856 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
1857 if( output.IsEmpty() )
1858 return -1;
1860 if( output.GetLength()<1)
1861 return -1;
1863 if( output[0] == _T('/'))
1865 if(output.GetLength()>=3)
1866 if(output[2] == _T('/'))
1868 output.GetBuffer()[0] = output[1];
1869 output.GetBuffer()[1] = _T(':');
1873 int start=0;
1874 output=output.Tokenize(_T("\n"),start);
1876 output.Replace(_T('/'),_T('\\'));
1880 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1881 CString str;
1882 while(file.ReadString(str))
1884 temp+=str+_T("\n");
1887 }catch(...)
1889 return -1;
1891 return 0;
1893 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1895 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1896 CString cmd,output;
1897 int cp=CP_UTF8;
1899 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1900 if(output.IsEmpty())
1901 cp=CP_UTF8;
1903 int start=0;
1904 output=output.Tokenize(_T("\n"),start);
1905 cp=CUnicodeUtils::GetCPCode(output);
1907 int len=message.GetLength();
1909 char * buf;
1910 buf = new char[len*4 + 4];
1911 SecureZeroMemory(buf, (len*4 + 4));
1913 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1915 file.Write(buf,lengthIncTerminator-1);
1916 file.Close();
1917 delete buf;
1918 return 0;
1921 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1923 CPullFetchDlg dlg;
1924 dlg.m_PreSelectRemote = remoteName;
1925 dlg.m_bAllowRebase = allowRebase;
1926 dlg.m_IsPull=FALSE;
1928 if(dlg.DoModal()==IDOK)
1930 if(dlg.m_bAutoLoad)
1932 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1935 CString url;
1936 url=dlg.m_RemoteURL;
1937 CString cmd;
1938 CString arg;
1940 int ver = CAppUtils::GetMsysgitVersion();
1942 if(ver >= 0x01070203) //above 1.7.0.2
1943 arg = _T("--progress ");
1945 if (dlg.m_bPrune) {
1946 arg += _T("--prune ");
1949 if (dlg.m_bFetchTags == 1)
1951 arg += _T("--tags ");
1953 else if (dlg.m_bFetchTags == 0)
1955 arg += _T("--no-tags ");
1958 if (dlg.m_bAllRemotes)
1959 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
1960 else
1961 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
1963 CProgressDlg progress;
1965 progress.m_bAutoCloseOnSuccess = autoClose;
1967 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
1969 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1971 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1974 progress.m_GitCmd=cmd;
1975 INT_PTR userResponse = progress.DoModal();
1977 if (userResponse == IDC_PROGRESS_BUTTON1)
1979 CString cmd = _T("/command:log");
1980 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1981 RunTortoiseProc(cmd);
1982 return TRUE;
1984 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1986 while(1)
1988 CRebaseDlg dlg;
1989 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
1990 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1991 INT_PTR response = dlg.DoModal();
1992 if(response == IDOK)
1994 return TRUE;
1996 if(response == IDC_REBASE_POST_BUTTON )
1998 CString cmd, out, err;
1999 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2000 g_Git.m_CurrentDir,
2001 g_Git.FixBranchName(dlg.m_Upstream),
2002 g_Git.FixBranchName(dlg.m_Branch));
2003 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2005 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2006 return FALSE;
2009 CAppUtils::SendPatchMail(cmd,out);
2010 return TRUE;
2013 if(response == IDC_REBASE_POST_BUTTON +1 )
2014 continue;
2016 if(response == IDCANCEL)
2017 return FALSE;
2019 return TRUE;
2021 else if (userResponse != IDCANCEL)
2022 return TRUE;
2024 return FALSE;
2027 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2029 CPushDlg dlg;
2030 dlg.m_BranchSourceName = selectLocalBranch;
2031 CString error;
2032 DWORD exitcode = 0xFFFFFFFF;
2033 CTGitPathList list;
2034 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2035 if (CHooks::Instance().PrePush(list,exitcode, error))
2037 if (exitcode)
2039 CString temp;
2040 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2041 //ReportError(temp);
2042 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2043 return false;
2047 if(dlg.DoModal()==IDOK)
2049 CString arg;
2051 if(dlg.m_bAutoLoad)
2053 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2056 if(dlg.m_bPack)
2057 arg += _T("--thin ");
2058 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2059 arg += _T("--tags ");
2060 if(dlg.m_bForce)
2061 arg += _T("--force ");
2062 if (dlg.m_bSetUpstream)
2063 arg += _T("--set-upstream ");
2065 int ver = CAppUtils::GetMsysgitVersion();
2067 if(ver >= 0x01070203) //above 1.7.0.2
2068 arg += _T("--progress ");
2070 CProgressDlg progress;
2071 progress.m_bAutoCloseOnSuccess=autoClose;
2073 STRING_VECTOR remotesList;
2074 if (dlg.m_bPushAllRemotes)
2075 g_Git.GetRemoteList(remotesList);
2076 else
2077 remotesList.push_back(dlg.m_URL);
2079 for (unsigned int i = 0; i < remotesList.size(); i++)
2081 CString cmd;
2082 if (dlg.m_bPushAllBranches)
2084 cmd.Format(_T("git.exe push --all %s \"%s\""),
2085 arg,
2086 remotesList[i]);
2088 else
2090 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2091 arg,
2092 remotesList[i],
2093 dlg.m_BranchSourceName);
2094 if (!dlg.m_BranchRemoteName.IsEmpty())
2096 cmd += _T(":") + dlg.m_BranchRemoteName;
2099 progress.m_GitCmdList.push_back(cmd);
2102 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2103 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2104 INT_PTR ret = progress.DoModal();
2106 if(!progress.m_GitStatus)
2108 if (CHooks::Instance().PostPush(list,exitcode, error))
2110 if (exitcode)
2112 CString temp;
2113 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2114 //ReportError(temp);
2115 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2116 return false;
2119 if(ret == IDC_PROGRESS_BUTTON1)
2121 RequestPull(dlg.m_BranchRemoteName);
2123 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2125 Push();
2127 return TRUE;
2131 return FALSE;
2134 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2136 CRequestPullDlg dlg;
2137 dlg.m_RepositoryURL = repositoryUrl;
2138 dlg.m_EndRevision = endrevision;
2139 if (dlg.DoModal()==IDOK)
2141 CString cmd;
2142 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2144 CString tempFileName = GetTempFile();
2145 if (g_Git.RunLogFile(cmd, tempFileName))
2147 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2148 return false;
2150 CAppUtils::LaunchAlternativeEditor(tempFileName);
2152 return true;
2155 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2157 CString strDir(szPath);
2158 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2160 strDir.AppendChar(_T('\\'));
2162 std::vector<CString> vPath;
2163 CString strTemp;
2164 bool bSuccess = false;
2166 for (int i=0;i<strDir.GetLength();++i)
2168 if (strDir.GetAt(i) != _T('\\'))
2170 strTemp.AppendChar(strDir.GetAt(i));
2172 else
2174 vPath.push_back(strTemp);
2175 strTemp.AppendChar(_T('\\'));
2179 std::vector<CString>::const_iterator vIter;
2180 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2182 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2185 return bSuccess;
2188 void CAppUtils::RemoveTrailSlash(CString &path)
2190 if(path.IsEmpty())
2191 return ;
2193 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2195 path=path.Left(path.GetLength()-1);
2196 if(path.IsEmpty())
2197 return;
2201 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2202 CTGitPathList &pathList,
2203 CTGitPathList &selectedList,
2204 bool bSelectFilesForCommit,
2205 bool autoClose)
2207 bool bFailed = true;
2209 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2211 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2213 CTGitPath path(g_Git.m_CurrentDir);
2214 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2215 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2216 dlg.SetTreeWidth(220);
2217 dlg.m_DefaultPage = _T("gitconfig");
2219 dlg.DoModal();
2220 dlg.HandleRestart();
2223 else
2224 return false;
2227 while (bFailed)
2229 bFailed = false;
2230 CCommitDlg dlg;
2231 dlg.m_sBugID = bugid;
2233 dlg.m_bWholeProject = bWholeProject;
2235 dlg.m_sLogMessage = sLogMsg;
2236 dlg.m_pathList = pathList;
2237 dlg.m_checkedPathList = selectedList;
2238 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2239 dlg.m_bAutoClose = autoClose;
2240 if (dlg.DoModal() == IDOK)
2242 if (dlg.m_pathList.GetCount()==0)
2243 return false;
2244 // if the user hasn't changed the list of selected items
2245 // we don't use that list. Because if we would use the list
2246 // of pre-checked items, the dialog would show different
2247 // checked items on the next startup: it would only try
2248 // to check the parent folder (which might not even show)
2249 // instead, we simply use an empty list and let the
2250 // default checking do its job.
2251 if (!dlg.m_pathList.IsEqual(pathList))
2252 selectedList = dlg.m_pathList;
2253 pathList = dlg.m_updatedPathList;
2254 sLogMsg = dlg.m_sLogMessage;
2255 bSelectFilesForCommit = true;
2257 if( dlg.m_bPushAfterCommit )
2259 switch(dlg.m_PostCmd)
2261 case GIT_POST_CMD_DCOMMIT:
2262 CAppUtils::SVNDCommit();
2263 break;
2264 default:
2265 CAppUtils::Push();
2268 else if (dlg.m_bCreateTagAfterCommit)
2270 CAppUtils::CreateBranchTag(TRUE);
2273 // CGitProgressDlg progDlg;
2274 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2275 // if (parser.HasVal(_T("closeonend")))
2276 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2277 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2278 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2279 // progDlg.SetPathList(dlg.m_pathList);
2280 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2281 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2282 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2283 // progDlg.SetItemCount(dlg.m_itemsCount);
2284 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2285 // progDlg.DoModal();
2286 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2287 // err = (DWORD)progDlg.DidErrorsOccur();
2288 // bFailed = progDlg.DidErrorsOccur();
2289 // bRet = progDlg.DidErrorsOccur();
2290 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2291 // if (DWORD(bFailRepeat)==0)
2292 // bFailed = false; // do not repeat if the user chose not to in the settings.
2295 return true;
2299 BOOL CAppUtils::SVNDCommit()
2301 CSVNDCommitDlg dcommitdlg;
2302 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2303 if (gitSetting == _T("")) {
2304 if (dcommitdlg.DoModal() != IDOK)
2306 return false;
2308 else
2310 if (dcommitdlg.m_remember)
2312 if (dcommitdlg.m_rmdir)
2314 gitSetting = _T("true");
2316 else
2318 gitSetting = _T("false");
2320 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2322 CString msg;
2323 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2324 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2330 BOOL IsStash = false;
2331 if(!g_Git.CheckCleanWorkTree())
2333 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2335 CString cmd,out;
2336 cmd=_T("git.exe stash");
2337 if (g_Git.Run(cmd, &out, CP_UTF8))
2339 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2340 return false;
2342 IsStash =true;
2345 else
2347 return false;
2351 CProgressDlg progress;
2352 if (dcommitdlg.m_rmdir)
2354 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2356 else
2358 progress.m_GitCmd=_T("git.exe svn dcommit");
2360 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2362 if( IsStash)
2364 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2366 CString cmd,out;
2367 cmd=_T("git.exe stash pop");
2368 if (g_Git.Run(cmd, &out, CP_UTF8))
2370 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2371 return false;
2375 else
2377 return false;
2380 return TRUE;
2382 return FALSE;
2385 BOOL CAppUtils::Merge(CString *commit)
2387 CMergeDlg dlg;
2388 if(commit)
2389 dlg.m_initialRefName = *commit;
2391 if(dlg.DoModal()==IDOK)
2393 CString cmd;
2394 CString noff;
2395 CString squash;
2396 CString nocommit;
2397 CString msg;
2399 if(dlg.m_bNoFF)
2400 noff=_T("--no-ff");
2402 if(dlg.m_bSquash)
2403 squash=_T("--squash");
2405 if(dlg.m_bNoCommit)
2406 nocommit=_T("--no-commit");
2408 if(!dlg.m_strLogMesage.IsEmpty())
2410 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2412 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2413 msg,
2414 noff,
2415 squash,
2416 nocommit,
2417 g_Git.FixBranchName(dlg.m_VersionName));
2419 CProgressDlg Prodlg;
2420 Prodlg.m_GitCmd = cmd;
2422 if (dlg.m_bNoCommit)
2423 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2424 else if (dlg.m_bIsBranch)
2425 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2427 INT_PTR ret = Prodlg.DoModal();
2429 if (ret == IDC_PROGRESS_BUTTON1)
2430 if (dlg.m_bNoCommit)
2432 CString sLogMsg;
2433 CTGitPathList pathList;
2434 CTGitPathList selectedList;
2435 return Commit(_T(""), TRUE, sLogMsg, pathList, selectedList, true);
2437 else if (dlg.m_bIsBranch)
2439 CString msg;
2440 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2441 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2443 CString cmd, out;
2444 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2445 if (g_Git.Run(cmd, &out, CP_UTF8))
2446 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2450 return !Prodlg.m_GitStatus;
2452 return false;
2455 void CAppUtils::EditNote(GitRev *rev)
2457 CInputDlg dlg;
2458 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2459 dlg.m_sInputText = rev->m_Notes;
2460 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2461 //dlg.m_pProjectProperties = &m_ProjectProperties;
2462 dlg.m_bUseLogWidth = true;
2463 if(dlg.DoModal() == IDOK)
2465 CString cmd,output;
2466 cmd=_T("notes add -f -F \"");
2468 CString tempfile=::GetTempFile();
2469 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2470 cmd += tempfile;
2471 cmd += _T("\" ");
2472 cmd += rev->m_CommitHash.ToString();
2476 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2478 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2481 else
2483 rev->m_Notes = dlg.m_sInputText;
2485 }catch(...)
2487 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2489 CFile::Remove(tempfile);
2494 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2496 CString cmd;
2497 CString progressarg;
2498 CString version;
2500 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2501 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2503 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2505 __int64 time=0;
2506 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2508 if((DWORD)time == regTime)
2510 return regVersion;
2514 if(versionstr)
2515 version = *versionstr;
2516 else
2518 CString err;
2519 cmd = _T("git.exe --version");
2520 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2522 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2523 return false;
2527 int start=0;
2528 int ver = 0;
2532 CString str=version.Tokenize(_T("."), start);
2533 int space = str.ReverseFind(_T(' '));
2534 str = str.Mid(space+1,start);
2535 ver = _ttol(str);
2536 ver <<=24;
2538 version = version.Mid(start);
2539 start = 0;
2541 str = version.Tokenize(_T("."), start);
2543 ver |= (_ttol(str) & 0xFF) << 16;
2545 str = version.Tokenize(_T("."), start);
2546 ver |= (_ttol(str) & 0xFF) << 8;
2548 str = version.Tokenize(_T("."), start);
2549 ver |= (_ttol(str) & 0xFF);
2551 catch(...)
2553 if (!ver)
2555 CMessageBox::Show(NULL, _T("Could not parse git.exe version number."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2556 return false;
2560 regTime = time&0xFFFFFFFF;
2561 regVersion = ver;
2563 return ver;
2566 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2568 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2570 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2572 if (hShell.IsValid()) {
2573 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2574 if (pfnSHGPSFW) {
2575 IPropertyStore *pps;
2576 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2577 if (SUCCEEDED(hr)) {
2578 PROPVARIANT var;
2579 var.vt = VT_BOOL;
2580 var.boolVal = VARIANT_TRUE;
2581 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2582 pps->Release();
2588 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2590 ASSERT(dialogname.GetLength() < 70);
2591 ASSERT(urlorpath.GetLength() < MAX_PATH);
2592 WCHAR pathbuf[MAX_PATH] = {0};
2594 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2596 wcscat_s(pathbuf, L" - ");
2597 wcscat_s(pathbuf, dialogname);
2598 wcscat_s(pathbuf, L" - ");
2599 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2600 SetWindowText(hWnd, pathbuf);