Disable warnings and drop prebuild scripts
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobd0c447f9241c93b0d66064025771255d02e83c42
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - TortoiseGit
4 // Copyright (C) 2003-2011 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "StdAfx.h"
21 #include "resource.h"
22 #include "TortoiseProc.h"
23 #include "PathUtils.h"
24 #include "AppUtils.h"
25 //#include "GitProperties.h"
26 #include "StringUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "TGitPath.h"
30 #include "Git.h"
31 //#include "RepositoryBrowser.h"
32 //#include "BrowseFolder.h"
33 #include "UnicodeUtils.h"
34 #include "ExportDlg.h"
35 #include "ProgressDlg.h"
36 #include "GitAdminDir.h"
37 #include "ProgressDlg.h"
38 #include "BrowseFolder.h"
39 #include "DirFileEnum.h"
40 #include "MessageBox.h"
41 #include "GitStatus.h"
42 #include "CreateBranchTagDlg.h"
43 #include "GitSwitchDlg.h"
44 #include "ResetDlg.h"
45 #include "DeleteConflictDlg.h"
46 #include "ChangedDlg.h"
47 #include "SendMailDlg.h"
48 #include "GITProgressDlg.h"
49 #include "PushDlg.h"
50 #include "CommitDlg.h"
51 #include "MergeDlg.h"
52 #include "hooks.h"
53 #include "..\Settings\Settings.h"
54 #include "InputDlg.h"
55 #include "SVNDCommitDlg.h"
56 #include "requestpulldlg.h"
57 #include "PullFetchDlg.h"
58 #include "RebaseDlg.h"
59 #include "PropKey.h"
60 #include "StashSave.h"
61 #include "IgnoreDlg.h"
62 #include "FormatMessageWrapper.h"
63 #include "SmartHandle.h"
64 #include "BisectStartDlg.h"
65 #include "SysProgressDlg.h"
67 CAppUtils::CAppUtils(void)
71 CAppUtils::~CAppUtils(void)
75 bool CAppUtils::StashSave()
77 CStashSaveDlg dlg;
79 if (dlg.DoModal() == IDOK)
81 CString cmd, out;
82 cmd = _T("git.exe stash save");
84 if (CAppUtils::GetMsysgitVersion() >= 0x01070700)
86 if (dlg.m_bIncludeUntracked)
87 cmd += _T(" --include-untracked");
88 else if (dlg.m_bAll)
89 cmd += _T(" --all");
92 if (!dlg.m_sMessage.IsEmpty())
94 CString message = dlg.m_sMessage;
95 message.Replace(_T("\""), _T("\"\""));
96 cmd += _T(" \"") + message + _T("\"");
99 CSysProgressDlg sysProgressDlg;
100 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
101 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
102 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
103 sysProgressDlg.SetShowProgressBar(false);
104 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
105 sysProgressDlg.ShowModeless((HWND)NULL, true);
107 if (g_Git.Run(cmd, &out, CP_UTF8))
109 sysProgressDlg.Stop();
110 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
112 else
114 sysProgressDlg.Stop();
115 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHSUCCESS)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
116 return true;
119 return false;
122 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
124 CString cmd,out;
125 cmd = _T("git.exe stash apply ");
126 if (ref.Find(_T("refs/")) == 0)
127 ref = ref.Mid(5);
128 if (ref.Find(_T("stash{")) == 0)
129 ref = _T("stash@") + ref.Mid(5);
130 cmd += ref;
132 CSysProgressDlg sysProgressDlg;
133 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
134 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
135 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
136 sysProgressDlg.SetShowProgressBar(false);
137 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
138 sysProgressDlg.ShowModeless((HWND)NULL, true);
140 int ret = g_Git.Run(cmd, &out, CP_UTF8);
142 sysProgressDlg.Stop();
144 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
145 if (ret && !(ret == 1 && hasConflicts))
147 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
149 else
151 CString message;
152 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
153 if (hasConflicts)
154 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
155 if (showChanges)
157 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
158 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
160 CChangedDlg dlg;
161 dlg.m_pathList.AddPath(CTGitPath());
162 dlg.DoModal();
164 return true;
166 else
168 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
169 return true;
172 return false;
175 bool CAppUtils::StashPop(bool showChanges /* true */)
177 CString cmd,out;
178 cmd=_T("git.exe stash pop ");
180 CSysProgressDlg sysProgressDlg;
181 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
182 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
183 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
184 sysProgressDlg.SetShowProgressBar(false);
185 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
186 sysProgressDlg.ShowModeless((HWND)NULL, true);
188 int ret = g_Git.Run(cmd, &out, CP_UTF8);
190 sysProgressDlg.Stop();
192 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
193 if (ret && !(ret == 1 && hasConflicts))
195 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
197 else
199 CString message;
200 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
201 if (hasConflicts)
202 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
203 if (showChanges)
205 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
206 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
208 CChangedDlg dlg;
209 dlg.m_pathList.AddPath(CTGitPath());
210 dlg.DoModal();
212 return true;
214 else
216 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
217 return true;
220 return false;
223 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
225 #if 0
226 GitProperties props(file, GitRev::REV_WC, false);
227 for (int i = 0; i < props.GetCount(); ++i)
229 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
231 mimetype = props.GetItemValue(i).c_str();
232 return true;
235 #endif
236 return false;
239 BOOL CAppUtils::StartExtMerge(
240 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
241 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
244 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
245 CString ext = mergedfile.GetFileExtension();
246 CString com = regCom;
247 bool bInternal = false;
249 CString mimetype;
250 if (ext != "")
252 // is there an extension specific merge tool?
253 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
254 if (CString(mergetool) != "")
256 com = mergetool;
259 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
261 // is there a mime type specific merge tool?
262 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
263 if (CString(mergetool) != "")
265 com = mergetool;
268 // is there a filename specific merge tool?
269 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
270 if (CString(mergetool) != "")
272 com = mergetool;
275 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
277 // use TortoiseGitMerge
278 bInternal = true;
279 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
280 com = tortoiseMergePath;
281 if (com.IsEmpty())
283 com = CPathUtils::GetAppDirectory();
284 com += _T("TortoiseGitMerge.exe");
286 com = _T("\"") + com + _T("\"");
287 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
288 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
290 // check if the params are set. If not, just add the files to the command line
291 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
293 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
294 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
295 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
296 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
298 if (basefile.IsEmpty())
300 com.Replace(_T("/base:%base"), _T(""));
301 com.Replace(_T("%base"), _T(""));
303 else
304 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
305 if (theirfile.IsEmpty())
307 com.Replace(_T("/theirs:%theirs"), _T(""));
308 com.Replace(_T("%theirs"), _T(""));
310 else
311 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
312 if (yourfile.IsEmpty())
314 com.Replace(_T("/mine:%mine"), _T(""));
315 com.Replace(_T("%mine"), _T(""));
317 else
318 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
319 if (mergedfile.IsEmpty())
321 com.Replace(_T("/merged:%merged"), _T(""));
322 com.Replace(_T("%merged"), _T(""));
324 else
325 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
326 if (basename.IsEmpty())
328 if (basefile.IsEmpty())
330 com.Replace(_T("/basename:%bname"), _T(""));
331 com.Replace(_T("%bname"), _T(""));
333 else
335 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
338 else
339 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
340 if (theirname.IsEmpty())
342 if (theirfile.IsEmpty())
344 com.Replace(_T("/theirsname:%tname"), _T(""));
345 com.Replace(_T("%tname"), _T(""));
347 else
349 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
352 else
353 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
354 if (yourname.IsEmpty())
356 if (yourfile.IsEmpty())
358 com.Replace(_T("/minename:%yname"), _T(""));
359 com.Replace(_T("%yname"), _T(""));
361 else
363 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
366 else
367 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
368 if (mergedname.IsEmpty())
370 if (mergedfile.IsEmpty())
372 com.Replace(_T("/mergedname:%mname"), _T(""));
373 com.Replace(_T("%mname"), _T(""));
375 else
377 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
380 else
381 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
383 if ((bReadOnly)&&(bInternal))
384 com += _T(" /readonly");
386 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
388 return FALSE;
391 return TRUE;
394 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
396 CString viewer;
397 // use TortoiseGitMerge
398 viewer = CPathUtils::GetAppDirectory();
399 viewer += _T("TortoiseGitMerge.exe");
401 viewer = _T("\"") + viewer + _T("\"");
402 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
403 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
404 if (bReversed)
405 viewer += _T(" /reversedpatch");
406 if (!sOriginalDescription.IsEmpty())
407 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
408 if (!sPatchedDescription.IsEmpty())
409 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
410 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
412 return FALSE;
414 return TRUE;
417 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
419 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file2.GetFilename().MakeLower());
420 if (!difftool.IsEmpty())
421 return difftool;
422 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file1.GetFilename().MakeLower());
423 if (!difftool.IsEmpty())
424 return difftool;
426 // Is there a mime type specific diff tool?
427 CString mimetype;
428 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
430 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
431 if (!difftool.IsEmpty())
432 return difftool;
435 // Is there an extension specific diff tool?
436 CString ext = file2.GetFileExtension().MakeLower();
437 if (!ext.IsEmpty())
439 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
440 if (!difftool.IsEmpty())
441 return difftool;
442 // Maybe we should use TortoiseIDiff?
443 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
444 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
445 (ext == _T(".png")) || (ext == _T(".ico")) ||
446 (ext == _T(".dib")) || (ext == _T(".emf")))
448 return
449 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
450 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
454 // Finally, pick a generic external diff tool
455 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
456 return difftool;
459 bool CAppUtils::StartExtDiff(
460 const CString& file1, const CString& file2,
461 const CString& sName1, const CString& sName2,
462 const CString& originalFile1, const CString& originalFile2,
463 const git_revnum_t& hash1, const git_revnum_t& hash2,
464 const DiffFlags& flags)
466 CString viewer;
468 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
469 if (!flags.bBlame || !(DWORD)blamediff)
471 viewer = PickDiffTool(file1, file2);
472 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
473 bool bCommentedOut = viewer.Left(1) == _T("#");
474 if (flags.bAlternativeTool)
476 // Invert external vs. internal diff tool selection.
477 if (bCommentedOut)
478 viewer.Delete(0); // uncomment
479 else
480 viewer = "";
482 else if (bCommentedOut)
483 viewer = "";
486 bool bInternal = viewer.IsEmpty();
487 if (bInternal)
489 viewer =
490 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
491 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
492 if (flags.bBlame)
493 viewer += _T(" /blame");
495 // check if the params are set. If not, just add the files to the command line
496 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
498 viewer += _T(" \"")+file1+_T("\"");
499 viewer += _T(" \"")+file2+_T("\"");
501 if (viewer.Find(_T("%base")) >= 0)
503 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
505 if (viewer.Find(_T("%mine")) >= 0)
507 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
510 if (sName1.IsEmpty())
511 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
512 else
513 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
515 if (sName2.IsEmpty())
516 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
517 else
518 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
520 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
521 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
523 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
524 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
526 if (flags.bReadOnly && bInternal)
527 viewer += _T(" /readonly");
529 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
532 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
534 CString viewer;
535 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
536 viewer = v;
537 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
539 // use TortoiseGitUDiff
540 viewer = CPathUtils::GetAppDirectory();
541 viewer += _T("TortoiseGitUDiff.exe");
542 // enquote the path to TortoiseGitUDiff
543 viewer = _T("\"") + viewer + _T("\"");
544 // add the params
545 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
548 if (viewer.Find(_T("%1"))>=0)
550 if (viewer.Find(_T("\"%1\"")) >= 0)
551 viewer.Replace(_T("%1"), patchfile);
552 else
553 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
555 else
556 viewer += _T(" \"") + patchfile + _T("\"");
557 if (viewer.Find(_T("%title")) >= 0)
559 viewer.Replace(_T("%title"), title);
562 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
564 return FALSE;
566 return TRUE;
569 BOOL CAppUtils::StartTextViewer(CString file)
571 CString viewer;
572 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
573 viewer = txt;
574 viewer = viewer + _T("\\Shell\\Open\\Command\\");
575 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
576 viewer = txtexe;
578 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
579 TCHAR * buf = new TCHAR[len+1];
580 ExpandEnvironmentStrings(viewer, buf, len);
581 viewer = buf;
582 delete [] buf;
583 len = ExpandEnvironmentStrings(file, NULL, 0);
584 buf = new TCHAR[len+1];
585 ExpandEnvironmentStrings(file, buf, len);
586 file = buf;
587 delete [] buf;
588 file = _T("\"")+file+_T("\"");
589 if (viewer.IsEmpty())
591 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
593 if (viewer.Find(_T("\"%1\"")) >= 0)
595 viewer.Replace(_T("\"%1\""), file);
597 else if (viewer.Find(_T("%1")) >= 0)
599 viewer.Replace(_T("%1"), file);
601 else
603 viewer += _T(" ");
604 viewer += file;
607 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
609 return FALSE;
611 return TRUE;
614 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
616 DWORD length = 0;
617 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
618 if (!hFile)
619 return TRUE;
620 length = ::GetFileSize(hFile, NULL);
621 if (length < 4)
622 return TRUE;
623 return FALSE;
627 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
629 LOGFONT logFont;
630 HDC hScreenDC = ::GetDC(NULL);
631 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
632 ::ReleaseDC(NULL, hScreenDC);
633 logFont.lfWidth = 0;
634 logFont.lfEscapement = 0;
635 logFont.lfOrientation = 0;
636 logFont.lfWeight = FW_NORMAL;
637 logFont.lfItalic = 0;
638 logFont.lfUnderline = 0;
639 logFont.lfStrikeOut = 0;
640 logFont.lfCharSet = DEFAULT_CHARSET;
641 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
642 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
643 logFont.lfQuality = DRAFT_QUALITY;
644 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
645 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
646 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
649 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
651 CString key,remote;
652 CString cmd,out;
653 if( pRemote == NULL)
655 remote=_T("origin");
657 else
659 remote=*pRemote;
661 if(keyfile == NULL)
663 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
664 key = g_Git.GetConfigValue(cmd);
665 int start=0;
666 key = key.Tokenize(_T("\n"),start);
668 else
669 key=*keyfile;
671 if(key.IsEmpty())
672 return false;
674 CString proc=CPathUtils::GetAppDirectory();
675 proc += _T("pageant.exe \"");
676 proc += key;
677 proc += _T("\"");
679 CString tempfile = GetTempFile();
680 ::DeleteFile(tempfile);
682 proc += _T(" -c \"");
683 proc += CPathUtils::GetAppDirectory();
684 proc += _T("touch.exe\"");
685 proc += _T(" \"");
686 proc += tempfile;
687 proc += _T("\"");
689 CString appDir = CPathUtils::GetAppDirectory();
690 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
691 if(!b)
692 return b;
694 int i=0;
695 while(!::PathFileExists(tempfile))
697 Sleep(100);
698 i++;
699 if(i>10*60*5)
700 break; //timeout 5 minutes
703 if( i== 10*60*5)
705 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
707 ::DeleteFile(tempfile);
708 return true;
710 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
712 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
713 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
714 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
717 CString sCmd;
718 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
720 LaunchApplication(sCmd, NULL, false, NULL, uac);
721 return true;
723 bool CAppUtils::LaunchRemoteSetting()
725 CTGitPath path(g_Git.m_CurrentDir);
726 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
727 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
728 dlg.SetTreeWidth(220);
729 dlg.m_DefaultPage = _T("gitremote");
731 dlg.DoModal();
732 dlg.HandleRestart();
733 return true;
736 * Launch the external blame viewer
738 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
740 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
741 viewer += _T("TortoiseGitBlame.exe");
742 viewer += _T("\" \"") + sBlameFile + _T("\"");
743 //viewer += _T(" \"") + sLogFile + _T("\"");
744 //viewer += _T(" \"") + sOriginalFile + _T("\"");
745 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
746 viewer += CString(_T(" /rev:"))+Rev;
747 viewer += _T(" ")+sParams;
749 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
752 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
754 CString sText;
755 if (pWnd == NULL)
756 return false;
757 bool bStyled = false;
758 pWnd->GetWindowText(sText);
759 // the rich edit control doesn't count the CR char!
760 // to be exact: CRLF is treated as one char.
761 sText.Remove('\r');
763 // style each line separately
764 int offset = 0;
765 int nNewlinePos;
768 nNewlinePos = sText.Find('\n', offset);
769 CString sLine = sText.Mid(offset);
770 if (nNewlinePos>=0)
771 sLine = sLine.Left(nNewlinePos-offset);
772 int start = 0;
773 int end = 0;
774 while (FindStyleChars(sLine, '*', start, end))
776 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
777 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
778 CHARFORMAT2 format;
779 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
780 format.cbSize = sizeof(CHARFORMAT2);
781 format.dwMask = CFM_BOLD;
782 format.dwEffects = CFE_BOLD;
783 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
784 bStyled = true;
785 start = end;
787 start = 0;
788 end = 0;
789 while (FindStyleChars(sLine, '^', start, end))
791 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
792 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
793 CHARFORMAT2 format;
794 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
795 format.cbSize = sizeof(CHARFORMAT2);
796 format.dwMask = CFM_ITALIC;
797 format.dwEffects = CFE_ITALIC;
798 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
799 bStyled = true;
800 start = end;
802 start = 0;
803 end = 0;
804 while (FindStyleChars(sLine, '_', start, end))
806 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
807 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
808 CHARFORMAT2 format;
809 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
810 format.cbSize = sizeof(CHARFORMAT2);
811 format.dwMask = CFM_UNDERLINE;
812 format.dwEffects = CFE_UNDERLINE;
813 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
814 bStyled = true;
815 start = end;
817 offset = nNewlinePos+1;
818 } while(nNewlinePos>=0);
819 return bStyled;
822 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
824 int i=start;
825 bool bFoundMarker = false;
826 // find a starting marker
827 while (sText[i] != 0)
829 if (sText[i] == stylechar)
831 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
832 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
834 start = i+1;
835 i++;
836 bFoundMarker = true;
837 break;
840 i++;
842 if (!bFoundMarker)
843 return false;
844 // find ending marker
845 bFoundMarker = false;
846 while (sText[i] != 0)
848 if (sText[i] == stylechar)
850 if ((IsCharAlphaNumeric(sText[i-1])) &&
851 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
853 end = i;
854 i++;
855 bFoundMarker = true;
856 break;
859 i++;
861 return bFoundMarker;
864 CString CAppUtils::GetProjectNameFromURL(CString url)
866 CString name;
867 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
868 (name.CompareNoCase(_T("tags"))==0) ||
869 (name.CompareNoCase(_T("trunk"))==0))
871 name = url.Mid(url.ReverseFind('/')+1);
872 url = url.Left(url.ReverseFind('/'));
874 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
876 // a name of svn or svnroot indicates that it's not really the project name. In that
877 // case, we try the first part of the URL
878 // of course, this won't work in all cases (but it works for Google project hosting)
879 url.Replace(_T("http://"), _T(""));
880 url.Replace(_T("https://"), _T(""));
881 url.Replace(_T("svn://"), _T(""));
882 url.Replace(_T("svn+ssh://"), _T(""));
883 url.TrimLeft(_T("/"));
884 name = url.Left(url.Find('.'));
886 return name;
889 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
890 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
891 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
892 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
895 CString tempfile=GetTempFile();
896 CString cmd;
897 if(rev2 == GitRev::GetWorkingCopy())
899 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
901 else if (rev1 == GitRev::GetWorkingCopy())
903 cmd.Format(_T("git.exe diff -R --stat -p %s "), rev2);
905 else
907 CString merge;
908 if(bMerge)
909 merge = _T("-c");
911 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
914 if( !url1.IsEmpty() )
916 cmd += _T(" -- \"");
917 cmd += url1.GetGitPathString();
918 cmd += _T("\" ");
920 g_Git.RunLogFile(cmd,tempfile);
921 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
924 #if 0
925 CString sCmd;
926 sCmd.Format(_T("%s /command:showcompare /unified"),
927 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
928 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
929 if (rev1.IsValid())
930 sCmd += _T(" /revision1:") + rev1.ToString();
931 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
932 if (rev2.IsValid())
933 sCmd += _T(" /revision2:") + rev2.ToString();
934 if (peg.IsValid())
935 sCmd += _T(" /pegrevision:") + peg.ToString();
936 if (headpeg.IsValid())
937 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
939 if (bAlternateDiff)
940 sCmd += _T(" /alternatediff");
942 if (bIgnoreAncestry)
943 sCmd += _T(" /ignoreancestry");
945 if (hWnd)
947 sCmd += _T(" /hwnd:");
948 TCHAR buf[30];
949 _stprintf_s(buf, 30, _T("%d"), hWnd);
950 sCmd += buf;
953 return CAppUtils::LaunchApplication(sCmd, NULL, false);
954 #endif
955 return TRUE;
958 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
960 CString scriptsdir = CPathUtils::GetAppParentDirectory();
961 scriptsdir += _T("Diff-Scripts");
962 CSimpleFileFind files(scriptsdir);
963 while (files.FindNextFileNoDirectories())
965 CString file = files.GetFilePath();
966 CString filename = files.GetFileName();
967 CString ext = file.Mid(file.ReverseFind('-') + 1);
968 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
969 std::set<CString> extensions;
970 extensions.insert(ext);
971 CString kind;
972 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
974 kind = _T(" //E:vbscript");
976 if (file.Right(2).CompareNoCase(_T("js"))==0)
978 kind = _T(" //E:javascript");
980 // open the file, read the first line and find possible extensions
981 // this script can handle
984 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
985 CString extline;
986 if (f.ReadString(extline))
988 if ((extline.GetLength() > 15 ) &&
989 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
990 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
992 if (extline[0] == '/')
993 extline = extline.Mid(15);
994 else
995 extline = extline.Mid(14);
996 CString sToken;
997 int curPos = 0;
998 sToken = extline.Tokenize(_T(";"), curPos);
999 while (!sToken.IsEmpty())
1001 if (!sToken.IsEmpty())
1003 if (sToken[0] != '.')
1004 sToken = _T(".") + sToken;
1005 extensions.insert(sToken);
1007 sToken = extline.Tokenize(_T(";"), curPos);
1011 f.Close();
1013 catch (CFileException* e)
1015 e->Delete();
1018 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
1020 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1022 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1024 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
1025 CString diffregstring = diffreg;
1026 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1027 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1030 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1032 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1034 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
1035 CString diffregstring = diffreg;
1036 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1037 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1043 return true;
1046 bool CAppUtils::Export(CString *BashHash)
1048 // ask from where the export has to be done
1049 CExportDlg dlg;
1050 if(BashHash)
1051 dlg.m_Revision=*BashHash;
1053 if (dlg.DoModal() == IDOK)
1055 CString cmd;
1056 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
1057 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
1059 CProgressDlg pro;
1060 pro.m_GitCmd=cmd;
1061 return (pro.DoModal() == IDOK);
1063 return false;
1066 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1068 CCreateBranchTagDlg dlg;
1069 dlg.m_bIsTag=IsTag;
1070 dlg.m_bSwitch=switch_new_brach;
1072 if(CommitHash)
1073 dlg.m_initialRefName = *CommitHash;
1075 if(dlg.DoModal()==IDOK)
1077 CString cmd;
1078 CString force;
1079 CString track;
1080 if(dlg.m_bTrack == TRUE)
1081 track=_T(" --track ");
1082 else if(dlg.m_bTrack == FALSE)
1083 track=_T(" --no-track");
1085 if(dlg.m_bForce)
1086 force=_T(" -f ");
1088 if(IsTag)
1090 CString sign;
1091 if(dlg.m_bSign)
1092 sign=_T("-s");
1094 cmd.Format(_T("git.exe tag %s %s %s %s"),
1095 force,
1096 sign,
1097 dlg.m_BranchTagName,
1098 g_Git.FixBranchName(dlg.m_VersionName)
1101 CString tempfile=::GetTempFile();
1102 if(!dlg.m_Message.Trim().IsEmpty())
1104 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1105 cmd += _T(" -F ")+tempfile;
1108 else
1110 cmd.Format(_T("git.exe branch %s %s %s %s"),
1111 track,
1112 force,
1113 dlg.m_BranchTagName,
1114 g_Git.FixBranchName(dlg.m_VersionName)
1117 CString out;
1118 if(g_Git.Run(cmd,&out,CP_UTF8))
1120 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1121 return FALSE;
1123 if( !IsTag && dlg.m_bSwitch )
1125 // it is a new branch and the user has requested to switch to it
1126 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1127 g_Git.Run(cmd,&out,CP_UTF8);
1128 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1131 return TRUE;
1133 return FALSE;
1136 bool CAppUtils::Switch(CString initialRefName, bool autoclose)
1138 CGitSwitchDlg dlg;
1139 if(!initialRefName.IsEmpty())
1140 dlg.m_initialRefName = initialRefName;
1142 if (dlg.DoModal() == IDOK)
1144 CString branch;
1145 if (dlg.m_bBranch)
1146 branch = dlg.m_NewBranch;
1148 // if refs/heads/ is not stripped, checkout will detach HEAD
1149 // checkout prefers branches on name clashes (with tags)
1150 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1151 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1153 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, autoclose);
1155 return FALSE;
1158 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool autoClose /* false */)
1160 CString cmd;
1161 CString track;
1162 CString force;
1163 CString branch;
1165 if(!sNewBranch.IsEmpty()){
1166 if (bBranchOverride)
1168 branch.Format(_T("-B %s"), sNewBranch);
1170 else
1172 branch.Format(_T("-b %s"), sNewBranch);
1174 if (bTrack == TRUE)
1175 track = _T("--track");
1176 else if (bTrack == FALSE)
1177 track = _T("--no-track");
1179 if (bForce)
1180 force = _T("-f");
1182 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1183 force,
1184 track,
1185 branch,
1186 g_Git.FixBranchName(ref));
1188 CProgressDlg progress;
1189 progress.m_bAutoCloseOnSuccess = autoClose;
1190 progress.m_GitCmd = cmd;
1192 CTGitPath gitPath = g_Git.m_CurrentDir;
1193 if (gitPath.HasSubmodules())
1194 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1196 INT_PTR ret = progress.DoModal();
1197 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1199 CString sCmd;
1200 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1202 RunTortoiseGitProc(sCmd);
1203 return TRUE;
1205 else if (ret == IDOK)
1206 return TRUE;
1208 return FALSE;
1211 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1213 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1215 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1216 return false;
1219 if (file.GetLength() > 0)
1221 file.Seek(file.GetLength() - 1, 0);
1222 auto_buffer<TCHAR> buf(1);
1223 file.Read(buf, 1);
1224 file.SeekToEnd();
1225 if (buf[0] != _T('\n'))
1226 file.WriteString(_T("\n"));
1228 else
1229 file.SeekToEnd();
1231 return true;
1234 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1236 CIgnoreDlg ignoreDlg;
1237 if (ignoreDlg.DoModal() == IDOK)
1239 CString ignorefile;
1240 ignorefile = g_Git.m_CurrentDir + _T("\\");
1242 switch (ignoreDlg.m_IgnoreFile)
1244 case 0:
1245 ignorefile += _T(".gitignore");
1246 break;
1247 case 2:
1248 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1249 ignorefile += _T("info/exclude");
1250 break;
1253 CStdioFile file;
1256 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1257 return false;
1259 for (int i = 0; i < path.GetCount(); i++)
1261 if (ignoreDlg.m_IgnoreFile == 1)
1263 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1264 if (!OpenIgnoreFile(file, ignorefile))
1265 return false;
1268 CString ignorePattern;
1269 if (ignoreDlg.m_IgnoreType == 0)
1271 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1272 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1274 ignorePattern += _T("/");
1276 if (IsMask)
1278 ignorePattern += _T("*") + path[i].GetFileExtension();
1280 else
1282 ignorePattern += path[i].GetFileOrDirectoryName();
1285 // escape [ and ] so that files get ignored correctly
1286 ignorePattern.Replace(_T("["), _T("\\["));
1287 ignorePattern.Replace(_T("]"), _T("\\]"));
1289 ignorePattern += _T("\n");
1290 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1291 file.Write(ignorePatternA.GetBuffer(), ignorePatternA.GetLength());
1292 ignorePatternA.ReleaseBuffer();
1294 if (ignoreDlg.m_IgnoreFile == 1)
1295 file.Close();
1298 if (ignoreDlg.m_IgnoreFile != 1)
1299 file.Close();
1301 catch(...)
1303 file.Abort();
1304 return false;
1307 return true;
1309 return false;
1313 bool CAppUtils::GitReset(CString *CommitHash,int type)
1315 CResetDlg dlg;
1316 dlg.m_ResetType=type;
1317 dlg.m_ResetToVersion=*CommitHash;
1318 dlg.m_initialRefName = *CommitHash;
1319 if (dlg.DoModal() == IDOK)
1321 CString cmd;
1322 CString type;
1323 switch(dlg.m_ResetType)
1325 case 0:
1326 type=_T("--soft");
1327 break;
1328 case 1:
1329 type=_T("--mixed");
1330 break;
1331 case 2:
1332 type=_T("--hard");
1333 break;
1334 default:
1335 type=_T("--mixed");
1336 break;
1338 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1340 while (true)
1342 CProgressDlg progress;
1343 progress.m_GitCmd=cmd;
1345 CTGitPath gitPath = g_Git.m_CurrentDir;
1346 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1347 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1349 progress.m_PostFailCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
1351 INT_PTR ret = progress.DoModal();
1352 if (progress.m_GitStatus == 0 && gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1354 CString sCmd;
1355 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1357 RunTortoiseGitProc(sCmd);
1358 return TRUE;
1360 else if (progress.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
1361 continue; // retry
1362 else if (ret == IDOK)
1363 return TRUE;
1364 else
1365 break;
1368 return FALSE;
1371 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1373 if(mode == FALSE)
1375 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1376 return;
1378 if(base)
1380 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1381 return;
1383 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1384 return;
1387 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1389 CString tempmergefile;
1392 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1393 CFile::Remove(tempmergefile);
1394 }catch(...)
1400 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1401 CFile::Remove(tempmergefile);
1402 }catch(...)
1408 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1409 CFile::Remove(tempmergefile);
1410 }catch(...)
1414 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1416 CString file;
1417 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1419 return file;
1422 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1424 bool bRet = false;
1426 CTGitPath merge=path;
1427 CTGitPath directory = merge.GetDirectory();
1429 // we have the conflicted file (%merged)
1430 // now look for the other required files
1431 //GitStatus stat;
1432 //stat.GetStatus(merge);
1433 //if (stat.status == NULL)
1434 // return false;
1436 BYTE_VECTOR vector;
1438 CString cmd;
1439 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1441 if (g_Git.Run(cmd, &vector))
1443 return FALSE;
1446 CTGitPathList list;
1447 list.ParserFromLsFile(vector);
1449 if(list.GetCount() == 0)
1450 return FALSE;
1452 CTGitPath theirs;
1453 CTGitPath mine;
1454 CTGitPath base;
1456 if (revertTheirMy)
1458 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1459 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1461 else
1463 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1464 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1466 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1468 CString format;
1470 //format=_T("git.exe cat-file blob \":%d:%s\"");
1471 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1472 CFile tempfile;
1473 //create a empty file, incase stage is not three
1474 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1475 tempfile.Close();
1476 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1477 tempfile.Close();
1478 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1479 tempfile.Close();
1481 bool b_base=false, b_local=false, b_remote=false;
1483 for(int i=0;i<list.GetCount();i++)
1485 CString cmd;
1486 CString outfile;
1487 cmd.Empty();
1488 outfile.Empty();
1490 if( list[i].m_Stage == 1)
1492 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1493 b_base = true;
1494 outfile = base.GetWinPathString();
1497 if( list[i].m_Stage == 2 )
1499 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1500 b_local = true;
1501 outfile = mine.GetWinPathString();
1504 if( list[i].m_Stage == 3 )
1506 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1507 b_remote = true;
1508 outfile = theirs.GetWinPathString();
1510 CString output, err;
1511 if(!outfile.IsEmpty())
1512 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1514 CString file;
1515 int start =0 ;
1516 file = output.Tokenize(_T("\t"), start);
1517 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1519 else
1521 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1525 if(b_local && b_remote )
1527 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1528 if( revertTheirMy )
1529 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"));
1530 else
1531 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"), _T("REMOTE"), _T("LOCAL"));
1534 else
1536 CFile::Remove(mine.GetWinPathString());
1537 CFile::Remove(theirs.GetWinPathString());
1538 CFile::Remove(base.GetWinPathString());
1540 CDeleteConflictDlg dlg;
1541 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1542 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1543 dlg.m_bShowModifiedButton=b_base;
1544 dlg.m_File=merge.GetGitPathString();
1545 if(dlg.DoModal() == IDOK)
1547 CString cmd,out;
1548 if(dlg.m_bIsDelete)
1550 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1552 else
1553 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1555 if (g_Git.Run(cmd, &out, CP_UTF8))
1557 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1558 return FALSE;
1560 return TRUE;
1562 else
1563 return FALSE;
1566 #if 0
1567 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1568 base, theirs, mine, merge);
1569 #endif
1570 #if 0
1571 if (stat.status->text_status == svn_wc_status_conflicted)
1573 // we have a text conflict, use our merge tool to resolve the conflict
1575 CTSVNPath theirs(directory);
1576 CTSVNPath mine(directory);
1577 CTSVNPath base(directory);
1578 bool bConflictData = false;
1580 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1582 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1583 bConflictData = true;
1585 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1587 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1588 bConflictData = true;
1590 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1592 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1593 bConflictData = true;
1595 else
1597 mine = merge;
1599 if (bConflictData)
1600 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1601 base, theirs, mine, merge);
1604 if (stat.status->prop_status == svn_wc_status_conflicted)
1606 // we have a property conflict
1607 CTSVNPath prej(directory);
1608 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1610 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1611 // there's a problem: the prej file contains a _description_ of the conflict, and
1612 // that description string might be translated. That means we have no way of parsing
1613 // the file to find out the conflicting values.
1614 // The only thing we can do: show a dialog with the conflict description, then
1615 // let the user either accept the existing property or open the property edit dialog
1616 // to manually change the properties and values. And a button to mark the conflict as
1617 // resolved.
1618 CEditPropConflictDlg dlg;
1619 dlg.SetPrejFile(prej);
1620 dlg.SetConflictedItem(merge);
1621 bRet = (dlg.DoModal() != IDCANCEL);
1625 if (stat.status->tree_conflict)
1627 // we have a tree conflict
1628 SVNInfo info;
1629 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1630 if (pInfoData)
1632 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1634 CTSVNPath theirs(directory);
1635 CTSVNPath mine(directory);
1636 CTSVNPath base(directory);
1637 bool bConflictData = false;
1639 if (pInfoData->treeconflict_theirfile)
1641 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1642 bConflictData = true;
1644 if (pInfoData->treeconflict_basefile)
1646 base.AppendPathString(pInfoData->treeconflict_basefile);
1647 bConflictData = true;
1649 if (pInfoData->treeconflict_myfile)
1651 mine.AppendPathString(pInfoData->treeconflict_myfile);
1652 bConflictData = true;
1654 else
1656 mine = merge;
1658 if (bConflictData)
1659 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1660 base, theirs, mine, merge);
1662 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1664 CString sConflictAction;
1665 CString sConflictReason;
1666 CString sResolveTheirs;
1667 CString sResolveMine;
1668 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1669 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1671 if (pInfoData->treeconflict_nodekind == svn_node_file)
1673 switch (pInfoData->treeconflict_operation)
1675 case svn_wc_operation_update:
1676 switch (pInfoData->treeconflict_action)
1678 case svn_wc_conflict_action_edit:
1679 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1680 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1681 break;
1682 case svn_wc_conflict_action_add:
1683 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1684 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1685 break;
1686 case svn_wc_conflict_action_delete:
1687 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1688 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1689 break;
1691 break;
1692 case svn_wc_operation_switch:
1693 switch (pInfoData->treeconflict_action)
1695 case svn_wc_conflict_action_edit:
1696 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1697 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1698 break;
1699 case svn_wc_conflict_action_add:
1700 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1701 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1702 break;
1703 case svn_wc_conflict_action_delete:
1704 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1705 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1706 break;
1708 break;
1709 case svn_wc_operation_merge:
1710 switch (pInfoData->treeconflict_action)
1712 case svn_wc_conflict_action_edit:
1713 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1714 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1715 break;
1716 case svn_wc_conflict_action_add:
1717 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1718 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1719 break;
1720 case svn_wc_conflict_action_delete:
1721 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1722 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1723 break;
1725 break;
1728 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1730 switch (pInfoData->treeconflict_operation)
1732 case svn_wc_operation_update:
1733 switch (pInfoData->treeconflict_action)
1735 case svn_wc_conflict_action_edit:
1736 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1737 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1738 break;
1739 case svn_wc_conflict_action_add:
1740 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1741 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1742 break;
1743 case svn_wc_conflict_action_delete:
1744 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1745 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1746 break;
1748 break;
1749 case svn_wc_operation_switch:
1750 switch (pInfoData->treeconflict_action)
1752 case svn_wc_conflict_action_edit:
1753 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1754 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1755 break;
1756 case svn_wc_conflict_action_add:
1757 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1758 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1759 break;
1760 case svn_wc_conflict_action_delete:
1761 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1762 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1763 break;
1765 break;
1766 case svn_wc_operation_merge:
1767 switch (pInfoData->treeconflict_action)
1769 case svn_wc_conflict_action_edit:
1770 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1771 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1772 break;
1773 case svn_wc_conflict_action_add:
1774 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1775 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1776 break;
1777 case svn_wc_conflict_action_delete:
1778 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1779 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1780 break;
1782 break;
1786 UINT uReasonID = 0;
1787 switch (pInfoData->treeconflict_reason)
1789 case svn_wc_conflict_reason_edited:
1790 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1791 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1792 break;
1793 case svn_wc_conflict_reason_obstructed:
1794 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1795 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1796 break;
1797 case svn_wc_conflict_reason_deleted:
1798 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1799 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1800 break;
1801 case svn_wc_conflict_reason_added:
1802 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1803 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1804 break;
1805 case svn_wc_conflict_reason_missing:
1806 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1807 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1808 break;
1809 case svn_wc_conflict_reason_unversioned:
1810 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1811 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1812 break;
1814 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1816 CTreeConflictEditorDlg dlg;
1817 dlg.SetConflictInfoText(sConflictReason);
1818 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1819 dlg.SetPath(treeConflictPath);
1820 INT_PTR dlgRet = dlg.DoModal();
1821 bRet = (dlgRet != IDCANCEL);
1825 #endif
1826 return bRet;
1829 bool CAppUtils::IsSSHPutty()
1831 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1832 sshclient=sshclient.MakeLower();
1833 if(sshclient.Find(_T("plink.exe"),0)>=0)
1835 return true;
1837 return false;
1840 CString CAppUtils::GetClipboardLink()
1842 if (!OpenClipboard(NULL))
1843 return CString();
1845 CString sClipboardText;
1846 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1847 if (hglb)
1849 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1850 sClipboardText = CString(lpstr);
1851 GlobalUnlock(hglb);
1853 hglb = GetClipboardData(CF_UNICODETEXT);
1854 if (hglb)
1856 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1857 sClipboardText = lpstr;
1858 GlobalUnlock(hglb);
1860 CloseClipboard();
1862 if(!sClipboardText.IsEmpty())
1864 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1865 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1867 if(sClipboardText.Find( _T("http://")) == 0)
1868 return sClipboardText;
1870 if(sClipboardText.Find( _T("https://")) == 0)
1871 return sClipboardText;
1873 if(sClipboardText.Find( _T("git://")) == 0)
1874 return sClipboardText;
1876 if(sClipboardText.Find( _T("ssh://")) == 0)
1877 return sClipboardText;
1879 if(sClipboardText.GetLength()>=2)
1880 if( sClipboardText[1] == _T(':') )
1881 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1882 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1883 return sClipboardText;
1886 return CString(_T(""));
1889 CString CAppUtils::ChooseRepository(CString *path)
1891 CBrowseFolder browseFolder;
1892 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1894 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1895 CString strCloneDirectory;
1896 if(path)
1897 strCloneDirectory=*path;
1898 else
1900 strCloneDirectory = regLastResopitory;
1903 CString title;
1904 title.LoadString(IDS_CHOOSE_REPOSITORY);
1906 browseFolder.SetInfo(title);
1908 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1910 regLastResopitory = strCloneDirectory;
1911 return strCloneDirectory;
1913 else
1915 return CString();
1919 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1921 CSendMailDlg dlg;
1923 dlg.m_PathList = list;
1925 if(dlg.DoModal()==IDOK)
1927 if(dlg.m_PathList.GetCount() == 0)
1928 return FALSE;
1930 CGitProgressDlg progDlg;
1932 theApp.m_pMainWnd = &progDlg;
1933 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1935 progDlg.SetAutoClose(autoclose);
1937 progDlg.SetPathList(dlg.m_PathList);
1938 //ProjectProperties props;
1939 //props.ReadPropsPathList(dlg.m_pathList);
1940 //progDlg.SetProjectProperties(props);
1941 progDlg.SetItemCount(dlg.m_PathList.GetCount());
1943 DWORD flags =0;
1944 if(dlg.m_bAttachment)
1945 flags |= SENDMAIL_ATTACHMENT;
1946 if(dlg.m_bCombine)
1947 flags |= SENDMAIL_COMBINED;
1948 if(dlg.m_bUseMAPI)
1949 flags |= SENDMAIL_MAPI;
1951 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
1953 progDlg.DoModal();
1955 return true;
1957 return false;
1960 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
1962 CTGitPathList list;
1963 CString log=formatpatchoutput;
1964 int start=log.Find(cmd);
1965 if(start >=0)
1966 CString one=log.Tokenize(_T("\n"),start);
1967 else
1968 start = 0;
1970 while(start>=0)
1972 CString one=log.Tokenize(_T("\n"),start);
1973 one=one.Trim();
1974 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
1975 continue;
1976 one.Replace(_T('/'),_T('\\'));
1977 CTGitPath path;
1978 path.SetFromWin(one);
1979 list.AddPath(path);
1981 if (list.GetCount() > 0)
1983 return SendPatchMail(list, autoclose);
1985 else
1987 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
1988 return true;
1993 int CAppUtils::GetLogOutputEncode(CGit *pGit)
1995 CString cmd,output;
1996 int start=0;
1998 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
1999 if(output.IsEmpty())
2001 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2002 if(output.IsEmpty())
2003 return CP_UTF8;
2005 int start=0;
2006 output=output.Tokenize(_T("\n"),start);
2007 return CUnicodeUtils::GetCPCode(output);
2010 else
2012 output=output.Tokenize(_T("\n"),start);
2013 return CUnicodeUtils::GetCPCode(output);
2016 int CAppUtils::GetCommitTemplate(CString &temp)
2018 CString cmd,output;
2020 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
2021 if( output.IsEmpty() )
2022 return -1;
2024 if( output.GetLength()<1)
2025 return -1;
2027 if( output[0] == _T('/'))
2029 if(output.GetLength()>=3)
2030 if(output[2] == _T('/'))
2032 output.GetBuffer()[0] = output[1];
2033 output.GetBuffer()[1] = _T(':');
2037 int start=0;
2038 output=output.Tokenize(_T("\n"),start);
2040 output.Replace(_T('/'),_T('\\'));
2044 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2045 CString str;
2046 while(file.ReadString(str))
2048 temp+=str+_T("\n");
2051 }catch(...)
2053 return -1;
2055 return 0;
2057 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2059 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2060 CString cmd,output;
2061 int cp=CP_UTF8;
2063 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2064 if(output.IsEmpty())
2065 cp=CP_UTF8;
2067 int start=0;
2068 output=output.Tokenize(_T("\n"),start);
2069 cp=CUnicodeUtils::GetCPCode(output);
2071 int len=message.GetLength();
2073 char * buf;
2074 buf = new char[len*4 + 4];
2075 SecureZeroMemory(buf, (len*4 + 4));
2077 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2079 file.Write(buf,lengthIncTerminator-1);
2080 file.Close();
2081 delete buf;
2082 return 0;
2085 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2087 CPullFetchDlg dlg;
2088 dlg.m_PreSelectRemote = remoteName;
2089 dlg.m_bAllowRebase = allowRebase;
2090 dlg.m_IsPull=FALSE;
2092 if(dlg.DoModal()==IDOK)
2094 if(dlg.m_bAutoLoad)
2096 if (dlg.m_bAllRemotes)
2098 STRING_VECTOR list;
2099 g_Git.GetRemoteList(list);
2101 STRING_VECTOR::const_iterator it = list.begin();
2102 while (it != list.end())
2104 CString remote(*it);
2105 CAppUtils::LaunchPAgent(NULL, &remote);
2106 it++;
2109 else
2110 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2113 CString url;
2114 url=dlg.m_RemoteURL;
2115 CString cmd;
2116 CString arg;
2118 int ver = CAppUtils::GetMsysgitVersion();
2120 if(ver >= 0x01070203) //above 1.7.0.2
2121 arg = _T("--progress ");
2123 if (dlg.m_bPrune) {
2124 arg += _T("--prune ");
2127 if (dlg.m_bFetchTags == 1)
2129 arg += _T("--tags ");
2131 else if (dlg.m_bFetchTags == 0)
2133 arg += _T("--no-tags ");
2136 if (dlg.m_bAllRemotes)
2137 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
2138 else
2139 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
2141 CProgressDlg progress;
2143 progress.m_bAutoCloseOnSuccess = autoClose;
2145 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2146 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_RESET)));
2148 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2150 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2153 progress.m_GitCmd=cmd;
2154 INT_PTR userResponse = progress.DoModal();
2156 if (userResponse == IDC_PROGRESS_BUTTON1)
2158 CString cmd = _T("/command:log");
2159 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2160 RunTortoiseGitProc(cmd);
2161 return TRUE;
2163 else if (userResponse == IDC_PROGRESS_BUTTON1 + 1)
2165 CString currentBranch = g_Git.GetSymbolicRef();
2166 CString configName;
2167 configName.Format(_T("branch.%s.remote"), currentBranch);
2168 CString pullRemote = g_Git.GetConfigValue(configName);
2170 //Select pull-branch from current branch
2171 configName.Format(_T("branch.%s.merge"), currentBranch);
2172 CString pullBranch = CGit::StripRefName(g_Git.GetConfigValue(configName));
2174 CString defaultUpstream;
2175 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2176 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2177 GitReset(&defaultUpstream, 2);
2178 return TRUE;
2180 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 2) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2182 while(1)
2184 CRebaseDlg dlg;
2185 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2186 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2187 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2188 INT_PTR response = dlg.DoModal();
2189 if(response == IDOK)
2191 return TRUE;
2193 else if (response == IDC_REBASE_POST_BUTTON)
2195 CString cmd = _T("/command:log");
2196 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2197 RunTortoiseGitProc(cmd);
2198 return TRUE;
2200 else if (response == IDC_REBASE_POST_BUTTON + 1)
2202 CString cmd, out, err;
2203 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2204 g_Git.m_CurrentDir,
2205 g_Git.FixBranchName(dlg.m_Upstream),
2206 g_Git.FixBranchName(dlg.m_Branch));
2207 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2209 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2210 return FALSE;
2213 CAppUtils::SendPatchMail(cmd,out);
2214 return TRUE;
2216 else if (response == IDC_REBASE_POST_BUTTON + 2)
2217 continue;
2218 else if(response == IDCANCEL)
2219 return FALSE;
2221 return TRUE;
2223 else if (userResponse != IDCANCEL)
2224 return TRUE;
2226 return FALSE;
2229 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2231 CPushDlg dlg;
2232 dlg.m_BranchSourceName = selectLocalBranch;
2233 CString error;
2234 DWORD exitcode = 0xFFFFFFFF;
2235 CTGitPathList list;
2236 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2237 if (CHooks::Instance().PrePush(list,exitcode, error))
2239 if (exitcode)
2241 CString temp;
2242 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2243 //ReportError(temp);
2244 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2245 return false;
2249 if(dlg.DoModal()==IDOK)
2251 CString arg;
2253 if(dlg.m_bPack)
2254 arg += _T("--thin ");
2255 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2256 arg += _T("--tags ");
2257 if(dlg.m_bForce)
2258 arg += _T("--force ");
2259 if (dlg.m_bSetUpstream)
2260 arg += _T("--set-upstream ");
2261 if (dlg.m_RecurseSubmodules == 1)
2262 arg += _T("--recurse-submodules=check ");
2263 if (dlg.m_RecurseSubmodules == 2)
2264 arg += _T("--recurse-submodules=on-demand ");
2266 int ver = CAppUtils::GetMsysgitVersion();
2268 if(ver >= 0x01070203) //above 1.7.0.2
2269 arg += _T("--progress ");
2271 CProgressDlg progress;
2272 progress.m_bAutoCloseOnSuccess=autoClose;
2274 STRING_VECTOR remotesList;
2275 if (dlg.m_bPushAllRemotes)
2276 g_Git.GetRemoteList(remotesList);
2277 else
2278 remotesList.push_back(dlg.m_URL);
2280 for (unsigned int i = 0; i < remotesList.size(); i++)
2282 if (dlg.m_bAutoLoad)
2283 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2285 CString cmd;
2286 if (dlg.m_bPushAllBranches)
2288 cmd.Format(_T("git.exe push --all %s \"%s\""),
2289 arg,
2290 remotesList[i]);
2292 else
2294 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2295 arg,
2296 remotesList[i],
2297 dlg.m_BranchSourceName);
2298 if (!dlg.m_BranchRemoteName.IsEmpty())
2300 cmd += _T(":") + dlg.m_BranchRemoteName;
2303 progress.m_GitCmdList.push_back(cmd);
2306 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2307 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2308 INT_PTR ret = progress.DoModal();
2310 if(!progress.m_GitStatus)
2312 if (CHooks::Instance().PostPush(list,exitcode, error))
2314 if (exitcode)
2316 CString temp;
2317 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2318 //ReportError(temp);
2319 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2320 return false;
2323 if(ret == IDC_PROGRESS_BUTTON1)
2325 RequestPull(dlg.m_BranchRemoteName);
2327 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2329 Push();
2331 return TRUE;
2335 return FALSE;
2338 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2340 CRequestPullDlg dlg;
2341 dlg.m_RepositoryURL = repositoryUrl;
2342 dlg.m_EndRevision = endrevision;
2343 if (dlg.DoModal()==IDOK)
2345 CString cmd;
2346 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2348 CSysProgressDlg sysProgressDlg;
2349 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2350 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2351 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2352 sysProgressDlg.SetShowProgressBar(false);
2353 sysProgressDlg.ShowModeless((HWND)NULL, true);
2355 CString tempFileName = GetTempFile();
2356 if (g_Git.RunLogFile(cmd, tempFileName))
2358 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2359 return false;
2362 if (sysProgressDlg.HasUserCancelled())
2364 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2365 ::DeleteFile(tempFileName);
2366 return false;
2369 sysProgressDlg.Stop();
2371 CAppUtils::LaunchAlternativeEditor(tempFileName);
2373 return true;
2376 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2378 CString strDir(szPath);
2379 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2381 strDir.AppendChar(_T('\\'));
2383 std::vector<CString> vPath;
2384 CString strTemp;
2385 bool bSuccess = false;
2387 for (int i=0;i<strDir.GetLength();++i)
2389 if (strDir.GetAt(i) != _T('\\'))
2391 strTemp.AppendChar(strDir.GetAt(i));
2393 else
2395 vPath.push_back(strTemp);
2396 strTemp.AppendChar(_T('\\'));
2400 std::vector<CString>::const_iterator vIter;
2401 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2403 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2406 return bSuccess;
2409 void CAppUtils::RemoveTrailSlash(CString &path)
2411 if(path.IsEmpty())
2412 return ;
2414 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2416 path=path.Left(path.GetLength()-1);
2417 if(path.IsEmpty())
2418 return;
2422 bool CAppUtils::CheckUserData()
2424 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2426 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2428 CTGitPath path(g_Git.m_CurrentDir);
2429 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2430 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2431 dlg.SetTreeWidth(220);
2432 dlg.m_DefaultPage = _T("gitconfig");
2434 dlg.DoModal();
2435 dlg.HandleRestart();
2438 else
2439 return false;
2442 return true;
2445 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2446 CTGitPathList &pathList,
2447 CTGitPathList &selectedList,
2448 bool bSelectFilesForCommit,
2449 bool autoClose)
2451 bool bFailed = true;
2453 if (!CheckUserData())
2454 return false;
2456 while (bFailed)
2458 bFailed = false;
2459 CCommitDlg dlg;
2460 dlg.m_sBugID = bugid;
2462 dlg.m_bWholeProject = bWholeProject;
2464 dlg.m_sLogMessage = sLogMsg;
2465 dlg.m_pathList = pathList;
2466 dlg.m_checkedPathList = selectedList;
2467 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2468 dlg.m_bAutoClose = autoClose;
2469 if (dlg.DoModal() == IDOK)
2471 if (dlg.m_pathList.GetCount()==0)
2472 return false;
2473 // if the user hasn't changed the list of selected items
2474 // we don't use that list. Because if we would use the list
2475 // of pre-checked items, the dialog would show different
2476 // checked items on the next startup: it would only try
2477 // to check the parent folder (which might not even show)
2478 // instead, we simply use an empty list and let the
2479 // default checking do its job.
2480 if (!dlg.m_pathList.IsEqual(pathList))
2481 selectedList = dlg.m_pathList;
2482 pathList = dlg.m_updatedPathList;
2483 sLogMsg = dlg.m_sLogMessage;
2484 bSelectFilesForCommit = true;
2486 if( dlg.m_bPushAfterCommit )
2488 switch(dlg.m_PostCmd)
2490 case GIT_POST_CMD_DCOMMIT:
2491 CAppUtils::SVNDCommit();
2492 break;
2493 default:
2494 CAppUtils::Push();
2497 else if (dlg.m_bCreateTagAfterCommit)
2499 CAppUtils::CreateBranchTag(TRUE);
2502 // CGitProgressDlg progDlg;
2503 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2504 // if (parser.HasVal(_T("closeonend")))
2505 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2506 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2507 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2508 // progDlg.SetPathList(dlg.m_pathList);
2509 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2510 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2511 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2512 // progDlg.SetItemCount(dlg.m_itemsCount);
2513 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2514 // progDlg.DoModal();
2515 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2516 // err = (DWORD)progDlg.DidErrorsOccur();
2517 // bFailed = progDlg.DidErrorsOccur();
2518 // bRet = progDlg.DidErrorsOccur();
2519 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2520 // if (DWORD(bFailRepeat)==0)
2521 // bFailed = false; // do not repeat if the user chose not to in the settings.
2524 return true;
2528 BOOL CAppUtils::SVNDCommit()
2530 CSVNDCommitDlg dcommitdlg;
2531 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2532 if (gitSetting == _T("")) {
2533 if (dcommitdlg.DoModal() != IDOK)
2535 return false;
2537 else
2539 if (dcommitdlg.m_remember)
2541 if (dcommitdlg.m_rmdir)
2543 gitSetting = _T("true");
2545 else
2547 gitSetting = _T("false");
2549 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2551 CString msg;
2552 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2553 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2559 BOOL IsStash = false;
2560 if(!g_Git.CheckCleanWorkTree())
2562 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2564 CSysProgressDlg sysProgressDlg;
2565 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2566 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2567 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2568 sysProgressDlg.SetShowProgressBar(false);
2569 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2570 sysProgressDlg.ShowModeless((HWND)NULL, true);
2572 CString cmd,out;
2573 cmd=_T("git.exe stash");
2574 if (g_Git.Run(cmd, &out, CP_UTF8))
2576 sysProgressDlg.Stop();
2577 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2578 return false;
2580 sysProgressDlg.Stop();
2582 IsStash =true;
2584 else
2586 return false;
2590 CProgressDlg progress;
2591 if (dcommitdlg.m_rmdir)
2593 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2595 else
2597 progress.m_GitCmd=_T("git.exe svn dcommit");
2599 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2601 if( IsStash)
2603 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2605 CSysProgressDlg sysProgressDlg;
2606 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2607 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2608 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2609 sysProgressDlg.SetShowProgressBar(false);
2610 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2611 sysProgressDlg.ShowModeless((HWND)NULL, true);
2613 CString cmd,out;
2614 cmd=_T("git.exe stash pop");
2615 if (g_Git.Run(cmd, &out, CP_UTF8))
2617 sysProgressDlg.Stop();
2618 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2619 return false;
2621 sysProgressDlg.Stop();
2623 else
2625 return false;
2628 return TRUE;
2630 return FALSE;
2633 static void MergeCallback(CProgressDlg *dlg, void *caller, int result)
2635 UNREFERENCED_PARAMETER(caller);
2637 if (result)
2639 dlg->m_PostCmdList.RemoveAll();
2641 CTGitPathList list;
2642 if (!g_Git.ListConflictFile(list) && list.GetCount() > 0)
2644 // there are conflict files
2645 dlg->m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROGRS_CMD_RESOLVE)));
2650 BOOL CAppUtils::Merge(CString *commit)
2652 if (!CheckUserData())
2653 return FALSE;
2655 CMergeDlg dlg;
2656 if(commit)
2657 dlg.m_initialRefName = *commit;
2659 if(dlg.DoModal()==IDOK)
2661 CString cmd;
2662 CString noff;
2663 CString squash;
2664 CString nocommit;
2665 CString msg;
2667 if(dlg.m_bNoFF)
2668 noff=_T("--no-ff");
2670 if(dlg.m_bSquash)
2671 squash=_T("--squash");
2673 if(dlg.m_bNoCommit)
2674 nocommit=_T("--no-commit");
2676 if(!dlg.m_strLogMesage.IsEmpty())
2678 CString logmsg = dlg.m_strLogMesage;
2679 logmsg.Replace(_T("\""), _T("\\\""));
2680 msg += _T("-m \"") + logmsg + _T("\"");
2682 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2683 msg,
2684 noff,
2685 squash,
2686 nocommit,
2687 g_Git.FixBranchName(dlg.m_VersionName));
2689 CProgressDlg Prodlg;
2690 Prodlg.m_GitCmd = cmd;
2692 if (dlg.m_bNoCommit)
2693 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2694 else if (dlg.m_bIsBranch)
2695 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2697 Prodlg.m_PostCmdCallback = MergeCallback;
2699 INT_PTR ret = Prodlg.DoModal();
2700 if (Prodlg.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
2702 CTGitPathList pathlist;
2703 CTGitPathList selectedlist;
2704 pathlist.AddPath(g_Git.m_CurrentDir);
2705 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
2706 CString str;
2707 CAppUtils::Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
2709 else if (ret == IDC_PROGRESS_BUTTON1)
2711 if (dlg.m_bNoCommit)
2713 CString sLogMsg;
2714 CTGitPathList pathList;
2715 CTGitPathList selectedList;
2716 return Commit(_T(""), TRUE, sLogMsg, pathList, selectedList, true);
2718 else if (dlg.m_bIsBranch)
2720 CString msg;
2721 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2722 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2724 CString cmd, out;
2725 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2726 if (g_Git.Run(cmd, &out, CP_UTF8))
2727 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2732 return !Prodlg.m_GitStatus;
2734 return false;
2737 void CAppUtils::EditNote(GitRev *rev)
2739 if (!CheckUserData())
2740 return;
2742 CInputDlg dlg;
2743 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2744 dlg.m_sInputText = rev->m_Notes;
2745 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2746 //dlg.m_pProjectProperties = &m_ProjectProperties;
2747 dlg.m_bUseLogWidth = true;
2748 if(dlg.DoModal() == IDOK)
2750 CString cmd,output;
2751 cmd=_T("notes add -f -F \"");
2753 CString tempfile=::GetTempFile();
2754 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2755 cmd += tempfile;
2756 cmd += _T("\" ");
2757 cmd += rev->m_CommitHash.ToString();
2761 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2763 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2766 else
2768 rev->m_Notes = dlg.m_sInputText;
2770 }catch(...)
2772 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2774 CFile::Remove(tempfile);
2779 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2781 CString cmd;
2782 CString versiondebug;
2783 CString version;
2785 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2786 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2788 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2790 __int64 time=0;
2791 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2793 if((DWORD)time == regTime)
2795 return regVersion;
2799 if(versionstr)
2800 version = *versionstr;
2801 else
2803 CString err;
2804 cmd = _T("git.exe --version");
2805 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2807 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2808 return false;
2812 int start=0;
2813 int ver = 0;
2815 versiondebug = version;
2819 CString str=version.Tokenize(_T("."), start);
2820 int space = str.ReverseFind(_T(' '));
2821 str = str.Mid(space+1,start);
2822 ver = _ttol(str);
2823 ver <<=24;
2825 version = version.Mid(start);
2826 start = 0;
2828 str = version.Tokenize(_T("."), start);
2830 ver |= (_ttol(str) & 0xFF) << 16;
2832 str = version.Tokenize(_T("."), start);
2833 ver |= (_ttol(str) & 0xFF) << 8;
2835 str = version.Tokenize(_T("."), start);
2836 ver |= (_ttol(str) & 0xFF);
2838 catch(...)
2840 if (!ver)
2842 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2843 return false;
2847 regTime = time&0xFFFFFFFF;
2848 regVersion = ver;
2850 return ver;
2853 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2855 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2857 CAutoLibrary hShell = LoadLibrary(_T("Shell32.dll"));
2859 if (hShell.IsValid()) {
2860 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2861 if (pfnSHGPSFW) {
2862 IPropertyStore *pps;
2863 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2864 if (SUCCEEDED(hr)) {
2865 PROPVARIANT var;
2866 var.vt = VT_BOOL;
2867 var.boolVal = VARIANT_TRUE;
2868 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2869 pps->Release();
2875 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2877 ASSERT(dialogname.GetLength() < 70);
2878 ASSERT(urlorpath.GetLength() < MAX_PATH);
2879 WCHAR pathbuf[MAX_PATH] = {0};
2881 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2883 wcscat_s(pathbuf, L" - ");
2884 wcscat_s(pathbuf, dialogname);
2885 wcscat_s(pathbuf, L" - ");
2886 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2887 SetWindowText(hWnd, pathbuf);
2890 bool CAppUtils::BisectStart(CString lastGood, CString firstBad, bool autoClose)
2892 if (!g_Git.CheckCleanWorkTree())
2894 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2896 CSysProgressDlg sysProgressDlg;
2897 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2898 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2899 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2900 sysProgressDlg.SetShowProgressBar(false);
2901 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2902 sysProgressDlg.ShowModeless((HWND)NULL, true);
2904 CString cmd, out;
2905 cmd = _T("git.exe stash");
2906 if (g_Git.Run(cmd, &out, CP_UTF8))
2908 sysProgressDlg.Stop();
2909 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
2910 return false;
2912 sysProgressDlg.Stop();
2914 else
2915 return false;
2918 CBisectStartDlg bisectStartDlg;
2920 if (!lastGood.IsEmpty())
2921 bisectStartDlg.m_sLastGood = lastGood;
2922 if (!firstBad.IsEmpty())
2923 bisectStartDlg.m_sFirstBad = firstBad;
2925 if (bisectStartDlg.DoModal() == IDOK)
2927 CProgressDlg progress;
2928 theApp.m_pMainWnd = &progress;
2929 progress.m_bAutoCloseOnSuccess = autoClose;
2930 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
2931 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
2932 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
2934 CTGitPath path(g_Git.m_CurrentDir);
2936 if (path.HasSubmodules())
2937 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
2939 INT_PTR ret = progress.DoModal();
2940 if (path.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
2942 CString sCmd;
2943 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
2945 CAppUtils::RunTortoiseGitProc(sCmd);
2946 return true;
2948 else if (ret == IDOK)
2949 return true;
2952 return false;