Moved last remaining strings to resources
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobd919c6fb66094a930e6cfa1518416c5e8977a51e
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_UTF8))
93 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
95 else
97 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHSUCCESS)) + _T("\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_UTF8);
115 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
116 if (ret && !(ret == 1 && hasConflicts))
118 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
120 else
122 CString message;
123 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
124 if (hasConflicts)
125 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
126 if (showChanges)
128 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
129 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
131 CChangedDlg dlg;
132 dlg.m_pathList.AddPath(CTGitPath());
133 dlg.DoModal();
135 return 0;
137 else
139 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
140 return 0;
143 return -1;
146 int CAppUtils::StashPop(bool showChanges /* true */)
148 CString cmd,out;
149 cmd=_T("git.exe stash pop ");
151 int ret = g_Git.Run(cmd, &out, CP_UTF8);
152 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
153 if (ret && !(ret == 1 && hasConflicts))
155 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
157 else
159 CString message;
160 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
161 if (hasConflicts)
162 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
163 if (showChanges)
165 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
166 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
168 CChangedDlg dlg;
169 dlg.m_pathList.AddPath(CTGitPath());
170 dlg.DoModal();
172 return 0;
174 else
176 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
177 return 0;
180 return -1;
183 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
185 #if 0
186 GitProperties props(file, GitRev::REV_WC, false);
187 for (int i = 0; i < props.GetCount(); ++i)
189 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
191 mimetype = props.GetItemValue(i).c_str();
192 return true;
195 #endif
196 return false;
199 BOOL CAppUtils::StartExtMerge(
200 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
201 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
204 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
205 CString ext = mergedfile.GetFileExtension();
206 CString com = regCom;
207 bool bInternal = false;
209 CString mimetype;
210 if (ext != "")
212 // is there an extension specific merge tool?
213 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
214 if (CString(mergetool) != "")
216 com = mergetool;
219 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
221 // is there a mime type specific merge tool?
222 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
223 if (CString(mergetool) != "")
225 com = mergetool;
229 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
231 // use TortoiseMerge
232 bInternal = true;
233 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
234 com = tortoiseMergePath;
235 if (com.IsEmpty())
237 com = CPathUtils::GetAppDirectory();
238 com += _T("TortoiseMerge.exe");
240 com = _T("\"") + com + _T("\"");
241 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
242 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
244 // check if the params are set. If not, just add the files to the command line
245 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
247 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
248 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
249 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
250 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
252 if (basefile.IsEmpty())
254 com.Replace(_T("/base:%base"), _T(""));
255 com.Replace(_T("%base"), _T(""));
257 else
258 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
259 if (theirfile.IsEmpty())
261 com.Replace(_T("/theirs:%theirs"), _T(""));
262 com.Replace(_T("%theirs"), _T(""));
264 else
265 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
266 if (yourfile.IsEmpty())
268 com.Replace(_T("/mine:%mine"), _T(""));
269 com.Replace(_T("%mine"), _T(""));
271 else
272 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
273 if (mergedfile.IsEmpty())
275 com.Replace(_T("/merged:%merged"), _T(""));
276 com.Replace(_T("%merged"), _T(""));
278 else
279 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
280 if (basename.IsEmpty())
282 if (basefile.IsEmpty())
284 com.Replace(_T("/basename:%bname"), _T(""));
285 com.Replace(_T("%bname"), _T(""));
287 else
289 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
292 else
293 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
294 if (theirname.IsEmpty())
296 if (theirfile.IsEmpty())
298 com.Replace(_T("/theirsname:%tname"), _T(""));
299 com.Replace(_T("%tname"), _T(""));
301 else
303 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
306 else
307 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
308 if (yourname.IsEmpty())
310 if (yourfile.IsEmpty())
312 com.Replace(_T("/minename:%yname"), _T(""));
313 com.Replace(_T("%yname"), _T(""));
315 else
317 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
320 else
321 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
322 if (mergedname.IsEmpty())
324 if (mergedfile.IsEmpty())
326 com.Replace(_T("/mergedname:%mname"), _T(""));
327 com.Replace(_T("%mname"), _T(""));
329 else
331 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
334 else
335 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
337 if ((bReadOnly)&&(bInternal))
338 com += _T(" /readonly");
340 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
342 return FALSE;
345 return TRUE;
348 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
350 CString viewer;
351 // use TortoiseMerge
352 viewer = CPathUtils::GetAppDirectory();
353 viewer += _T("TortoiseMerge.exe");
355 viewer = _T("\"") + viewer + _T("\"");
356 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
357 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
358 if (bReversed)
359 viewer += _T(" /reversedpatch");
360 if (!sOriginalDescription.IsEmpty())
361 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
362 if (!sPatchedDescription.IsEmpty())
363 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
364 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
366 return FALSE;
368 return TRUE;
371 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
373 // Is there a mime type specific diff tool?
374 CString mimetype;
375 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
377 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
378 if (!difftool.IsEmpty())
379 return difftool;
382 // Is there an extension specific diff tool?
383 CString ext = file2.GetFileExtension().MakeLower();
384 if (!ext.IsEmpty())
386 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
387 if (!difftool.IsEmpty())
388 return difftool;
389 // Maybe we should use TortoiseIDiff?
390 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
391 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
392 (ext == _T(".png")) || (ext == _T(".ico")) ||
393 (ext == _T(".dib")) || (ext == _T(".emf")))
395 return
396 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
397 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
401 // Finally, pick a generic external diff tool
402 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
403 return difftool;
406 bool CAppUtils::StartExtDiff(
407 const CString& file1, const CString& file2,
408 const CString& sName1, const CString& sName2,
409 const DiffFlags& flags)
411 CString viewer;
413 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
414 if (!flags.bBlame || !(DWORD)blamediff)
416 viewer = PickDiffTool(file1, file2);
417 // If registry entry for a diff program is commented out, use TortoiseMerge.
418 bool bCommentedOut = viewer.Left(1) == _T("#");
419 if (flags.bAlternativeTool)
421 // Invert external vs. internal diff tool selection.
422 if (bCommentedOut)
423 viewer.Delete(0); // uncomment
424 else
425 viewer = "";
427 else if (bCommentedOut)
428 viewer = "";
431 bool bInternal = viewer.IsEmpty();
432 if (bInternal)
434 viewer =
435 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
436 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
437 if (flags.bBlame)
438 viewer += _T(" /blame");
440 // check if the params are set. If not, just add the files to the command line
441 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
443 viewer += _T(" \"")+file1+_T("\"");
444 viewer += _T(" \"")+file2+_T("\"");
446 if (viewer.Find(_T("%base")) >= 0)
448 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
450 if (viewer.Find(_T("%mine")) >= 0)
452 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
455 if (sName1.IsEmpty())
456 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
457 else
458 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
460 if (sName2.IsEmpty())
461 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
462 else
463 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
465 if (flags.bReadOnly && bInternal)
466 viewer += _T(" /readonly");
468 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
471 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
473 CString viewer;
474 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
475 viewer = v;
476 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
478 // use TortoiseUDiff
479 viewer = CPathUtils::GetAppDirectory();
480 viewer += _T("TortoiseUDiff.exe");
481 // enquote the path to TortoiseUDiff
482 viewer = _T("\"") + viewer + _T("\"");
483 // add the params
484 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
487 if (viewer.Find(_T("%1"))>=0)
489 if (viewer.Find(_T("\"%1\"")) >= 0)
490 viewer.Replace(_T("%1"), patchfile);
491 else
492 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
494 else
495 viewer += _T(" \"") + patchfile + _T("\"");
496 if (viewer.Find(_T("%title")) >= 0)
498 viewer.Replace(_T("%title"), title);
501 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
503 return FALSE;
505 return TRUE;
508 BOOL CAppUtils::StartTextViewer(CString file)
510 CString viewer;
511 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
512 viewer = txt;
513 viewer = viewer + _T("\\Shell\\Open\\Command\\");
514 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
515 viewer = txtexe;
517 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
518 TCHAR * buf = new TCHAR[len+1];
519 ExpandEnvironmentStrings(viewer, buf, len);
520 viewer = buf;
521 delete [] buf;
522 len = ExpandEnvironmentStrings(file, NULL, 0);
523 buf = new TCHAR[len+1];
524 ExpandEnvironmentStrings(file, buf, len);
525 file = buf;
526 delete [] buf;
527 file = _T("\"")+file+_T("\"");
528 if (viewer.IsEmpty())
530 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
532 if (viewer.Find(_T("\"%1\"")) >= 0)
534 viewer.Replace(_T("\"%1\""), file);
536 else if (viewer.Find(_T("%1")) >= 0)
538 viewer.Replace(_T("%1"), file);
540 else
542 viewer += _T(" ");
543 viewer += file;
546 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
548 return FALSE;
550 return TRUE;
553 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
555 DWORD length = 0;
556 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
557 if (!hFile)
558 return TRUE;
559 length = ::GetFileSize(hFile, NULL);
560 if (length < 4)
561 return TRUE;
562 return FALSE;
566 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
568 LOGFONT logFont;
569 HDC hScreenDC = ::GetDC(NULL);
570 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
571 ::ReleaseDC(NULL, hScreenDC);
572 logFont.lfWidth = 0;
573 logFont.lfEscapement = 0;
574 logFont.lfOrientation = 0;
575 logFont.lfWeight = FW_NORMAL;
576 logFont.lfItalic = 0;
577 logFont.lfUnderline = 0;
578 logFont.lfStrikeOut = 0;
579 logFont.lfCharSet = DEFAULT_CHARSET;
580 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
581 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
582 logFont.lfQuality = DRAFT_QUALITY;
583 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
584 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
585 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
588 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
590 CString key,remote;
591 CString cmd,out;
592 if( pRemote == NULL)
594 remote=_T("origin");
596 else
598 remote=*pRemote;
600 if(keyfile == NULL)
602 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
603 key = g_Git.GetConfigValue(cmd);
604 int start=0;
605 key = key.Tokenize(_T("\n"),start);
607 else
608 key=*keyfile;
610 if(key.IsEmpty())
611 return false;
613 CString proc=CPathUtils::GetAppDirectory();
614 proc += _T("pageant.exe \"");
615 proc += key;
616 proc += _T("\"");
618 CString tempfile = GetTempFile();
619 ::DeleteFile(tempfile);
621 proc += _T(" -c \"");
622 proc += CPathUtils::GetAppDirectory();
623 proc += _T("touch.exe\"");
624 proc += _T(" \"");
625 proc += tempfile;
626 proc += _T("\"");
628 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &CPathUtils::GetAppDirectory());
629 if(!b)
630 return b;
632 int i=0;
633 while(!::PathFileExists(tempfile))
635 Sleep(100);
636 i++;
637 if(i>10*60*5)
638 break; //timeout 5 minutes
641 if( i== 10*60*5)
643 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
645 ::DeleteFile(tempfile);
646 return true;
648 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
650 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
651 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
652 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
655 CString sCmd;
656 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
658 LaunchApplication(sCmd, NULL, false);
659 return true;
661 bool CAppUtils::LaunchRemoteSetting()
663 CTGitPath path(g_Git.m_CurrentDir);
664 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
665 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
666 //dlg.SetTreeWidth(220);
667 dlg.m_DefaultPage = _T("gitremote");
669 dlg.DoModal();
670 dlg.HandleRestart();
671 return true;
674 * Launch the external blame viewer
676 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
678 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
679 viewer += _T("TortoiseGitBlame.exe");
680 viewer += _T("\" \"") + sBlameFile + _T("\"");
681 //viewer += _T(" \"") + sLogFile + _T("\"");
682 //viewer += _T(" \"") + sOriginalFile + _T("\"");
683 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
684 viewer += CString(_T(" /rev:"))+Rev;
685 viewer += _T(" ")+sParams;
687 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
690 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
692 CString sText;
693 if (pWnd == NULL)
694 return false;
695 bool bStyled = false;
696 pWnd->GetWindowText(sText);
697 // the rich edit control doesn't count the CR char!
698 // to be exact: CRLF is treated as one char.
699 sText.Remove('\r');
701 // style each line separately
702 int offset = 0;
703 int nNewlinePos;
706 nNewlinePos = sText.Find('\n', offset);
707 CString sLine = sText.Mid(offset);
708 if (nNewlinePos>=0)
709 sLine = sLine.Left(nNewlinePos-offset);
710 int start = 0;
711 int end = 0;
712 while (FindStyleChars(sLine, '*', start, end))
714 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
715 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
716 CHARFORMAT2 format;
717 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
718 format.cbSize = sizeof(CHARFORMAT2);
719 format.dwMask = CFM_BOLD;
720 format.dwEffects = CFE_BOLD;
721 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
722 bStyled = true;
723 start = end;
725 start = 0;
726 end = 0;
727 while (FindStyleChars(sLine, '^', start, end))
729 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
730 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
731 CHARFORMAT2 format;
732 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
733 format.cbSize = sizeof(CHARFORMAT2);
734 format.dwMask = CFM_ITALIC;
735 format.dwEffects = CFE_ITALIC;
736 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
737 bStyled = true;
738 start = end;
740 start = 0;
741 end = 0;
742 while (FindStyleChars(sLine, '_', start, end))
744 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
745 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
746 CHARFORMAT2 format;
747 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
748 format.cbSize = sizeof(CHARFORMAT2);
749 format.dwMask = CFM_UNDERLINE;
750 format.dwEffects = CFE_UNDERLINE;
751 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
752 bStyled = true;
753 start = end;
755 offset = nNewlinePos+1;
756 } while(nNewlinePos>=0);
757 return bStyled;
760 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
762 int i=start;
763 bool bFoundMarker = false;
764 // find a starting marker
765 while (sText[i] != 0)
767 if (sText[i] == stylechar)
769 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
770 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
772 start = i+1;
773 i++;
774 bFoundMarker = true;
775 break;
778 i++;
780 if (!bFoundMarker)
781 return false;
782 // find ending marker
783 bFoundMarker = false;
784 while (sText[i] != 0)
786 if (sText[i] == stylechar)
788 if ((IsCharAlphaNumeric(sText[i-1])) &&
789 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
791 end = i;
792 i++;
793 bFoundMarker = true;
794 break;
797 i++;
799 return bFoundMarker;
802 CString CAppUtils::GetProjectNameFromURL(CString url)
804 CString name;
805 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
806 (name.CompareNoCase(_T("tags"))==0) ||
807 (name.CompareNoCase(_T("trunk"))==0))
809 name = url.Mid(url.ReverseFind('/')+1);
810 url = url.Left(url.ReverseFind('/'));
812 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
814 // a name of svn or svnroot indicates that it's not really the project name. In that
815 // case, we try the first part of the URL
816 // of course, this won't work in all cases (but it works for Google project hosting)
817 url.Replace(_T("http://"), _T(""));
818 url.Replace(_T("https://"), _T(""));
819 url.Replace(_T("svn://"), _T(""));
820 url.Replace(_T("svn+ssh://"), _T(""));
821 url.TrimLeft(_T("/"));
822 name = url.Left(url.Find('.'));
824 return name;
827 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
828 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
829 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
830 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
833 CString tempfile=GetTempFile();
834 CString cmd;
835 if(rev2 == GitRev::GetWorkingCopy())
837 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
839 else
841 CString merge;
842 if(bMerge)
843 merge = _T("-c");
845 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
848 if( !url1.IsEmpty() )
850 cmd += _T(" -- \"");
851 cmd += url1.GetGitPathString();
852 cmd += _T("\" ");
854 g_Git.RunLogFile(cmd,tempfile);
855 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
858 #if 0
859 CString sCmd;
860 sCmd.Format(_T("%s /command:showcompare /unified"),
861 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
862 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
863 if (rev1.IsValid())
864 sCmd += _T(" /revision1:") + rev1.ToString();
865 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
866 if (rev2.IsValid())
867 sCmd += _T(" /revision2:") + rev2.ToString();
868 if (peg.IsValid())
869 sCmd += _T(" /pegrevision:") + peg.ToString();
870 if (headpeg.IsValid())
871 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
873 if (bAlternateDiff)
874 sCmd += _T(" /alternatediff");
876 if (bIgnoreAncestry)
877 sCmd += _T(" /ignoreancestry");
879 if (hWnd)
881 sCmd += _T(" /hwnd:");
882 TCHAR buf[30];
883 _stprintf_s(buf, 30, _T("%d"), hWnd);
884 sCmd += buf;
887 return CAppUtils::LaunchApplication(sCmd, NULL, false);
888 #endif
889 return TRUE;
893 bool CAppUtils::Export(CString *BashHash)
895 bool bRet = false;
897 // ask from where the export has to be done
898 CExportDlg dlg;
899 if(BashHash)
900 dlg.m_Revision=*BashHash;
902 if (dlg.DoModal() == IDOK)
904 CString cmd;
905 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
906 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
908 CProgressDlg pro;
909 pro.m_GitCmd=cmd;
910 pro.DoModal();
911 return TRUE;
913 return bRet;
916 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
918 CCreateBranchTagDlg dlg;
919 dlg.m_bIsTag=IsTag;
920 dlg.m_bSwitch=switch_new_brach;
922 if(CommitHash)
923 dlg.m_Base = *CommitHash;
925 if(dlg.DoModal()==IDOK)
927 CString cmd;
928 CString force;
929 CString track;
930 if(dlg.m_bTrack == TRUE)
931 track=_T(" --track ");
932 else if(dlg.m_bTrack == FALSE)
933 track=_T(" --no-track");
935 if(dlg.m_bForce)
936 force=_T(" -f ");
938 if(IsTag)
940 CString sign;
941 if(dlg.m_bSign)
942 sign=_T("-s");
944 cmd.Format(_T("git.exe tag %s %s %s %s"),
945 force,
946 sign,
947 dlg.m_BranchTagName,
948 g_Git.FixBranchName(dlg.m_VersionName)
951 CString tempfile=::GetTempFile();
952 if(!dlg.m_Message.Trim().IsEmpty())
954 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
955 cmd += _T(" -F ")+tempfile;
958 else
960 cmd.Format(_T("git.exe branch %s %s %s %s"),
961 track,
962 force,
963 dlg.m_BranchTagName,
964 g_Git.FixBranchName(dlg.m_VersionName)
967 CString out;
968 if(g_Git.Run(cmd,&out,CP_UTF8))
970 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
972 if( !IsTag && dlg.m_bSwitch )
974 // it is a new branch and the user has requested to switch to it
975 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
976 g_Git.Run(cmd,&out,CP_UTF8);
977 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
980 return TRUE;
982 return FALSE;
985 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
987 CGitSwitchDlg dlg;
988 if(CommitHash)
989 dlg.m_Base=*CommitHash;
990 if(!initialRefName.IsEmpty())
991 dlg.m_initialRefName = initialRefName;
993 if (dlg.DoModal() == IDOK)
995 CString branch;
996 if (dlg.m_bBranch)
997 branch = dlg.m_NewBranch;
999 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1001 return FALSE;
1004 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1006 CString cmd;
1007 CString track;
1008 CString force;
1009 CString branch;
1011 if(!sNewBranch.IsEmpty()){
1012 if (bBranchOverride)
1014 branch.Format(_T("-B %s"), sNewBranch);
1016 else
1018 branch.Format(_T("-b %s"), sNewBranch);
1020 if (bTrack)
1021 track = _T("--track");
1023 if (bForce)
1024 force = _T("-f");
1026 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1027 force,
1028 track,
1029 branch,
1030 g_Git.FixBranchName(ref));
1032 CProgressDlg progress;
1033 progress.m_bAutoCloseOnSuccess = autoClose;
1034 progress.m_GitCmd = cmd;
1036 CTGitPath gitPath = g_Git.m_CurrentDir;
1037 if (gitPath.HasSubmodules())
1038 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1040 int ret = progress.DoModal();
1041 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1043 CString sCmd;
1044 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1046 RunTortoiseProc(sCmd);
1047 return TRUE;
1049 else if (ret == IDOK)
1050 return TRUE;
1052 return FALSE;
1055 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1057 CString ignorefile;
1058 ignorefile=g_Git.m_CurrentDir+_T("\\");
1060 if(IsMask)
1062 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1065 else
1067 ignorefile += _T("\\.gitignore");
1070 CStdioFile file;
1071 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1073 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1074 return FALSE;
1077 CString ignorelist;
1078 CString mask;
1081 //file.ReadString(ignorelist);
1082 file.SeekToEnd();
1083 for(int i=0;i<path.GetCount();i++)
1085 if(IsMask)
1087 mask=_T("*")+path[i].GetFileExtension();
1088 if(ignorelist.Find(mask)<0)
1089 ignorelist += _T("\n")+mask;
1091 else
1093 ignorelist += _T("\n/")+path[i].GetGitPathString();
1096 file.WriteString(ignorelist);
1098 file.Close();
1100 }catch(...)
1102 file.Close();
1103 return FALSE;
1106 return TRUE;
1110 bool CAppUtils::GitReset(CString *CommitHash,int type)
1112 CResetDlg dlg;
1113 dlg.m_ResetType=type;
1114 dlg.m_ResetToVersion=*CommitHash;
1115 if (dlg.DoModal() == IDOK)
1117 CString cmd;
1118 CString type;
1119 switch(dlg.m_ResetType)
1121 case 0:
1122 type=_T("--soft");
1123 break;
1124 case 1:
1125 type=_T("--mixed");
1126 break;
1127 case 2:
1128 type=_T("--hard");
1129 break;
1130 default:
1131 type=_T("--mixed");
1132 break;
1134 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1136 CProgressDlg progress;
1137 progress.m_GitCmd=cmd;
1139 CTGitPath gitPath = g_Git.m_CurrentDir;
1140 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1141 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1143 int ret = progress.DoModal();
1144 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1146 CString sCmd;
1147 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1149 RunTortoiseProc(sCmd);
1150 return TRUE;
1152 else if (ret == IDOK)
1153 return TRUE;
1156 return FALSE;
1159 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1161 if(mode == FALSE)
1163 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1164 return;
1166 if(base)
1168 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1169 return;
1171 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1172 return;
1175 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1177 CString tempmergefile;
1180 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1181 CFile::Remove(tempmergefile);
1182 }catch(...)
1188 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1189 CFile::Remove(tempmergefile);
1190 }catch(...)
1196 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1197 CFile::Remove(tempmergefile);
1198 }catch(...)
1202 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1204 CString file;
1205 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1207 return file;
1210 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1212 bool bRet = false;
1214 CTGitPath merge=path;
1215 CTGitPath directory = merge.GetDirectory();
1217 // we have the conflicted file (%merged)
1218 // now look for the other required files
1219 //GitStatus stat;
1220 //stat.GetStatus(merge);
1221 //if (stat.status == NULL)
1222 // return false;
1224 BYTE_VECTOR vector;
1226 CString cmd;
1227 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1229 if (g_Git.Run(cmd, &vector))
1231 return FALSE;
1234 CTGitPathList list;
1235 list.ParserFromLsFile(vector);
1237 if(list.GetCount() == 0)
1238 return FALSE;
1240 CTGitPath theirs;
1241 CTGitPath mine;
1242 CTGitPath base;
1244 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1245 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1246 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1248 CString format;
1250 //format=_T("git.exe cat-file blob \":%d:%s\"");
1251 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1252 CFile tempfile;
1253 //create a empty file, incase stage is not three
1254 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1255 tempfile.Close();
1256 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1257 tempfile.Close();
1258 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1259 tempfile.Close();
1261 bool b_base=false, b_local=false, b_remote=false;
1263 for(int i=0;i<list.GetCount();i++)
1265 CString cmd;
1266 CString outfile;
1267 cmd.Empty();
1268 outfile.Empty();
1270 if( list[i].m_Stage == 1)
1272 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1273 b_base = true;
1274 outfile = base.GetWinPathString();
1277 if( list[i].m_Stage == 2 )
1279 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1280 b_local = true;
1281 outfile = mine.GetWinPathString();
1284 if( list[i].m_Stage == 3 )
1286 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1287 b_remote = true;
1288 outfile = theirs.GetWinPathString();
1290 CString output, err;
1291 if(!outfile.IsEmpty())
1292 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1294 CString file;
1295 int start =0 ;
1296 file = output.Tokenize(_T("\t"), start);
1297 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1299 else
1301 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1305 if(b_local && b_remote )
1307 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1308 if( revertTheirMy )
1309 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1310 else
1311 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1314 else
1316 CFile::Remove(mine.GetWinPathString());
1317 CFile::Remove(theirs.GetWinPathString());
1318 CFile::Remove(base.GetWinPathString());
1320 CDeleteConflictDlg dlg;
1321 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1322 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1323 dlg.m_bShowModifiedButton=b_base;
1324 dlg.m_File=merge.GetGitPathString();
1325 if(dlg.DoModal() == IDOK)
1327 CString cmd,out;
1328 if(dlg.m_bIsDelete)
1330 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1332 else
1333 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1335 if (g_Git.Run(cmd, &out, CP_UTF8))
1337 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1338 return FALSE;
1340 return TRUE;
1342 else
1343 return FALSE;
1346 #if 0
1347 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1348 base, theirs, mine, merge);
1349 #endif
1350 #if 0
1351 if (stat.status->text_status == svn_wc_status_conflicted)
1353 // we have a text conflict, use our merge tool to resolve the conflict
1355 CTSVNPath theirs(directory);
1356 CTSVNPath mine(directory);
1357 CTSVNPath base(directory);
1358 bool bConflictData = false;
1360 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1362 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1363 bConflictData = true;
1365 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1367 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1368 bConflictData = true;
1370 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1372 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1373 bConflictData = true;
1375 else
1377 mine = merge;
1379 if (bConflictData)
1380 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1381 base, theirs, mine, merge);
1384 if (stat.status->prop_status == svn_wc_status_conflicted)
1386 // we have a property conflict
1387 CTSVNPath prej(directory);
1388 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1390 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1391 // there's a problem: the prej file contains a _description_ of the conflict, and
1392 // that description string might be translated. That means we have no way of parsing
1393 // the file to find out the conflicting values.
1394 // The only thing we can do: show a dialog with the conflict description, then
1395 // let the user either accept the existing property or open the property edit dialog
1396 // to manually change the properties and values. And a button to mark the conflict as
1397 // resolved.
1398 CEditPropConflictDlg dlg;
1399 dlg.SetPrejFile(prej);
1400 dlg.SetConflictedItem(merge);
1401 bRet = (dlg.DoModal() != IDCANCEL);
1405 if (stat.status->tree_conflict)
1407 // we have a tree conflict
1408 SVNInfo info;
1409 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1410 if (pInfoData)
1412 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1414 CTSVNPath theirs(directory);
1415 CTSVNPath mine(directory);
1416 CTSVNPath base(directory);
1417 bool bConflictData = false;
1419 if (pInfoData->treeconflict_theirfile)
1421 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1422 bConflictData = true;
1424 if (pInfoData->treeconflict_basefile)
1426 base.AppendPathString(pInfoData->treeconflict_basefile);
1427 bConflictData = true;
1429 if (pInfoData->treeconflict_myfile)
1431 mine.AppendPathString(pInfoData->treeconflict_myfile);
1432 bConflictData = true;
1434 else
1436 mine = merge;
1438 if (bConflictData)
1439 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1440 base, theirs, mine, merge);
1442 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1444 CString sConflictAction;
1445 CString sConflictReason;
1446 CString sResolveTheirs;
1447 CString sResolveMine;
1448 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1449 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1451 if (pInfoData->treeconflict_nodekind == svn_node_file)
1453 switch (pInfoData->treeconflict_operation)
1455 case svn_wc_operation_update:
1456 switch (pInfoData->treeconflict_action)
1458 case svn_wc_conflict_action_edit:
1459 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1460 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1461 break;
1462 case svn_wc_conflict_action_add:
1463 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1464 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1465 break;
1466 case svn_wc_conflict_action_delete:
1467 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1468 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1469 break;
1471 break;
1472 case svn_wc_operation_switch:
1473 switch (pInfoData->treeconflict_action)
1475 case svn_wc_conflict_action_edit:
1476 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1477 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1478 break;
1479 case svn_wc_conflict_action_add:
1480 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1481 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1482 break;
1483 case svn_wc_conflict_action_delete:
1484 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1485 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1486 break;
1488 break;
1489 case svn_wc_operation_merge:
1490 switch (pInfoData->treeconflict_action)
1492 case svn_wc_conflict_action_edit:
1493 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1494 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1495 break;
1496 case svn_wc_conflict_action_add:
1497 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1498 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1499 break;
1500 case svn_wc_conflict_action_delete:
1501 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1502 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1503 break;
1505 break;
1508 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1510 switch (pInfoData->treeconflict_operation)
1512 case svn_wc_operation_update:
1513 switch (pInfoData->treeconflict_action)
1515 case svn_wc_conflict_action_edit:
1516 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1517 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1518 break;
1519 case svn_wc_conflict_action_add:
1520 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1521 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1522 break;
1523 case svn_wc_conflict_action_delete:
1524 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1525 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1526 break;
1528 break;
1529 case svn_wc_operation_switch:
1530 switch (pInfoData->treeconflict_action)
1532 case svn_wc_conflict_action_edit:
1533 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1534 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1535 break;
1536 case svn_wc_conflict_action_add:
1537 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1538 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1539 break;
1540 case svn_wc_conflict_action_delete:
1541 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1542 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1543 break;
1545 break;
1546 case svn_wc_operation_merge:
1547 switch (pInfoData->treeconflict_action)
1549 case svn_wc_conflict_action_edit:
1550 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1551 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1552 break;
1553 case svn_wc_conflict_action_add:
1554 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1555 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1556 break;
1557 case svn_wc_conflict_action_delete:
1558 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1559 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1560 break;
1562 break;
1566 UINT uReasonID = 0;
1567 switch (pInfoData->treeconflict_reason)
1569 case svn_wc_conflict_reason_edited:
1570 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1571 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1572 break;
1573 case svn_wc_conflict_reason_obstructed:
1574 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1575 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1576 break;
1577 case svn_wc_conflict_reason_deleted:
1578 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1579 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1580 break;
1581 case svn_wc_conflict_reason_added:
1582 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1583 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1584 break;
1585 case svn_wc_conflict_reason_missing:
1586 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1587 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1588 break;
1589 case svn_wc_conflict_reason_unversioned:
1590 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1591 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1592 break;
1594 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1596 CTreeConflictEditorDlg dlg;
1597 dlg.SetConflictInfoText(sConflictReason);
1598 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1599 dlg.SetPath(treeConflictPath);
1600 INT_PTR dlgRet = dlg.DoModal();
1601 bRet = (dlgRet != IDCANCEL);
1605 #endif
1606 return bRet;
1609 bool CAppUtils::IsSSHPutty()
1611 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1612 sshclient=sshclient.MakeLower();
1613 if(sshclient.Find(_T("plink.exe"),0)>=0)
1615 return true;
1617 return false;
1620 CString CAppUtils::GetClipboardLink()
1622 if (!OpenClipboard(NULL))
1623 return CString();
1625 CString sClipboardText;
1626 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1627 if (hglb)
1629 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1630 sClipboardText = CString(lpstr);
1631 GlobalUnlock(hglb);
1633 hglb = GetClipboardData(CF_UNICODETEXT);
1634 if (hglb)
1636 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1637 sClipboardText = lpstr;
1638 GlobalUnlock(hglb);
1640 CloseClipboard();
1642 if(!sClipboardText.IsEmpty())
1644 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1645 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1647 if(sClipboardText.Find( _T("http://")) == 0)
1648 return sClipboardText;
1650 if(sClipboardText.Find( _T("https://")) == 0)
1651 return sClipboardText;
1653 if(sClipboardText.Find( _T("git://")) == 0)
1654 return sClipboardText;
1656 if(sClipboardText.Find( _T("ssh://")) == 0)
1657 return sClipboardText;
1659 if(sClipboardText.GetLength()>=2)
1660 if( sClipboardText[1] == _T(':') )
1661 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1662 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1663 return sClipboardText;
1666 return CString(_T(""));
1669 CString CAppUtils::ChooseRepository(CString *path)
1671 CBrowseFolder browseFolder;
1672 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1674 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1675 CString strCloneDirectory;
1676 if(path)
1677 strCloneDirectory=*path;
1678 else
1680 strCloneDirectory = regLastResopitory;
1683 CString title;
1684 title.LoadString(IDS_CHOOSE_REPOSITORY);
1686 browseFolder.SetInfo(title);
1688 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1690 regLastResopitory = strCloneDirectory;
1691 return strCloneDirectory;
1693 else
1695 return CString();
1699 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1701 CSendMailDlg dlg;
1703 dlg.m_PathList = list;
1705 if(dlg.DoModal()==IDOK)
1707 if(dlg.m_PathList.GetCount() == 0)
1708 return FALSE;
1710 CGitProgressDlg progDlg;
1712 theApp.m_pMainWnd = &progDlg;
1713 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1715 progDlg.SetAutoClose(autoclose);
1717 progDlg.SetPathList(dlg.m_PathList);
1718 //ProjectProperties props;
1719 //props.ReadPropsPathList(dlg.m_pathList);
1720 //progDlg.SetProjectProperties(props);
1721 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1723 DWORD flags =0;
1724 if(dlg.m_bAttachment)
1725 flags |= SENDMAIL_ATTACHMENT;
1726 if(dlg.m_bCombine)
1727 flags |= SENDMAIL_COMBINED;
1728 if(dlg.m_bUseMAPI)
1729 flags |= SENDMAIL_MAPI;
1731 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1733 progDlg.DoModal();
1735 return true;
1737 return false;
1740 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1742 CTGitPathList list;
1743 CString log=formatpatchoutput;
1744 int start=log.Find(cmd);
1745 if(start >=0)
1746 CString one=log.Tokenize(_T("\n"),start);
1747 else
1748 start = 0;
1750 while(start>=0)
1752 CString one=log.Tokenize(_T("\n"),start);
1753 one=one.Trim();
1754 if(one.IsEmpty() || one == _T("Success"))
1755 continue;
1756 one.Replace(_T('/'),_T('\\'));
1757 CTGitPath path;
1758 path.SetFromWin(one);
1759 list.AddPath(path);
1761 if (list.GetCount() > 0)
1763 return SendPatchMail(list, autoclose);
1765 else
1767 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1768 return true;
1773 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1775 CString cmd,output;
1776 int start=0;
1778 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1779 if(output.IsEmpty())
1781 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
1782 if(output.IsEmpty())
1783 return CP_UTF8;
1785 int start=0;
1786 output=output.Tokenize(_T("\n"),start);
1787 return CUnicodeUtils::GetCPCode(output);
1790 else
1792 output=output.Tokenize(_T("\n"),start);
1793 return CUnicodeUtils::GetCPCode(output);
1796 int CAppUtils::GetCommitTemplate(CString &temp)
1798 CString cmd,output;
1800 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
1801 if( output.IsEmpty() )
1802 return -1;
1804 if( output.GetLength()<1)
1805 return -1;
1807 if( output[0] == _T('/'))
1809 if(output.GetLength()>=3)
1810 if(output[2] == _T('/'))
1812 output.GetBuffer()[0] = output[1];
1813 output.GetBuffer()[1] = _T(':');
1817 int start=0;
1818 output=output.Tokenize(_T("\n"),start);
1820 output.Replace(_T('/'),_T('\\'));
1824 CStdioFile file(output,CFile::modeRead|CFile::typeText);
1825 CString str;
1826 while(file.ReadString(str))
1828 temp+=str+_T("\n");
1831 }catch(...)
1833 return -1;
1835 return 0;
1837 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
1839 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
1840 CString cmd,output;
1841 int cp=CP_UTF8;
1843 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
1844 if(output.IsEmpty())
1845 cp=CP_UTF8;
1847 int start=0;
1848 output=output.Tokenize(_T("\n"),start);
1849 cp=CUnicodeUtils::GetCPCode(output);
1851 int len=message.GetLength();
1853 char * buf;
1854 buf = new char[len*4 + 4];
1855 SecureZeroMemory(buf, (len*4 + 4));
1857 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
1859 file.Write(buf,lengthIncTerminator-1);
1860 file.Close();
1861 delete buf;
1862 return 0;
1865 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
1867 CPullFetchDlg dlg;
1868 dlg.m_PreSelectRemote = remoteName;
1869 dlg.m_bAllowRebase = allowRebase;
1870 dlg.m_IsPull=FALSE;
1872 if(dlg.DoModal()==IDOK)
1874 if(dlg.m_bAutoLoad)
1876 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
1879 CString url;
1880 url=dlg.m_RemoteURL;
1881 CString cmd;
1882 CString arg;
1884 int ver = CAppUtils::GetMsysgitVersion();
1886 if(ver >= 0x01070203) //above 1.7.0.2
1887 arg = _T("--progress ");
1889 if (dlg.m_bPrune) {
1890 arg += _T("--prune ");
1893 if (dlg.m_bFetchTags == 1)
1895 arg += _T("--tags ");
1897 else if (dlg.m_bFetchTags == 0)
1899 arg += _T("--no-tags ");
1902 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
1903 CProgressDlg progress;
1905 progress.m_bAutoCloseOnSuccess = autoClose;
1907 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
1909 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
1911 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1914 progress.m_GitCmd=cmd;
1915 int userResponse=progress.DoModal();
1917 if (userResponse == IDC_PROGRESS_BUTTON1)
1919 CString cmd = _T("/command:log");
1920 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
1921 RunTortoiseProc(cmd);
1922 return TRUE;
1924 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
1926 while(1)
1928 CRebaseDlg dlg;
1929 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
1930 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
1931 int response = dlg.DoModal();
1932 if(response == IDOK)
1934 return TRUE;
1936 if(response == IDC_REBASE_POST_BUTTON )
1938 CString cmd, out, err;
1939 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
1940 g_Git.m_CurrentDir,
1941 g_Git.FixBranchName(dlg.m_Upstream),
1942 g_Git.FixBranchName(dlg.m_Branch));
1943 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
1945 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1946 return FALSE;
1949 CAppUtils::SendPatchMail(cmd,out);
1950 return TRUE;
1953 if(response == IDC_REBASE_POST_BUTTON +1 )
1954 continue;
1956 if(response == IDCANCEL)
1957 return FALSE;
1959 return TRUE;
1961 else if (userResponse != IDCANCEL)
1962 return TRUE;
1964 return FALSE;
1967 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
1969 CPushDlg dlg;
1970 dlg.m_BranchSourceName = selectLocalBranch;
1971 CString error;
1972 DWORD exitcode = 0xFFFFFFFF;
1973 CTGitPathList list;
1974 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
1975 if (CHooks::Instance().PrePush(list,exitcode, error))
1977 if (exitcode)
1979 CString temp;
1980 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
1981 //ReportError(temp);
1982 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1983 return false;
1987 if(dlg.DoModal()==IDOK)
1989 CString cmd;
1990 CString arg;
1992 if(dlg.m_bAutoLoad)
1994 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
1997 if(dlg.m_bPack)
1998 arg += _T("--thin ");
1999 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2000 arg += _T("--tags ");
2001 if(dlg.m_bForce)
2002 arg += _T("--force ");
2004 int ver = CAppUtils::GetMsysgitVersion();
2006 if(ver >= 0x01070203) //above 1.7.0.2
2007 arg += _T("--progress ");
2009 if (dlg.m_bPushAllBranches)
2011 cmd.Format(_T("git.exe push --all %s \"%s\""),
2012 arg,
2013 dlg.m_URL);
2015 else
2017 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2018 arg,
2019 dlg.m_URL,
2020 dlg.m_BranchSourceName);
2021 if (!dlg.m_BranchRemoteName.IsEmpty())
2023 cmd += _T(":") + dlg.m_BranchRemoteName;
2027 CProgressDlg progress;
2028 progress.m_bAutoCloseOnSuccess=autoClose;
2029 progress.m_GitCmd=cmd;
2030 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2031 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2032 int ret = progress.DoModal();
2034 if(!progress.m_GitStatus)
2036 if (CHooks::Instance().PostPush(list,exitcode, error))
2038 if (exitcode)
2040 CString temp;
2041 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2042 //ReportError(temp);
2043 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2044 return false;
2047 if(ret == IDC_PROGRESS_BUTTON1)
2049 RequestPull(dlg.m_BranchRemoteName);
2051 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2053 Push();
2055 return TRUE;
2059 return FALSE;
2062 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2064 CRequestPullDlg dlg;
2065 dlg.m_RepositoryURL = repositoryUrl;
2066 dlg.m_EndRevision = endrevision;
2067 if (dlg.DoModal()==IDOK)
2069 CString cmd;
2070 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2072 CString tempFileName = GetTempFile();
2073 if (g_Git.RunLogFile(cmd, tempFileName))
2075 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2076 return false;
2078 CAppUtils::LaunchAlternativeEditor(tempFileName);
2080 return true;
2083 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2085 CString strDir(szPath);
2086 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2088 strDir.AppendChar(_T('\\'));
2090 std::vector<CString> vPath;
2091 CString strTemp;
2092 bool bSuccess = false;
2094 for (int i=0;i<strDir.GetLength();++i)
2096 if (strDir.GetAt(i) != _T('\\'))
2098 strTemp.AppendChar(strDir.GetAt(i));
2100 else
2102 vPath.push_back(strTemp);
2103 strTemp.AppendChar(_T('\\'));
2107 std::vector<CString>::const_iterator vIter;
2108 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2110 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2113 return bSuccess;
2116 void CAppUtils::RemoveTrailSlash(CString &path)
2118 if(path.IsEmpty())
2119 return ;
2121 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2123 path=path.Left(path.GetLength()-1);
2124 if(path.IsEmpty())
2125 return;
2129 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2130 CTGitPathList &pathList,
2131 CTGitPathList &selectedList,
2132 bool bSelectFilesForCommit,
2133 bool autoClose)
2135 bool bFailed = true;
2137 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2139 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2141 CTGitPath path(g_Git.m_CurrentDir);
2142 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2143 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2144 dlg.SetTreeWidth(220);
2145 dlg.m_DefaultPage = _T("gitconfig");
2147 dlg.DoModal();
2148 dlg.HandleRestart();
2151 else
2152 return false;
2155 while (bFailed)
2157 bFailed = false;
2158 CCommitDlg dlg;
2159 dlg.m_sBugID = bugid;
2161 dlg.m_bWholeProject = bWholeProject;
2163 dlg.m_sLogMessage = sLogMsg;
2164 dlg.m_pathList = pathList;
2165 dlg.m_checkedPathList = selectedList;
2166 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2167 dlg.m_bAutoClose = autoClose;
2168 if (dlg.DoModal() == IDOK)
2170 if (dlg.m_pathList.GetCount()==0)
2171 return false;
2172 // if the user hasn't changed the list of selected items
2173 // we don't use that list. Because if we would use the list
2174 // of pre-checked items, the dialog would show different
2175 // checked items on the next startup: it would only try
2176 // to check the parent folder (which might not even show)
2177 // instead, we simply use an empty list and let the
2178 // default checking do its job.
2179 if (!dlg.m_pathList.IsEqual(pathList))
2180 selectedList = dlg.m_pathList;
2181 pathList = dlg.m_updatedPathList;
2182 sLogMsg = dlg.m_sLogMessage;
2183 bSelectFilesForCommit = true;
2185 if( dlg.m_bPushAfterCommit )
2187 switch(dlg.m_PostCmd)
2189 case GIT_POST_CMD_DCOMMIT:
2190 CAppUtils::SVNDCommit();
2191 break;
2192 default:
2193 CAppUtils::Push();
2196 else if (dlg.m_bCreateTagAfterCommit)
2198 CAppUtils::CreateBranchTag(TRUE);
2201 // CGitProgressDlg progDlg;
2202 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2203 // if (parser.HasVal(_T("closeonend")))
2204 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2205 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2206 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2207 // progDlg.SetPathList(dlg.m_pathList);
2208 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2209 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2210 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2211 // progDlg.SetItemCount(dlg.m_itemsCount);
2212 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2213 // progDlg.DoModal();
2214 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2215 // err = (DWORD)progDlg.DidErrorsOccur();
2216 // bFailed = progDlg.DidErrorsOccur();
2217 // bRet = progDlg.DidErrorsOccur();
2218 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2219 // if (DWORD(bFailRepeat)==0)
2220 // bFailed = false; // do not repeat if the user chose not to in the settings.
2223 return true;
2227 BOOL CAppUtils::SVNDCommit()
2229 CSVNDCommitDlg dcommitdlg;
2230 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2231 if (gitSetting == _T("")) {
2232 if (dcommitdlg.DoModal() != IDOK)
2234 return false;
2236 else
2238 if (dcommitdlg.m_remember)
2240 if (dcommitdlg.m_rmdir)
2242 gitSetting = _T("true");
2244 else
2246 gitSetting = _T("false");
2248 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2250 CString msg;
2251 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2252 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2258 BOOL IsStash = false;
2259 if(!g_Git.CheckCleanWorkTree())
2261 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2263 CString cmd,out;
2264 cmd=_T("git.exe stash");
2265 if (g_Git.Run(cmd, &out, CP_UTF8))
2267 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2268 return false;
2270 IsStash =true;
2273 else
2275 return false;
2279 CProgressDlg progress;
2280 if (dcommitdlg.m_rmdir)
2282 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2284 else
2286 progress.m_GitCmd=_T("git.exe svn dcommit");
2288 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2290 if( IsStash)
2292 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2294 CString cmd,out;
2295 cmd=_T("git.exe stash pop");
2296 if (g_Git.Run(cmd, &out, CP_UTF8))
2298 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2299 return false;
2303 else
2305 return false;
2308 return TRUE;
2310 return FALSE;
2313 BOOL CAppUtils::Merge(CString *commit)
2315 CMergeDlg dlg;
2316 if(commit)
2317 dlg.m_initialRefName = *commit;
2319 if(dlg.DoModal()==IDOK)
2321 CString cmd;
2322 CString noff;
2323 CString squash;
2324 CString nocommit;
2325 CString msg;
2327 if(dlg.m_bNoFF)
2328 noff=_T("--no-ff");
2330 if(dlg.m_bSquash)
2331 squash=_T("--squash");
2333 if(dlg.m_bNoCommit)
2334 nocommit=_T("--no-commit");
2336 if(!dlg.m_strLogMesage.IsEmpty())
2338 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2340 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2341 msg,
2342 noff,
2343 squash,
2344 nocommit,
2345 g_Git.FixBranchName(dlg.m_VersionName));
2347 CProgressDlg Prodlg;
2348 Prodlg.m_GitCmd = cmd;
2350 if (dlg.m_bNoCommit)
2351 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2352 else if (dlg.m_bIsBranch)
2353 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2355 int ret = Prodlg.DoModal();
2357 if (ret == IDC_PROGRESS_BUTTON1)
2358 if (dlg.m_bNoCommit)
2359 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2360 else if (dlg.m_bIsBranch)
2362 CString msg;
2363 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2364 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2366 CString cmd, out;
2367 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2368 if (g_Git.Run(cmd, &out, CP_UTF8))
2369 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2373 return !Prodlg.m_GitStatus;
2375 return false;
2378 void CAppUtils::EditNote(GitRev *rev)
2380 CInputDlg dlg;
2381 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2382 dlg.m_sInputText = rev->m_Notes;
2383 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2384 //dlg.m_pProjectProperties = &m_ProjectProperties;
2385 dlg.m_bUseLogWidth = true;
2386 if(dlg.DoModal() == IDOK)
2388 CString cmd,output;
2389 cmd=_T("notes add -f -F \"");
2391 CString tempfile=::GetTempFile();
2392 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2393 cmd += tempfile;
2394 cmd += _T("\" ");
2395 cmd += rev->m_CommitHash.ToString();
2399 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2401 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2404 else
2406 rev->m_Notes = dlg.m_sInputText;
2408 }catch(...)
2410 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2412 CFile::Remove(tempfile);
2417 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2419 CString cmd;
2420 CString progressarg;
2421 CString version;
2423 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2424 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2426 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2428 __int64 time=0;
2429 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2431 if((DWORD)time == regTime)
2433 return regVersion;
2437 if(versionstr)
2438 version = *versionstr;
2439 else
2441 CString err;
2442 cmd = _T("git.exe --version");
2443 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2445 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2446 return false;
2450 int start=0;
2451 int ver;
2453 CString str=version.Tokenize(_T("."),start);
2454 int space = str.ReverseFind(_T(' '));
2455 str=str.Mid(space+1,start);
2456 ver = _ttol(str);
2457 ver <<=24;
2459 version = version.Mid(start);
2460 start = 0;
2461 str = version.Tokenize(_T("."),start);
2463 ver |= (_ttol(str)&0xFF)<<16;
2465 str = version.Tokenize(_T("."),start);
2466 ver |= (_ttol(str)&0xFF)<<8;
2468 str = version.Tokenize(_T("."),start);
2469 ver |= (_ttol(str)&0xFF);
2471 regTime = time&0xFFFFFFFF;
2472 regVersion = ver;
2474 return ver;
2477 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2479 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2481 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2483 if (hShell.IsValid()) {
2484 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2485 if (pfnSHGPSFW) {
2486 IPropertyStore *pps;
2487 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2488 if (SUCCEEDED(hr)) {
2489 PROPVARIANT var;
2490 var.vt = VT_BOOL;
2491 var.boolVal = VARIANT_TRUE;
2492 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2493 pps->Release();
2499 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2501 ASSERT(dialogname.GetLength() < 70);
2502 ASSERT(urlorpath.GetLength() < MAX_PATH);
2503 WCHAR pathbuf[MAX_PATH] = {0};
2505 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2507 wcscat_s(pathbuf, L" - ");
2508 wcscat_s(pathbuf, dialogname);
2509 wcscat_s(pathbuf, L" - ");
2510 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2511 SetWindowText(hWnd, pathbuf);