some spaces-tabs code cleanup
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob13e1fb991c82bb9d779f7ab04707997a5dcdc85c
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - 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 "SVNProgressDlg.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"
61 CAppUtils::CAppUtils(void)
65 CAppUtils::~CAppUtils(void)
69 int CAppUtils::StashApply(CString ref)
71 CString cmd,out;
72 cmd=_T("git.exe stash apply ");
73 cmd+=ref;
75 if(g_Git.Run(cmd,&out,CP_ACP))
77 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
79 }else
81 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
82 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
84 CChangedDlg dlg;
85 dlg.m_pathList.AddPath(CTGitPath());
86 dlg.DoModal();
88 return 0;
90 return -1;
93 int CAppUtils::StashPop()
95 CString cmd,out;
96 cmd=_T("git.exe stash pop ");
98 if(g_Git.Run(cmd,&out,CP_ACP))
100 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
102 }else
104 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
105 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
107 CChangedDlg dlg;
108 dlg.m_pathList.AddPath(CTGitPath());
109 dlg.DoModal();
111 return 0;
113 return -1;
116 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
118 #if 0
119 GitProperties props(file, GitRev::REV_WC, false);
120 for (int i = 0; i < props.GetCount(); ++i)
122 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
124 mimetype = props.GetItemValue(i).c_str();
125 return true;
128 #endif
129 return false;
132 BOOL CAppUtils::StartExtMerge(
133 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
134 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
137 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
138 CString ext = mergedfile.GetFileExtension();
139 CString com = regCom;
140 bool bInternal = false;
142 CString mimetype;
143 if (ext != "")
145 // is there an extension specific merge tool?
146 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
147 if (CString(mergetool) != "")
149 com = mergetool;
152 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
154 // is there a mime type specific merge tool?
155 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
156 if (CString(mergetool) != "")
158 com = mergetool;
162 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
164 // use TortoiseMerge
165 bInternal = true;
166 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
167 com = tortoiseMergePath;
168 if (com.IsEmpty())
170 com = CPathUtils::GetAppDirectory();
171 com += _T("TortoiseMerge.exe");
173 com = _T("\"") + com + _T("\"");
174 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
175 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
177 // check if the params are set. If not, just add the files to the command line
178 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
180 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
181 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
182 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
183 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
185 if (basefile.IsEmpty())
187 com.Replace(_T("/base:%base"), _T(""));
188 com.Replace(_T("%base"), _T(""));
190 else
191 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
192 if (theirfile.IsEmpty())
194 com.Replace(_T("/theirs:%theirs"), _T(""));
195 com.Replace(_T("%theirs"), _T(""));
197 else
198 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
199 if (yourfile.IsEmpty())
201 com.Replace(_T("/mine:%mine"), _T(""));
202 com.Replace(_T("%mine"), _T(""));
204 else
205 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
206 if (mergedfile.IsEmpty())
208 com.Replace(_T("/merged:%merged"), _T(""));
209 com.Replace(_T("%merged"), _T(""));
211 else
212 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
213 if (basename.IsEmpty())
215 if (basefile.IsEmpty())
217 com.Replace(_T("/basename:%bname"), _T(""));
218 com.Replace(_T("%bname"), _T(""));
220 else
222 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
225 else
226 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
227 if (theirname.IsEmpty())
229 if (theirfile.IsEmpty())
231 com.Replace(_T("/theirsname:%tname"), _T(""));
232 com.Replace(_T("%tname"), _T(""));
234 else
236 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
239 else
240 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
241 if (yourname.IsEmpty())
243 if (yourfile.IsEmpty())
245 com.Replace(_T("/minename:%yname"), _T(""));
246 com.Replace(_T("%yname"), _T(""));
248 else
250 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
253 else
254 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
255 if (mergedname.IsEmpty())
257 if (mergedfile.IsEmpty())
259 com.Replace(_T("/mergedname:%mname"), _T(""));
260 com.Replace(_T("%mname"), _T(""));
262 else
264 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
267 else
268 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
270 if ((bReadOnly)&&(bInternal))
271 com += _T(" /readonly");
273 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
275 return FALSE;
278 return TRUE;
281 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
283 CString viewer;
284 // use TortoiseMerge
285 viewer = CPathUtils::GetAppDirectory();
286 viewer += _T("TortoiseMerge.exe");
288 viewer = _T("\"") + viewer + _T("\"");
289 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
290 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
291 if (bReversed)
292 viewer += _T(" /reversedpatch");
293 if (!sOriginalDescription.IsEmpty())
294 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
295 if (!sPatchedDescription.IsEmpty())
296 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
297 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
299 return FALSE;
301 return TRUE;
304 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
306 // Is there a mime type specific diff tool?
307 CString mimetype;
308 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
310 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
311 if (!difftool.IsEmpty())
312 return difftool;
315 // Is there an extension specific diff tool?
316 CString ext = file2.GetFileExtension().MakeLower();
317 if (!ext.IsEmpty())
319 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
320 if (!difftool.IsEmpty())
321 return difftool;
322 // Maybe we should use TortoiseIDiff?
323 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
324 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
325 (ext == _T(".png")) || (ext == _T(".ico")) ||
326 (ext == _T(".dib")) || (ext == _T(".emf")))
328 return
329 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
330 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
334 // Finally, pick a generic external diff tool
335 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
336 return difftool;
339 bool CAppUtils::StartExtDiff(
340 const CString& file1, const CString& file2,
341 const CString& sName1, const CString& sName2,
342 const DiffFlags& flags)
344 CString viewer;
346 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
347 if (!flags.bBlame || !(DWORD)blamediff)
349 viewer = PickDiffTool(file1, file2);
350 // If registry entry for a diff program is commented out, use TortoiseMerge.
351 bool bCommentedOut = viewer.Left(1) == _T("#");
352 if (flags.bAlternativeTool)
354 // Invert external vs. internal diff tool selection.
355 if (bCommentedOut)
356 viewer.Delete(0); // uncomment
357 else
358 viewer = "";
360 else if (bCommentedOut)
361 viewer = "";
364 bool bInternal = viewer.IsEmpty();
365 if (bInternal)
367 viewer =
368 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
369 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
370 if (flags.bBlame)
371 viewer += _T(" /blame");
373 // check if the params are set. If not, just add the files to the command line
374 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
376 viewer += _T(" \"")+file1+_T("\"");
377 viewer += _T(" \"")+file2+_T("\"");
379 if (viewer.Find(_T("%base")) >= 0)
381 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
383 if (viewer.Find(_T("%mine")) >= 0)
385 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
388 if (sName1.IsEmpty())
389 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
390 else
391 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
393 if (sName2.IsEmpty())
394 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
395 else
396 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
398 if (flags.bReadOnly && bInternal)
399 viewer += _T(" /readonly");
401 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
404 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
406 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
407 CString viewer = diffpropsexe;
408 bool bInternal = false;
409 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
411 //no registry entry (or commented out) for a diff program
412 //use TortoiseMerge
413 bInternal = true;
414 viewer = CPathUtils::GetAppDirectory();
415 viewer += _T("TortoiseMerge.exe");
416 viewer = _T("\"") + viewer + _T("\"");
417 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
419 // check if the params are set. If not, just add the files to the command line
420 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
422 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
423 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
425 if (viewer.Find(_T("%base")) >= 0)
427 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
429 if (viewer.Find(_T("%mine")) >= 0)
431 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
434 if (sName1.IsEmpty())
435 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
436 else
437 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
439 if (sName2.IsEmpty())
440 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
441 else
442 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
444 if ((bReadOnly)&&(bInternal))
445 viewer += _T(" /readonly");
447 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
449 return FALSE;
451 return TRUE;
454 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
456 CString viewer;
457 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
458 viewer = v;
459 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
461 // use TortoiseUDiff
462 viewer = CPathUtils::GetAppDirectory();
463 viewer += _T("TortoiseUDiff.exe");
464 // enquote the path to TortoiseUDiff
465 viewer = _T("\"") + viewer + _T("\"");
466 // add the params
467 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
470 if (viewer.Find(_T("%1"))>=0)
472 if (viewer.Find(_T("\"%1\"")) >= 0)
473 viewer.Replace(_T("%1"), patchfile);
474 else
475 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
477 else
478 viewer += _T(" \"") + patchfile + _T("\"");
479 if (viewer.Find(_T("%title")) >= 0)
481 viewer.Replace(_T("%title"), title);
484 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
486 return FALSE;
488 return TRUE;
491 BOOL CAppUtils::StartTextViewer(CString file)
493 CString viewer;
494 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
495 viewer = txt;
496 viewer = viewer + _T("\\Shell\\Open\\Command\\");
497 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
498 viewer = txtexe;
500 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
501 TCHAR * buf = new TCHAR[len+1];
502 ExpandEnvironmentStrings(viewer, buf, len);
503 viewer = buf;
504 delete [] buf;
505 len = ExpandEnvironmentStrings(file, NULL, 0);
506 buf = new TCHAR[len+1];
507 ExpandEnvironmentStrings(file, buf, len);
508 file = buf;
509 delete [] buf;
510 file = _T("\"")+file+_T("\"");
511 if (viewer.IsEmpty())
513 OPENFILENAME ofn = {0}; // common dialog box structure
514 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
515 // Initialize OPENFILENAME
516 ofn.lStructSize = sizeof(OPENFILENAME);
517 ofn.hwndOwner = NULL;
518 ofn.lpstrFile = szFile;
519 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
520 CString sFilter;
521 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
522 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
523 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
524 // Replace '|' delimiters with '\0's
525 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
526 while (ptr != pszFilters)
528 if (*ptr == '|')
529 *ptr = '\0';
530 ptr--;
532 ofn.lpstrFilter = pszFilters;
533 ofn.nFilterIndex = 1;
534 ofn.lpstrFileTitle = NULL;
535 ofn.nMaxFileTitle = 0;
536 ofn.lpstrInitialDir = NULL;
537 CString temp;
538 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
539 CStringUtils::RemoveAccelerators(temp);
540 ofn.lpstrTitle = temp;
541 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
543 // Display the Open dialog box.
545 if (GetOpenFileName(&ofn)==TRUE)
547 delete [] pszFilters;
548 viewer = CString(ofn.lpstrFile);
550 else
552 delete [] pszFilters;
553 return FALSE;
556 if (viewer.Find(_T("\"%1\"")) >= 0)
558 viewer.Replace(_T("\"%1\""), file);
560 else if (viewer.Find(_T("%1")) >= 0)
562 viewer.Replace(_T("%1"), file);
564 else
566 viewer += _T(" ");
567 viewer += file;
570 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
572 return FALSE;
574 return TRUE;
577 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
579 DWORD length = 0;
580 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
581 if (hFile == INVALID_HANDLE_VALUE)
582 return TRUE;
583 length = ::GetFileSize(hFile, NULL);
584 ::CloseHandle(hFile);
585 if (length < 4)
586 return TRUE;
587 return FALSE;
591 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
593 LOGFONT logFont;
594 HDC hScreenDC = ::GetDC(NULL);
595 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
596 ::ReleaseDC(NULL, hScreenDC);
597 logFont.lfWidth = 0;
598 logFont.lfEscapement = 0;
599 logFont.lfOrientation = 0;
600 logFont.lfWeight = FW_NORMAL;
601 logFont.lfItalic = 0;
602 logFont.lfUnderline = 0;
603 logFont.lfStrikeOut = 0;
604 logFont.lfCharSet = DEFAULT_CHARSET;
605 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
606 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
607 logFont.lfQuality = DRAFT_QUALITY;
608 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
609 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
610 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
613 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
615 STARTUPINFO startup;
616 PROCESS_INFORMATION process;
617 memset(&startup, 0, sizeof(startup));
618 startup.cb = sizeof(startup);
619 memset(&process, 0, sizeof(process));
621 CString cleanCommandLine(sCommandLine);
623 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
625 if(idErrMessageFormat != 0)
627 LPVOID lpMsgBuf;
628 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
629 FORMAT_MESSAGE_FROM_SYSTEM |
630 FORMAT_MESSAGE_IGNORE_INSERTS,
631 NULL,
632 GetLastError(),
633 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
634 (LPTSTR) &lpMsgBuf,
636 NULL
638 CString temp;
639 temp.Format(idErrMessageFormat, lpMsgBuf);
640 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
641 LocalFree( lpMsgBuf );
643 return false;
646 if (bWaitForStartup)
648 WaitForInputIdle(process.hProcess, 10000);
651 CloseHandle(process.hThread);
652 CloseHandle(process.hProcess);
653 return true;
655 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
657 CString key,remote;
658 CString cmd,out;
659 if( pRemote == NULL)
661 remote=_T("origin");
662 }else
664 remote=*pRemote;
666 if(keyfile == NULL)
668 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
669 key = g_Git.GetConfigValue(cmd);
670 int start=0;
671 key = key.Tokenize(_T("\n"),start);
673 else
674 key=*keyfile;
676 if(key.IsEmpty())
677 return false;
679 CString proc=CPathUtils::GetAppDirectory();
680 proc += _T("pageant.exe \"");
681 proc += key;
682 proc += _T("\"");
684 CString tempfile = GetTempFile();
685 ::DeleteFile(tempfile);
687 proc +=_T(" -c \"");
688 proc += CPathUtils::GetAppDirectory();
689 proc += _T("touch.exe\"");
690 proc +=_T(" \"");
691 proc +=tempfile;
692 proc +=_T("\"");
694 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
695 if(!b)
696 return b;
698 int i=0;
699 while(!::PathFileExists(tempfile))
701 Sleep(100);
702 i++;
703 if(i>10*60*5)
704 break; //timeout 5 minutes
707 if( i== 10*60*5)
709 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
711 ::DeleteFile(tempfile);
712 return true;
714 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
716 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
717 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
718 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
721 CString sCmd;
722 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
724 LaunchApplication(sCmd, NULL, false);
725 return true;
727 bool CAppUtils::LaunchRemoteSetting()
729 CTGitPath path(g_Git.m_CurrentDir);
730 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
731 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
732 //dlg.SetTreeWidth(220);
733 dlg.m_DefaultPage = _T("gitremote");
735 dlg.DoModal();
736 dlg.HandleRestart();
737 return true;
740 * Launch the external blame viewer
742 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
744 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
745 viewer += _T("TortoiseGitBlame.exe");
746 viewer += _T("\" \"") + sBlameFile + _T("\"");
747 //viewer += _T(" \"") + sLogFile + _T("\"");
748 //viewer += _T(" \"") + sOriginalFile + _T("\"");
749 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
750 viewer += CString(_T(" /rev:"))+Rev;
751 viewer += _T(" ")+sParams;
753 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
756 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
758 CString sText;
759 if (pWnd == NULL)
760 return false;
761 bool bStyled = false;
762 pWnd->GetWindowText(sText);
763 // the rich edit control doesn't count the CR char!
764 // to be exact: CRLF is treated as one char.
765 sText.Remove('\r');
767 // style each line separately
768 int offset = 0;
769 int nNewlinePos;
772 nNewlinePos = sText.Find('\n', offset);
773 CString sLine = sText.Mid(offset);
774 if (nNewlinePos>=0)
775 sLine = sLine.Left(nNewlinePos-offset);
776 int start = 0;
777 int end = 0;
778 while (FindStyleChars(sLine, '*', start, end))
780 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
781 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
782 CHARFORMAT2 format;
783 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
784 format.cbSize = sizeof(CHARFORMAT2);
785 format.dwMask = CFM_BOLD;
786 format.dwEffects = CFE_BOLD;
787 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
788 bStyled = true;
789 start = end;
791 start = 0;
792 end = 0;
793 while (FindStyleChars(sLine, '^', start, end))
795 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
796 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
797 CHARFORMAT2 format;
798 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
799 format.cbSize = sizeof(CHARFORMAT2);
800 format.dwMask = CFM_ITALIC;
801 format.dwEffects = CFE_ITALIC;
802 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
803 bStyled = true;
804 start = end;
806 start = 0;
807 end = 0;
808 while (FindStyleChars(sLine, '_', start, end))
810 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
811 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
812 CHARFORMAT2 format;
813 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
814 format.cbSize = sizeof(CHARFORMAT2);
815 format.dwMask = CFM_UNDERLINE;
816 format.dwEffects = CFE_UNDERLINE;
817 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
818 bStyled = true;
819 start = end;
821 offset = nNewlinePos+1;
822 } while(nNewlinePos>=0);
823 return bStyled;
826 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
828 int i=start;
829 bool bFoundMarker = false;
830 // find a starting marker
831 while (sText[i] != 0)
833 if (sText[i] == stylechar)
835 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
836 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
838 start = i+1;
839 i++;
840 bFoundMarker = true;
841 break;
844 i++;
846 if (!bFoundMarker)
847 return false;
848 // find ending marker
849 bFoundMarker = false;
850 while (sText[i] != 0)
852 if (sText[i] == stylechar)
854 if ((IsCharAlphaNumeric(sText[i-1])) &&
855 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
857 end = i;
858 i++;
859 bFoundMarker = true;
860 break;
863 i++;
865 return bFoundMarker;
868 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
870 OPENFILENAME ofn = {0}; // common dialog box structure
871 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
872 ofn.lStructSize = sizeof(OPENFILENAME);
873 ofn.hwndOwner = hwndOwner;
874 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
875 ofn.lpstrFile = szFile;
876 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
877 CString sFilter;
878 TCHAR * pszFilters = NULL;
879 if (filter)
881 sFilter.LoadString(filter);
882 pszFilters = new TCHAR[sFilter.GetLength()+4];
883 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
884 // Replace '|' delimiters with '\0's
885 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
886 while (ptr != pszFilters)
888 if (*ptr == '|')
889 *ptr = '\0';
890 ptr--;
892 ofn.lpstrFilter = pszFilters;
894 ofn.nFilterIndex = 1;
895 ofn.lpstrFileTitle = NULL;
896 ofn.nMaxFileTitle = 0;
897 ofn.lpstrInitialDir = NULL;
898 CString temp;
899 if (title)
901 temp.LoadString(title);
902 CStringUtils::RemoveAccelerators(temp);
904 ofn.lpstrTitle = temp;
905 if (bOpen)
906 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
907 else
908 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
911 // Display the Open dialog box.
912 bool bRet = false;
913 if (bOpen)
915 bRet = !!GetOpenFileName(&ofn);
917 else
919 bRet = !!GetSaveFileName(&ofn);
921 if (bRet)
923 if (pszFilters)
924 delete [] pszFilters;
925 path = CString(ofn.lpstrFile);
926 if (filterindex)
927 *filterindex = ofn.nFilterIndex;
928 return true;
930 if (pszFilters)
931 delete [] pszFilters;
932 return false;
935 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
937 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
938 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
939 // create a bitmap from the icon
940 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
941 if (!hIcon)
942 return false;
944 RECT rect = {0};
945 rect.right = width;
946 rect.bottom = height;
947 HBITMAP bmp = NULL;
949 HWND desktop = ::GetDesktopWindow();
950 if (desktop)
952 HDC screen_dev = ::GetDC(desktop);
953 if (screen_dev)
955 // Create a compatible DC
956 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
957 if (dst_hdc)
959 // Create a new bitmap of icon size
960 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
961 if (bmp)
963 // Select it into the compatible DC
964 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
965 // Fill the background of the compatible DC with the given color
966 ::SetBkColor(dst_hdc, bkColor);
967 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
969 // Draw the icon into the compatible DC
970 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
971 ::SelectObject(dst_hdc, old_dst_bmp);
973 ::DeleteDC(dst_hdc);
976 ::ReleaseDC(desktop, screen_dev);
979 // Restore settings
980 DestroyIcon(hIcon);
982 if (bmp == NULL)
983 return false;
985 LVBKIMAGE lv;
986 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
987 lv.hbm = bmp;
988 lv.xOffsetPercent = 100;
989 lv.yOffsetPercent = 100;
990 ListView_SetBkImage(hListCtrl, &lv);
991 return true;
994 CString CAppUtils::GetProjectNameFromURL(CString url)
996 CString name;
997 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
998 (name.CompareNoCase(_T("tags"))==0) ||
999 (name.CompareNoCase(_T("trunk"))==0))
1001 name = url.Mid(url.ReverseFind('/')+1);
1002 url = url.Left(url.ReverseFind('/'));
1004 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1006 // a name of svn or svnroot indicates that it's not really the project name. In that
1007 // case, we try the first part of the URL
1008 // of course, this won't work in all cases (but it works for Google project hosting)
1009 url.Replace(_T("http://"), _T(""));
1010 url.Replace(_T("https://"), _T(""));
1011 url.Replace(_T("svn://"), _T(""));
1012 url.Replace(_T("svn+ssh://"), _T(""));
1013 url.TrimLeft(_T("/"));
1014 name = url.Left(url.Find('.'));
1016 return name;
1019 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1020 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1021 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1022 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1025 CString tempfile=GetTempFile();
1026 CString cmd;
1027 if(rev1 == GitRev::GetWorkingCopy())
1029 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1030 }else
1032 CString merge;
1033 if(bMerge)
1034 merge = _T("-c");
1036 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1039 if( !url1.IsEmpty() )
1041 cmd+=_T(" \"");
1042 cmd+=url1.GetGitPathString();
1043 cmd+=_T("\" ");
1045 g_Git.RunLogFile(cmd,tempfile);
1046 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1049 #if 0
1050 CString sCmd;
1051 sCmd.Format(_T("%s /command:showcompare /unified"),
1052 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1053 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1054 if (rev1.IsValid())
1055 sCmd += _T(" /revision1:") + rev1.ToString();
1056 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1057 if (rev2.IsValid())
1058 sCmd += _T(" /revision2:") + rev2.ToString();
1059 if (peg.IsValid())
1060 sCmd += _T(" /pegrevision:") + peg.ToString();
1061 if (headpeg.IsValid())
1062 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1064 if (bAlternateDiff)
1065 sCmd += _T(" /alternatediff");
1067 if (bIgnoreAncestry)
1068 sCmd += _T(" /ignoreancestry");
1070 if (hWnd)
1072 sCmd += _T(" /hwnd:");
1073 TCHAR buf[30];
1074 _stprintf_s(buf, 30, _T("%d"), hWnd);
1075 sCmd += buf;
1078 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1079 #endif
1080 return TRUE;
1084 bool CAppUtils::Export(CString *BashHash)
1086 bool bRet = false;
1088 // ask from where the export has to be done
1089 CExportDlg dlg;
1090 if(BashHash)
1091 dlg.m_Revision=*BashHash;
1093 if (dlg.DoModal() == IDOK)
1095 CString cmd;
1096 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1097 g_Git.FixBranchName(dlg.m_VersionName));
1099 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1100 CProgressDlg pro;
1101 pro.m_GitCmd=cmd;
1102 pro.m_LogFile=dlg.m_strExportDirectory;
1103 pro.DoModal();
1104 return TRUE;
1106 return bRet;
1109 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1111 CCreateBranchTagDlg dlg;
1112 dlg.m_bIsTag=IsTag;
1113 dlg.m_bSwitch=switch_new_brach;
1115 if(CommitHash)
1116 dlg.m_Base = *CommitHash;
1118 if(dlg.DoModal()==IDOK)
1120 CString cmd;
1121 CString force;
1122 CString track;
1123 if(dlg.m_bTrack)
1124 track=_T(" --track ");
1126 if(dlg.m_bForce)
1127 force=_T(" -f ");
1129 if(IsTag)
1131 CString sign;
1132 if(dlg.m_bSign)
1133 sign=_T("-s");
1135 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1136 track,
1137 force,
1138 sign,
1139 dlg.m_BranchTagName,
1140 g_Git.FixBranchName(dlg.m_VersionName)
1143 CString tempfile=::GetTempFile();
1144 if(!dlg.m_Message.Trim().IsEmpty())
1146 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1147 cmd += _T(" -F ")+tempfile;
1150 else
1152 cmd.Format(_T("git.exe branch %s %s %s %s"),
1153 track,
1154 force,
1155 dlg.m_BranchTagName,
1156 g_Git.FixBranchName(dlg.m_VersionName)
1159 CString out;
1160 if(g_Git.Run(cmd,&out,CP_UTF8))
1162 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1164 if( !IsTag && dlg.m_bSwitch )
1166 // it is a new branch and the user has requested to switch to it
1167 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1168 g_Git.Run(cmd,&out,CP_UTF8);
1169 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1172 return TRUE;
1174 return FALSE;
1177 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1179 CGitSwitchDlg dlg;
1180 if(CommitHash)
1181 dlg.m_Base=*CommitHash;
1182 if(!initialRefName.IsEmpty())
1183 dlg.m_initialRefName = initialRefName;
1185 if (dlg.DoModal() == IDOK)
1187 CString cmd;
1188 CString track;
1189 // CString base;
1190 CString force;
1191 CString branch;
1193 if(dlg.m_bBranch){
1194 if (dlg.m_bBranchOverride)
1196 branch.Format(_T("-B %s"),dlg.m_NewBranch);
1198 else
1200 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1203 if(dlg.m_bForce)
1204 force=_T("-f");
1205 if(dlg.m_bTrack)
1206 track=_T("--track");
1208 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1209 force,
1210 track,
1211 branch,
1212 g_Git.FixBranchName(dlg.m_VersionName));
1214 CProgressDlg progress;
1215 progress.m_bAutoCloseOnSuccess = autoclose;
1216 progress.m_GitCmd=cmd;
1217 if(progress.DoModal()==IDOK)
1218 return TRUE;
1221 return FALSE;
1224 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1226 CString ignorefile;
1227 ignorefile=g_Git.m_CurrentDir+_T("\\");
1229 if(IsMask)
1231 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1233 }else
1235 ignorefile+=_T("\\.gitignore");
1238 CStdioFile file;
1239 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1241 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1242 return FALSE;
1245 CString ignorelist;
1246 CString mask;
1249 //file.ReadString(ignorelist);
1250 file.SeekToEnd();
1251 for(int i=0;i<path.GetCount();i++)
1253 if(IsMask)
1255 mask=_T("*")+path[i].GetFileExtension();
1256 if(ignorelist.Find(mask)<0)
1257 ignorelist+=_T("\n")+mask;
1259 else
1261 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1264 file.WriteString(ignorelist);
1266 file.Close();
1268 }catch(...)
1270 file.Close();
1271 return FALSE;
1274 return TRUE;
1278 bool CAppUtils::GitReset(CString *CommitHash,int type)
1280 CResetDlg dlg;
1281 dlg.m_ResetType=type;
1282 dlg.m_ResetToVersion=*CommitHash;
1283 if (dlg.DoModal() == IDOK)
1285 CString cmd;
1286 CString type;
1287 switch(dlg.m_ResetType)
1289 case 0:
1290 type=_T("--soft");
1291 break;
1292 case 1:
1293 type=_T("--mixed");
1294 break;
1295 case 2:
1296 type=_T("--hard");
1297 break;
1298 default:
1299 type=_T("--mixed");
1300 break;
1302 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1304 CProgressDlg progress;
1305 progress.m_GitCmd=cmd;
1306 if(progress.DoModal()==IDOK)
1307 return TRUE;
1310 return FALSE;
1313 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1315 if(mode == FALSE)
1317 descript=_T("Deleted");
1318 return;
1320 if(base)
1322 descript=_T("Modified");
1323 return;
1325 descript=_T("Created");
1326 return;
1329 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1331 CString tempmergefile;
1334 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1335 CFile::Remove(tempmergefile);
1336 }catch(...)
1342 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1343 CFile::Remove(tempmergefile);
1344 }catch(...)
1350 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1351 CFile::Remove(tempmergefile);
1352 }catch(...)
1356 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1358 CString file;
1359 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1361 return file;
1364 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1366 bool bRet = false;
1368 CTGitPath merge=path;
1369 CTGitPath directory = merge.GetDirectory();
1371 // we have the conflicted file (%merged)
1372 // now look for the other required files
1373 //GitStatus stat;
1374 //stat.GetStatus(merge);
1375 //if (stat.status == NULL)
1376 // return false;
1378 BYTE_VECTOR vector;
1380 CString cmd;
1381 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1383 if(g_Git.Run(cmd,&vector))
1385 return FALSE;
1388 CTGitPathList list;
1389 list.ParserFromLsFile(vector);
1391 if(list.GetCount() == 0)
1392 return FALSE;
1394 CTGitPath theirs;
1395 CTGitPath mine;
1396 CTGitPath base;
1398 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1399 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1400 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1402 CString format;
1404 //format=_T("git.exe cat-file blob \":%d:%s\"");
1405 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1406 CFile tempfile;
1407 //create a empty file, incase stage is not three
1408 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1409 tempfile.Close();
1410 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1411 tempfile.Close();
1412 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1413 tempfile.Close();
1415 bool b_base=false, b_local=false, b_remote=false;
1417 for(int i=0;i<list.GetCount();i++)
1419 CString cmd;
1420 CString outfile;
1421 cmd.Empty();
1422 outfile.Empty();
1424 if( list[i].m_Stage == 1)
1426 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1427 b_base = true;
1428 outfile = base.GetWinPathString();
1431 if( list[i].m_Stage == 2 )
1433 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1434 b_local = true;
1435 outfile = mine.GetWinPathString();
1438 if( list[i].m_Stage == 3 )
1440 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1441 b_remote = true;
1442 outfile = theirs.GetWinPathString();
1444 CString output;
1445 if(!outfile.IsEmpty())
1446 if(!g_Git.Run(cmd,&output,CP_ACP))
1448 CString file;
1449 int start =0 ;
1450 file = output.Tokenize(_T("\t"), start);
1451 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1453 else
1455 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1459 if(b_local && b_remote )
1461 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1462 if( revertTheirMy )
1463 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1464 else
1465 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1468 else
1470 CFile::Remove(mine.GetWinPathString());
1471 CFile::Remove(theirs.GetWinPathString());
1472 CFile::Remove(base.GetWinPathString());
1474 CDeleteConflictDlg dlg;
1475 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1476 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1477 dlg.m_bShowModifiedButton=b_base;
1478 dlg.m_File=merge.GetGitPathString();
1479 if(dlg.DoModal() == IDOK)
1481 CString cmd,out;
1482 if(dlg.m_bIsDelete)
1484 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1485 }else
1486 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1488 if(g_Git.Run(cmd,&out,CP_ACP))
1490 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1491 return FALSE;
1493 return TRUE;
1495 else
1496 return FALSE;
1499 #if 0
1500 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1501 base, theirs, mine, merge);
1502 #endif
1503 #if 0
1504 if (stat.status->text_status == svn_wc_status_conflicted)
1506 // we have a text conflict, use our merge tool to resolve the conflict
1508 CTSVNPath theirs(directory);
1509 CTSVNPath mine(directory);
1510 CTSVNPath base(directory);
1511 bool bConflictData = false;
1513 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1515 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1516 bConflictData = true;
1518 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1520 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1521 bConflictData = true;
1523 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1525 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1526 bConflictData = true;
1528 else
1530 mine = merge;
1532 if (bConflictData)
1533 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1534 base, theirs, mine, merge);
1537 if (stat.status->prop_status == svn_wc_status_conflicted)
1539 // we have a property conflict
1540 CTSVNPath prej(directory);
1541 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1543 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1544 // there's a problem: the prej file contains a _description_ of the conflict, and
1545 // that description string might be translated. That means we have no way of parsing
1546 // the file to find out the conflicting values.
1547 // The only thing we can do: show a dialog with the conflict description, then
1548 // let the user either accept the existing property or open the property edit dialog
1549 // to manually change the properties and values. And a button to mark the conflict as
1550 // resolved.
1551 CEditPropConflictDlg dlg;
1552 dlg.SetPrejFile(prej);
1553 dlg.SetConflictedItem(merge);
1554 bRet = (dlg.DoModal() != IDCANCEL);
1558 if (stat.status->tree_conflict)
1560 // we have a tree conflict
1561 SVNInfo info;
1562 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1563 if (pInfoData)
1565 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1567 CTSVNPath theirs(directory);
1568 CTSVNPath mine(directory);
1569 CTSVNPath base(directory);
1570 bool bConflictData = false;
1572 if (pInfoData->treeconflict_theirfile)
1574 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1575 bConflictData = true;
1577 if (pInfoData->treeconflict_basefile)
1579 base.AppendPathString(pInfoData->treeconflict_basefile);
1580 bConflictData = true;
1582 if (pInfoData->treeconflict_myfile)
1584 mine.AppendPathString(pInfoData->treeconflict_myfile);
1585 bConflictData = true;
1587 else
1589 mine = merge;
1591 if (bConflictData)
1592 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1593 base, theirs, mine, merge);
1595 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1597 CString sConflictAction;
1598 CString sConflictReason;
1599 CString sResolveTheirs;
1600 CString sResolveMine;
1601 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1602 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1604 if (pInfoData->treeconflict_nodekind == svn_node_file)
1606 switch (pInfoData->treeconflict_operation)
1608 case svn_wc_operation_update:
1609 switch (pInfoData->treeconflict_action)
1611 case svn_wc_conflict_action_edit:
1612 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1613 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1614 break;
1615 case svn_wc_conflict_action_add:
1616 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1617 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1618 break;
1619 case svn_wc_conflict_action_delete:
1620 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1621 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1622 break;
1624 break;
1625 case svn_wc_operation_switch:
1626 switch (pInfoData->treeconflict_action)
1628 case svn_wc_conflict_action_edit:
1629 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1630 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1631 break;
1632 case svn_wc_conflict_action_add:
1633 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1634 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1635 break;
1636 case svn_wc_conflict_action_delete:
1637 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1638 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1639 break;
1641 break;
1642 case svn_wc_operation_merge:
1643 switch (pInfoData->treeconflict_action)
1645 case svn_wc_conflict_action_edit:
1646 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1647 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1648 break;
1649 case svn_wc_conflict_action_add:
1650 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1651 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1652 break;
1653 case svn_wc_conflict_action_delete:
1654 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1655 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1656 break;
1658 break;
1661 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1663 switch (pInfoData->treeconflict_operation)
1665 case svn_wc_operation_update:
1666 switch (pInfoData->treeconflict_action)
1668 case svn_wc_conflict_action_edit:
1669 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1670 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1671 break;
1672 case svn_wc_conflict_action_add:
1673 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1674 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1675 break;
1676 case svn_wc_conflict_action_delete:
1677 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1678 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1679 break;
1681 break;
1682 case svn_wc_operation_switch:
1683 switch (pInfoData->treeconflict_action)
1685 case svn_wc_conflict_action_edit:
1686 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1687 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1688 break;
1689 case svn_wc_conflict_action_add:
1690 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1691 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1692 break;
1693 case svn_wc_conflict_action_delete:
1694 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1695 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1696 break;
1698 break;
1699 case svn_wc_operation_merge:
1700 switch (pInfoData->treeconflict_action)
1702 case svn_wc_conflict_action_edit:
1703 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1704 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1705 break;
1706 case svn_wc_conflict_action_add:
1707 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1708 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1709 break;
1710 case svn_wc_conflict_action_delete:
1711 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1712 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1713 break;
1715 break;
1719 UINT uReasonID = 0;
1720 switch (pInfoData->treeconflict_reason)
1722 case svn_wc_conflict_reason_edited:
1723 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1724 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1725 break;
1726 case svn_wc_conflict_reason_obstructed:
1727 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1728 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1729 break;
1730 case svn_wc_conflict_reason_deleted:
1731 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1732 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1733 break;
1734 case svn_wc_conflict_reason_added:
1735 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1736 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1737 break;
1738 case svn_wc_conflict_reason_missing:
1739 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1740 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1741 break;
1742 case svn_wc_conflict_reason_unversioned:
1743 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1744 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1745 break;
1747 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1749 CTreeConflictEditorDlg dlg;
1750 dlg.SetConflictInfoText(sConflictReason);
1751 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1752 dlg.SetPath(treeConflictPath);
1753 INT_PTR dlgRet = dlg.DoModal();
1754 bRet = (dlgRet != IDCANCEL);
1758 #endif
1759 return bRet;
1763 * FUNCTION : FormatDateAndTime
1764 * DESCRIPTION : Generates a displayable string from a CTime object in
1765 * system short or long format or as a relative value
1766 * cTime - the time
1767 * option - DATE_SHORTDATE or DATE_LONGDATE
1768 * bIncluedeTime - whether to show time as well as date
1769 * bRelative - if true then relative time is shown if reasonable
1770 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1771 * rather than locale
1772 * RETURN : CString containing date/time
1774 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1775 bool bRelative /*=false*/)
1777 CString datetime;
1778 if ( bRelative )
1780 datetime = ToRelativeTimeString( cTime );
1782 else
1784 // should we use the locale settings for formatting the date/time?
1785 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1787 // yes
1788 SYSTEMTIME sysTime;
1789 cTime.GetAsSystemTime( sysTime );
1791 TCHAR buf[100];
1793 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1794 sizeof(buf)/sizeof(TCHAR)-1);
1795 datetime = buf;
1796 if ( bIncludeTime )
1798 datetime += _T(" ");
1799 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1800 datetime += buf;
1803 else
1805 // no, so fixed format
1806 if ( bIncludeTime )
1808 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1810 else
1812 datetime = cTime.Format(_T("%Y-%m-%d"));
1816 return datetime;
1820 * Converts a given time to a relative display string (relative to current time)
1821 * Given time must be in local timezone
1823 CString CAppUtils::ToRelativeTimeString(CTime time)
1825 CString answer;
1826 // convert to COleDateTime
1827 SYSTEMTIME sysTime;
1828 time.GetAsSystemTime( sysTime );
1829 COleDateTime oleTime( sysTime );
1830 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1831 return answer;
1835 * Generates a display string showing the relative time between the two given times as COleDateTimes
1837 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1839 CString answer;
1840 COleDateTimeSpan ts = RelativeTo - time;
1841 //years
1842 if(fabs(ts.GetTotalDays()) >= 3*365)
1844 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1846 //Months
1847 if(fabs(ts.GetTotalDays()) >= 60)
1849 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1850 return answer;
1852 //Weeks
1853 if(fabs(ts.GetTotalDays()) >= 14)
1855 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1856 return answer;
1858 //Days
1859 if(fabs(ts.GetTotalDays()) >= 2)
1861 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1862 return answer;
1864 //hours
1865 if(fabs(ts.GetTotalHours()) >= 2)
1867 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1868 return answer;
1870 //minutes
1871 if(fabs(ts.GetTotalMinutes()) >= 2)
1873 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1874 return answer;
1876 //seconds
1877 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1878 return answer;
1882 * Passed a value and two resource string ids
1883 * if count is 1 then FormatString is called with format_1 and the value
1884 * otherwise format_2 is used
1885 * the formatted string is returned
1887 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1889 CString answer;
1890 if ( count == 1 )
1892 answer.FormatMessage( format_1, count );
1894 else
1896 answer.FormatMessage( format_n, count );
1898 return answer;
1901 bool CAppUtils::IsSSHPutty()
1903 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1904 sshclient=sshclient.MakeLower();
1905 if(sshclient.Find(_T("plink.exe"),0)>=0)
1907 return true;
1909 return false;
1912 CString CAppUtils::GetClipboardLink()
1914 if (!OpenClipboard(NULL))
1915 return CString();
1917 CString sClipboardText;
1918 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1919 if (hglb)
1921 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1922 sClipboardText = CString(lpstr);
1923 GlobalUnlock(hglb);
1925 hglb = GetClipboardData(CF_UNICODETEXT);
1926 if (hglb)
1928 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1929 sClipboardText = lpstr;
1930 GlobalUnlock(hglb);
1932 CloseClipboard();
1934 if(!sClipboardText.IsEmpty())
1936 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1937 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1939 if(sClipboardText.Find( _T("http://")) == 0)
1940 return sClipboardText;
1942 if(sClipboardText.Find( _T("https://")) == 0)
1943 return sClipboardText;
1945 if(sClipboardText.Find( _T("git://")) == 0)
1946 return sClipboardText;
1948 if(sClipboardText.Find( _T("ssh://")) == 0)
1949 return sClipboardText;
1951 if(sClipboardText.GetLength()>=2)
1952 if( sClipboardText[1] == _T(':') )
1953 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1954 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1955 return sClipboardText;
1958 return CString(_T(""));
1961 CString CAppUtils::ChooseRepository(CString *path)
1963 CBrowseFolder browseFolder;
1964 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1966 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1967 CString strCloneDirectory;
1968 if(path)
1969 strCloneDirectory=*path;
1970 else
1972 strCloneDirectory = regLastResopitory;
1975 CString title;
1976 title.LoadString(IDS_CHOOSE_REPOSITORY);
1978 browseFolder.SetInfo(title);
1980 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1982 regLastResopitory = strCloneDirectory;
1983 return strCloneDirectory;
1985 else
1987 return CString();
1991 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1993 CSendMailDlg dlg;
1995 dlg.m_PathList = list;
1997 if(dlg.DoModal()==IDOK)
1999 if(dlg.m_PathList.GetCount() == 0)
2000 return FALSE;
2002 CGitProgressDlg progDlg;
2004 theApp.m_pMainWnd = &progDlg;
2005 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2007 progDlg.SetAutoClose(autoclose);
2009 progDlg.SetPathList(dlg.m_PathList);
2010 //ProjectProperties props;
2011 //props.ReadPropsPathList(dlg.m_pathList);
2012 //progDlg.SetProjectProperties(props);
2013 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2015 DWORD flags =0;
2016 if(dlg.m_bAttachment)
2017 flags |= SENDMAIL_ATTACHMENT;
2018 if(dlg.m_bCombine)
2019 flags |= SENDMAIL_COMBINED;
2020 if(dlg.m_bUseMAPI)
2021 flags |= SENDMAIL_MAPI;
2023 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2025 progDlg.DoModal();
2027 return true;
2029 return false;
2032 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2034 CTGitPathList list;
2035 CString log=formatpatchoutput;
2036 int start=log.Find(cmd);
2037 if(start >=0)
2038 CString one=log.Tokenize(_T("\n"),start);
2039 else
2040 start = 0;
2042 while(start>=0)
2044 CString one=log.Tokenize(_T("\n"),start);
2045 one=one.Trim();
2046 if(one.IsEmpty() || one == _T("Success"))
2047 continue;
2048 one.Replace(_T('/'),_T('\\'));
2049 CTGitPath path;
2050 path.SetFromWin(one);
2051 list.AddPath(path);
2053 if (list.GetCount() > 0)
2055 return SendPatchMail(list, autoclose);
2057 else
2059 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2060 return true;
2065 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2067 CString cmd,output;
2068 int start=0;
2070 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2071 if(output.IsEmpty())
2073 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2074 if(output.IsEmpty())
2075 return CP_UTF8;
2077 int start=0;
2078 output=output.Tokenize(_T("\n"),start);
2079 return CUnicodeUtils::GetCPCode(output);
2081 }else
2083 output=output.Tokenize(_T("\n"),start);
2084 return CUnicodeUtils::GetCPCode(output);
2087 int CAppUtils::GetCommitTemplate(CString &temp)
2089 CString cmd,output;
2091 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2092 if( output.IsEmpty() )
2093 return -1;
2095 if( output.GetLength()<1)
2096 return -1;
2098 if( output[0] == _T('/'))
2100 if(output.GetLength()>=3)
2101 if(output[2] == _T('/'))
2103 output.GetBuffer()[0] = output[1];
2104 output.GetBuffer()[1] = _T(':');
2108 int start=0;
2109 output=output.Tokenize(_T("\n"),start);
2111 output.Replace(_T('/'),_T('\\'));
2115 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2116 CString str;
2117 while(file.ReadString(str))
2119 temp+=str+_T("\n");
2122 }catch(...)
2124 return -1;
2126 return 0;
2128 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2130 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2131 CString cmd,output;
2132 int cp=CP_UTF8;
2134 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2135 if(output.IsEmpty())
2136 cp=CP_UTF8;
2138 int start=0;
2139 output=output.Tokenize(_T("\n"),start);
2140 cp=CUnicodeUtils::GetCPCode(output);
2142 int len=message.GetLength();
2144 char * buf;
2145 buf = new char[len*4 + 4];
2146 SecureZeroMemory(buf, (len*4 + 4));
2148 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2150 file.Write(buf,lengthIncTerminator-1);
2151 file.Close();
2152 delete buf;
2153 return 0;
2156 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2158 CPullFetchDlg dlg;
2159 dlg.m_PreSelectRemote = remoteName;
2160 dlg.m_bAllowRebase = allowRebase;
2161 dlg.m_IsPull=FALSE;
2163 if(dlg.DoModal()==IDOK)
2165 if(dlg.m_bAutoLoad)
2167 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2170 CString url;
2171 url=dlg.m_RemoteURL;
2172 CString cmd;
2173 CString arg;
2175 int ver = CAppUtils::GetMsysgitVersion();
2177 if(ver >= 0x01070203) //above 1.7.0.2
2178 arg = _T("--progress ");
2180 if (dlg.m_bPrune) {
2181 arg += _T("--prune ");
2184 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2185 CProgressDlg progress;
2187 progress.m_bAutoCloseOnSuccess = autoClose;
2189 if(!dlg.m_bRebase)
2191 progress.m_PostCmdList.Add(_T("&Rebase"));
2194 progress.m_GitCmd=cmd;
2195 int userResponse=progress.DoModal();
2197 if( (userResponse==IDC_PROGRESS_BUTTON1) || ( progress.m_GitStatus ==0 && dlg.m_bRebase) )
2199 while(1)
2201 CRebaseDlg dlg;
2202 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2203 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2204 int response = dlg.DoModal();
2205 if(response == IDOK)
2207 return TRUE;
2209 if(response == IDC_REBASE_POST_BUTTON )
2211 CString cmd,out;
2212 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2213 g_Git.m_CurrentDir,
2214 g_Git.FixBranchName(dlg.m_Upstream),
2215 g_Git.FixBranchName(dlg.m_Branch));
2216 if(g_Git.Run(cmd,&out,CP_ACP))
2218 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2219 return FALSE;
2222 CAppUtils::SendPatchMail(cmd,out);
2223 return TRUE;
2226 if(response == IDC_REBASE_POST_BUTTON +1 )
2227 continue;
2229 if(response == IDCANCEL)
2230 return FALSE;
2232 return TRUE;
2235 return FALSE;
2238 bool CAppUtils::Push(bool autoClose)
2240 CPushDlg dlg;
2241 CString error;
2242 DWORD exitcode = 0xFFFFFFFF;
2243 CTGitPathList list;
2244 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2245 if (CHooks::Instance().PrePush(list,exitcode, error))
2247 if (exitcode)
2249 CString temp;
2250 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2251 //ReportError(temp);
2252 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2253 return false;
2257 if(dlg.DoModal()==IDOK)
2259 CString cmd;
2260 CString arg;
2262 if(dlg.m_bAutoLoad)
2264 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2267 if(dlg.m_bPack)
2268 arg +=_T("--thin ");
2269 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2270 arg +=_T("--tags ");
2271 if(dlg.m_bForce)
2272 arg +=_T("--force ");
2274 int ver = CAppUtils::GetMsysgitVersion();
2276 if(ver >= 0x01070203) //above 1.7.0.2
2277 arg += _T("--progress ");
2279 if (dlg.m_bPushAllBranches)
2281 cmd.Format(_T("git.exe push --all %s \"%s\""),
2282 arg,
2283 dlg.m_URL);
2285 else
2287 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2288 arg,
2289 dlg.m_URL,
2290 dlg.m_BranchSourceName);
2291 if (!dlg.m_BranchRemoteName.IsEmpty())
2293 cmd += _T(":") + dlg.m_BranchRemoteName;
2297 CProgressDlg progress;
2298 progress.m_bAutoCloseOnSuccess=autoClose;
2299 progress.m_GitCmd=cmd;
2300 progress.m_PostCmdList.Add(_T("&Request pull"));
2301 progress.m_PostCmdList.Add(_T("Re&Push"));
2302 int ret = progress.DoModal();
2304 if(!progress.m_GitStatus)
2306 if (CHooks::Instance().PostPush(list,exitcode, error))
2308 if (exitcode)
2310 CString temp;
2311 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2312 //ReportError(temp);
2313 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2314 return false;
2317 if(ret == IDC_PROGRESS_BUTTON1)
2319 RequestPull(dlg.m_BranchRemoteName);
2321 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2323 Push();
2325 return TRUE;
2329 return FALSE;
2332 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2334 CRequestPullDlg dlg;
2335 dlg.m_RepositoryURL = repositoryUrl;
2336 dlg.m_EndRevision = endrevision;
2337 if (dlg.DoModal()==IDOK)
2339 CString cmd;
2340 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2342 CProgressDlg progress;
2343 progress.m_GitCmd=cmd;
2344 progress.DoModal();
2346 return true;
2349 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2351 CString strDir(szPath);
2352 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2354 strDir.AppendChar(_T('\\'));
2356 std::vector<CString> vPath;
2357 CString strTemp;
2358 bool bSuccess = false;
2360 for (int i=0;i<strDir.GetLength();++i)
2362 if (strDir.GetAt(i) != _T('\\'))
2364 strTemp.AppendChar(strDir.GetAt(i));
2366 else
2368 vPath.push_back(strTemp);
2369 strTemp.AppendChar(_T('\\'));
2373 std::vector<CString>::const_iterator vIter;
2374 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2376 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2379 return bSuccess;
2382 void CAppUtils::RemoveTrailSlash(CString &path)
2384 if(path.IsEmpty())
2385 return ;
2387 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2389 path=path.Left(path.GetLength()-1);
2390 if(path.IsEmpty())
2391 return;
2395 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2396 CTGitPathList &pathList,
2397 CTGitPathList &selectedList,
2398 bool bSelectFilesForCommit,
2399 bool autoClose)
2401 bool bFailed = true;
2403 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2405 if(CMessageBox::Show(NULL,_T("User name and email must be set before commit.\r\n Do you want to set these now?\r\n"),
2406 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2408 CTGitPath path(g_Git.m_CurrentDir);
2409 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2410 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2411 dlg.SetTreeWidth(220);
2412 dlg.m_DefaultPage = _T("gitconfig");
2414 dlg.DoModal();
2415 dlg.HandleRestart();
2417 }else
2418 return false;
2421 while (bFailed)
2423 bFailed = false;
2424 CCommitDlg dlg;
2425 dlg.m_sBugID = bugid;
2427 dlg.m_bWholeProject = bWholeProject;
2429 dlg.m_sLogMessage = sLogMsg;
2430 dlg.m_pathList = pathList;
2431 dlg.m_checkedPathList = selectedList;
2432 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2433 dlg.m_bAutoClose = autoClose;
2434 if (dlg.DoModal() == IDOK)
2436 if (dlg.m_pathList.GetCount()==0)
2437 return false;
2438 // if the user hasn't changed the list of selected items
2439 // we don't use that list. Because if we would use the list
2440 // of pre-checked items, the dialog would show different
2441 // checked items on the next startup: it would only try
2442 // to check the parent folder (which might not even show)
2443 // instead, we simply use an empty list and let the
2444 // default checking do its job.
2445 if (!dlg.m_pathList.IsEqual(pathList))
2446 selectedList = dlg.m_pathList;
2447 pathList = dlg.m_updatedPathList;
2448 sLogMsg = dlg.m_sLogMessage;
2449 bSelectFilesForCommit = true;
2451 if( dlg.m_bPushAfterCommit )
2453 switch(dlg.m_PostCmd)
2455 case GIT_POST_CMD_DCOMMIT:
2456 CAppUtils::SVNDCommit();
2457 break;
2458 default:
2459 CAppUtils::Push();
2462 // CGitProgressDlg progDlg;
2463 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2464 // if (parser.HasVal(_T("closeonend")))
2465 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2466 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2467 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2468 // progDlg.SetPathList(dlg.m_pathList);
2469 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2470 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2471 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2472 // progDlg.SetItemCount(dlg.m_itemsCount);
2473 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2474 // progDlg.DoModal();
2475 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2476 // err = (DWORD)progDlg.DidErrorsOccur();
2477 // bFailed = progDlg.DidErrorsOccur();
2478 // bRet = progDlg.DidErrorsOccur();
2479 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2480 // if (DWORD(bFailRepeat)==0)
2481 // bFailed = false; // do not repeat if the user chose not to in the settings.
2484 return true;
2488 BOOL CAppUtils::SVNDCommit()
2490 CSVNDCommitDlg dcommitdlg;
2491 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2492 if (gitSetting == _T("")) {
2493 if (dcommitdlg.DoModal() != IDOK)
2495 return false;
2497 else
2499 if (dcommitdlg.m_remember)
2501 if (dcommitdlg.m_rmdir)
2503 gitSetting = _T("true");
2505 else
2507 gitSetting = _T("false");
2509 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2511 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2517 BOOL IsStash = false;
2518 if(!g_Git.CheckCleanWorkTree())
2520 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2522 CString cmd,out;
2523 cmd=_T("git.exe stash");
2524 if(g_Git.Run(cmd,&out,CP_ACP))
2526 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2527 return false;
2529 IsStash =true;
2531 }else
2533 return false;
2537 CProgressDlg progress;
2538 if (dcommitdlg.m_rmdir)
2540 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2542 else
2544 progress.m_GitCmd=_T("git.exe svn dcommit");
2546 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2548 if( IsStash)
2550 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2552 CString cmd,out;
2553 cmd=_T("git.exe stash pop");
2554 if(g_Git.Run(cmd,&out,CP_ACP))
2556 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2557 return false;
2561 else
2563 return false;
2566 return TRUE;
2568 return FALSE;
2571 BOOL CAppUtils::Merge(CString *commit)
2573 CMergeDlg dlg;
2574 if(commit)
2575 dlg.m_initialRefName = *commit;
2577 if(dlg.DoModal()==IDOK)
2579 CString cmd;
2580 CString noff;
2581 CString squash;
2582 CString nocommit;
2583 CString msg;
2585 if(dlg.m_bNoFF)
2586 noff=_T("--no-ff");
2588 if(dlg.m_bSquash)
2589 squash=_T("--squash");
2591 if(dlg.m_bNoCommit)
2592 nocommit=_T("--no-commit");
2594 if(!dlg.m_strLogMesage.IsEmpty())
2596 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2598 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2599 msg,
2600 noff,
2601 squash,
2602 nocommit,
2603 g_Git.FixBranchName(dlg.m_VersionName));
2605 CProgressDlg Prodlg;
2606 Prodlg.m_GitCmd = cmd;
2608 Prodlg.DoModal();
2610 return !Prodlg.m_GitStatus;
2612 return false;
2615 void CAppUtils::EditNote(GitRev *rev)
2617 CInputDlg dlg;
2618 dlg.m_sHintText=_T("Edit Notes");
2619 dlg.m_sInputText = rev->m_Notes;
2620 dlg.m_sTitle=_T("Edit Notes");
2621 //dlg.m_pProjectProperties = &m_ProjectProperties;
2622 dlg.m_bUseLogWidth = true;
2623 if(dlg.DoModal() == IDOK)
2625 CString cmd,output;
2626 cmd=_T("notes add -f -F \"");
2628 CString tempfile=::GetTempFile();
2629 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2630 cmd+=tempfile;
2631 cmd+=_T("\" ");
2632 cmd+=rev->m_CommitHash.ToString();
2636 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2638 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2641 else
2643 rev->m_Notes = dlg.m_sInputText;
2645 }catch(...)
2647 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2649 CFile::Remove(tempfile);
2654 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2656 CString cmd;
2657 CString progressarg;
2658 CString version;
2660 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2661 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2663 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2665 __int64 time=0;
2666 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2668 if((DWORD)time == regTime)
2670 return regVersion;
2674 if(versionstr)
2675 version = *versionstr;
2676 else
2678 cmd = _T("git.exe --version");
2679 if(g_Git.Run(cmd, &version, CP_ACP))
2681 CMessageBox::Show(NULL,_T("git have not installed"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2682 return false;
2686 int start=0;
2687 int ver;
2689 CString str=version.Tokenize(_T("."),start);
2690 int space = str.ReverseFind(_T(' '));
2691 str=str.Mid(space+1,start);
2692 ver = _ttol(str);
2693 ver <<=24;
2695 version = version.Mid(start);
2696 start = 0;
2697 str = version.Tokenize(_T("."),start);
2699 ver |= (_ttol(str)&0xFF)<<16;
2701 str = version.Tokenize(_T("."),start);
2702 ver |= (_ttol(str)&0xFF)<<8;
2704 str = version.Tokenize(_T("."),start);
2705 ver |= (_ttol(str)&0xFF);
2707 regTime = time&0xFFFFFFFF;
2708 regVersion = ver;
2710 return ver;
2713 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2715 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2717 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2719 if (hShell) {
2720 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2721 if (pfnSHGPSFW) {
2722 IPropertyStore *pps;
2723 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2724 if (SUCCEEDED(hr)) {
2725 PROPVARIANT var;
2726 var.vt = VT_BOOL;
2727 var.boolVal = VARIANT_TRUE;
2728 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2729 pps->Release();
2732 FreeLibrary(hShell);
2736 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2738 ASSERT(dialogname.GetLength() < 70);
2739 ASSERT(urlorpath.GetLength() < MAX_PATH);
2740 WCHAR pathbuf[MAX_PATH] = {0};
2742 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2744 wcscat_s(pathbuf, L" - ");
2745 wcscat_s(pathbuf, dialogname);
2746 wcscat_s(pathbuf, L" - ");
2747 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2748 SetWindowText(hWnd, pathbuf);