Add try-catch blocks and critical sections to wrap libgit functions in CLogDataVector...
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob964fbae1d2440e2832414a2c3f48e3ee5d6ce3ff
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2013 - 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"
66 #include "UserPassword.h"
67 #include "Patch.h"
69 CAppUtils::CAppUtils(void)
73 CAppUtils::~CAppUtils(void)
77 bool CAppUtils::StashSave()
79 CStashSaveDlg dlg;
81 if (dlg.DoModal() == IDOK)
83 CString cmd, out;
84 cmd = _T("git.exe stash save");
86 if (CAppUtils::GetMsysgitVersion() >= 0x01070700)
88 if (dlg.m_bIncludeUntracked)
89 cmd += _T(" --include-untracked");
90 else if (dlg.m_bAll)
91 cmd += _T(" --all");
94 if (!dlg.m_sMessage.IsEmpty())
96 CString message = dlg.m_sMessage;
97 message.Replace(_T("\""), _T("\"\""));
98 cmd += _T(" \"") + message + _T("\"");
101 CSysProgressDlg sysProgressDlg;
102 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
103 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
104 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
105 sysProgressDlg.SetShowProgressBar(false);
106 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
107 sysProgressDlg.ShowModeless((HWND)NULL, true);
109 if (g_Git.Run(cmd, &out, CP_UTF8))
111 sysProgressDlg.Stop();
112 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
114 else
116 sysProgressDlg.Stop();
117 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHSUCCESS)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
118 return true;
121 return false;
124 bool CAppUtils::StashApply(CString ref, bool showChanges /* true */)
126 CString cmd,out;
127 cmd = _T("git.exe stash apply ");
128 if (ref.Find(_T("refs/")) == 0)
129 ref = ref.Mid(5);
130 if (ref.Find(_T("stash{")) == 0)
131 ref = _T("stash@") + ref.Mid(5);
132 cmd += ref;
134 CSysProgressDlg sysProgressDlg;
135 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
136 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
137 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
138 sysProgressDlg.SetShowProgressBar(false);
139 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
140 sysProgressDlg.ShowModeless((HWND)NULL, true);
142 int ret = g_Git.Run(cmd, &out, CP_UTF8);
144 sysProgressDlg.Stop();
146 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
147 if (ret && !(ret == 1 && hasConflicts))
149 CMessageBox::Show(NULL, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
151 else
153 CString message;
154 message.LoadString(IDS_PROC_STASHAPPLYSUCCESS);
155 if (hasConflicts)
156 message.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS);
157 if (showChanges)
159 if(CMessageBox::Show(NULL,message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES))
160 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
162 CChangedDlg dlg;
163 dlg.m_pathList.AddPath(CTGitPath());
164 dlg.DoModal();
166 return true;
168 else
170 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
171 return true;
174 return false;
177 bool CAppUtils::StashPop(bool showChanges /* true */)
179 CString cmd,out;
180 cmd=_T("git.exe stash pop ");
182 CSysProgressDlg sysProgressDlg;
183 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
184 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
185 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
186 sysProgressDlg.SetShowProgressBar(false);
187 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
188 sysProgressDlg.ShowModeless((HWND)NULL, true);
190 int ret = g_Git.Run(cmd, &out, CP_UTF8);
192 sysProgressDlg.Stop();
194 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
195 if (ret && !(ret == 1 && hasConflicts))
197 CMessageBox::Show(NULL,CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED)) + _T("\n") + out, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
199 else
201 CString message;
202 message.LoadString(IDS_PROC_STASHPOPSUCCESS);
203 if (hasConflicts)
204 message.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS);
205 if (showChanges)
207 if(CMessageBox::Show(NULL,CString(message + _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES)))
208 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
210 CChangedDlg dlg;
211 dlg.m_pathList.AddPath(CTGitPath());
212 dlg.DoModal();
214 return true;
216 else
218 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
219 return true;
222 return false;
225 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
227 #if 0
228 GitProperties props(file, GitRev::REV_WC, false);
229 for (int i = 0; i < props.GetCount(); ++i)
231 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
233 mimetype = props.GetItemValue(i).c_str();
234 return true;
237 #endif
238 return false;
241 BOOL CAppUtils::StartExtMerge(
242 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
243 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
246 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
247 CString ext = mergedfile.GetFileExtension();
248 CString com = regCom;
249 bool bInternal = false;
251 CString mimetype;
252 if (ext != "")
254 // is there an extension specific merge tool?
255 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
256 if (CString(mergetool) != "")
258 com = mergetool;
261 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
263 // is there a mime type specific merge tool?
264 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
265 if (CString(mergetool) != "")
267 com = mergetool;
270 // is there a filename specific merge tool?
271 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile.GetFilename().MakeLower());
272 if (CString(mergetool) != "")
274 com = mergetool;
277 // Maybe we should use TortoiseIDiff?
278 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
279 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
280 (ext == _T(".png")) || (ext == _T(".ico")) ||
281 (ext == _T(".dib")) || (ext == _T(".emf")))
283 com = _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
284 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") + _T("\n") +
285 // delimited by \n
286 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
287 _T(" /left:%base /right:%theirs /lefttitle:%bname /righttitle:%tname");
290 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
292 // use TortoiseGitMerge
293 bInternal = true;
294 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
295 com = tortoiseMergePath;
296 if (com.IsEmpty())
298 com = CPathUtils::GetAppDirectory();
299 com += _T("TortoiseGitMerge.exe");
301 com = _T("\"") + com + _T("\"");
302 if (!g_sGroupingUUID.IsEmpty())
304 com += L" /groupuuid:\"";
305 com += g_sGroupingUUID;
306 com += L"\"";
308 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
309 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
311 // check if the params are set. If not, just add the files to the command line
312 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
314 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
315 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
316 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
317 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
319 if (basefile.IsEmpty())
321 com.Replace(_T("/base:%base"), _T(""));
322 com.Replace(_T("%base"), _T(""));
324 else
325 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
326 if (theirfile.IsEmpty())
328 com.Replace(_T("/theirs:%theirs"), _T(""));
329 com.Replace(_T("%theirs"), _T(""));
331 else
332 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
333 if (yourfile.IsEmpty())
335 com.Replace(_T("/mine:%mine"), _T(""));
336 com.Replace(_T("%mine"), _T(""));
338 else
339 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
340 if (mergedfile.IsEmpty())
342 com.Replace(_T("/merged:%merged"), _T(""));
343 com.Replace(_T("%merged"), _T(""));
345 else
346 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
347 if (basename.IsEmpty())
349 if (basefile.IsEmpty())
351 com.Replace(_T("/basename:%bname"), _T(""));
352 com.Replace(_T("%bname"), _T(""));
354 else
356 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
359 else
360 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
361 if (theirname.IsEmpty())
363 if (theirfile.IsEmpty())
365 com.Replace(_T("/theirsname:%tname"), _T(""));
366 com.Replace(_T("%tname"), _T(""));
368 else
370 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
373 else
374 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
375 if (yourname.IsEmpty())
377 if (yourfile.IsEmpty())
379 com.Replace(_T("/minename:%yname"), _T(""));
380 com.Replace(_T("%yname"), _T(""));
382 else
384 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
387 else
388 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
389 if (mergedname.IsEmpty())
391 if (mergedfile.IsEmpty())
393 com.Replace(_T("/mergedname:%mname"), _T(""));
394 com.Replace(_T("%mname"), _T(""));
396 else
398 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
401 else
402 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
404 if ((bReadOnly)&&(bInternal))
405 com += _T(" /readonly");
407 CString com2;
408 int newLine = com.Find(_T('\n'));
409 if (newLine >= 0)
411 com2 = com.Mid(newLine + 1);
412 com = com.Left(newLine);
414 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
416 return FALSE;
418 if (!com2.IsEmpty() && !LaunchApplication(com2, IDS_ERR_EXTMERGESTART, false))
420 return FALSE;
423 return TRUE;
426 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
428 CString viewer;
429 // use TortoiseGitMerge
430 viewer = CPathUtils::GetAppDirectory();
431 viewer += _T("TortoiseGitMerge.exe");
433 viewer = _T("\"") + viewer + _T("\"");
434 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
435 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
436 if (bReversed)
437 viewer += _T(" /reversedpatch");
438 if (!sOriginalDescription.IsEmpty())
439 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
440 if (!sPatchedDescription.IsEmpty())
441 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
442 if (!g_sGroupingUUID.IsEmpty())
444 viewer += L" /groupuuid:\"";
445 viewer += g_sGroupingUUID;
446 viewer += L"\"";
448 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
450 return FALSE;
452 return TRUE;
455 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
457 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file2.GetFilename().MakeLower());
458 if (!difftool.IsEmpty())
459 return difftool;
460 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\.") + file1.GetFilename().MakeLower());
461 if (!difftool.IsEmpty())
462 return difftool;
464 // Is there a mime type specific diff tool?
465 CString mimetype;
466 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
468 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
469 if (!difftool.IsEmpty())
470 return difftool;
473 // Is there an extension specific diff tool?
474 CString ext = file2.GetFileExtension().MakeLower();
475 if (!ext.IsEmpty())
477 difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
478 if (!difftool.IsEmpty())
479 return difftool;
480 // Maybe we should use TortoiseIDiff?
481 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
482 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
483 (ext == _T(".png")) || (ext == _T(".ico")) ||
484 (ext == _T(".dib")) || (ext == _T(".emf")))
486 return
487 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
488 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
489 L" /groupuuid:\"" + g_sGroupingUUID + L"\"";
493 // Finally, pick a generic external diff tool
494 difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
495 return difftool;
498 bool CAppUtils::StartExtDiff(
499 const CString& file1, const CString& file2,
500 const CString& sName1, const CString& sName2,
501 const CString& originalFile1, const CString& originalFile2,
502 const git_revnum_t& hash1, const git_revnum_t& hash2,
503 const DiffFlags& flags)
505 CString viewer;
507 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
508 if (!flags.bBlame || !(DWORD)blamediff)
510 viewer = PickDiffTool(file1, file2);
511 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
512 bool bCommentedOut = viewer.Left(1) == _T("#");
513 if (flags.bAlternativeTool)
515 // Invert external vs. internal diff tool selection.
516 if (bCommentedOut)
517 viewer.Delete(0); // uncomment
518 else
519 viewer = "";
521 else if (bCommentedOut)
522 viewer = "";
525 bool bInternal = viewer.IsEmpty();
526 if (bInternal)
528 viewer =
529 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
530 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
531 if (!g_sGroupingUUID.IsEmpty())
533 viewer += L" /groupuuid:\"";
534 viewer += g_sGroupingUUID;
535 viewer += L"\"";
537 if (flags.bBlame)
538 viewer += _T(" /blame");
540 // check if the params are set. If not, just add the files to the command line
541 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
543 viewer += _T(" \"")+file1+_T("\"");
544 viewer += _T(" \"")+file2+_T("\"");
546 if (viewer.Find(_T("%base")) >= 0)
548 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
550 if (viewer.Find(_T("%mine")) >= 0)
552 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
555 if (sName1.IsEmpty())
556 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
557 else
558 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
560 if (sName2.IsEmpty())
561 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
562 else
563 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
565 viewer.Replace(_T("%bpath"), _T("\"") + originalFile1 + _T("\""));
566 viewer.Replace(_T("%ypath"), _T("\"") + originalFile2 + _T("\""));
568 viewer.Replace(_T("%brev"), _T("\"") + hash1 + _T("\""));
569 viewer.Replace(_T("%yrev"), _T("\"") + hash2 + _T("\""));
571 if (flags.bReadOnly && bInternal)
572 viewer += _T(" /readonly");
574 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
577 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
579 CString viewer;
580 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
581 viewer = v;
582 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
584 // use TortoiseGitUDiff
585 viewer = CPathUtils::GetAppDirectory();
586 viewer += _T("TortoiseGitUDiff.exe");
587 // enquote the path to TortoiseGitUDiff
588 viewer = _T("\"") + viewer + _T("\"");
589 // add the params
590 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
591 if (!g_sGroupingUUID.IsEmpty())
593 viewer += L" /groupuuid:\"";
594 viewer += g_sGroupingUUID;
595 viewer += L"\"";
598 if (viewer.Find(_T("%1"))>=0)
600 if (viewer.Find(_T("\"%1\"")) >= 0)
601 viewer.Replace(_T("%1"), patchfile);
602 else
603 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
605 else
606 viewer += _T(" \"") + patchfile + _T("\"");
607 if (viewer.Find(_T("%title")) >= 0)
609 viewer.Replace(_T("%title"), title);
612 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
614 return FALSE;
616 return TRUE;
619 BOOL CAppUtils::StartTextViewer(CString file)
621 CString viewer;
622 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
623 viewer = txt;
624 viewer = viewer + _T("\\Shell\\Open\\Command\\");
625 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
626 viewer = txtexe;
628 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
629 std::unique_ptr<TCHAR[]> buf(new TCHAR[len + 1]);
630 ExpandEnvironmentStrings(viewer, buf.get(), len);
631 viewer = buf.get();
632 len = ExpandEnvironmentStrings(file, NULL, 0);
633 std::unique_ptr<TCHAR[]> buf2(new TCHAR[len + 1]);
634 ExpandEnvironmentStrings(file, buf2.get(), len);
635 file = buf2.get();
636 file = _T("\"")+file+_T("\"");
637 if (viewer.IsEmpty())
639 viewer = _T("RUNDLL32 Shell32,OpenAs_RunDLL");
641 if (viewer.Find(_T("\"%1\"")) >= 0)
643 viewer.Replace(_T("\"%1\""), file);
645 else if (viewer.Find(_T("%1")) >= 0)
647 viewer.Replace(_T("%1"), file);
649 else
651 viewer += _T(" ");
652 viewer += file;
655 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
657 return FALSE;
659 return TRUE;
662 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
664 DWORD length = 0;
665 CAutoFile hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
666 if (!hFile)
667 return TRUE;
668 length = ::GetFileSize(hFile, NULL);
669 if (length < 4)
670 return TRUE;
671 return FALSE;
675 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
677 LOGFONT logFont;
678 HDC hScreenDC = ::GetDC(NULL);
679 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
680 ::ReleaseDC(NULL, hScreenDC);
681 logFont.lfWidth = 0;
682 logFont.lfEscapement = 0;
683 logFont.lfOrientation = 0;
684 logFont.lfWeight = FW_NORMAL;
685 logFont.lfItalic = 0;
686 logFont.lfUnderline = 0;
687 logFont.lfStrikeOut = 0;
688 logFont.lfCharSet = DEFAULT_CHARSET;
689 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
690 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
691 logFont.lfQuality = DRAFT_QUALITY;
692 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
693 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
694 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
697 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
699 CString key,remote;
700 CString cmd,out;
701 if( pRemote == NULL)
703 remote=_T("origin");
705 else
707 remote=*pRemote;
709 if(keyfile == NULL)
711 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
712 key = g_Git.GetConfigValue(cmd);
713 int start=0;
714 key = key.Tokenize(_T("\n"),start);
716 else
717 key=*keyfile;
719 if(key.IsEmpty())
720 return false;
722 CString proc=CPathUtils::GetAppDirectory();
723 proc += _T("pageant.exe \"");
724 proc += key;
725 proc += _T("\"");
727 CString tempfile = GetTempFile();
728 ::DeleteFile(tempfile);
730 proc += _T(" -c \"");
731 proc += CPathUtils::GetAppDirectory();
732 proc += _T("touch.exe\"");
733 proc += _T(" \"");
734 proc += tempfile;
735 proc += _T("\"");
737 CString appDir = CPathUtils::GetAppDirectory();
738 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true, &appDir);
739 if(!b)
740 return b;
742 int i=0;
743 while(!::PathFileExists(tempfile))
745 Sleep(100);
746 ++i;
747 if(i>10*60*5)
748 break; //timeout 5 minutes
751 if( i== 10*60*5)
753 CMessageBox::Show(NULL, IDS_ERR_PAEGENTTIMEOUT, IDS_APPNAME, MB_OK | MB_ICONERROR);
755 ::DeleteFile(tempfile);
756 return true;
758 bool CAppUtils::LaunchAlternativeEditor(const CString& filename, bool uac)
760 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
761 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
762 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
765 CString sCmd;
766 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
768 LaunchApplication(sCmd, NULL, false, NULL, uac);
769 return true;
771 bool CAppUtils::LaunchRemoteSetting()
773 CTGitPath path(g_Git.m_CurrentDir);
774 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
775 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
776 dlg.SetTreeWidth(220);
777 dlg.m_DefaultPage = _T("gitremote");
779 dlg.DoModal();
780 dlg.HandleRestart();
781 return true;
784 * Launch the external blame viewer
786 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
788 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
789 viewer += _T("TortoiseGitBlame.exe");
790 viewer += _T("\" \"") + sBlameFile + _T("\"");
791 //viewer += _T(" \"") + sLogFile + _T("\"");
792 //viewer += _T(" \"") + sOriginalFile + _T("\"");
793 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
794 viewer += CString(_T(" /rev:"))+Rev;
795 if (!g_sGroupingUUID.IsEmpty())
797 viewer += L" /groupuuid:\"";
798 viewer += g_sGroupingUUID;
799 viewer += L"\"";
801 viewer += _T(" ")+sParams;
803 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
806 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
808 CString sText;
809 if (pWnd == NULL)
810 return false;
811 bool bStyled = false;
812 pWnd->GetWindowText(sText);
813 // the rich edit control doesn't count the CR char!
814 // to be exact: CRLF is treated as one char.
815 sText.Remove('\r');
817 // style each line separately
818 int offset = 0;
819 int nNewlinePos;
822 nNewlinePos = sText.Find('\n', offset);
823 CString sLine = sText.Mid(offset);
824 if (nNewlinePos>=0)
825 sLine = sLine.Left(nNewlinePos-offset);
826 int start = 0;
827 int end = 0;
828 while (FindStyleChars(sLine, '*', start, end))
830 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
831 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
832 CHARFORMAT2 format;
833 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
834 format.cbSize = sizeof(CHARFORMAT2);
835 format.dwMask = CFM_BOLD;
836 format.dwEffects = CFE_BOLD;
837 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
838 bStyled = true;
839 start = end;
841 start = 0;
842 end = 0;
843 while (FindStyleChars(sLine, '^', start, end))
845 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
846 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
847 CHARFORMAT2 format;
848 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
849 format.cbSize = sizeof(CHARFORMAT2);
850 format.dwMask = CFM_ITALIC;
851 format.dwEffects = CFE_ITALIC;
852 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
853 bStyled = true;
854 start = end;
856 start = 0;
857 end = 0;
858 while (FindStyleChars(sLine, '_', start, end))
860 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
861 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
862 CHARFORMAT2 format;
863 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
864 format.cbSize = sizeof(CHARFORMAT2);
865 format.dwMask = CFM_UNDERLINE;
866 format.dwEffects = CFE_UNDERLINE;
867 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
868 bStyled = true;
869 start = end;
871 offset = nNewlinePos+1;
872 } while(nNewlinePos>=0);
873 return bStyled;
876 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
878 int i=start;
879 bool bFoundMarker = false;
880 // find a starting marker
881 while (sText[i] != 0)
883 if (sText[i] == stylechar)
885 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
886 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
888 start = i+1;
889 ++i;
890 bFoundMarker = true;
891 break;
894 ++i;
896 if (!bFoundMarker)
897 return false;
898 // find ending marker
899 bFoundMarker = false;
900 while (sText[i] != 0)
902 if (sText[i] == stylechar)
904 if ((IsCharAlphaNumeric(sText[i-1])) &&
905 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
907 end = i;
908 ++i;
909 bFoundMarker = true;
910 break;
913 ++i;
915 return bFoundMarker;
918 CString CAppUtils::GetProjectNameFromURL(CString url)
920 CString name;
921 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
922 (name.CompareNoCase(_T("tags"))==0) ||
923 (name.CompareNoCase(_T("trunk"))==0))
925 name = url.Mid(url.ReverseFind('/')+1);
926 url = url.Left(url.ReverseFind('/'));
928 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
930 // a name of svn or svnroot indicates that it's not really the project name. In that
931 // case, we try the first part of the URL
932 // of course, this won't work in all cases (but it works for Google project hosting)
933 url.Replace(_T("http://"), _T(""));
934 url.Replace(_T("https://"), _T(""));
935 url.Replace(_T("svn://"), _T(""));
936 url.Replace(_T("svn+ssh://"), _T(""));
937 url.TrimLeft(_T("/"));
938 name = url.Left(url.Find('.'));
940 return name;
943 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
944 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
945 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
946 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
949 CString tempfile=GetTempFile();
950 CString cmd;
951 if(rev2 == GitRev::GetWorkingCopy())
953 cmd.Format(_T("git.exe diff --stat -p %s "), rev1);
955 else if (rev1 == GitRev::GetWorkingCopy())
957 cmd.Format(_T("git.exe diff -R --stat -p %s "), rev2);
959 else
961 CString merge;
962 if(bMerge)
963 merge = _T("-c");
965 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
968 if( !url1.IsEmpty() )
970 cmd += _T(" -- \"");
971 cmd += url1.GetGitPathString();
972 cmd += _T("\" ");
974 g_Git.RunLogFile(cmd,tempfile);
975 CAppUtils::StartUnifiedDiffViewer(tempfile, rev1 + _T(":") + rev2);
978 #if 0
979 CString sCmd;
980 sCmd.Format(_T("%s /command:showcompare /unified"),
981 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
982 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
983 if (rev1.IsValid())
984 sCmd += _T(" /revision1:") + rev1.ToString();
985 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
986 if (rev2.IsValid())
987 sCmd += _T(" /revision2:") + rev2.ToString();
988 if (peg.IsValid())
989 sCmd += _T(" /pegrevision:") + peg.ToString();
990 if (headpeg.IsValid())
991 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
993 if (bAlternateDiff)
994 sCmd += _T(" /alternatediff");
996 if (bIgnoreAncestry)
997 sCmd += _T(" /ignoreancestry");
999 if (hWnd)
1001 sCmd += _T(" /hwnd:");
1002 TCHAR buf[30];
1003 _stprintf_s(buf, 30, _T("%d"), hWnd);
1004 sCmd += buf;
1007 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1008 #endif
1009 return TRUE;
1012 bool CAppUtils::SetupDiffScripts(bool force, const CString& type)
1014 CString scriptsdir = CPathUtils::GetAppParentDirectory();
1015 scriptsdir += _T("Diff-Scripts");
1016 CSimpleFileFind files(scriptsdir);
1017 while (files.FindNextFileNoDirectories())
1019 CString file = files.GetFilePath();
1020 CString filename = files.GetFileName();
1021 CString ext = file.Mid(file.ReverseFind('-') + 1);
1022 ext = _T(".") + ext.Left(ext.ReverseFind('.'));
1023 std::set<CString> extensions;
1024 extensions.insert(ext);
1025 CString kind;
1026 if (file.Right(3).CompareNoCase(_T("vbs"))==0)
1028 kind = _T(" //E:vbscript");
1030 if (file.Right(2).CompareNoCase(_T("js"))==0)
1032 kind = _T(" //E:javascript");
1034 // open the file, read the first line and find possible extensions
1035 // this script can handle
1038 CStdioFile f(file, CFile::modeRead | CFile::shareDenyNone);
1039 CString extline;
1040 if (f.ReadString(extline))
1042 if ((extline.GetLength() > 15 ) &&
1043 ((extline.Left(15).Compare(_T("// extensions: ")) == 0) ||
1044 (extline.Left(14).Compare(_T("' extensions: ")) == 0)))
1046 if (extline[0] == '/')
1047 extline = extline.Mid(15);
1048 else
1049 extline = extline.Mid(14);
1050 CString sToken;
1051 int curPos = 0;
1052 sToken = extline.Tokenize(_T(";"), curPos);
1053 while (!sToken.IsEmpty())
1055 if (!sToken.IsEmpty())
1057 if (sToken[0] != '.')
1058 sToken = _T(".") + sToken;
1059 extensions.insert(sToken);
1061 sToken = extline.Tokenize(_T(";"), curPos);
1065 f.Close();
1067 catch (CFileException* e)
1069 e->Delete();
1072 for (std::set<CString>::const_iterator it = extensions.begin(); it != extensions.end(); ++it)
1074 if (type.IsEmpty() || (type.Compare(_T("Diff")) == 0))
1076 if (filename.Left(5).CompareNoCase(_T("diff-")) == 0)
1078 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + *it);
1079 CString diffregstring = diffreg;
1080 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1081 diffreg = _T("wscript.exe \"") + file + _T("\" %base %mine") + kind;
1084 if (type.IsEmpty() || (type.Compare(_T("Merge"))==0))
1086 if (filename.Left(6).CompareNoCase(_T("merge-"))==0)
1088 CRegString diffreg = CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + *it);
1089 CString diffregstring = diffreg;
1090 if (force || (diffregstring.IsEmpty()) || (diffregstring.Find(filename) >= 0))
1091 diffreg = _T("wscript.exe \"") + file + _T("\" %merged %theirs %mine %base") + kind;
1097 return true;
1100 bool CAppUtils::Export(CString *BashHash)
1102 // ask from where the export has to be done
1103 CExportDlg dlg;
1104 if(BashHash)
1105 dlg.m_Revision=*BashHash;
1107 if (dlg.DoModal() == IDOK)
1109 CString cmd;
1110 cmd.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s"),
1111 dlg.m_strExportDirectory, g_Git.FixBranchName(dlg.m_VersionName));
1113 CProgressDlg pro;
1114 pro.m_GitCmd=cmd;
1115 return (pro.DoModal() == IDOK);
1117 return false;
1120 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1122 CCreateBranchTagDlg dlg;
1123 dlg.m_bIsTag=IsTag;
1124 dlg.m_bSwitch=switch_new_brach;
1126 if(CommitHash)
1127 dlg.m_initialRefName = *CommitHash;
1129 if(dlg.DoModal()==IDOK)
1131 CString cmd;
1132 CString force;
1133 CString track;
1134 if(dlg.m_bTrack == TRUE)
1135 track=_T(" --track ");
1136 else if(dlg.m_bTrack == FALSE)
1137 track=_T(" --no-track");
1139 if(dlg.m_bForce)
1140 force=_T(" -f ");
1142 if(IsTag)
1144 CString sign;
1145 if(dlg.m_bSign)
1146 sign=_T("-s");
1148 cmd.Format(_T("git.exe tag %s %s %s %s"),
1149 force,
1150 sign,
1151 dlg.m_BranchTagName,
1152 g_Git.FixBranchName(dlg.m_VersionName)
1155 CString tempfile=::GetTempFile();
1156 if(!dlg.m_Message.Trim().IsEmpty())
1158 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1159 cmd += _T(" -F ")+tempfile;
1162 else
1164 cmd.Format(_T("git.exe branch %s %s %s %s"),
1165 track,
1166 force,
1167 dlg.m_BranchTagName,
1168 g_Git.FixBranchName(dlg.m_VersionName)
1171 CString out;
1172 if(g_Git.Run(cmd,&out,CP_UTF8))
1174 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1175 return FALSE;
1177 if( !IsTag && dlg.m_bSwitch )
1179 // it is a new branch and the user has requested to switch to it
1180 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1181 g_Git.Run(cmd,&out,CP_UTF8);
1182 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1185 return TRUE;
1187 return FALSE;
1190 bool CAppUtils::Switch(CString initialRefName, bool autoclose)
1192 CGitSwitchDlg dlg;
1193 if(!initialRefName.IsEmpty())
1194 dlg.m_initialRefName = initialRefName;
1196 if (dlg.DoModal() == IDOK)
1198 CString branch;
1199 if (dlg.m_bBranch)
1200 branch = dlg.m_NewBranch;
1202 // if refs/heads/ is not stripped, checkout will detach HEAD
1203 // checkout prefers branches on name clashes (with tags)
1204 if (dlg.m_VersionName.Left(11) ==_T("refs/heads/") && dlg.m_bBranchOverride != TRUE)
1205 dlg.m_VersionName = dlg.m_VersionName.Mid(11);
1207 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack, autoclose);
1209 return FALSE;
1212 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, BOOL bTrack /* 2 */, bool autoClose /* false */)
1214 CString cmd;
1215 CString track;
1216 CString force;
1217 CString branch;
1219 if(!sNewBranch.IsEmpty()){
1220 if (bBranchOverride)
1222 branch.Format(_T("-B %s"), sNewBranch);
1224 else
1226 branch.Format(_T("-b %s"), sNewBranch);
1228 if (bTrack == TRUE)
1229 track = _T("--track");
1230 else if (bTrack == FALSE)
1231 track = _T("--no-track");
1233 if (bForce)
1234 force = _T("-f");
1236 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1237 force,
1238 track,
1239 branch,
1240 g_Git.FixBranchName(ref));
1242 CProgressDlg progress;
1243 progress.m_bAutoCloseOnSuccess = autoClose;
1244 progress.m_GitCmd = cmd;
1246 CTGitPath gitPath = g_Git.m_CurrentDir;
1247 if (gitPath.HasSubmodules())
1248 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1250 INT_PTR ret = progress.DoModal();
1251 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1253 CString sCmd;
1254 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1256 RunTortoiseGitProc(sCmd);
1257 return TRUE;
1259 else if (ret == IDOK)
1260 return TRUE;
1262 return FALSE;
1265 bool CAppUtils::OpenIgnoreFile(CStdioFile &file, const CString& filename)
1267 if (!file.Open(filename, CFile::modeCreate | CFile::modeReadWrite | CFile::modeNoTruncate))
1269 CMessageBox::Show(NULL, filename + _T(" Open Failure"), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
1270 return false;
1273 if (file.GetLength() > 0)
1275 file.Seek(file.GetLength() - 1, 0);
1276 std::unique_ptr<TCHAR[]> buf(new TCHAR[1]);
1277 file.Read(buf.get(), 1);
1278 file.SeekToEnd();
1279 if (buf.get()[0] != _T('\n'))
1280 file.WriteString(_T("\n"));
1282 else
1283 file.SeekToEnd();
1285 return true;
1288 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1290 CIgnoreDlg ignoreDlg;
1291 if (ignoreDlg.DoModal() == IDOK)
1293 CString ignorefile;
1294 ignorefile = g_Git.m_CurrentDir + _T("\\");
1296 switch (ignoreDlg.m_IgnoreFile)
1298 case 0:
1299 ignorefile += _T(".gitignore");
1300 break;
1301 case 2:
1302 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, ignorefile);
1303 ignorefile += _T("info/exclude");
1304 break;
1307 CStdioFile file;
1310 if (ignoreDlg.m_IgnoreFile != 1 && !OpenIgnoreFile(file, ignorefile))
1311 return false;
1313 for (int i = 0; i < path.GetCount(); ++i)
1315 if (ignoreDlg.m_IgnoreFile == 1)
1317 ignorefile = g_Git.m_CurrentDir + _T("\\") + path[i].GetContainingDirectory().GetWinPathString() + _T("\\.gitignore");
1318 if (!OpenIgnoreFile(file, ignorefile))
1319 return false;
1322 CString ignorePattern;
1323 if (ignoreDlg.m_IgnoreType == 0)
1325 if (ignoreDlg.m_IgnoreFile != 1 && !path[i].GetContainingDirectory().GetGitPathString().IsEmpty())
1326 ignorePattern += _T("/") + path[i].GetContainingDirectory().GetGitPathString();
1328 ignorePattern += _T("/");
1330 if (IsMask)
1332 ignorePattern += _T("*") + path[i].GetFileExtension();
1334 else
1336 ignorePattern += path[i].GetFileOrDirectoryName();
1339 // escape [ and ] so that files get ignored correctly
1340 ignorePattern.Replace(_T("["), _T("\\["));
1341 ignorePattern.Replace(_T("]"), _T("\\]"));
1343 ignorePattern += _T("\n");
1344 CStringA ignorePatternA = CUnicodeUtils::GetUTF8(ignorePattern);
1345 file.Write(ignorePatternA.GetBuffer(), ignorePatternA.GetLength());
1346 ignorePatternA.ReleaseBuffer();
1348 if (ignoreDlg.m_IgnoreFile == 1)
1349 file.Close();
1352 if (ignoreDlg.m_IgnoreFile != 1)
1353 file.Close();
1355 catch(...)
1357 file.Abort();
1358 return false;
1361 return true;
1363 return false;
1367 bool CAppUtils::GitReset(CString *CommitHash,int type)
1369 CResetDlg dlg;
1370 dlg.m_ResetType=type;
1371 dlg.m_ResetToVersion=*CommitHash;
1372 dlg.m_initialRefName = *CommitHash;
1373 if (dlg.DoModal() == IDOK)
1375 CString cmd;
1376 CString type;
1377 switch(dlg.m_ResetType)
1379 case 0:
1380 type=_T("--soft");
1381 break;
1382 case 1:
1383 type=_T("--mixed");
1384 break;
1385 case 2:
1386 type=_T("--hard");
1387 break;
1388 default:
1389 type=_T("--mixed");
1390 break;
1392 cmd.Format(_T("git.exe reset %s %s"),type, dlg.m_ResetToVersion);
1394 while (true)
1396 CProgressDlg progress;
1397 progress.m_GitCmd=cmd;
1399 CTGitPath gitPath = g_Git.m_CurrentDir;
1400 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1401 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
1403 progress.m_PostFailCmdList.Add(CString(MAKEINTRESOURCE(IDS_MSGBOX_RETRY)));
1405 INT_PTR ret = progress.DoModal();
1406 if (progress.m_GitStatus == 0 && gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1408 CString sCmd;
1409 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
1411 RunTortoiseGitProc(sCmd);
1412 return TRUE;
1414 else if (progress.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
1415 continue; // retry
1416 else if (ret == IDOK)
1417 return TRUE;
1418 else
1419 break;
1422 return FALSE;
1425 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1427 if(mode == FALSE)
1429 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_DELETE));
1430 return;
1432 if(base)
1434 descript = CString(MAKEINTRESOURCE(IDS_SVNACTION_MODIFIED));
1435 return;
1437 descript = CString(MAKEINTRESOURCE(IDS_PROC_CREATED));
1438 return;
1441 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1443 CString tempmergefile;
1446 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1447 CFile::Remove(tempmergefile);
1448 }catch(...)
1454 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1455 CFile::Remove(tempmergefile);
1456 }catch(...)
1462 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1463 CFile::Remove(tempmergefile);
1464 }catch(...)
1468 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1470 CString file;
1471 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1473 return file;
1476 bool ParseHashesFromLsFile(BYTE_VECTOR &out, CString &hash1, CString &hash2, CString &hash3)
1478 unsigned int pos = 0;
1479 CString one;
1480 CString part;
1482 while (pos >= 0 && pos < out.size())
1484 one.Empty();
1486 g_Git.StringAppend(&one, &out[pos], CP_UTF8);
1487 int tabstart = 0;
1488 one.Tokenize(_T("\t"), tabstart);
1490 tabstart = 0;
1491 part = one.Tokenize(_T(" "), tabstart); //Tag
1492 part = one.Tokenize(_T(" "), tabstart); //Mode
1493 part = one.Tokenize(_T(" "), tabstart); //Hash
1494 CString hash = part;
1495 part = one.Tokenize(_T("\t"), tabstart); //Stage
1496 int stage = _ttol(part);
1497 if (stage == 1)
1498 hash1 = hash;
1499 else if (stage == 2)
1500 hash2 = hash;
1501 else if (stage == 3)
1503 hash3 = hash;
1504 return true;
1507 pos = out.findNextString(pos);
1510 return false;
1513 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1515 bool bRet = false;
1517 CTGitPath merge=path;
1518 CTGitPath directory = merge.GetDirectory();
1520 // we have the conflicted file (%merged)
1521 // now look for the other required files
1522 //GitStatus stat;
1523 //stat.GetStatus(merge);
1524 //if (stat.status == NULL)
1525 // return false;
1527 BYTE_VECTOR vector;
1529 CString cmd;
1530 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1532 if (g_Git.Run(cmd, &vector))
1534 return FALSE;
1537 if (merge.IsDirectory())
1539 CString baseHash, localHash, remoteHash;
1540 if (!ParseHashesFromLsFile(vector, baseHash, localHash, remoteHash))
1541 return FALSE;
1543 CString msg;
1544 msg.Format(_T("BASE: %s\nLOCAL: %s\nREMOTE: %s"), baseHash, localHash, remoteHash);
1545 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK);
1546 return TRUE;
1549 CTGitPathList list;
1550 if (list.ParserFromLsFile(vector))
1552 CMessageBox::Show(NULL, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK);
1553 return FALSE;
1556 if(list.GetCount() == 0)
1557 return FALSE;
1559 CTGitPath theirs;
1560 CTGitPath mine;
1561 CTGitPath base;
1563 if (revertTheirMy)
1565 mine.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1566 theirs.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1568 else
1570 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge));
1571 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge));
1573 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1575 CString format;
1577 //format=_T("git.exe cat-file blob \":%d:%s\"");
1578 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1579 CFile tempfile;
1580 //create a empty file, incase stage is not three
1581 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1582 tempfile.Close();
1583 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1584 tempfile.Close();
1585 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1586 tempfile.Close();
1588 bool b_base=false, b_local=false, b_remote=false;
1590 for (int i = 0; i< list.GetCount(); ++i)
1592 CString cmd;
1593 CString outfile;
1594 cmd.Empty();
1595 outfile.Empty();
1597 if( list[i].m_Stage == 1)
1599 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1600 b_base = true;
1601 outfile = base.GetWinPathString();
1604 if( list[i].m_Stage == 2 )
1606 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1607 b_local = true;
1608 outfile = mine.GetWinPathString();
1611 if( list[i].m_Stage == 3 )
1613 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1614 b_remote = true;
1615 outfile = theirs.GetWinPathString();
1617 CString output, err;
1618 if(!outfile.IsEmpty())
1619 if (!g_Git.Run(cmd, &output, &err, CP_UTF8))
1621 CString file;
1622 int start =0 ;
1623 file = output.Tokenize(_T("\t"), start);
1624 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1626 else
1628 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1632 if(b_local && b_remote )
1634 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1635 if( revertTheirMy )
1636 bRet = !!CAppUtils::StartExtMerge(base, mine, theirs, merge, _T("BASE"), _T("REMOTE"), _T("LOCAL"));
1637 else
1638 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"), _T("REMOTE"), _T("LOCAL"));
1641 else
1643 CFile::Remove(mine.GetWinPathString());
1644 CFile::Remove(theirs.GetWinPathString());
1645 CFile::Remove(base.GetWinPathString());
1647 CDeleteConflictDlg dlg;
1648 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1649 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1650 dlg.m_bShowModifiedButton=b_base;
1651 dlg.m_File=merge.GetGitPathString();
1652 if(dlg.DoModal() == IDOK)
1654 CString cmd,out;
1655 if(dlg.m_bIsDelete)
1657 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1659 else
1660 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1662 if (g_Git.Run(cmd, &out, CP_UTF8))
1664 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1665 return FALSE;
1667 return TRUE;
1669 else
1670 return FALSE;
1673 #if 0
1674 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1675 base, theirs, mine, merge);
1676 #endif
1677 #if 0
1678 if (stat.status->text_status == svn_wc_status_conflicted)
1680 // we have a text conflict, use our merge tool to resolve the conflict
1682 CTSVNPath theirs(directory);
1683 CTSVNPath mine(directory);
1684 CTSVNPath base(directory);
1685 bool bConflictData = false;
1687 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1689 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1690 bConflictData = true;
1692 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1694 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1695 bConflictData = true;
1697 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1699 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1700 bConflictData = true;
1702 else
1704 mine = merge;
1706 if (bConflictData)
1707 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1708 base, theirs, mine, merge);
1711 if (stat.status->prop_status == svn_wc_status_conflicted)
1713 // we have a property conflict
1714 CTSVNPath prej(directory);
1715 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1717 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1718 // there's a problem: the prej file contains a _description_ of the conflict, and
1719 // that description string might be translated. That means we have no way of parsing
1720 // the file to find out the conflicting values.
1721 // The only thing we can do: show a dialog with the conflict description, then
1722 // let the user either accept the existing property or open the property edit dialog
1723 // to manually change the properties and values. And a button to mark the conflict as
1724 // resolved.
1725 CEditPropConflictDlg dlg;
1726 dlg.SetPrejFile(prej);
1727 dlg.SetConflictedItem(merge);
1728 bRet = (dlg.DoModal() != IDCANCEL);
1732 if (stat.status->tree_conflict)
1734 // we have a tree conflict
1735 SVNInfo info;
1736 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1737 if (pInfoData)
1739 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1741 CTSVNPath theirs(directory);
1742 CTSVNPath mine(directory);
1743 CTSVNPath base(directory);
1744 bool bConflictData = false;
1746 if (pInfoData->treeconflict_theirfile)
1748 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1749 bConflictData = true;
1751 if (pInfoData->treeconflict_basefile)
1753 base.AppendPathString(pInfoData->treeconflict_basefile);
1754 bConflictData = true;
1756 if (pInfoData->treeconflict_myfile)
1758 mine.AppendPathString(pInfoData->treeconflict_myfile);
1759 bConflictData = true;
1761 else
1763 mine = merge;
1765 if (bConflictData)
1766 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1767 base, theirs, mine, merge);
1769 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1771 CString sConflictAction;
1772 CString sConflictReason;
1773 CString sResolveTheirs;
1774 CString sResolveMine;
1775 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1776 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1778 if (pInfoData->treeconflict_nodekind == svn_node_file)
1780 switch (pInfoData->treeconflict_operation)
1782 case svn_wc_operation_update:
1783 switch (pInfoData->treeconflict_action)
1785 case svn_wc_conflict_action_edit:
1786 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1787 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1788 break;
1789 case svn_wc_conflict_action_add:
1790 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1791 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1792 break;
1793 case svn_wc_conflict_action_delete:
1794 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1795 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1796 break;
1798 break;
1799 case svn_wc_operation_switch:
1800 switch (pInfoData->treeconflict_action)
1802 case svn_wc_conflict_action_edit:
1803 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1804 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1805 break;
1806 case svn_wc_conflict_action_add:
1807 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1808 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1809 break;
1810 case svn_wc_conflict_action_delete:
1811 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1812 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1813 break;
1815 break;
1816 case svn_wc_operation_merge:
1817 switch (pInfoData->treeconflict_action)
1819 case svn_wc_conflict_action_edit:
1820 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1821 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1822 break;
1823 case svn_wc_conflict_action_add:
1824 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1825 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1826 break;
1827 case svn_wc_conflict_action_delete:
1828 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1829 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1830 break;
1832 break;
1835 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1837 switch (pInfoData->treeconflict_operation)
1839 case svn_wc_operation_update:
1840 switch (pInfoData->treeconflict_action)
1842 case svn_wc_conflict_action_edit:
1843 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1844 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1845 break;
1846 case svn_wc_conflict_action_add:
1847 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1848 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1849 break;
1850 case svn_wc_conflict_action_delete:
1851 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1852 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1853 break;
1855 break;
1856 case svn_wc_operation_switch:
1857 switch (pInfoData->treeconflict_action)
1859 case svn_wc_conflict_action_edit:
1860 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1861 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1862 break;
1863 case svn_wc_conflict_action_add:
1864 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1865 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1866 break;
1867 case svn_wc_conflict_action_delete:
1868 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1869 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1870 break;
1872 break;
1873 case svn_wc_operation_merge:
1874 switch (pInfoData->treeconflict_action)
1876 case svn_wc_conflict_action_edit:
1877 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1878 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1879 break;
1880 case svn_wc_conflict_action_add:
1881 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1882 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1883 break;
1884 case svn_wc_conflict_action_delete:
1885 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1886 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1887 break;
1889 break;
1893 UINT uReasonID = 0;
1894 switch (pInfoData->treeconflict_reason)
1896 case svn_wc_conflict_reason_edited:
1897 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1898 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1899 break;
1900 case svn_wc_conflict_reason_obstructed:
1901 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1902 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1903 break;
1904 case svn_wc_conflict_reason_deleted:
1905 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1906 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1907 break;
1908 case svn_wc_conflict_reason_added:
1909 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1910 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1911 break;
1912 case svn_wc_conflict_reason_missing:
1913 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1914 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1915 break;
1916 case svn_wc_conflict_reason_unversioned:
1917 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1918 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1919 break;
1921 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1923 CTreeConflictEditorDlg dlg;
1924 dlg.SetConflictInfoText(sConflictReason);
1925 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1926 dlg.SetPath(treeConflictPath);
1927 INT_PTR dlgRet = dlg.DoModal();
1928 bRet = (dlgRet != IDCANCEL);
1932 #endif
1933 return bRet;
1936 bool CAppUtils::IsSSHPutty()
1938 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1939 sshclient=sshclient.MakeLower();
1940 if(sshclient.Find(_T("plink.exe"),0)>=0)
1942 return true;
1944 return false;
1947 CString CAppUtils::GetClipboardLink()
1949 if (!OpenClipboard(NULL))
1950 return CString();
1952 CString sClipboardText;
1953 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1954 if (hglb)
1956 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1957 sClipboardText = CString(lpstr);
1958 GlobalUnlock(hglb);
1960 hglb = GetClipboardData(CF_UNICODETEXT);
1961 if (hglb)
1963 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1964 sClipboardText = lpstr;
1965 GlobalUnlock(hglb);
1967 CloseClipboard();
1969 if(!sClipboardText.IsEmpty())
1971 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1972 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1974 if(sClipboardText.Find( _T("http://")) == 0)
1975 return sClipboardText;
1977 if(sClipboardText.Find( _T("https://")) == 0)
1978 return sClipboardText;
1980 if(sClipboardText.Find( _T("git://")) == 0)
1981 return sClipboardText;
1983 if(sClipboardText.Find( _T("ssh://")) == 0)
1984 return sClipboardText;
1986 if(sClipboardText.GetLength()>=2)
1987 if( sClipboardText[1] == _T(':') )
1988 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1989 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1990 return sClipboardText;
1993 return CString(_T(""));
1996 CString CAppUtils::ChooseRepository(CString *path)
1998 CBrowseFolder browseFolder;
1999 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2001 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2002 CString strCloneDirectory;
2003 if(path)
2004 strCloneDirectory=*path;
2005 else
2007 strCloneDirectory = regLastResopitory;
2010 CString title;
2011 title.LoadString(IDS_CHOOSE_REPOSITORY);
2013 browseFolder.SetInfo(title);
2015 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2017 regLastResopitory = strCloneDirectory;
2018 return strCloneDirectory;
2020 else
2022 return CString();
2026 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2028 CSendMailDlg dlg;
2030 dlg.m_PathList = list;
2032 if(dlg.DoModal()==IDOK)
2034 if(dlg.m_PathList.GetCount() == 0)
2035 return FALSE;
2037 CGitProgressDlg progDlg;
2039 theApp.m_pMainWnd = &progDlg;
2040 progDlg.SetCommand(CGitProgressList::GitProgress_SendMail);
2042 progDlg.SetAutoClose(autoclose);
2044 progDlg.SetPathList(dlg.m_PathList);
2045 //ProjectProperties props;
2046 //props.ReadPropsPathList(dlg.m_pathList);
2047 //progDlg.SetProjectProperties(props);
2048 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2050 CSendMailPatch sendMailPatch(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine, !!dlg.m_bUseMAPI);
2051 progDlg.SetSendMailOption(&sendMailPatch);
2053 progDlg.DoModal();
2055 return true;
2057 return false;
2060 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2062 CTGitPathList list;
2063 CString log=formatpatchoutput;
2064 int start=log.Find(cmd);
2065 if(start >=0)
2066 CString one=log.Tokenize(_T("\n"),start);
2067 else
2068 start = 0;
2070 while(start>=0)
2072 CString one=log.Tokenize(_T("\n"),start);
2073 one=one.Trim();
2074 if(one.IsEmpty() || one.Find(_T("Success")) == 0)
2075 continue;
2076 one.Replace(_T('/'),_T('\\'));
2077 CTGitPath path;
2078 path.SetFromWin(one);
2079 list.AddPath(path);
2081 if (list.GetCount() > 0)
2083 return SendPatchMail(list, autoclose);
2085 else
2087 CMessageBox::Show(NULL, IDS_ERR_NOPATCHES, IDS_APPNAME, MB_ICONINFORMATION);
2088 return true;
2093 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2095 CString cmd,output;
2096 int start=0;
2098 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2099 if(output.IsEmpty())
2101 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2102 if(output.IsEmpty())
2103 return CP_UTF8;
2105 int start=0;
2106 output=output.Tokenize(_T("\n"),start);
2107 return CUnicodeUtils::GetCPCode(output);
2110 else
2112 output=output.Tokenize(_T("\n"),start);
2113 return CUnicodeUtils::GetCPCode(output);
2116 int CAppUtils::GetCommitTemplate(CString &temp)
2118 CString cmd,output;
2120 output = g_Git.GetConfigValue(_T("commit.template"), CP_UTF8);
2121 if( output.IsEmpty() )
2122 return -1;
2124 if( output.GetLength()<1)
2125 return -1;
2127 if( output[0] == _T('/'))
2129 if(output.GetLength()>=3)
2130 if(output[2] == _T('/'))
2132 output.GetBuffer()[0] = output[1];
2133 output.GetBuffer()[1] = _T(':');
2137 int start=0;
2138 output=output.Tokenize(_T("\n"),start);
2140 output.Replace(_T('/'),_T('\\'));
2144 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2145 CString str;
2146 while(file.ReadString(str))
2148 temp+=str+_T("\n");
2151 }catch(...)
2153 return -1;
2155 return 0;
2157 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2159 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2160 CString cmd,output;
2161 int cp=CP_UTF8;
2163 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2164 if(output.IsEmpty())
2165 cp=CP_UTF8;
2167 int start=0;
2168 output=output.Tokenize(_T("\n"),start);
2169 cp=CUnicodeUtils::GetCPCode(output);
2171 int len=message.GetLength();
2173 std::unique_ptr<char[]> buf(new char[len * 4 + 4]);
2174 SecureZeroMemory(buf.get(), len * 4 + 4);
2176 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf.get(), len * 4, NULL, NULL);
2178 file.Write(buf.get(), lengthIncTerminator - 1);
2179 file.Close();
2180 return 0;
2183 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2185 CPullFetchDlg dlg;
2186 dlg.m_PreSelectRemote = remoteName;
2187 dlg.m_bAllowRebase = allowRebase;
2188 dlg.m_IsPull=FALSE;
2190 if(dlg.DoModal()==IDOK)
2192 if(dlg.m_bAutoLoad)
2194 if (dlg.m_bAllRemotes)
2196 STRING_VECTOR list;
2197 g_Git.GetRemoteList(list);
2199 STRING_VECTOR::const_iterator it = list.begin();
2200 while (it != list.end())
2202 CString remote(*it);
2203 CAppUtils::LaunchPAgent(NULL, &remote);
2204 ++it;
2207 else
2208 CAppUtils::LaunchPAgent(NULL, &dlg.m_RemoteURL);
2211 CString url;
2212 url=dlg.m_RemoteURL;
2213 CString cmd;
2214 CString arg;
2216 int ver = CAppUtils::GetMsysgitVersion();
2218 if(ver >= 0x01070203) //above 1.7.0.2
2219 arg = _T("--progress ");
2221 if (dlg.m_bPrune) {
2222 arg += _T("--prune ");
2225 if (dlg.m_bFetchTags == 1)
2227 arg += _T("--tags ");
2229 else if (dlg.m_bFetchTags == 0)
2231 arg += _T("--no-tags ");
2234 if (dlg.m_bAllRemotes)
2235 cmd.Format(_T("git.exe fetch --all -v %s"), arg);
2236 else
2237 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"), arg, url, dlg.m_RemoteBranchName);
2239 CProgressDlg progress;
2241 progress.m_bAutoCloseOnSuccess = autoClose;
2243 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2244 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_RESET)));
2246 if(!dlg.m_bRebase && !g_GitAdminDir.IsBareRepo(g_Git.m_CurrentDir))
2248 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2251 progress.m_GitCmd=cmd;
2252 INT_PTR userResponse;
2254 if (g_Git.UsingLibGit2(CGit::GIT_CMD_FETCH))
2256 CGitProgressDlg gitdlg;
2257 if (!dlg.m_bAllRemotes)
2258 gitdlg.SetUrl(url);
2259 gitdlg.SetCommand(CGitProgressList::GitProgress_Fetch);
2260 gitdlg.SetAutoTag(dlg.m_bFetchTags ? GIT_REMOTE_DOWNLOAD_TAGS_ALL : GIT_REMOTE_DOWNLOAD_TAGS_NONE);
2261 if (!dlg.m_bAllRemotes)
2262 gitdlg.SetRefSpec(dlg.m_RemoteBranchName);
2263 userResponse = gitdlg.DoModal();
2266 else
2267 userResponse = progress.DoModal();
2269 if (userResponse == IDC_PROGRESS_BUTTON1)
2271 CString cmd = _T("/command:log");
2272 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2273 RunTortoiseGitProc(cmd);
2274 return TRUE;
2276 else if (userResponse == IDC_PROGRESS_BUTTON1 + 1)
2278 CString currentBranch = g_Git.GetSymbolicRef();
2279 CString configName;
2280 configName.Format(_T("branch.%s.remote"), currentBranch);
2281 CString pullRemote = g_Git.GetConfigValue(configName);
2283 //Select pull-branch from current branch
2284 configName.Format(_T("branch.%s.merge"), currentBranch);
2285 CString pullBranch = CGit::StripRefName(g_Git.GetConfigValue(configName));
2287 CString defaultUpstream;
2288 if (!pullRemote.IsEmpty() && !pullBranch.IsEmpty())
2289 defaultUpstream.Format(_T("remotes/%s/%s"), pullRemote, pullBranch);
2290 GitReset(&defaultUpstream, 2);
2291 return TRUE;
2293 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 2) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2295 while(1)
2297 CRebaseDlg dlg;
2298 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENULOG)));
2299 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL)));
2300 dlg.m_PostButtonTexts.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE)));
2301 INT_PTR response = dlg.DoModal();
2302 if(response == IDOK)
2304 return TRUE;
2306 else if (response == IDC_REBASE_POST_BUTTON)
2308 CString cmd = _T("/command:log");
2309 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2310 RunTortoiseGitProc(cmd);
2311 return TRUE;
2313 else if (response == IDC_REBASE_POST_BUTTON + 1)
2315 CString cmd, out, err;
2316 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2317 g_Git.m_CurrentDir,
2318 g_Git.FixBranchName(dlg.m_Upstream),
2319 g_Git.FixBranchName(dlg.m_Branch));
2320 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
2322 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2323 return FALSE;
2326 CAppUtils::SendPatchMail(cmd,out);
2327 return TRUE;
2329 else if (response == IDC_REBASE_POST_BUTTON + 2)
2330 continue;
2331 else if(response == IDCANCEL)
2332 return FALSE;
2334 return TRUE;
2336 else if (userResponse != IDCANCEL)
2337 return TRUE;
2339 return FALSE;
2342 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2344 CPushDlg dlg;
2345 dlg.m_BranchSourceName = selectLocalBranch;
2346 CString error;
2347 DWORD exitcode = 0xFFFFFFFF;
2348 CTGitPathList list;
2349 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2350 if (CHooks::Instance().PrePush(list,exitcode, error))
2352 if (exitcode)
2354 CString temp;
2355 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2356 //ReportError(temp);
2357 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2358 return false;
2362 if(dlg.DoModal()==IDOK)
2364 CString arg;
2366 if(dlg.m_bPack)
2367 arg += _T("--thin ");
2368 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2369 arg += _T("--tags ");
2370 if(dlg.m_bForce)
2371 arg += _T("--force ");
2372 if (dlg.m_bSetUpstream)
2373 arg += _T("--set-upstream ");
2374 if (dlg.m_RecurseSubmodules == 1)
2375 arg += _T("--recurse-submodules=check ");
2376 if (dlg.m_RecurseSubmodules == 2)
2377 arg += _T("--recurse-submodules=on-demand ");
2379 int ver = CAppUtils::GetMsysgitVersion();
2381 if(ver >= 0x01070203) //above 1.7.0.2
2382 arg += _T("--progress ");
2384 CProgressDlg progress;
2385 progress.m_bAutoCloseOnSuccess=autoClose;
2387 STRING_VECTOR remotesList;
2388 if (dlg.m_bPushAllRemotes)
2389 g_Git.GetRemoteList(remotesList);
2390 else
2391 remotesList.push_back(dlg.m_URL);
2393 for (unsigned int i = 0; i < remotesList.size(); ++i)
2395 if (dlg.m_bAutoLoad)
2396 CAppUtils::LaunchPAgent(NULL, &remotesList[i]);
2398 CString cmd;
2399 if (dlg.m_bPushAllBranches)
2401 cmd.Format(_T("git.exe push --all %s \"%s\""),
2402 arg,
2403 remotesList[i]);
2405 if (dlg.m_bTags)
2407 progress.m_GitCmdList.push_back(cmd);
2408 cmd.Format(_T("git.exe push --tags %s \"%s\""), arg, remotesList[i]);
2411 else
2413 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2414 arg,
2415 remotesList[i],
2416 dlg.m_BranchSourceName);
2417 if (!dlg.m_BranchRemoteName.IsEmpty())
2419 cmd += _T(":") + dlg.m_BranchRemoteName;
2422 progress.m_GitCmdList.push_back(cmd);
2425 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REQUESTPULL)));
2426 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH)));
2427 INT_PTR ret = progress.DoModal();
2429 if(!progress.m_GitStatus)
2431 if (CHooks::Instance().PostPush(list,exitcode, error))
2433 if (exitcode)
2435 CString temp;
2436 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2437 //ReportError(temp);
2438 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2439 return false;
2442 if(ret == IDC_PROGRESS_BUTTON1)
2444 RequestPull(dlg.m_BranchRemoteName);
2446 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2448 Push();
2450 return TRUE;
2454 return FALSE;
2457 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2459 CRequestPullDlg dlg;
2460 dlg.m_RepositoryURL = repositoryUrl;
2461 dlg.m_EndRevision = endrevision;
2462 if (dlg.DoModal()==IDOK)
2464 CString cmd;
2465 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2467 CSysProgressDlg sysProgressDlg;
2468 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2469 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST)));
2470 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2471 sysProgressDlg.SetShowProgressBar(false);
2472 sysProgressDlg.ShowModeless((HWND)NULL, true);
2474 CString tempFileName = GetTempFile();
2475 DeleteFile(tempFileName);
2476 CreateDirectory(tempFileName, NULL);
2477 tempFileName += _T("\\pullrequest.txt");
2478 if (g_Git.RunLogFile(cmd, tempFileName))
2480 CMessageBox::Show(NULL, IDS_ERR_PULLREUQESTFAILED, IDS_APPNAME, MB_OK);
2481 return false;
2484 if (sysProgressDlg.HasUserCancelled())
2486 CMessageBox::Show(NULL, IDS_SVN_USERCANCELLED, IDS_APPNAME, MB_OK);
2487 ::DeleteFile(tempFileName);
2488 return false;
2491 sysProgressDlg.Stop();
2493 if (dlg.m_bSendMail)
2495 CSendMailDlg dlg;
2496 dlg.m_PathList = CTGitPathList(CTGitPath(tempFileName));
2497 dlg.m_bCustomSubject = true;
2499 if (dlg.DoModal() == IDOK)
2501 if(dlg.m_PathList.GetCount() == 0)
2502 return FALSE;
2504 CGitProgressDlg progDlg;
2506 theApp.m_pMainWnd = &progDlg;
2507 progDlg.SetCommand(CGitProgressList::GitProgress_SendMail);
2509 progDlg.SetPathList(dlg.m_PathList);
2510 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2512 CSendMailCombineable sendMailCombineable(dlg.m_To, dlg.m_CC, dlg.m_Subject, !!dlg.m_bAttachment, !!dlg.m_bCombine, !!dlg.m_bUseMAPI);
2513 progDlg.SetSendMailOption(&sendMailCombineable);
2515 progDlg.DoModal();
2517 return true;
2519 return false;
2522 CAppUtils::LaunchAlternativeEditor(tempFileName);
2524 return true;
2527 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2529 CString strDir(szPath);
2530 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2532 strDir.AppendChar(_T('\\'));
2534 std::vector<CString> vPath;
2535 CString strTemp;
2536 bool bSuccess = false;
2538 for (int i=0;i<strDir.GetLength();++i)
2540 if (strDir.GetAt(i) != _T('\\'))
2542 strTemp.AppendChar(strDir.GetAt(i));
2544 else
2546 vPath.push_back(strTemp);
2547 strTemp.AppendChar(_T('\\'));
2551 for (auto vIter = vPath.begin(); vIter != vPath.end(); ++vIter)
2553 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2556 return bSuccess;
2559 void CAppUtils::RemoveTrailSlash(CString &path)
2561 if(path.IsEmpty())
2562 return ;
2564 // For URL, do not trim the slash just after the host name component.
2565 int index = path.Find(_T("://"));
2566 if (index >= 0)
2568 index += 4;
2569 index = path.Find(_T('/'), index);
2570 if (index == path.GetLength() - 1)
2571 return;
2574 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2576 path=path.Left(path.GetLength()-1);
2577 if(path.IsEmpty())
2578 return;
2582 bool CAppUtils::CheckUserData()
2584 while(g_Git.GetUserName().IsEmpty() || g_Git.GetUserEmail().IsEmpty())
2586 if(CMessageBox::Show(NULL, IDS_PROC_NOUSERDATA, IDS_APPNAME, MB_YESNO| MB_ICONERROR) == IDYES)
2588 CTGitPath path(g_Git.m_CurrentDir);
2589 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2590 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2591 dlg.SetTreeWidth(220);
2592 dlg.m_DefaultPage = _T("gitconfig");
2594 dlg.DoModal();
2595 dlg.HandleRestart();
2598 else
2599 return false;
2602 return true;
2605 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2606 CTGitPathList &pathList,
2607 CTGitPathList &selectedList,
2608 bool bSelectFilesForCommit,
2609 bool autoClose)
2611 bool bFailed = true;
2613 if (!CheckUserData())
2614 return false;
2616 while (bFailed)
2618 bFailed = false;
2619 CCommitDlg dlg;
2620 dlg.m_sBugID = bugid;
2622 dlg.m_bWholeProject = bWholeProject;
2624 dlg.m_sLogMessage = sLogMsg;
2625 dlg.m_pathList = pathList;
2626 dlg.m_checkedPathList = selectedList;
2627 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2628 dlg.m_bAutoClose = autoClose;
2629 if (dlg.DoModal() == IDOK)
2631 if (dlg.m_pathList.GetCount()==0)
2632 return false;
2633 // if the user hasn't changed the list of selected items
2634 // we don't use that list. Because if we would use the list
2635 // of pre-checked items, the dialog would show different
2636 // checked items on the next startup: it would only try
2637 // to check the parent folder (which might not even show)
2638 // instead, we simply use an empty list and let the
2639 // default checking do its job.
2640 if (!dlg.m_pathList.IsEqual(pathList))
2641 selectedList = dlg.m_pathList;
2642 pathList = dlg.m_updatedPathList;
2643 sLogMsg = dlg.m_sLogMessage;
2644 bSelectFilesForCommit = true;
2646 if( dlg.m_bPushAfterCommit )
2648 switch(dlg.m_PostCmd)
2650 case GIT_POST_CMD_DCOMMIT:
2651 CAppUtils::SVNDCommit();
2652 break;
2653 default:
2654 CAppUtils::Push();
2657 else if (dlg.m_bCreateTagAfterCommit)
2659 CAppUtils::CreateBranchTag(TRUE);
2662 // CGitProgressDlg progDlg;
2663 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2664 // if (parser.HasVal(_T("closeonend")))
2665 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2666 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2667 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2668 // progDlg.SetPathList(dlg.m_pathList);
2669 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2670 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2671 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2672 // progDlg.SetItemCount(dlg.m_itemsCount);
2673 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2674 // progDlg.DoModal();
2675 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2676 // err = (DWORD)progDlg.DidErrorsOccur();
2677 // bFailed = progDlg.DidErrorsOccur();
2678 // bRet = progDlg.DidErrorsOccur();
2679 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2680 // if (DWORD(bFailRepeat)==0)
2681 // bFailed = false; // do not repeat if the user chose not to in the settings.
2684 return true;
2688 BOOL CAppUtils::SVNDCommit()
2690 CSVNDCommitDlg dcommitdlg;
2691 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2692 if (gitSetting == _T("")) {
2693 if (dcommitdlg.DoModal() != IDOK)
2695 return false;
2697 else
2699 if (dcommitdlg.m_remember)
2701 if (dcommitdlg.m_rmdir)
2703 gitSetting = _T("true");
2705 else
2707 gitSetting = _T("false");
2709 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2711 CString msg;
2712 msg.Format(IDS_PROC_SAVECONFIGFAILED, _T("svn.rmdir"), gitSetting);
2713 CMessageBox::Show(NULL, msg, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
2719 BOOL IsStash = false;
2720 if(!g_Git.CheckCleanWorkTree())
2722 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
2724 CSysProgressDlg sysProgressDlg;
2725 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2726 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2727 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2728 sysProgressDlg.SetShowProgressBar(false);
2729 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2730 sysProgressDlg.ShowModeless((HWND)NULL, true);
2732 CString cmd,out;
2733 cmd=_T("git.exe stash");
2734 if (g_Git.Run(cmd, &out, CP_UTF8))
2736 sysProgressDlg.Stop();
2737 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2738 return false;
2740 sysProgressDlg.Stop();
2742 IsStash =true;
2744 else
2746 return false;
2750 CProgressDlg progress;
2751 if (dcommitdlg.m_rmdir)
2753 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2755 else
2757 progress.m_GitCmd=_T("git.exe svn dcommit");
2759 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2761 if( IsStash)
2763 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2765 CSysProgressDlg sysProgressDlg;
2766 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
2767 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
2768 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
2769 sysProgressDlg.SetShowProgressBar(false);
2770 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
2771 sysProgressDlg.ShowModeless((HWND)NULL, true);
2773 CString cmd,out;
2774 cmd=_T("git.exe stash pop");
2775 if (g_Git.Run(cmd, &out, CP_UTF8))
2777 sysProgressDlg.Stop();
2778 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2779 return false;
2781 sysProgressDlg.Stop();
2783 else
2785 return false;
2788 return TRUE;
2790 return FALSE;
2793 static void MergeCallback(CProgressDlg *dlg, void * /*caller*/, int result)
2795 if (result)
2797 dlg->m_PostCmdList.RemoveAll();
2799 CTGitPathList list;
2800 if (!g_Git.ListConflictFile(list) && list.GetCount() > 0)
2802 // there are conflict files
2803 dlg->m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROGRS_CMD_RESOLVE)));
2808 BOOL CAppUtils::Merge(CString *commit)
2810 if (!CheckUserData())
2811 return FALSE;
2813 CMergeDlg dlg;
2814 if(commit)
2815 dlg.m_initialRefName = *commit;
2817 if(dlg.DoModal()==IDOK)
2819 CString cmd;
2820 CString args;
2822 if(dlg.m_bNoFF)
2823 args += _T(" --no-ff");
2825 if(dlg.m_bSquash)
2826 args += _T(" --squash");
2828 if(dlg.m_bNoCommit)
2829 args += _T(" --no-commit");
2831 if (dlg.m_bLog)
2833 CString fmt;
2834 fmt.Format(_T(" --log=%d"), dlg.m_nLog);
2835 args += fmt;
2838 if (!dlg.m_MergeStrategy.IsEmpty())
2840 args += _T(" --strategy=") + dlg.m_MergeStrategy;
2841 if (!dlg.m_StrategyOption.IsEmpty())
2843 args += _T(" --strategy-option=") + dlg.m_StrategyOption;
2844 if (!dlg.m_StrategyParam.IsEmpty())
2845 args += _T("=") + dlg.m_StrategyParam;
2849 if(!dlg.m_strLogMesage.IsEmpty())
2851 CString logmsg = dlg.m_strLogMesage;
2852 logmsg.Replace(_T("\""), _T("\\\""));
2853 args += _T(" -m \"") + logmsg + _T("\"");
2855 cmd.Format(_T("git.exe merge %s %s"), args, g_Git.FixBranchName(dlg.m_VersionName));
2857 CProgressDlg Prodlg;
2858 Prodlg.m_GitCmd = cmd;
2860 if (dlg.m_bNoCommit)
2861 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_MENUCOMMIT)));
2862 else if (dlg.m_bIsBranch)
2863 Prodlg.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_REMOVEBRANCH)));
2865 Prodlg.m_PostCmdCallback = MergeCallback;
2867 INT_PTR ret = Prodlg.DoModal();
2868 if (Prodlg.m_GitStatus != 0 && ret == IDC_PROGRESS_BUTTON1)
2870 CTGitPathList pathlist;
2871 CTGitPathList selectedlist;
2872 pathlist.AddPath(g_Git.m_CurrentDir);
2873 bool bSelectFilesForCommit = !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE));
2874 CString str;
2875 CAppUtils::Commit(CString(), false, str, pathlist, selectedlist, bSelectFilesForCommit);
2877 else if (ret == IDC_PROGRESS_BUTTON1)
2879 if (dlg.m_bNoCommit)
2881 CString sLogMsg;
2882 CTGitPathList pathList;
2883 CTGitPathList selectedList;
2884 return Commit(_T(""), TRUE, sLogMsg, pathList, selectedList, true);
2886 else if (dlg.m_bIsBranch)
2888 CString msg;
2889 msg.Format(IDS_PROC_DELETEBRANCHTAG, dlg.m_VersionName);
2890 if (CMessageBox::Show(NULL, msg, _T("TortoiseGit"), 2, IDI_QUESTION, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON))) == 1)
2892 CString cmd, out;
2893 cmd.Format(_T("git.exe branch -D -- %s"), dlg.m_VersionName);
2894 if (g_Git.Run(cmd, &out, CP_UTF8))
2895 MessageBox(NULL, out, _T("TortoiseGit"), MB_OK);
2900 return !Prodlg.m_GitStatus;
2902 return false;
2905 void CAppUtils::EditNote(GitRev *rev)
2907 if (!CheckUserData())
2908 return;
2910 CInputDlg dlg;
2911 dlg.m_sHintText = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2912 dlg.m_sInputText = rev->m_Notes;
2913 dlg.m_sTitle = CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES));
2914 //dlg.m_pProjectProperties = &m_ProjectProperties;
2915 dlg.m_bUseLogWidth = true;
2916 if(dlg.DoModal() == IDOK)
2918 CString cmd,output;
2919 cmd=_T("notes add -f -F \"");
2921 CString tempfile=::GetTempFile();
2922 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2923 cmd += tempfile;
2924 cmd += _T("\" ");
2925 cmd += rev->m_CommitHash.ToString();
2929 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd, CP_UTF8).GetBuffer()))
2931 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2934 else
2936 rev->m_Notes = dlg.m_sInputText;
2938 }catch(...)
2940 CMessageBox::Show(NULL, IDS_PROC_FAILEDSAVINGNOTES, IDS_APPNAME, MB_OK | MB_ICONERROR);
2942 CFile::Remove(tempfile);
2947 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2949 CString cmd;
2950 CString versiondebug;
2951 CString version;
2953 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2954 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2956 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2958 __int64 time=0;
2959 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2961 if((DWORD)time == regTime)
2963 return regVersion;
2967 if(versionstr)
2968 version = *versionstr;
2969 else
2971 CString err;
2972 cmd = _T("git.exe --version");
2973 if (g_Git.Run(cmd, &version, &err, CP_UTF8))
2975 CMessageBox::Show(NULL, _T("git.exe not correctly set up (") + err + _T(")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\"."), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2976 return false;
2980 int start=0;
2981 int ver = 0;
2983 versiondebug = version;
2987 CString str=version.Tokenize(_T("."), start);
2988 int space = str.ReverseFind(_T(' '));
2989 str = str.Mid(space+1,start);
2990 ver = _ttol(str);
2991 ver <<=24;
2993 version = version.Mid(start);
2994 start = 0;
2996 str = version.Tokenize(_T("."), start);
2998 ver |= (_ttol(str) & 0xFF) << 16;
3000 str = version.Tokenize(_T("."), start);
3001 ver |= (_ttol(str) & 0xFF) << 8;
3003 str = version.Tokenize(_T("."), start);
3004 ver |= (_ttol(str) & 0xFF);
3006 catch(...)
3008 if (!ver)
3010 CMessageBox::Show(NULL, _T("Could not parse git.exe version number: \"") + versiondebug + _T("\""), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3011 return false;
3015 regTime = time&0xFFFFFFFF;
3016 regVersion = ver;
3018 return ver;
3021 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
3023 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
3025 CAutoLibrary hShell = AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3027 if (hShell.IsValid()) {
3028 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
3029 if (pfnSHGPSFW) {
3030 IPropertyStore *pps;
3031 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
3032 if (SUCCEEDED(hr)) {
3033 PROPVARIANT var;
3034 var.vt = VT_BOOL;
3035 var.boolVal = VARIANT_TRUE;
3036 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
3037 pps->Release();
3043 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
3045 ASSERT(dialogname.GetLength() < 70);
3046 ASSERT(urlorpath.GetLength() < MAX_PATH);
3047 WCHAR pathbuf[MAX_PATH] = {0};
3049 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
3051 wcscat_s(pathbuf, L" - ");
3052 wcscat_s(pathbuf, dialogname);
3053 wcscat_s(pathbuf, L" - ");
3054 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
3055 SetWindowText(hWnd, pathbuf);
3058 bool CAppUtils::BisectStart(CString lastGood, CString firstBad, bool autoClose)
3060 if (!g_Git.CheckCleanWorkTree())
3062 if (CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH, IDS_APPNAME, 1, IDI_QUESTION, IDS_STASHBUTTON, IDS_ABORTBUTTON) == 1)
3064 CSysProgressDlg sysProgressDlg;
3065 sysProgressDlg.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME)));
3066 sysProgressDlg.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING)));
3067 sysProgressDlg.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT)));
3068 sysProgressDlg.SetShowProgressBar(false);
3069 sysProgressDlg.SetCancelMsg(IDS_PROGRS_INFOFAILED);
3070 sysProgressDlg.ShowModeless((HWND)NULL, true);
3072 CString cmd, out;
3073 cmd = _T("git.exe stash");
3074 if (g_Git.Run(cmd, &out, CP_UTF8))
3076 sysProgressDlg.Stop();
3077 CMessageBox::Show(NULL, out, _T("TortoiseGit"), MB_OK);
3078 return false;
3080 sysProgressDlg.Stop();
3082 else
3083 return false;
3086 CBisectStartDlg bisectStartDlg;
3088 if (!lastGood.IsEmpty())
3089 bisectStartDlg.m_sLastGood = lastGood;
3090 if (!firstBad.IsEmpty())
3091 bisectStartDlg.m_sFirstBad = firstBad;
3093 if (bisectStartDlg.DoModal() == IDOK)
3095 CProgressDlg progress;
3096 theApp.m_pMainWnd = &progress;
3097 progress.m_bAutoCloseOnSuccess = autoClose;
3098 progress.m_GitCmdList.push_back(_T("git.exe bisect start"));
3099 progress.m_GitCmdList.push_back(_T("git.exe bisect good ") + bisectStartDlg.m_LastGoodRevision);
3100 progress.m_GitCmdList.push_back(_T("git.exe bisect bad ") + bisectStartDlg.m_FirstBadRevision);
3102 CTGitPath path(g_Git.m_CurrentDir);
3104 if (path.HasSubmodules())
3105 progress.m_PostCmdList.Add(CString(MAKEINTRESOURCE(IDS_PROC_SUBMODULESUPDATE)));
3107 INT_PTR ret = progress.DoModal();
3108 if (path.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
3110 CString sCmd;
3111 sCmd.Format(_T("/command:subupdate /bkpath:\"%s\""), g_Git.m_CurrentDir);
3113 CAppUtils::RunTortoiseGitProc(sCmd);
3114 return true;
3116 else if (ret == IDOK)
3117 return true;
3120 return false;
3123 int CAppUtils::Git2GetUserPassword(git_cred **out, const char *url, const char *username_from_url, unsigned int /*allowed_types*/, void * /*payload*/)
3125 CUserPassword dlg;
3126 dlg.m_URL = CUnicodeUtils::GetUnicode(url, CP_UTF8);
3127 if (username_from_url)
3128 dlg.m_UserName = CUnicodeUtils::GetUnicode(username_from_url, CP_UTF8);
3130 CStringA username, password;
3131 if (dlg.DoModal() == IDOK)
3133 username = CUnicodeUtils::GetMulti(dlg.m_UserName, CP_UTF8);
3134 password = CUnicodeUtils::GetMulti(dlg.m_Password, CP_UTF8);
3135 return git_cred_userpass_plaintext_new(out, username, password);
3137 return -1;