Fixed issue #1110: Tracking branches when you don't want to/incorrectly
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob2bffc849511b778fdbab01515ac9a32308a91e0f
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 "FormatMessageWrapper.h"
62 #include "SmartHandle.h"
64 CAppUtils::CAppUtils(void)
68 CAppUtils::~CAppUtils(void)
72 bool CAppUtils::StashSave()
74 CStashSaveDlg dlg;
76 if (dlg.DoModal() == IDOK)
78 CString cmd, out;
79 cmd = _T("git.exe stash save");
81 if (dlg.m_bIncludeUntracked && CAppUtils::GetMsysgitVersion() >= 0x01070700)
82 cmd += _T(" --include-untracked");
84 if (!dlg.m_sMessage.IsEmpty())
86 CString message = dlg.m_sMessage;
87 message.Replace(_T("\""), _T("\"\""));
88 cmd += _T(" \"") + message + _T("\"");
91 if (g_Git.Run(cmd, &out, CP_ACP))
93 CMessageBox::Show(NULL, CString(_T("<ct=0x0000FF>Stash Fail!!!</ct>\n")) + out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
95 else
97 CMessageBox::Show(NULL, CString(_T("<ct=0xff0000>Stash Success</ct>\n")) + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
98 return true;
101 return false;
104 int CAppUtils::StashApply(CString ref, bool showChanges /* true */)
106 CString cmd,out;
107 cmd = _T("git.exe stash apply ");
108 if (ref.Find(_T("refs/")) == 0)
109 ref = ref.Mid(5);
110 if (ref.Find(_T("stash{")) == 0)
111 ref = _T("stash@") + ref.Mid(5);
112 cmd += ref;
114 int ret = g_Git.Run(cmd, &out, CP_ACP);
115 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
116 if (ret && !(ret == 1 && hasConflicts))
118 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
120 else
122 CString withConflicts;
123 if (hasConflicts)
124 withConflicts = _T(" with conflicts");
125 if (showChanges)
127 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success") + withConflicts + _T("</ct>\nDo you want to show change?"))
128 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
130 CChangedDlg dlg;
131 dlg.m_pathList.AddPath(CTGitPath());
132 dlg.DoModal();
134 return 0;
136 else
138 CMessageBox::Show(NULL, _T("<ct=0xff0000>Stash Apply Success") + withConflicts + _T("</ct>") ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
139 return 0;
142 return -1;
145 int CAppUtils::StashPop(bool showChanges /* true */)
147 CString cmd,out;
148 cmd=_T("git.exe stash pop ");
150 int ret = g_Git.Run(cmd, &out, CP_ACP);
151 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
152 if (ret && !(ret == 1 && hasConflicts))
154 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
156 else
158 CString message = _T("<ct=0xff0000>Stash POP Success</ct>");
159 if (hasConflicts)
160 message = _T("<ct=0x000000ff>Stash POP Failed, there are conflicts</ct>");
161 if (showChanges)
163 if(CMessageBox::Show(NULL,CString(message + _T("\nDo you want to show change?"))
164 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
166 CChangedDlg dlg;
167 dlg.m_pathList.AddPath(CTGitPath());
168 dlg.DoModal();
170 return 0;
172 else
174 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
175 return 0;
178 return -1;
181 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
183 #if 0
184 GitProperties props(file, GitRev::REV_WC, false);
185 for (int i = 0; i < props.GetCount(); ++i)
187 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
189 mimetype = props.GetItemValue(i).c_str();
190 return true;
193 #endif
194 return false;
197 BOOL CAppUtils::StartExtMerge(
198 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
199 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
202 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
203 CString ext = mergedfile.GetFileExtension();
204 CString com = regCom;
205 bool bInternal = false;
207 CString mimetype;
208 if (ext != "")
210 // is there an extension specific merge tool?
211 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
212 if (CString(mergetool) != "")
214 com = mergetool;
217 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
219 // is there a mime type specific merge tool?
220 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
221 if (CString(mergetool) != "")
223 com = mergetool;
227 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
229 // use TortoiseMerge
230 bInternal = true;
231 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
232 com = tortoiseMergePath;
233 if (com.IsEmpty())
235 com = CPathUtils::GetAppDirectory();
236 com += _T("TortoiseMerge.exe");
238 com = _T("\"") + com + _T("\"");
239 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
240 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
242 // check if the params are set. If not, just add the files to the command line
243 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
245 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
246 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
247 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
248 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
250 if (basefile.IsEmpty())
252 com.Replace(_T("/base:%base"), _T(""));
253 com.Replace(_T("%base"), _T(""));
255 else
256 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
257 if (theirfile.IsEmpty())
259 com.Replace(_T("/theirs:%theirs"), _T(""));
260 com.Replace(_T("%theirs"), _T(""));
262 else
263 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
264 if (yourfile.IsEmpty())
266 com.Replace(_T("/mine:%mine"), _T(""));
267 com.Replace(_T("%mine"), _T(""));
269 else
270 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
271 if (mergedfile.IsEmpty())
273 com.Replace(_T("/merged:%merged"), _T(""));
274 com.Replace(_T("%merged"), _T(""));
276 else
277 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
278 if (basename.IsEmpty())
280 if (basefile.IsEmpty())
282 com.Replace(_T("/basename:%bname"), _T(""));
283 com.Replace(_T("%bname"), _T(""));
285 else
287 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
290 else
291 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
292 if (theirname.IsEmpty())
294 if (theirfile.IsEmpty())
296 com.Replace(_T("/theirsname:%tname"), _T(""));
297 com.Replace(_T("%tname"), _T(""));
299 else
301 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
304 else
305 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
306 if (yourname.IsEmpty())
308 if (yourfile.IsEmpty())
310 com.Replace(_T("/minename:%yname"), _T(""));
311 com.Replace(_T("%yname"), _T(""));
313 else
315 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
318 else
319 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
320 if (mergedname.IsEmpty())
322 if (mergedfile.IsEmpty())
324 com.Replace(_T("/mergedname:%mname"), _T(""));
325 com.Replace(_T("%mname"), _T(""));
327 else
329 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
332 else
333 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
335 if ((bReadOnly)&&(bInternal))
336 com += _T(" /readonly");
338 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
340 return FALSE;
343 return TRUE;
346 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
348 CString viewer;
349 // use TortoiseMerge
350 viewer = CPathUtils::GetAppDirectory();
351 viewer += _T("TortoiseMerge.exe");
353 viewer = _T("\"") + viewer + _T("\"");
354 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
355 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
356 if (bReversed)
357 viewer += _T(" /reversedpatch");
358 if (!sOriginalDescription.IsEmpty())
359 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
360 if (!sPatchedDescription.IsEmpty())
361 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
362 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
364 return FALSE;
366 return TRUE;
369 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
371 // Is there a mime type specific diff tool?
372 CString mimetype;
373 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
375 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
376 if (!difftool.IsEmpty())
377 return difftool;
380 // Is there an extension specific diff tool?
381 CString ext = file2.GetFileExtension().MakeLower();
382 if (!ext.IsEmpty())
384 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
385 if (!difftool.IsEmpty())
386 return difftool;
387 // Maybe we should use TortoiseIDiff?
388 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
389 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
390 (ext == _T(".png")) || (ext == _T(".ico")) ||
391 (ext == _T(".dib")) || (ext == _T(".emf")))
393 return
394 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
395 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
399 // Finally, pick a generic external diff tool
400 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
401 return difftool;
404 bool CAppUtils::StartExtDiff(
405 const CString& file1, const CString& file2,
406 const CString& sName1, const CString& sName2,
407 const DiffFlags& flags)
409 CString viewer;
411 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
412 if (!flags.bBlame || !(DWORD)blamediff)
414 viewer = PickDiffTool(file1, file2);
415 // If registry entry for a diff program is commented out, use TortoiseMerge.
416 bool bCommentedOut = viewer.Left(1) == _T("#");
417 if (flags.bAlternativeTool)
419 // Invert external vs. internal diff tool selection.
420 if (bCommentedOut)
421 viewer.Delete(0); // uncomment
422 else
423 viewer = "";
425 else if (bCommentedOut)
426 viewer = "";
429 bool bInternal = viewer.IsEmpty();
430 if (bInternal)
432 viewer =
433 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
434 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
435 if (flags.bBlame)
436 viewer += _T(" /blame");
438 // check if the params are set. If not, just add the files to the command line
439 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
441 viewer += _T(" \"")+file1+_T("\"");
442 viewer += _T(" \"")+file2+_T("\"");
444 if (viewer.Find(_T("%base")) >= 0)
446 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
448 if (viewer.Find(_T("%mine")) >= 0)
450 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
453 if (sName1.IsEmpty())
454 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
455 else
456 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
458 if (sName2.IsEmpty())
459 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
460 else
461 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
463 if (flags.bReadOnly && bInternal)
464 viewer += _T(" /readonly");
466 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
469 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
471 CString viewer;
472 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
473 viewer = v;
474 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
476 // use TortoiseUDiff
477 viewer = CPathUtils::GetAppDirectory();
478 viewer += _T("TortoiseUDiff.exe");
479 // enquote the path to TortoiseUDiff
480 viewer = _T("\"") + viewer + _T("\"");
481 // add the params
482 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
485 if (viewer.Find(_T("%1"))>=0)
487 if (viewer.Find(_T("\"%1\"")) >= 0)
488 viewer.Replace(_T("%1"), patchfile);
489 else
490 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
492 else
493 viewer += _T(" \"") + patchfile + _T("\"");
494 if (viewer.Find(_T("%title")) >= 0)
496 viewer.Replace(_T("%title"), title);
499 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
501 return FALSE;
503 return TRUE;
506 BOOL CAppUtils::StartTextViewer(CString file)
508 CString viewer;
509 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
510 viewer = txt;
511 viewer = viewer + _T("\\Shell\\Open\\Command\\");
512 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
513 viewer = txtexe;
515 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
516 TCHAR * buf = new TCHAR[len+1];
517 ExpandEnvironmentStrings(viewer, buf, len);
518 viewer = buf;
519 delete [] buf;
520 len = ExpandEnvironmentStrings(file, NULL, 0);
521 buf = new TCHAR[len+1];
522 ExpandEnvironmentStrings(file, buf, len);
523 file = buf;
524 delete [] buf;
525 file = _T("\"")+file+_T("\"");
526 if (viewer.IsEmpty())
528 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
530 if (viewer.Find(_T("\"%1\"")) >= 0)
532 viewer.Replace(_T("\"%1\""), file);
534 else if (viewer.Find(_T("%1")) >= 0)
536 viewer.Replace(_T("%1"), file);
538 else
540 viewer += _T(" ");
541 viewer += file;
544 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
546 return FALSE;
548 return TRUE;
551 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
553 DWORD length = 0;
554 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
555 if (!hFile)
556 return TRUE;
557 length = ::GetFileSize(hFile, NULL);
558 if (length < 4)
559 return TRUE;
560 return FALSE;
564 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
566 LOGFONT logFont;
567 HDC hScreenDC = ::GetDC(NULL);
568 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
569 ::ReleaseDC(NULL, hScreenDC);
570 logFont.lfWidth = 0;
571 logFont.lfEscapement = 0;
572 logFont.lfOrientation = 0;
573 logFont.lfWeight = FW_NORMAL;
574 logFont.lfItalic = 0;
575 logFont.lfUnderline = 0;
576 logFont.lfStrikeOut = 0;
577 logFont.lfCharSet = DEFAULT_CHARSET;
578 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
579 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
580 logFont.lfQuality = DRAFT_QUALITY;
581 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
582 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
583 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
586 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
588 CString key,remote;
589 CString cmd,out;
590 if( pRemote == NULL)
592 remote=_T("origin");
594 else
596 remote=*pRemote;
598 if(keyfile == NULL)
600 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
601 key = g_Git.GetConfigValue(cmd);
602 int start=0;
603 key = key.Tokenize(_T("\n"),start);
605 else
606 key=*keyfile;
608 if(key.IsEmpty())
609 return false;
611 CString proc=CPathUtils::GetAppDirectory();
612 proc += _T("pageant.exe \"");
613 proc += key;
614 proc += _T("\"");
616 CString tempfile = GetTempFile();
617 ::DeleteFile(tempfile);
619 proc += _T(" -c \"");
620 proc += CPathUtils::GetAppDirectory();
621 proc += _T("touch.exe\"");
622 proc += _T(" \"");
623 proc += tempfile;
624 proc += _T("\"");
626 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
627 if(!b)
628 return b;
630 int i=0;
631 while(!::PathFileExists(tempfile))
633 Sleep(100);
634 i++;
635 if(i>10*60*5)
636 break; //timeout 5 minutes
639 if( i== 10*60*5)
641 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
643 ::DeleteFile(tempfile);
644 return true;
646 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
648 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
649 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
650 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
653 CString sCmd;
654 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
656 LaunchApplication(sCmd, NULL, false);
657 return true;
659 bool CAppUtils::LaunchRemoteSetting()
661 CTGitPath path(g_Git.m_CurrentDir);
662 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
663 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
664 //dlg.SetTreeWidth(220);
665 dlg.m_DefaultPage = _T("gitremote");
667 dlg.DoModal();
668 dlg.HandleRestart();
669 return true;
672 * Launch the external blame viewer
674 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
676 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
677 viewer += _T("TortoiseGitBlame.exe");
678 viewer += _T("\" \"") + sBlameFile + _T("\"");
679 //viewer += _T(" \"") + sLogFile + _T("\"");
680 //viewer += _T(" \"") + sOriginalFile + _T("\"");
681 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
682 viewer += CString(_T(" /rev:"))+Rev;
683 viewer += _T(" ")+sParams;
685 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
688 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
690 CString sText;
691 if (pWnd == NULL)
692 return false;
693 bool bStyled = false;
694 pWnd->GetWindowText(sText);
695 // the rich edit control doesn't count the CR char!
696 // to be exact: CRLF is treated as one char.
697 sText.Remove('\r');
699 // style each line separately
700 int offset = 0;
701 int nNewlinePos;
704 nNewlinePos = sText.Find('\n', offset);
705 CString sLine = sText.Mid(offset);
706 if (nNewlinePos>=0)
707 sLine = sLine.Left(nNewlinePos-offset);
708 int start = 0;
709 int end = 0;
710 while (FindStyleChars(sLine, '*', start, end))
712 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
713 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
714 CHARFORMAT2 format;
715 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
716 format.cbSize = sizeof(CHARFORMAT2);
717 format.dwMask = CFM_BOLD;
718 format.dwEffects = CFE_BOLD;
719 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
720 bStyled = true;
721 start = end;
723 start = 0;
724 end = 0;
725 while (FindStyleChars(sLine, '^', start, end))
727 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
728 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
729 CHARFORMAT2 format;
730 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
731 format.cbSize = sizeof(CHARFORMAT2);
732 format.dwMask = CFM_ITALIC;
733 format.dwEffects = CFE_ITALIC;
734 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
735 bStyled = true;
736 start = end;
738 start = 0;
739 end = 0;
740 while (FindStyleChars(sLine, '_', start, end))
742 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
743 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
744 CHARFORMAT2 format;
745 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
746 format.cbSize = sizeof(CHARFORMAT2);
747 format.dwMask = CFM_UNDERLINE;
748 format.dwEffects = CFE_UNDERLINE;
749 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
750 bStyled = true;
751 start = end;
753 offset = nNewlinePos+1;
754 } while(nNewlinePos>=0);
755 return bStyled;
758 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
760 int i=start;
761 bool bFoundMarker = false;
762 // find a starting marker
763 while (sText[i] != 0)
765 if (sText[i] == stylechar)
767 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
768 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
770 start = i+1;
771 i++;
772 bFoundMarker = true;
773 break;
776 i++;
778 if (!bFoundMarker)
779 return false;
780 // find ending marker
781 bFoundMarker = false;
782 while (sText[i] != 0)
784 if (sText[i] == stylechar)
786 if ((IsCharAlphaNumeric(sText[i-1])) &&
787 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
789 end = i;
790 i++;
791 bFoundMarker = true;
792 break;
795 i++;
797 return bFoundMarker;
800 CString CAppUtils::GetProjectNameFromURL(CString url)
802 CString name;
803 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
804 (name.CompareNoCase(_T("tags"))==0) ||
805 (name.CompareNoCase(_T("trunk"))==0))
807 name = url.Mid(url.ReverseFind('/')+1);
808 url = url.Left(url.ReverseFind('/'));
810 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
812 // a name of svn or svnroot indicates that it's not really the project name. In that
813 // case, we try the first part of the URL
814 // of course, this won't work in all cases (but it works for Google project hosting)
815 url.Replace(_T("http://"), _T(""));
816 url.Replace(_T("https://"), _T(""));
817 url.Replace(_T("svn://"), _T(""));
818 url.Replace(_T("svn+ssh://"), _T(""));
819 url.TrimLeft(_T("/"));
820 name = url.Left(url.Find('.'));
822 return name;
825 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
826 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
827 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
828 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
831 CString tempfile=GetTempFile();
832 CString cmd;
833 if(rev1 == GitRev::GetWorkingCopy())
835 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
837 else
839 CString merge;
840 if(bMerge)
841 merge = _T("-c");
843 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
846 if( !url1.IsEmpty() )
848 cmd += _T(" -- \"");
849 cmd += url1.GetGitPathString();
850 cmd += _T("\" ");
852 g_Git.RunLogFile(cmd,tempfile);
853 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
856 #if 0
857 CString sCmd;
858 sCmd.Format(_T("%s /command:showcompare /unified"),
859 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
860 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
861 if (rev1.IsValid())
862 sCmd += _T(" /revision1:") + rev1.ToString();
863 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
864 if (rev2.IsValid())
865 sCmd += _T(" /revision2:") + rev2.ToString();
866 if (peg.IsValid())
867 sCmd += _T(" /pegrevision:") + peg.ToString();
868 if (headpeg.IsValid())
869 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
871 if (bAlternateDiff)
872 sCmd += _T(" /alternatediff");
874 if (bIgnoreAncestry)
875 sCmd += _T(" /ignoreancestry");
877 if (hWnd)
879 sCmd += _T(" /hwnd:");
880 TCHAR buf[30];
881 _stprintf_s(buf, 30, _T("%d"), hWnd);
882 sCmd += buf;
885 return CAppUtils::LaunchApplication(sCmd, NULL, false);
886 #endif
887 return TRUE;
891 bool CAppUtils::Export(CString *BashHash)
893 bool bRet = false;
895 // ask from where the export has to be done
896 CExportDlg dlg;
897 if(BashHash)
898 dlg.m_Revision=*BashHash;
900 if (dlg.DoModal() == IDOK)
902 CString cmd;
903 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
904 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
906 CProgressDlg pro;
907 pro.m_GitCmd=cmd;
908 pro.DoModal();
909 return TRUE;
911 return bRet;
914 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
916 CCreateBranchTagDlg dlg;
917 dlg.m_bIsTag=IsTag;
918 dlg.m_bSwitch=switch_new_brach;
920 if(CommitHash)
921 dlg.m_Base = *CommitHash;
923 if(dlg.DoModal()==IDOK)
925 CString cmd;
926 CString force;
927 CString track;
928 if(dlg.m_bTrack == TRUE)
929 track=_T(" --track ");
930 else if(dlg.m_bTrack == FALSE)
931 track=_T(" --no-track");
933 if(dlg.m_bForce)
934 force=_T(" -f ");
936 if(IsTag)
938 CString sign;
939 if(dlg.m_bSign)
940 sign=_T("-s");
942 cmd.Format(_T("git.exe tag %s %s %s %s"),
943 force,
944 sign,
945 dlg.m_BranchTagName,
946 g_Git.FixBranchName(dlg.m_VersionName)
949 CString tempfile=::GetTempFile();
950 if(!dlg.m_Message.Trim().IsEmpty())
952 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
953 cmd += _T(" -F ")+tempfile;
956 else
958 cmd.Format(_T("git.exe branch %s %s %s %s"),
959 track,
960 force,
961 dlg.m_BranchTagName,
962 g_Git.FixBranchName(dlg.m_VersionName)
965 CString out;
966 if(g_Git.Run(cmd,&out,CP_UTF8))
968 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
970 if( !IsTag && dlg.m_bSwitch )
972 // it is a new branch and the user has requested to switch to it
973 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
974 g_Git.Run(cmd,&out,CP_UTF8);
975 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
978 return TRUE;
980 return FALSE;
983 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
985 CGitSwitchDlg dlg;
986 if(CommitHash)
987 dlg.m_Base=*CommitHash;
988 if(!initialRefName.IsEmpty())
989 dlg.m_initialRefName = initialRefName;
991 if (dlg.DoModal() == IDOK)
993 CString branch;
994 if (dlg.m_bBranch)
995 branch = dlg.m_NewBranch;
997 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
999 return FALSE;
1002 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1004 CString cmd;
1005 CString track;
1006 CString force;
1007 CString branch;
1009 if(!sNewBranch.IsEmpty()){
1010 if (bBranchOverride)
1012 branch.Format(_T("-B %s"), sNewBranch);
1014 else
1016 branch.Format(_T("-b %s"), sNewBranch);
1018 if (bTrack)
1019 track = _T("--track");
1021 if (bForce)
1022 force = _T("-f");
1024 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1025 force,
1026 track,
1027 branch,
1028 g_Git.FixBranchName(ref));
1030 CProgressDlg progress;
1031 progress.m_bAutoCloseOnSuccess = autoClose;
1032 progress.m_GitCmd = cmd;
1034 CTGitPath gitPath = g_Git.m_CurrentDir;
1035 if (gitPath.HasSubmodules())
1036 progress.m_PostCmdList.Add(_T("Update Submodules"));
1038 int ret = progress.DoModal();
1039 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1041 CString sCmd;
1042 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1044 RunTortoiseProc(sCmd);
1045 return TRUE;
1047 else if (ret == IDOK)
1048 return TRUE;
1050 return FALSE;
1053 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1055 CString ignorefile;
1056 ignorefile=g_Git.m_CurrentDir+_T("\\");
1058 if(IsMask)
1060 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1063 else
1065 ignorefile += _T("\\.gitignore");
1068 CStdioFile file;
1069 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1071 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1072 return FALSE;
1075 CString ignorelist;
1076 CString mask;
1079 //file.ReadString(ignorelist);
1080 file.SeekToEnd();
1081 for(int i=0;i<path.GetCount();i++)
1083 if(IsMask)
1085 mask=_T("*")+path[i].GetFileExtension();
1086 if(ignorelist.Find(mask)<0)
1087 ignorelist += _T("\n")+mask;
1089 else
1091 ignorelist += _T("\n/")+path[i].GetGitPathString();
1094 file.WriteString(ignorelist);
1096 file.Close();
1098 }catch(...)
1100 file.Close();
1101 return FALSE;
1104 return TRUE;
1108 bool CAppUtils::GitReset(CString *CommitHash,int type)
1110 CResetDlg dlg;
1111 dlg.m_ResetType=type;
1112 dlg.m_ResetToVersion=*CommitHash;
1113 if (dlg.DoModal() == IDOK)
1115 CString cmd;
1116 CString type;
1117 switch(dlg.m_ResetType)
1119 case 0:
1120 type=_T("--soft");
1121 break;
1122 case 1:
1123 type=_T("--mixed");
1124 break;
1125 case 2:
1126 type=_T("--hard");
1127 break;
1128 default:
1129 type=_T("--mixed");
1130 break;
1132 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1134 CProgressDlg progress;
1135 progress.m_GitCmd=cmd;
1137 CTGitPath gitPath = g_Git.m_CurrentDir;
1138 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1139 progress.m_PostCmdList.Add(_T("Update Submodules"));
1141 int ret = progress.DoModal();
1142 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1144 CString sCmd;
1145 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1147 RunTortoiseProc(sCmd);
1148 return TRUE;
1150 else if (ret == IDOK)
1151 return TRUE;
1154 return FALSE;
1157 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1159 if(mode == FALSE)
1161 descript=_T("Deleted");
1162 return;
1164 if(base)
1166 descript=_T("Modified");
1167 return;
1169 descript=_T("Created");
1170 return;
1173 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1175 CString tempmergefile;
1178 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1179 CFile::Remove(tempmergefile);
1180 }catch(...)
1186 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1187 CFile::Remove(tempmergefile);
1188 }catch(...)
1194 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1195 CFile::Remove(tempmergefile);
1196 }catch(...)
1200 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1202 CString file;
1203 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1205 return file;
1208 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1210 bool bRet = false;
1212 CTGitPath merge=path;
1213 CTGitPath directory = merge.GetDirectory();
1215 // we have the conflicted file (%merged)
1216 // now look for the other required files
1217 //GitStatus stat;
1218 //stat.GetStatus(merge);
1219 //if (stat.status == NULL)
1220 // return false;
1222 BYTE_VECTOR vector;
1224 CString cmd;
1225 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1227 if (g_Git.Run(cmd, &vector))
1229 return FALSE;
1232 CTGitPathList list;
1233 list.ParserFromLsFile(vector);
1235 if(list.GetCount() == 0)
1236 return FALSE;
1238 CTGitPath theirs;
1239 CTGitPath mine;
1240 CTGitPath base;
1242 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1243 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1244 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1246 CString format;
1248 //format=_T("git.exe cat-file blob \":%d:%s\"");
1249 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1250 CFile tempfile;
1251 //create a empty file, incase stage is not three
1252 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1253 tempfile.Close();
1254 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1255 tempfile.Close();
1256 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1257 tempfile.Close();
1259 bool b_base=false, b_local=false, b_remote=false;
1261 for(int i=0;i<list.GetCount();i++)
1263 CString cmd;
1264 CString outfile;
1265 cmd.Empty();
1266 outfile.Empty();
1268 if( list[i].m_Stage == 1)
1270 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1271 b_base = true;
1272 outfile = base.GetWinPathString();
1275 if( list[i].m_Stage == 2 )
1277 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1278 b_local = true;
1279 outfile = mine.GetWinPathString();
1282 if( list[i].m_Stage == 3 )
1284 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1285 b_remote = true;
1286 outfile = theirs.GetWinPathString();
1288 CString output, err;
1289 if(!outfile.IsEmpty())
1290 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1292 CString file;
1293 int start =0 ;
1294 file = output.Tokenize(_T("\t"), start);
1295 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1297 else
1299 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1303 if(b_local && b_remote )
1305 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1306 if( revertTheirMy )
1307 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1308 else
1309 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1312 else
1314 CFile::Remove(mine.GetWinPathString());
1315 CFile::Remove(theirs.GetWinPathString());
1316 CFile::Remove(base.GetWinPathString());
1318 CDeleteConflictDlg dlg;
1319 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1320 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1321 dlg.m_bShowModifiedButton=b_base;
1322 dlg.m_File=merge.GetGitPathString();
1323 if(dlg.DoModal() == IDOK)
1325 CString cmd,out;
1326 if(dlg.m_bIsDelete)
1328 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1330 else
1331 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1333 if(g_Git.Run(cmd,&out,CP_ACP))
1335 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1336 return FALSE;
1338 return TRUE;
1340 else
1341 return FALSE;
1344 #if 0
1345 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1346 base, theirs, mine, merge);
1347 #endif
1348 #if 0
1349 if (stat.status->text_status == svn_wc_status_conflicted)
1351 // we have a text conflict, use our merge tool to resolve the conflict
1353 CTSVNPath theirs(directory);
1354 CTSVNPath mine(directory);
1355 CTSVNPath base(directory);
1356 bool bConflictData = false;
1358 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1360 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1361 bConflictData = true;
1363 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1365 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1366 bConflictData = true;
1368 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1370 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1371 bConflictData = true;
1373 else
1375 mine = merge;
1377 if (bConflictData)
1378 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1379 base, theirs, mine, merge);
1382 if (stat.status->prop_status == svn_wc_status_conflicted)
1384 // we have a property conflict
1385 CTSVNPath prej(directory);
1386 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1388 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1389 // there's a problem: the prej file contains a _description_ of the conflict, and
1390 // that description string might be translated. That means we have no way of parsing
1391 // the file to find out the conflicting values.
1392 // The only thing we can do: show a dialog with the conflict description, then
1393 // let the user either accept the existing property or open the property edit dialog
1394 // to manually change the properties and values. And a button to mark the conflict as
1395 // resolved.
1396 CEditPropConflictDlg dlg;
1397 dlg.SetPrejFile(prej);
1398 dlg.SetConflictedItem(merge);
1399 bRet = (dlg.DoModal() != IDCANCEL);
1403 if (stat.status->tree_conflict)
1405 // we have a tree conflict
1406 SVNInfo info;
1407 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1408 if (pInfoData)
1410 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1412 CTSVNPath theirs(directory);
1413 CTSVNPath mine(directory);
1414 CTSVNPath base(directory);
1415 bool bConflictData = false;
1417 if (pInfoData->treeconflict_theirfile)
1419 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1420 bConflictData = true;
1422 if (pInfoData->treeconflict_basefile)
1424 base.AppendPathString(pInfoData->treeconflict_basefile);
1425 bConflictData = true;
1427 if (pInfoData->treeconflict_myfile)
1429 mine.AppendPathString(pInfoData->treeconflict_myfile);
1430 bConflictData = true;
1432 else
1434 mine = merge;
1436 if (bConflictData)
1437 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1438 base, theirs, mine, merge);
1440 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1442 CString sConflictAction;
1443 CString sConflictReason;
1444 CString sResolveTheirs;
1445 CString sResolveMine;
1446 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1447 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1449 if (pInfoData->treeconflict_nodekind == svn_node_file)
1451 switch (pInfoData->treeconflict_operation)
1453 case svn_wc_operation_update:
1454 switch (pInfoData->treeconflict_action)
1456 case svn_wc_conflict_action_edit:
1457 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1458 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1459 break;
1460 case svn_wc_conflict_action_add:
1461 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1462 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1463 break;
1464 case svn_wc_conflict_action_delete:
1465 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1466 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1467 break;
1469 break;
1470 case svn_wc_operation_switch:
1471 switch (pInfoData->treeconflict_action)
1473 case svn_wc_conflict_action_edit:
1474 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1475 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1476 break;
1477 case svn_wc_conflict_action_add:
1478 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1479 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1480 break;
1481 case svn_wc_conflict_action_delete:
1482 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1483 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1484 break;
1486 break;
1487 case svn_wc_operation_merge:
1488 switch (pInfoData->treeconflict_action)
1490 case svn_wc_conflict_action_edit:
1491 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1492 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1493 break;
1494 case svn_wc_conflict_action_add:
1495 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1496 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1497 break;
1498 case svn_wc_conflict_action_delete:
1499 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1500 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1501 break;
1503 break;
1506 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
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_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1515 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1516 break;
1517 case svn_wc_conflict_action_add:
1518 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1519 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1520 break;
1521 case svn_wc_conflict_action_delete:
1522 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1523 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
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_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1532 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1533 break;
1534 case svn_wc_conflict_action_add:
1535 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1536 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1537 break;
1538 case svn_wc_conflict_action_delete:
1539 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1540 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
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_DIRMERGEEDIT, (LPCTSTR)sItemName);
1549 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1550 break;
1551 case svn_wc_conflict_action_add:
1552 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1553 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1554 break;
1555 case svn_wc_conflict_action_delete:
1556 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1557 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1558 break;
1560 break;
1564 UINT uReasonID = 0;
1565 switch (pInfoData->treeconflict_reason)
1567 case svn_wc_conflict_reason_edited:
1568 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1569 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1570 break;
1571 case svn_wc_conflict_reason_obstructed:
1572 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1573 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1574 break;
1575 case svn_wc_conflict_reason_deleted:
1576 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1577 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1578 break;
1579 case svn_wc_conflict_reason_added:
1580 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1581 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1582 break;
1583 case svn_wc_conflict_reason_missing:
1584 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1585 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1586 break;
1587 case svn_wc_conflict_reason_unversioned:
1588 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1589 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1590 break;
1592 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1594 CTreeConflictEditorDlg dlg;
1595 dlg.SetConflictInfoText(sConflictReason);
1596 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1597 dlg.SetPath(treeConflictPath);
1598 INT_PTR dlgRet = dlg.DoModal();
1599 bRet = (dlgRet != IDCANCEL);
1603 #endif
1604 return bRet;
1607 bool CAppUtils::IsSSHPutty()
1609 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1610 sshclient=sshclient.MakeLower();
1611 if(sshclient.Find(_T("plink.exe"),0)>=0)
1613 return true;
1615 return false;
1618 CString CAppUtils::GetClipboardLink()
1620 if (!OpenClipboard(NULL))
1621 return CString();
1623 CString sClipboardText;
1624 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1625 if (hglb)
1627 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1628 sClipboardText = CString(lpstr);
1629 GlobalUnlock(hglb);
1631 hglb = GetClipboardData(CF_UNICODETEXT);
1632 if (hglb)
1634 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1635 sClipboardText = lpstr;
1636 GlobalUnlock(hglb);
1638 CloseClipboard();
1640 if(!sClipboardText.IsEmpty())
1642 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1643 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1645 if(sClipboardText.Find( _T("http://")) == 0)
1646 return sClipboardText;
1648 if(sClipboardText.Find( _T("https://")) == 0)
1649 return sClipboardText;
1651 if(sClipboardText.Find( _T("git://")) == 0)
1652 return sClipboardText;
1654 if(sClipboardText.Find( _T("ssh://")) == 0)
1655 return sClipboardText;
1657 if(sClipboardText.GetLength()>=2)
1658 if( sClipboardText[1] == _T(':') )
1659 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1660 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1661 return sClipboardText;
1664 return CString(_T(""));
1667 CString CAppUtils::ChooseRepository(CString *path)
1669 CBrowseFolder browseFolder;
1670 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1672 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1673 CString strCloneDirectory;
1674 if(path)
1675 strCloneDirectory=*path;
1676 else
1678 strCloneDirectory = regLastResopitory;
1681 CString title;
1682 title.LoadString(IDS_CHOOSE_REPOSITORY);
1684 browseFolder.SetInfo(title);
1686 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1688 regLastResopitory = strCloneDirectory;
1689 return strCloneDirectory;
1691 else
1693 return CString();
1697 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1699 CSendMailDlg dlg;
1701 dlg.m_PathList = list;
1703 if(dlg.DoModal()==IDOK)
1705 if(dlg.m_PathList.GetCount() == 0)
1706 return FALSE;
1708 CGitProgressDlg progDlg;
1710 theApp.m_pMainWnd = &progDlg;
1711 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1713 progDlg.SetAutoClose(autoclose);
1715 progDlg.SetPathList(dlg.m_PathList);
1716 //ProjectProperties props;
1717 //props.ReadPropsPathList(dlg.m_pathList);
1718 //progDlg.SetProjectProperties(props);
1719 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1721 DWORD flags =0;
1722 if(dlg.m_bAttachment)
1723 flags |= SENDMAIL_ATTACHMENT;
1724 if(dlg.m_bCombine)
1725 flags |= SENDMAIL_COMBINED;
1726 if(dlg.m_bUseMAPI)
1727 flags |= SENDMAIL_MAPI;
1729 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1731 progDlg.DoModal();
1733 return true;
1735 return false;
1738 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1740 CTGitPathList list;
1741 CString log=formatpatchoutput;
1742 int start=log.Find(cmd);
1743 if(start >=0)
1744 CString one=log.Tokenize(_T("\n"),start);
1745 else
1746 start = 0;
1748 while(start>=0)
1750 CString one=log.Tokenize(_T("\n"),start);
1751 one=one.Trim();
1752 if(one.IsEmpty() || one == _T("Success"))
1753 continue;
1754 one.Replace(_T('/'),_T('\\'));
1755 CTGitPath path;
1756 path.SetFromWin(one);
1757 list.AddPath(path);
1759 if (list.GetCount() > 0)
1761 return SendPatchMail(list, autoclose);
1763 else
1765 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
1766 return true;
1771 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1773 CString cmd,output;
1774 int start=0;
1776 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1777 if(output.IsEmpty())
1779 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1780 if(output.IsEmpty())
1781 return CP_UTF8;
1783 int start=0;
1784 output=output.Tokenize(_T("\n"),start);
1785 return CUnicodeUtils::GetCPCode(output);
1788 else
1790 output=output.Tokenize(_T("\n"),start);
1791 return CUnicodeUtils::GetCPCode(output);
1794 int CAppUtils::GetCommitTemplate(CString &temp)
1796 CString cmd,output;
1798 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
1799 if( output.IsEmpty() )
1800 return -1;
1802 if( output.GetLength()<1)
1803 return -1;
1805 if( output[0] == _T('/'))
1807 if(output.GetLength()>=3)
1808 if(output[2] == _T('/'))
1810 output.GetBuffer()[0] = output[1];
1811 output.GetBuffer()[1] = _T(':');
1815 int start=0;
1816 output=output.Tokenize(_T("\n"),start);
1818 output.Replace(_T('/'),_T('\\'));
1822 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1823 CString str;
1824 while(file.ReadString(str))
1826 temp+=str+_T("\n");
1829 }catch(...)
1831 return -1;
1833 return 0;
1835 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1837 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1838 CString cmd,output;
1839 int cp=CP_UTF8;
1841 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1842 if(output.IsEmpty())
1843 cp=CP_UTF8;
1845 int start=0;
1846 output=output.Tokenize(_T("\n"),start);
1847 cp=CUnicodeUtils::GetCPCode(output);
1849 int len=message.GetLength();
1851 char * buf;
1852 buf = new char[len*4 + 4];
1853 SecureZeroMemory(buf, (len*4 + 4));
1855 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1857 file.Write(buf,lengthIncTerminator-1);
1858 file.Close();
1859 delete buf;
1860 return 0;
1863 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1865 CPullFetchDlg dlg;
1866 dlg.m_PreSelectRemote = remoteName;
1867 dlg.m_bAllowRebase = allowRebase;
1868 dlg.m_IsPull=FALSE;
1870 if(dlg.DoModal()==IDOK)
1872 if(dlg.m_bAutoLoad)
1874 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1877 CString url;
1878 url=dlg.m_RemoteURL;
1879 CString cmd;
1880 CString arg;
1882 int ver = CAppUtils::GetMsysgitVersion();
1884 if(ver >= 0x01070203) //above 1.7.0.2
1885 arg = _T("--progress ");
1887 if (dlg.m_bPrune) {
1888 arg += _T("--prune ");
1891 if (dlg.m_bFetchTags) {
1892 arg += _T("--tags ");
1895 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
1896 CProgressDlg progress;
1898 progress.m_bAutoCloseOnSuccess = autoClose;
1900 progress.m_PostCmdList.Add(_T("Show Log"));
1902 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1904 progress.m_PostCmdList.Add(_T("&Rebase"));
1907 progress.m_GitCmd=cmd;
1908 int userResponse=progress.DoModal();
1910 if (userResponse == IDC_PROGRESS_BUTTON1)
1912 CString cmd = _T("/command:log");
1913 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1914 RunTortoiseProc(cmd);
1915 return TRUE;
1917 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1919 while(1)
1921 CRebaseDlg dlg;
1922 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
1923 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
1924 int response = dlg.DoModal();
1925 if(response == IDOK)
1927 return TRUE;
1929 if(response == IDC_REBASE_POST_BUTTON )
1931 CString cmd, out, err;
1932 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
1933 g_Git.m_CurrentDir,
1934 g_Git.FixBranchName(dlg.m_Upstream),
1935 g_Git.FixBranchName(dlg.m_Branch));
1936 if (g_Git.Run(cmd, &out, &err, CP_ACP))
1938 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1939 return FALSE;
1942 CAppUtils::SendPatchMail(cmd,out);
1943 return TRUE;
1946 if(response == IDC_REBASE_POST_BUTTON +1 )
1947 continue;
1949 if(response == IDCANCEL)
1950 return FALSE;
1952 return TRUE;
1955 return FALSE;
1958 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
1960 CPushDlg dlg;
1961 dlg.m_BranchSourceName = selectLocalBranch;
1962 CString error;
1963 DWORD exitcode = 0xFFFFFFFF;
1964 CTGitPathList list;
1965 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
1966 if (CHooks::Instance().PrePush(list,exitcode, error))
1968 if (exitcode)
1970 CString temp;
1971 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
1972 //ReportError(temp);
1973 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1974 return false;
1978 if(dlg.DoModal()==IDOK)
1980 CString cmd;
1981 CString arg;
1983 if(dlg.m_bAutoLoad)
1985 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
1988 if(dlg.m_bPack)
1989 arg += _T("--thin ");
1990 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
1991 arg += _T("--tags ");
1992 if(dlg.m_bForce)
1993 arg += _T("--force ");
1995 int ver = CAppUtils::GetMsysgitVersion();
1997 if(ver >= 0x01070203) //above 1.7.0.2
1998 arg += _T("--progress ");
2000 if (dlg.m_bPushAllBranches)
2002 cmd.Format(_T("git.exe push --all %s \"%s\""),
2003 arg,
2004 dlg.m_URL);
2006 else
2008 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2009 arg,
2010 dlg.m_URL,
2011 dlg.m_BranchSourceName);
2012 if (!dlg.m_BranchRemoteName.IsEmpty())
2014 cmd += _T(":") + dlg.m_BranchRemoteName;
2018 CProgressDlg progress;
2019 progress.m_bAutoCloseOnSuccess=autoClose;
2020 progress.m_GitCmd=cmd;
2021 progress.m_PostCmdList.Add(_T("&Request pull"));
2022 progress.m_PostCmdList.Add(_T("Re&Push"));
2023 int ret = progress.DoModal();
2025 if(!progress.m_GitStatus)
2027 if (CHooks::Instance().PostPush(list,exitcode, error))
2029 if (exitcode)
2031 CString temp;
2032 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2033 //ReportError(temp);
2034 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2035 return false;
2038 if(ret == IDC_PROGRESS_BUTTON1)
2040 RequestPull(dlg.m_BranchRemoteName);
2042 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2044 Push();
2046 return TRUE;
2050 return FALSE;
2053 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2055 CRequestPullDlg dlg;
2056 dlg.m_RepositoryURL = repositoryUrl;
2057 dlg.m_EndRevision = endrevision;
2058 if (dlg.DoModal()==IDOK)
2060 CString cmd;
2061 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2063 CString tempFileName = GetTempFile();
2064 if (g_Git.RunLogFile(cmd, tempFileName))
2066 MessageBox(NULL, _T("Failed to create pull-request."), _T("TortoiseGit"), MB_OK);
2067 return false;
2069 CAppUtils::LaunchAlternativeEditor(tempFileName);
2071 return true;
2074 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2076 CString strDir(szPath);
2077 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2079 strDir.AppendChar(_T('\\'));
2081 std::vector<CString> vPath;
2082 CString strTemp;
2083 bool bSuccess = false;
2085 for (int i=0;i<strDir.GetLength();++i)
2087 if (strDir.GetAt(i) != _T('\\'))
2089 strTemp.AppendChar(strDir.GetAt(i));
2091 else
2093 vPath.push_back(strTemp);
2094 strTemp.AppendChar(_T('\\'));
2098 std::vector<CString>::const_iterator vIter;
2099 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2101 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2104 return bSuccess;
2107 void CAppUtils::RemoveTrailSlash(CString &path)
2109 if(path.IsEmpty())
2110 return ;
2112 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2114 path=path.Left(path.GetLength()-1);
2115 if(path.IsEmpty())
2116 return;
2120 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2121 CTGitPathList &pathList,
2122 CTGitPathList &selectedList,
2123 bool bSelectFilesForCommit,
2124 bool autoClose)
2126 bool bFailed = true;
2128 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2130 if(CMessageBox::Show(NULL,_T("User name and email must be set before commit.\r\n Do you want to set these now?\r\n"),
2131 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2133 CTGitPath path(g_Git.m_CurrentDir);
2134 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2135 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2136 dlg.SetTreeWidth(220);
2137 dlg.m_DefaultPage = _T("gitconfig");
2139 dlg.DoModal();
2140 dlg.HandleRestart();
2143 else
2144 return false;
2147 while (bFailed)
2149 bFailed = false;
2150 CCommitDlg dlg;
2151 dlg.m_sBugID = bugid;
2153 dlg.m_bWholeProject = bWholeProject;
2155 dlg.m_sLogMessage = sLogMsg;
2156 dlg.m_pathList = pathList;
2157 dlg.m_checkedPathList = selectedList;
2158 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2159 dlg.m_bAutoClose = autoClose;
2160 if (dlg.DoModal() == IDOK)
2162 if (dlg.m_pathList.GetCount()==0)
2163 return false;
2164 // if the user hasn't changed the list of selected items
2165 // we don't use that list. Because if we would use the list
2166 // of pre-checked items, the dialog would show different
2167 // checked items on the next startup: it would only try
2168 // to check the parent folder (which might not even show)
2169 // instead, we simply use an empty list and let the
2170 // default checking do its job.
2171 if (!dlg.m_pathList.IsEqual(pathList))
2172 selectedList = dlg.m_pathList;
2173 pathList = dlg.m_updatedPathList;
2174 sLogMsg = dlg.m_sLogMessage;
2175 bSelectFilesForCommit = true;
2177 if( dlg.m_bPushAfterCommit )
2179 switch(dlg.m_PostCmd)
2181 case GIT_POST_CMD_DCOMMIT:
2182 CAppUtils::SVNDCommit();
2183 break;
2184 default:
2185 CAppUtils::Push();
2188 // CGitProgressDlg progDlg;
2189 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2190 // if (parser.HasVal(_T("closeonend")))
2191 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2192 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2193 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2194 // progDlg.SetPathList(dlg.m_pathList);
2195 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2196 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2197 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2198 // progDlg.SetItemCount(dlg.m_itemsCount);
2199 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2200 // progDlg.DoModal();
2201 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2202 // err = (DWORD)progDlg.DidErrorsOccur();
2203 // bFailed = progDlg.DidErrorsOccur();
2204 // bRet = progDlg.DidErrorsOccur();
2205 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2206 // if (DWORD(bFailRepeat)==0)
2207 // bFailed = false; // do not repeat if the user chose not to in the settings.
2210 return true;
2214 BOOL CAppUtils::SVNDCommit()
2216 CSVNDCommitDlg dcommitdlg;
2217 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2218 if (gitSetting == _T("")) {
2219 if (dcommitdlg.DoModal() != IDOK)
2221 return false;
2223 else
2225 if (dcommitdlg.m_remember)
2227 if (dcommitdlg.m_rmdir)
2229 gitSetting = _T("true");
2231 else
2233 gitSetting = _T("false");
2235 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2237 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2243 BOOL IsStash = false;
2244 if(!g_Git.CheckCleanWorkTree())
2246 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2248 CString cmd,out;
2249 cmd=_T("git.exe stash");
2250 if(g_Git.Run(cmd,&out,CP_ACP))
2252 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2253 return false;
2255 IsStash =true;
2258 else
2260 return false;
2264 CProgressDlg progress;
2265 if (dcommitdlg.m_rmdir)
2267 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2269 else
2271 progress.m_GitCmd=_T("git.exe svn dcommit");
2273 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2275 if( IsStash)
2277 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2279 CString cmd,out;
2280 cmd=_T("git.exe stash pop");
2281 if(g_Git.Run(cmd,&out,CP_ACP))
2283 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2284 return false;
2288 else
2290 return false;
2293 return TRUE;
2295 return FALSE;
2298 BOOL CAppUtils::Merge(CString *commit)
2300 CMergeDlg dlg;
2301 if(commit)
2302 dlg.m_initialRefName = *commit;
2304 if(dlg.DoModal()==IDOK)
2306 CString cmd;
2307 CString noff;
2308 CString squash;
2309 CString nocommit;
2310 CString msg;
2312 if(dlg.m_bNoFF)
2313 noff=_T("--no-ff");
2315 if(dlg.m_bSquash)
2316 squash=_T("--squash");
2318 if(dlg.m_bNoCommit)
2319 nocommit=_T("--no-commit");
2321 if(!dlg.m_strLogMesage.IsEmpty())
2323 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2325 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2326 msg,
2327 noff,
2328 squash,
2329 nocommit,
2330 g_Git.FixBranchName(dlg.m_VersionName));
2332 CProgressDlg Prodlg;
2333 Prodlg.m_GitCmd = cmd;
2335 if (dlg.m_bNoCommit)
2336 Prodlg.m_PostCmdList.Add(_T("Commit"));
2337 else if (dlg.m_bIsBranch)
2338 Prodlg.m_PostCmdList.Add(_T("Remove branch"));
2340 int ret = Prodlg.DoModal();
2342 if (ret == IDC_PROGRESS_BUTTON1)
2343 if (dlg.m_bNoCommit)
2344 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2345 else if (dlg.m_bIsBranch)
2347 if (CMessageBox::Show(NULL, _T("Do you really want to <ct=0x0000FF>delete</ct> <b>") + dlg.m_VersionName + _T("</b>?"), _T("TortoiseGit"), 2, IDI_QUESTION, _T("&Delete"), _T("&Abort")) == 1)
2349 CString cmd, out;
2350 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2351 if (g_Git.Run(cmd, &out, CP_UTF8))
2352 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2356 return !Prodlg.m_GitStatus;
2358 return false;
2361 void CAppUtils::EditNote(GitRev *rev)
2363 CInputDlg dlg;
2364 dlg.m_sHintText=_T("Edit Notes");
2365 dlg.m_sInputText = rev->m_Notes;
2366 dlg.m_sTitle=_T("Edit Notes");
2367 //dlg.m_pProjectProperties = &m_ProjectProperties;
2368 dlg.m_bUseLogWidth = true;
2369 if(dlg.DoModal() == IDOK)
2371 CString cmd,output;
2372 cmd=_T("notes add -f -F \"");
2374 CString tempfile=::GetTempFile();
2375 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2376 cmd += tempfile;
2377 cmd += _T("\" ");
2378 cmd += rev->m_CommitHash.ToString();
2382 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2384 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2387 else
2389 rev->m_Notes = dlg.m_sInputText;
2391 }catch(...)
2393 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2395 CFile::Remove(tempfile);
2400 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2402 CString cmd;
2403 CString progressarg;
2404 CString version;
2406 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2407 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2409 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2411 __int64 time=0;
2412 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2414 if((DWORD)time == regTime)
2416 return regVersion;
2420 if(versionstr)
2421 version = *versionstr;
2422 else
2424 CString err;
2425 cmd = _T("git.exe --version");
2426 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2428 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2429 return false;
2433 int start=0;
2434 int ver;
2436 CString str=version.Tokenize(_T("."),start);
2437 int space = str.ReverseFind(_T(' '));
2438 str=str.Mid(space+1,start);
2439 ver = _ttol(str);
2440 ver <<=24;
2442 version = version.Mid(start);
2443 start = 0;
2444 str = version.Tokenize(_T("."),start);
2446 ver |= (_ttol(str)&0xFF)<<16;
2448 str = version.Tokenize(_T("."),start);
2449 ver |= (_ttol(str)&0xFF)<<8;
2451 str = version.Tokenize(_T("."),start);
2452 ver |= (_ttol(str)&0xFF);
2454 regTime = time&0xFFFFFFFF;
2455 regVersion = ver;
2457 return ver;
2460 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2462 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2464 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2466 if (hShell.IsValid()) {
2467 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2468 if (pfnSHGPSFW) {
2469 IPropertyStore *pps;
2470 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2471 if (SUCCEEDED(hr)) {
2472 PROPVARIANT var;
2473 var.vt = VT_BOOL;
2474 var.boolVal = VARIANT_TRUE;
2475 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2476 pps->Release();
2482 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2484 ASSERT(dialogname.GetLength() < 70);
2485 ASSERT(urlorpath.GetLength() < MAX_PATH);
2486 WCHAR pathbuf[MAX_PATH] = {0};
2488 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2490 wcscat_s(pathbuf, L" - ");
2491 wcscat_s(pathbuf, dialogname);
2492 wcscat_s(pathbuf, L" - ");
2493 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2494 SetWindowText(hWnd, pathbuf);