Fixed issue #568: push using ssh private key with a password fails the first time
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobf76beb1475d8890d963427ecf6307d87d1cec939
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2003-2008 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 #include "StdAfx.h"
20 #include "resource.h"
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
23 #include "AppUtils.h"
24 //#include "GitProperties.h"
25 #include "StringUtils.h"
26 #include "MessageBox.h"
27 #include "Registry.h"
28 #include "TGitPath.h"
29 #include "Git.h"
30 //#include "RepositoryBrowser.h"
31 //#include "BrowseFolder.h"
32 #include "UnicodeUtils.h"
33 #include "ExportDlg.h"
34 #include "ProgressDlg.h"
35 #include "GitAdminDir.h"
36 #include "ProgressDlg.h"
37 #include "BrowseFolder.h"
38 #include "DirFileEnum.h"
39 #include "MessageBox.h"
40 #include "GitStatus.h"
41 #include "CreateBranchTagDlg.h"
42 #include "GitSwitchDlg.h"
43 #include "ResetDlg.h"
44 #include "DeleteConflictDlg.h"
45 #include "ChangedDlg.h"
46 #include "SendMailDlg.h"
47 #include "SVNProgressDlg.h"
48 #include "PushDlg.h"
49 #include "CommitDlg.h"
50 #include "MergeDlg.h"
51 #include "hooks.h"
52 #include "..\Settings\Settings.h"
53 #include "InputDlg.h"
55 CAppUtils::CAppUtils(void)
59 CAppUtils::~CAppUtils(void)
63 int CAppUtils::StashApply(CString ref)
65 CString cmd,out;
66 cmd=_T("git.exe stash apply ");
67 cmd+=ref;
69 if(g_Git.Run(cmd,&out,CP_ACP))
71 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
73 }else
75 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
76 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
78 CChangedDlg dlg;
79 dlg.m_pathList.AddPath(CTGitPath());
80 dlg.DoModal();
82 return 0;
84 return -1;
87 int CAppUtils::StashPop()
89 CString cmd,out;
90 cmd=_T("git.exe stash pop ");
92 if(g_Git.Run(cmd,&out,CP_ACP))
94 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
96 }else
98 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
99 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
101 CChangedDlg dlg;
102 dlg.m_pathList.AddPath(CTGitPath());
103 dlg.DoModal();
105 return 0;
107 return -1;
110 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
112 #if 0
113 GitProperties props(file, GitRev::REV_WC, false);
114 for (int i = 0; i < props.GetCount(); ++i)
116 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
118 mimetype = props.GetItemValue(i).c_str();
119 return true;
122 #endif
123 return false;
126 BOOL CAppUtils::StartExtMerge(
127 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
128 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
131 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
132 CString ext = mergedfile.GetFileExtension();
133 CString com = regCom;
134 bool bInternal = false;
136 CString mimetype;
137 if (ext != "")
139 // is there an extension specific merge tool?
140 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
141 if (CString(mergetool) != "")
143 com = mergetool;
146 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
148 // is there a mime type specific merge tool?
149 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
150 if (CString(mergetool) != "")
152 com = mergetool;
156 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
158 // use TortoiseMerge
159 bInternal = true;
160 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
161 com = tortoiseMergePath;
162 if (com.IsEmpty())
164 com = CPathUtils::GetAppDirectory();
165 com += _T("TortoiseMerge.exe");
167 com = _T("\"") + com + _T("\"");
168 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
169 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
171 // check if the params are set. If not, just add the files to the command line
172 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
174 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
175 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
176 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
177 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
179 if (basefile.IsEmpty())
181 com.Replace(_T("/base:%base"), _T(""));
182 com.Replace(_T("%base"), _T(""));
184 else
185 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
186 if (theirfile.IsEmpty())
188 com.Replace(_T("/theirs:%theirs"), _T(""));
189 com.Replace(_T("%theirs"), _T(""));
191 else
192 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
193 if (yourfile.IsEmpty())
195 com.Replace(_T("/mine:%mine"), _T(""));
196 com.Replace(_T("%mine"), _T(""));
198 else
199 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
200 if (mergedfile.IsEmpty())
202 com.Replace(_T("/merged:%merged"), _T(""));
203 com.Replace(_T("%merged"), _T(""));
205 else
206 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
207 if (basename.IsEmpty())
209 if (basefile.IsEmpty())
211 com.Replace(_T("/basename:%bname"), _T(""));
212 com.Replace(_T("%bname"), _T(""));
214 else
216 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
219 else
220 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
221 if (theirname.IsEmpty())
223 if (theirfile.IsEmpty())
225 com.Replace(_T("/theirsname:%tname"), _T(""));
226 com.Replace(_T("%tname"), _T(""));
228 else
230 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
233 else
234 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
235 if (yourname.IsEmpty())
237 if (yourfile.IsEmpty())
239 com.Replace(_T("/minename:%yname"), _T(""));
240 com.Replace(_T("%yname"), _T(""));
242 else
244 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
247 else
248 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
249 if (mergedname.IsEmpty())
251 if (mergedfile.IsEmpty())
253 com.Replace(_T("/mergedname:%mname"), _T(""));
254 com.Replace(_T("%mname"), _T(""));
256 else
258 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
261 else
262 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
264 if ((bReadOnly)&&(bInternal))
265 com += _T(" /readonly");
267 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
269 return FALSE;
272 return TRUE;
275 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
277 CString viewer;
278 // use TortoiseMerge
279 viewer = CPathUtils::GetAppDirectory();
280 viewer += _T("TortoiseMerge.exe");
282 viewer = _T("\"") + viewer + _T("\"");
283 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
284 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
285 if (bReversed)
286 viewer += _T(" /reversedpatch");
287 if (!sOriginalDescription.IsEmpty())
288 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
289 if (!sPatchedDescription.IsEmpty())
290 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
291 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
293 return FALSE;
295 return TRUE;
298 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
300 // Is there a mime type specific diff tool?
301 CString mimetype;
302 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
304 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
305 if (!difftool.IsEmpty())
306 return difftool;
309 // Is there an extension specific diff tool?
310 CString ext = file2.GetFileExtension().MakeLower();
311 if (!ext.IsEmpty())
313 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
314 if (!difftool.IsEmpty())
315 return difftool;
316 // Maybe we should use TortoiseIDiff?
317 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
318 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
319 (ext == _T(".png")) || (ext == _T(".ico")) ||
320 (ext == _T(".dib")) || (ext == _T(".emf")))
322 return
323 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
324 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
328 // Finally, pick a generic external diff tool
329 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
330 return difftool;
333 bool CAppUtils::StartExtDiff(
334 const CString& file1, const CString& file2,
335 const CString& sName1, const CString& sName2,
336 const DiffFlags& flags)
338 CString viewer;
340 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
341 if (!flags.bBlame || !(DWORD)blamediff)
343 viewer = PickDiffTool(file1, file2);
344 // If registry entry for a diff program is commented out, use TortoiseMerge.
345 bool bCommentedOut = viewer.Left(1) == _T("#");
346 if (flags.bAlternativeTool)
348 // Invert external vs. internal diff tool selection.
349 if (bCommentedOut)
350 viewer.Delete(0); // uncomment
351 else
352 viewer = "";
354 else if (bCommentedOut)
355 viewer = "";
358 bool bInternal = viewer.IsEmpty();
359 if (bInternal)
361 viewer =
362 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
363 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
364 if (flags.bBlame)
365 viewer += _T(" /blame");
367 // check if the params are set. If not, just add the files to the command line
368 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
370 viewer += _T(" \"")+file1+_T("\"");
371 viewer += _T(" \"")+file2+_T("\"");
373 if (viewer.Find(_T("%base")) >= 0)
375 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
377 if (viewer.Find(_T("%mine")) >= 0)
379 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
382 if (sName1.IsEmpty())
383 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
384 else
385 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
387 if (sName2.IsEmpty())
388 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
389 else
390 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
392 if (flags.bReadOnly && bInternal)
393 viewer += _T(" /readonly");
395 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
398 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
400 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
401 CString viewer = diffpropsexe;
402 bool bInternal = false;
403 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
405 //no registry entry (or commented out) for a diff program
406 //use TortoiseMerge
407 bInternal = true;
408 viewer = CPathUtils::GetAppDirectory();
409 viewer += _T("TortoiseMerge.exe");
410 viewer = _T("\"") + viewer + _T("\"");
411 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
413 // check if the params are set. If not, just add the files to the command line
414 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
416 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
417 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
419 if (viewer.Find(_T("%base")) >= 0)
421 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
423 if (viewer.Find(_T("%mine")) >= 0)
425 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
428 if (sName1.IsEmpty())
429 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
430 else
431 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
433 if (sName2.IsEmpty())
434 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
435 else
436 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
438 if ((bReadOnly)&&(bInternal))
439 viewer += _T(" /readonly");
441 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
443 return FALSE;
445 return TRUE;
448 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
450 CString viewer;
451 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
452 viewer = v;
453 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
455 // use TortoiseUDiff
456 viewer = CPathUtils::GetAppDirectory();
457 viewer += _T("TortoiseUDiff.exe");
458 // enquote the path to TortoiseUDiff
459 viewer = _T("\"") + viewer + _T("\"");
460 // add the params
461 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
464 if (viewer.Find(_T("%1"))>=0)
466 if (viewer.Find(_T("\"%1\"")) >= 0)
467 viewer.Replace(_T("%1"), patchfile);
468 else
469 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
471 else
472 viewer += _T(" \"") + patchfile + _T("\"");
473 if (viewer.Find(_T("%title")) >= 0)
475 viewer.Replace(_T("%title"), title);
478 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
480 return FALSE;
482 return TRUE;
485 BOOL CAppUtils::StartTextViewer(CString file)
487 CString viewer;
488 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
489 viewer = txt;
490 viewer = viewer + _T("\\Shell\\Open\\Command\\");
491 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
492 viewer = txtexe;
494 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
495 TCHAR * buf = new TCHAR[len+1];
496 ExpandEnvironmentStrings(viewer, buf, len);
497 viewer = buf;
498 delete [] buf;
499 len = ExpandEnvironmentStrings(file, NULL, 0);
500 buf = new TCHAR[len+1];
501 ExpandEnvironmentStrings(file, buf, len);
502 file = buf;
503 delete [] buf;
504 file = _T("\"")+file+_T("\"");
505 if (viewer.IsEmpty())
507 OPENFILENAME ofn = {0}; // common dialog box structure
508 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
509 // Initialize OPENFILENAME
510 ofn.lStructSize = sizeof(OPENFILENAME);
511 ofn.hwndOwner = NULL;
512 ofn.lpstrFile = szFile;
513 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
514 CString sFilter;
515 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
516 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
517 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
518 // Replace '|' delimiters with '\0's
519 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
520 while (ptr != pszFilters)
522 if (*ptr == '|')
523 *ptr = '\0';
524 ptr--;
526 ofn.lpstrFilter = pszFilters;
527 ofn.nFilterIndex = 1;
528 ofn.lpstrFileTitle = NULL;
529 ofn.nMaxFileTitle = 0;
530 ofn.lpstrInitialDir = NULL;
531 CString temp;
532 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
533 CStringUtils::RemoveAccelerators(temp);
534 ofn.lpstrTitle = temp;
535 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
537 // Display the Open dialog box.
539 if (GetOpenFileName(&ofn)==TRUE)
541 delete [] pszFilters;
542 viewer = CString(ofn.lpstrFile);
544 else
546 delete [] pszFilters;
547 return FALSE;
550 if (viewer.Find(_T("\"%1\"")) >= 0)
552 viewer.Replace(_T("\"%1\""), file);
554 else if (viewer.Find(_T("%1")) >= 0)
556 viewer.Replace(_T("%1"), file);
558 else
560 viewer += _T(" ");
561 viewer += file;
564 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
566 return FALSE;
568 return TRUE;
571 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
573 DWORD length = 0;
574 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
575 if (hFile == INVALID_HANDLE_VALUE)
576 return TRUE;
577 length = ::GetFileSize(hFile, NULL);
578 ::CloseHandle(hFile);
579 if (length < 4)
580 return TRUE;
581 return FALSE;
585 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
587 LOGFONT logFont;
588 HDC hScreenDC = ::GetDC(NULL);
589 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
590 ::ReleaseDC(NULL, hScreenDC);
591 logFont.lfWidth = 0;
592 logFont.lfEscapement = 0;
593 logFont.lfOrientation = 0;
594 logFont.lfWeight = FW_NORMAL;
595 logFont.lfItalic = 0;
596 logFont.lfUnderline = 0;
597 logFont.lfStrikeOut = 0;
598 logFont.lfCharSet = DEFAULT_CHARSET;
599 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
600 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
601 logFont.lfQuality = DRAFT_QUALITY;
602 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
603 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
604 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
607 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
609 STARTUPINFO startup;
610 PROCESS_INFORMATION process;
611 memset(&startup, 0, sizeof(startup));
612 startup.cb = sizeof(startup);
613 memset(&process, 0, sizeof(process));
615 CString cleanCommandLine(sCommandLine);
617 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
619 if(idErrMessageFormat != 0)
621 LPVOID lpMsgBuf;
622 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
623 FORMAT_MESSAGE_FROM_SYSTEM |
624 FORMAT_MESSAGE_IGNORE_INSERTS,
625 NULL,
626 GetLastError(),
627 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
628 (LPTSTR) &lpMsgBuf,
630 NULL
632 CString temp;
633 temp.Format(idErrMessageFormat, lpMsgBuf);
634 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
635 LocalFree( lpMsgBuf );
637 return false;
640 if (bWaitForStartup)
642 WaitForInputIdle(process.hProcess, 10000);
645 CloseHandle(process.hThread);
646 CloseHandle(process.hProcess);
647 return true;
649 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
651 CString key,remote;
652 CString cmd,out;
653 if( pRemote == NULL)
655 remote=_T("origin");
656 }else
658 remote=*pRemote;
660 if(keyfile == NULL)
662 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
663 g_Git.Run(cmd,&key,CP_ACP);
664 int start=0;
665 key = key.Tokenize(_T("\n"),start);
667 else
668 key=*keyfile;
670 if(key.IsEmpty())
671 return false;
673 CString proc=CPathUtils::GetAppDirectory();
674 proc += _T("pageant.exe \"");
675 proc += key;
676 proc += _T("\"");
678 CString tempfile = GetTempFile();
679 ::DeleteFile(tempfile);
681 proc +=_T(" -c \"");
682 proc += CPathUtils::GetAppDirectory();
683 proc += _T("touch.exe\"");
684 proc +=_T(" \"");
685 proc +=tempfile;
686 proc +=_T("\"");
688 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
689 if(!b)
690 return b;
692 int i=0;
693 while(!::PathFileExists(tempfile))
695 Sleep(100);
696 i++;
697 if(i>10*60*5)
698 break; //timeout 5 minutes
701 if( i== 10*60*5)
703 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
705 ::DeleteFile(tempfile);
706 return true;
708 bool CAppUtils::LaunchRemoteSetting()
710 CString proc=CPathUtils::GetAppDirectory();
711 proc += _T("TortoiseProc.exe /command:settings");
712 proc += _T(" /path:\"");
713 proc += g_Git.m_CurrentDir;
714 proc += _T("\" /page:gitremote");
715 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
718 * Launch the external blame viewer
720 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
722 CString viewer = CPathUtils::GetAppDirectory();
723 viewer += _T("TortoiseGitBlame.exe");
724 viewer += _T(" \"") + sBlameFile + _T("\"");
725 //viewer += _T(" \"") + sLogFile + _T("\"");
726 //viewer += _T(" \"") + sOriginalFile + _T("\"");
727 if(!Rev.IsEmpty())
728 viewer += CString(_T(" /rev:"))+Rev;
729 viewer += _T(" ")+sParams;
731 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
734 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
736 CString sText;
737 if (pWnd == NULL)
738 return false;
739 bool bStyled = false;
740 pWnd->GetWindowText(sText);
741 // the rich edit control doesn't count the CR char!
742 // to be exact: CRLF is treated as one char.
743 sText.Replace(_T("\r"), _T(""));
745 // style each line separately
746 int offset = 0;
747 int nNewlinePos;
750 nNewlinePos = sText.Find('\n', offset);
751 CString sLine = sText.Mid(offset);
752 if (nNewlinePos>=0)
753 sLine = sLine.Left(nNewlinePos-offset);
754 int start = 0;
755 int end = 0;
756 while (FindStyleChars(sLine, '*', start, end))
758 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
759 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
760 CHARFORMAT2 format;
761 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
762 format.cbSize = sizeof(CHARFORMAT2);
763 format.dwMask = CFM_BOLD;
764 format.dwEffects = CFE_BOLD;
765 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
766 bStyled = true;
767 start = end;
769 start = 0;
770 end = 0;
771 while (FindStyleChars(sLine, '^', start, end))
773 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
774 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
775 CHARFORMAT2 format;
776 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
777 format.cbSize = sizeof(CHARFORMAT2);
778 format.dwMask = CFM_ITALIC;
779 format.dwEffects = CFE_ITALIC;
780 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
781 bStyled = true;
782 start = end;
784 start = 0;
785 end = 0;
786 while (FindStyleChars(sLine, '_', start, end))
788 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
789 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
790 CHARFORMAT2 format;
791 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
792 format.cbSize = sizeof(CHARFORMAT2);
793 format.dwMask = CFM_UNDERLINE;
794 format.dwEffects = CFE_UNDERLINE;
795 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
796 bStyled = true;
797 start = end;
799 offset = nNewlinePos+1;
800 } while(nNewlinePos>=0);
801 return bStyled;
804 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
806 int i=start;
807 bool bFoundMarker = false;
808 // find a starting marker
809 while (sText[i] != 0)
811 if (sText[i] == stylechar)
813 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
814 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
816 start = i+1;
817 i++;
818 bFoundMarker = true;
819 break;
822 i++;
824 if (!bFoundMarker)
825 return false;
826 // find ending marker
827 bFoundMarker = false;
828 while (sText[i] != 0)
830 if (sText[i] == stylechar)
832 if ((IsCharAlphaNumeric(sText[i-1])) &&
833 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
835 end = i;
836 i++;
837 bFoundMarker = true;
838 break;
841 i++;
843 return bFoundMarker;
846 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
848 #if 0
849 CString strUrl;
850 combo.GetWindowText(strUrl);
851 strUrl.Replace('\\', '/');
852 strUrl.Replace(_T("%"), _T("%25"));
853 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
854 if (strUrl.Left(7) == _T("file://"))
856 CString strFile(strUrl);
857 Git::UrlToPath(strFile);
859 Git svn;
860 if (svn.IsRepository(CTGitPath(strFile)))
862 // browse repository - show repository browser
863 Git::preparePath(strUrl);
864 CRepositoryBrowser browser(strUrl, rev, pParent);
865 if (browser.DoModal() == IDOK)
867 combo.SetCurSel(-1);
868 combo.SetWindowText(browser.GetPath());
869 rev = browser.GetRevision();
870 return true;
873 else
875 // browse local directories
876 CBrowseFolder folderBrowser;
877 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
878 // remove the 'file:///' so the shell can recognize the local path
879 Git::UrlToPath(strUrl);
880 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
882 Git::PathToUrl(strUrl);
884 combo.SetCurSel(-1);
885 combo.SetWindowText(strUrl);
886 return true;
890 else if ((strUrl.Left(7) == _T("http://")
891 ||(strUrl.Left(8) == _T("https://"))
892 ||(strUrl.Left(6) == _T("svn://"))
893 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
895 // browse repository - show repository browser
896 CRepositoryBrowser browser(strUrl, rev, pParent);
897 if (browser.DoModal() == IDOK)
899 combo.SetCurSel(-1);
900 combo.SetWindowText(browser.GetPath());
901 rev = browser.GetRevision();
902 return true;
905 else
907 // browse local directories
908 CBrowseFolder folderBrowser;
909 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
910 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
912 Git::PathToUrl(strUrl);
914 combo.SetCurSel(-1);
915 combo.SetWindowText(strUrl);
916 return true;
919 #endif
920 return false;
923 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
925 OPENFILENAME ofn = {0}; // common dialog box structure
926 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
927 ofn.lStructSize = sizeof(OPENFILENAME);
928 ofn.hwndOwner = hwndOwner;
929 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
930 ofn.lpstrFile = szFile;
931 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
932 CString sFilter;
933 TCHAR * pszFilters = NULL;
934 if (filter)
936 sFilter.LoadString(filter);
937 pszFilters = new TCHAR[sFilter.GetLength()+4];
938 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
939 // Replace '|' delimiters with '\0's
940 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
941 while (ptr != pszFilters)
943 if (*ptr == '|')
944 *ptr = '\0';
945 ptr--;
947 ofn.lpstrFilter = pszFilters;
949 ofn.nFilterIndex = 1;
950 ofn.lpstrFileTitle = NULL;
951 ofn.nMaxFileTitle = 0;
952 ofn.lpstrInitialDir = NULL;
953 CString temp;
954 if (title)
956 temp.LoadString(title);
957 CStringUtils::RemoveAccelerators(temp);
959 ofn.lpstrTitle = temp;
960 if (bOpen)
961 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
962 else
963 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
966 // Display the Open dialog box.
967 bool bRet = false;
968 if (bOpen)
970 bRet = !!GetOpenFileName(&ofn);
972 else
974 bRet = !!GetSaveFileName(&ofn);
976 if (bRet)
978 if (pszFilters)
979 delete [] pszFilters;
980 path = CString(ofn.lpstrFile);
981 if (filterindex)
982 *filterindex = ofn.nFilterIndex;
983 return true;
985 if (pszFilters)
986 delete [] pszFilters;
987 return false;
990 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
992 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
993 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
994 // create a bitmap from the icon
995 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
996 if (!hIcon)
997 return false;
999 RECT rect = {0};
1000 rect.right = width;
1001 rect.bottom = height;
1002 HBITMAP bmp = NULL;
1004 HWND desktop = ::GetDesktopWindow();
1005 if (desktop)
1007 HDC screen_dev = ::GetDC(desktop);
1008 if (screen_dev)
1010 // Create a compatible DC
1011 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
1012 if (dst_hdc)
1014 // Create a new bitmap of icon size
1015 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
1016 if (bmp)
1018 // Select it into the compatible DC
1019 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
1020 // Fill the background of the compatible DC with the given color
1021 ::SetBkColor(dst_hdc, bkColor);
1022 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
1024 // Draw the icon into the compatible DC
1025 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
1026 ::SelectObject(dst_hdc, old_dst_bmp);
1028 ::DeleteDC(dst_hdc);
1031 ::ReleaseDC(desktop, screen_dev);
1034 // Restore settings
1035 DestroyIcon(hIcon);
1037 if (bmp == NULL)
1038 return false;
1040 LVBKIMAGE lv;
1041 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1042 lv.hbm = bmp;
1043 lv.xOffsetPercent = 100;
1044 lv.yOffsetPercent = 100;
1045 ListView_SetBkImage(hListCtrl, &lv);
1046 return true;
1049 CString CAppUtils::GetProjectNameFromURL(CString url)
1051 CString name;
1052 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1053 (name.CompareNoCase(_T("tags"))==0) ||
1054 (name.CompareNoCase(_T("trunk"))==0))
1056 name = url.Mid(url.ReverseFind('/')+1);
1057 url = url.Left(url.ReverseFind('/'));
1059 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1061 // a name of svn or svnroot indicates that it's not really the project name. In that
1062 // case, we try the first part of the URL
1063 // of course, this won't work in all cases (but it works for Google project hosting)
1064 url.Replace(_T("http://"), _T(""));
1065 url.Replace(_T("https://"), _T(""));
1066 url.Replace(_T("svn://"), _T(""));
1067 url.Replace(_T("svn+ssh://"), _T(""));
1068 url.TrimLeft(_T("/"));
1069 name = url.Left(url.Find('.'));
1071 return name;
1074 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1075 const CTGitPath& url2, const git_revnum_t& rev2,
1076 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1077 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1080 CString tempfile=GetTempFile();
1081 CString cmd;
1082 if(rev1 == GitRev::GetWorkingCopy())
1084 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1085 }else
1087 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1090 if( !url1.IsEmpty() )
1092 cmd+=_T(" \"");
1093 cmd+=url1.GetGitPathString();
1094 cmd+=_T("\" ");
1096 g_Git.RunLogFile(cmd,tempfile);
1097 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1100 #if 0
1101 CString sCmd;
1102 sCmd.Format(_T("%s /command:showcompare /unified"),
1103 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1104 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1105 if (rev1.IsValid())
1106 sCmd += _T(" /revision1:") + rev1.ToString();
1107 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1108 if (rev2.IsValid())
1109 sCmd += _T(" /revision2:") + rev2.ToString();
1110 if (peg.IsValid())
1111 sCmd += _T(" /pegrevision:") + peg.ToString();
1112 if (headpeg.IsValid())
1113 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1115 if (bAlternateDiff)
1116 sCmd += _T(" /alternatediff");
1118 if (bIgnoreAncestry)
1119 sCmd += _T(" /ignoreancestry");
1121 if (hWnd)
1123 sCmd += _T(" /hwnd:");
1124 TCHAR buf[30];
1125 _stprintf_s(buf, 30, _T("%d"), hWnd);
1126 sCmd += buf;
1129 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1130 #endif
1131 return TRUE;
1134 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1135 const CTGitPath& url2, const GitRev& rev2,
1136 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1137 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1139 #if 0
1140 CString sCmd;
1141 sCmd.Format(_T("%s /command:showcompare"),
1142 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1143 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1144 if (rev1.IsValid())
1145 sCmd += _T(" /revision1:") + rev1.ToString();
1146 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1147 if (rev2.IsValid())
1148 sCmd += _T(" /revision2:") + rev2.ToString();
1149 if (peg.IsValid())
1150 sCmd += _T(" /pegrevision:") + peg.ToString();
1151 if (headpeg.IsValid())
1152 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1153 if (bAlternateDiff)
1154 sCmd += _T(" /alternatediff");
1155 if (bIgnoreAncestry)
1156 sCmd += _T(" /ignoreancestry");
1157 if (blame)
1158 sCmd += _T(" /blame");
1160 if (hWnd)
1162 sCmd += _T(" /hwnd:");
1163 TCHAR buf[30];
1164 _stprintf_s(buf, 30, _T("%d"), hWnd);
1165 sCmd += buf;
1168 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1169 #endif
1170 return true;
1173 bool CAppUtils::Export(CString *BashHash)
1175 bool bRet = false;
1177 // ask from where the export has to be done
1178 CExportDlg dlg;
1179 if(BashHash)
1180 dlg.m_Revision=*BashHash;
1182 if (dlg.DoModal() == IDOK)
1184 CString cmd;
1185 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1186 dlg.m_VersionName);
1188 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1189 CProgressDlg pro;
1190 pro.m_GitCmd=cmd;
1191 pro.m_LogFile=dlg.m_strExportDirectory;
1192 pro.DoModal();
1193 return TRUE;
1195 return bRet;
1198 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1200 CCreateBranchTagDlg dlg;
1201 dlg.m_bIsTag=IsTag;
1202 if(CommitHash)
1203 dlg.m_Base = *CommitHash;
1205 if(dlg.DoModal()==IDOK)
1207 CString cmd;
1208 CString force;
1209 CString track;
1210 if(dlg.m_bTrack)
1211 track=_T(" --track ");
1213 if(dlg.m_bForce)
1214 force=_T(" -f ");
1216 if(IsTag)
1218 cmd.Format(_T("git.exe tag %s %s %s %s"),
1219 track,
1220 force,
1221 dlg.m_BranchTagName,
1222 dlg.m_VersionName
1225 CString tempfile=::GetTempFile();
1226 if(!dlg.m_Message.Trim().IsEmpty())
1228 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1229 cmd += _T(" -F ")+tempfile;
1232 }else
1234 cmd.Format(_T("git.exe branch %s %s %s %s"),
1235 track,
1236 force,
1237 dlg.m_BranchTagName,
1238 dlg.m_VersionName
1241 CString out;
1242 if(g_Git.Run(cmd,&out,CP_UTF8))
1244 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1246 if( !IsTag && dlg.m_bSwitch )
1248 // it is a new branch and the user has requested to switch to it
1249 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1250 g_Git.Run(cmd,&out,CP_UTF8);
1251 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1254 return TRUE;
1257 return FALSE;
1260 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1262 CGitSwitchDlg dlg;
1263 if(CommitHash)
1264 dlg.m_Base=*CommitHash;
1265 if(!initialRefName.IsEmpty())
1266 dlg.m_initialRefName = initialRefName;
1268 if (dlg.DoModal() == IDOK)
1270 CString cmd;
1271 CString track;
1272 // CString base;
1273 CString force;
1274 CString branch;
1276 if(dlg.m_bBranch)
1277 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1278 if(dlg.m_bForce)
1279 force=_T("-f");
1280 if(dlg.m_bTrack)
1281 track=_T("--track");
1283 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1284 force,
1285 track,
1286 branch,
1287 dlg.m_VersionName);
1289 CProgressDlg progress;
1290 progress.m_GitCmd=cmd;
1291 if(progress.DoModal()==IDOK)
1292 return TRUE;
1295 return FALSE;
1298 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1300 CString ignorefile;
1301 ignorefile=g_Git.m_CurrentDir+_T("\\");
1303 if(IsMask)
1305 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1307 }else
1309 ignorefile+=_T("\\.gitignore");
1312 CStdioFile file;
1313 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1315 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1316 return FALSE;
1319 CString ignorelist;
1320 CString mask;
1323 //file.ReadString(ignorelist);
1324 file.SeekToEnd();
1325 for(int i=0;i<path.GetCount();i++)
1327 if(IsMask)
1329 mask=_T("*")+path[i].GetFileExtension();
1330 if(ignorelist.Find(mask)<0)
1331 ignorelist+=_T("\n")+mask;
1333 }else
1335 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1338 file.WriteString(ignorelist);
1340 file.Close();
1342 }catch(...)
1344 file.Close();
1345 return FALSE;
1348 return TRUE;
1352 bool CAppUtils::GitReset(CString *CommitHash,int type)
1354 CResetDlg dlg;
1355 dlg.m_ResetType=type;
1356 if (dlg.DoModal() == IDOK)
1358 CString cmd;
1359 CString type;
1360 switch(dlg.m_ResetType)
1362 case 0:
1363 type=_T("--soft");
1364 break;
1365 case 1:
1366 type=_T("--mixed");
1367 break;
1368 case 2:
1369 type=_T("--hard");
1370 break;
1371 default:
1372 type=_T("--mixed");
1373 break;
1375 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1377 CProgressDlg progress;
1378 progress.m_GitCmd=cmd;
1379 if(progress.DoModal()==IDOK)
1380 return TRUE;
1383 return FALSE;
1386 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1388 if(mode == FALSE)
1390 descript=_T("Deleted");
1391 return;
1393 if(base)
1395 descript=_T("Modified");
1396 return;
1398 descript=_T("Created");
1399 return;
1402 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1404 CString tempmergefile;
1407 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1408 CFile::Remove(tempmergefile);
1409 }catch(...)
1415 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1416 CFile::Remove(tempmergefile);
1417 }catch(...)
1423 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1424 CFile::Remove(tempmergefile);
1425 }catch(...)
1429 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1431 CString file;
1432 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1434 return file;
1437 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool,bool revertTheirMy)
1439 bool bRet = false;
1441 CTGitPath merge=path;
1442 CTGitPath directory = merge.GetDirectory();
1446 // we have the conflicted file (%merged)
1447 // now look for the other required files
1448 //GitStatus stat;
1449 //stat.GetStatus(merge);
1450 //if (stat.status == NULL)
1451 // return false;
1453 BYTE_VECTOR vector;
1455 CString cmd;
1456 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1458 if(g_Git.Run(cmd,&vector))
1460 return FALSE;
1463 CTGitPathList list;
1464 list.ParserFromLsFile(vector);
1466 if(list.GetCount() == 0)
1467 return FALSE;
1469 TCHAR szTempName[512];
1470 GetTempFileName(_T(""),_T(""),0,szTempName);
1471 CString temp(szTempName);
1472 temp=temp.Mid(1,temp.GetLength()-5);
1474 CTGitPath theirs;
1475 CTGitPath mine;
1476 CTGitPath base;
1479 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1480 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1481 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1483 CString format;
1485 //format=_T("git.exe cat-file blob \":%d:%s\"");
1486 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1487 CFile tempfile;
1488 //create a empty file, incase stage is not three
1489 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1490 tempfile.Close();
1491 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1492 tempfile.Close();
1493 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1494 tempfile.Close();
1496 bool b_base=false, b_local=false, b_remote=false;
1498 for(int i=0;i<list.GetCount();i++)
1500 CString cmd;
1501 CString outfile;
1502 cmd.Empty();
1503 outfile.Empty();
1505 if( list[i].m_Stage == 1)
1507 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1508 b_base = true;
1509 outfile = base.GetWinPathString();
1512 if( list[i].m_Stage == 2 )
1514 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1515 b_local = true;
1516 outfile = mine.GetWinPathString();
1519 if( list[i].m_Stage == 3 )
1521 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1522 b_remote = true;
1523 outfile = theirs.GetWinPathString();
1525 CString output;
1526 if(!outfile.IsEmpty())
1527 if(!g_Git.Run(cmd,&output,CP_ACP))
1529 CString file;
1530 int start =0 ;
1531 file = output.Tokenize(_T("\t"), start);
1532 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1534 else
1536 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1540 if(b_local && b_remote )
1542 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1543 if( revertTheirMy )
1544 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1545 else
1546 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1548 }else
1550 CFile::Remove(mine.GetWinPathString());
1551 CFile::Remove(theirs.GetWinPathString());
1552 CFile::Remove(base.GetWinPathString());
1554 CDeleteConflictDlg dlg;
1555 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1556 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1557 dlg.m_bShowModifiedButton=b_base;
1558 dlg.m_File=merge.GetGitPathString();
1559 if(dlg.DoModal() == IDOK)
1561 CString cmd,out;
1562 if(dlg.m_bIsDelete)
1564 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1565 }else
1566 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1568 if(g_Git.Run(cmd,&out,CP_ACP))
1570 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1571 return FALSE;
1573 return TRUE;
1575 else
1576 return FALSE;
1582 #if 0
1584 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1585 base, theirs, mine, merge);
1586 #endif
1587 #if 0
1588 if (stat.status->text_status == svn_wc_status_conflicted)
1590 // we have a text conflict, use our merge tool to resolve the conflict
1592 CTSVNPath theirs(directory);
1593 CTSVNPath mine(directory);
1594 CTSVNPath base(directory);
1595 bool bConflictData = false;
1597 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1599 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1600 bConflictData = true;
1602 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1604 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1605 bConflictData = true;
1607 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1609 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1610 bConflictData = true;
1612 else
1614 mine = merge;
1616 if (bConflictData)
1617 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1618 base, theirs, mine, merge);
1621 if (stat.status->prop_status == svn_wc_status_conflicted)
1623 // we have a property conflict
1624 CTSVNPath prej(directory);
1625 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1627 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1628 // there's a problem: the prej file contains a _description_ of the conflict, and
1629 // that description string might be translated. That means we have no way of parsing
1630 // the file to find out the conflicting values.
1631 // The only thing we can do: show a dialog with the conflict description, then
1632 // let the user either accept the existing property or open the property edit dialog
1633 // to manually change the properties and values. And a button to mark the conflict as
1634 // resolved.
1635 CEditPropConflictDlg dlg;
1636 dlg.SetPrejFile(prej);
1637 dlg.SetConflictedItem(merge);
1638 bRet = (dlg.DoModal() != IDCANCEL);
1642 if (stat.status->tree_conflict)
1644 // we have a tree conflict
1645 SVNInfo info;
1646 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1647 if (pInfoData)
1649 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1651 CTSVNPath theirs(directory);
1652 CTSVNPath mine(directory);
1653 CTSVNPath base(directory);
1654 bool bConflictData = false;
1656 if (pInfoData->treeconflict_theirfile)
1658 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1659 bConflictData = true;
1661 if (pInfoData->treeconflict_basefile)
1663 base.AppendPathString(pInfoData->treeconflict_basefile);
1664 bConflictData = true;
1666 if (pInfoData->treeconflict_myfile)
1668 mine.AppendPathString(pInfoData->treeconflict_myfile);
1669 bConflictData = true;
1671 else
1673 mine = merge;
1675 if (bConflictData)
1676 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1677 base, theirs, mine, merge);
1679 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1681 CString sConflictAction;
1682 CString sConflictReason;
1683 CString sResolveTheirs;
1684 CString sResolveMine;
1685 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1686 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1688 if (pInfoData->treeconflict_nodekind == svn_node_file)
1690 switch (pInfoData->treeconflict_operation)
1692 case svn_wc_operation_update:
1693 switch (pInfoData->treeconflict_action)
1695 case svn_wc_conflict_action_edit:
1696 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1697 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1698 break;
1699 case svn_wc_conflict_action_add:
1700 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1701 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1702 break;
1703 case svn_wc_conflict_action_delete:
1704 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1705 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1706 break;
1708 break;
1709 case svn_wc_operation_switch:
1710 switch (pInfoData->treeconflict_action)
1712 case svn_wc_conflict_action_edit:
1713 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1714 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1715 break;
1716 case svn_wc_conflict_action_add:
1717 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1718 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1719 break;
1720 case svn_wc_conflict_action_delete:
1721 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1722 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1723 break;
1725 break;
1726 case svn_wc_operation_merge:
1727 switch (pInfoData->treeconflict_action)
1729 case svn_wc_conflict_action_edit:
1730 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1731 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1732 break;
1733 case svn_wc_conflict_action_add:
1734 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1735 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1736 break;
1737 case svn_wc_conflict_action_delete:
1738 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1739 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1740 break;
1742 break;
1745 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1747 switch (pInfoData->treeconflict_operation)
1749 case svn_wc_operation_update:
1750 switch (pInfoData->treeconflict_action)
1752 case svn_wc_conflict_action_edit:
1753 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1754 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1755 break;
1756 case svn_wc_conflict_action_add:
1757 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1758 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1759 break;
1760 case svn_wc_conflict_action_delete:
1761 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1762 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1763 break;
1765 break;
1766 case svn_wc_operation_switch:
1767 switch (pInfoData->treeconflict_action)
1769 case svn_wc_conflict_action_edit:
1770 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1771 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1772 break;
1773 case svn_wc_conflict_action_add:
1774 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1775 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1776 break;
1777 case svn_wc_conflict_action_delete:
1778 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1779 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1780 break;
1782 break;
1783 case svn_wc_operation_merge:
1784 switch (pInfoData->treeconflict_action)
1786 case svn_wc_conflict_action_edit:
1787 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1788 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1789 break;
1790 case svn_wc_conflict_action_add:
1791 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1792 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1793 break;
1794 case svn_wc_conflict_action_delete:
1795 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1796 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1797 break;
1799 break;
1803 UINT uReasonID = 0;
1804 switch (pInfoData->treeconflict_reason)
1806 case svn_wc_conflict_reason_edited:
1807 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1808 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1809 break;
1810 case svn_wc_conflict_reason_obstructed:
1811 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1812 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1813 break;
1814 case svn_wc_conflict_reason_deleted:
1815 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1816 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1817 break;
1818 case svn_wc_conflict_reason_added:
1819 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1820 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1821 break;
1822 case svn_wc_conflict_reason_missing:
1823 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1824 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1825 break;
1826 case svn_wc_conflict_reason_unversioned:
1827 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1828 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1829 break;
1831 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1833 CTreeConflictEditorDlg dlg;
1834 dlg.SetConflictInfoText(sConflictReason);
1835 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1836 dlg.SetPath(treeConflictPath);
1837 INT_PTR dlgRet = dlg.DoModal();
1838 bRet = (dlgRet != IDCANCEL);
1842 #endif
1843 return bRet;
1847 * FUNCTION : FormatDateAndTime
1848 * DESCRIPTION : Generates a displayable string from a CTime object in
1849 * system short or long format or as a relative value
1850 * cTime - the time
1851 * option - DATE_SHORTDATE or DATE_LONGDATE
1852 * bIncluedeTime - whether to show time as well as date
1853 * bRelative - if true then relative time is shown if reasonable
1854 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1855 * rather than locale
1856 * RETURN : CString containing date/time
1858 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1859 bool bRelative /*=false*/)
1861 CString datetime;
1862 if ( bRelative )
1864 datetime = ToRelativeTimeString( cTime );
1866 else
1868 // should we use the locale settings for formatting the date/time?
1869 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1871 // yes
1872 SYSTEMTIME sysTime;
1873 cTime.GetAsSystemTime( sysTime );
1875 TCHAR buf[100];
1877 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1878 sizeof(buf)/sizeof(TCHAR)-1);
1879 datetime = buf;
1880 if ( bIncludeTime )
1882 datetime += _T(" ");
1883 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1884 datetime += buf;
1887 else
1889 // no, so fixed format
1890 if ( bIncludeTime )
1892 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1894 else
1896 datetime = cTime.Format(_T("%Y-%m-%d"));
1900 return datetime;
1904 * Converts a given time to a relative display string (relative to current time)
1905 * Given time must be in local timezone
1907 CString CAppUtils::ToRelativeTimeString(CTime time)
1909 CString answer;
1910 // convert to COleDateTime
1911 SYSTEMTIME sysTime;
1912 time.GetAsSystemTime( sysTime );
1913 COleDateTime oleTime( sysTime );
1914 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1915 return answer;
1919 * Generates a display string showing the relative time between the two given times as COleDateTimes
1921 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1923 CString answer;
1924 COleDateTimeSpan ts = RelativeTo - time;
1925 //years
1926 if(fabs(ts.GetTotalDays()) >= 3*365)
1928 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1930 //Months
1931 if(fabs(ts.GetTotalDays()) >= 60)
1933 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1934 return answer;
1936 //Weeks
1937 if(fabs(ts.GetTotalDays()) >= 14)
1939 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1940 return answer;
1942 //Days
1943 if(fabs(ts.GetTotalDays()) >= 2)
1945 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1946 return answer;
1948 //hours
1949 if(fabs(ts.GetTotalHours()) >= 2)
1951 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1952 return answer;
1954 //minutes
1955 if(fabs(ts.GetTotalMinutes()) >= 2)
1957 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1958 return answer;
1960 //seconds
1961 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1962 return answer;
1965 /**
1966 * Passed a value and two resource string ids
1967 * if count is 1 then FormatString is called with format_1 and the value
1968 * otherwise format_2 is used
1969 * the formatted string is returned
1971 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1973 CString answer;
1974 if ( count == 1 )
1976 answer.FormatMessage( format_1, count );
1978 else
1980 answer.FormatMessage( format_n, count );
1982 return answer;
1985 bool CAppUtils::IsSSHPutty()
1987 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1988 sshclient=sshclient.MakeLower();
1989 if(sshclient.Find(_T("plink.exe"),0)>=0)
1991 return true;
1993 return false;
1996 CString CAppUtils::GetClipboardLink()
1998 if (!OpenClipboard(NULL))
1999 return CString();
2001 CString sClipboardText;
2002 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2003 if (hglb)
2005 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2006 sClipboardText = CString(lpstr);
2007 GlobalUnlock(hglb);
2009 hglb = GetClipboardData(CF_UNICODETEXT);
2010 if (hglb)
2012 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2013 sClipboardText = lpstr;
2014 GlobalUnlock(hglb);
2016 CloseClipboard();
2018 if(!sClipboardText.IsEmpty())
2020 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2021 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2023 if(sClipboardText.Find( _T("http://")) == 0)
2024 return sClipboardText;
2026 if(sClipboardText.Find( _T("https://")) == 0)
2027 return sClipboardText;
2029 if(sClipboardText.Find( _T("git://")) == 0)
2030 return sClipboardText;
2032 if(sClipboardText.Find( _T("ssh://")) == 0)
2033 return sClipboardText;
2035 if(sClipboardText.GetLength()>=2)
2036 if( sClipboardText[1] == _T(':') )
2037 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2038 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2039 return sClipboardText;
2042 return CString(_T(""));
2045 CString CAppUtils::ChooseRepository(CString *path)
2047 CBrowseFolder browseFolder;
2048 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2050 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2051 CString strCloneDirectory;
2052 if(path)
2053 strCloneDirectory=*path;
2054 else
2056 strCloneDirectory = regLastResopitory;
2059 CString title;
2060 title.LoadString(IDS_CHOOSE_REPOSITORY);
2062 browseFolder.SetInfo(title);
2064 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2066 regLastResopitory = strCloneDirectory;
2067 return strCloneDirectory;
2069 }else
2071 return CString();
2076 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2078 CSendMailDlg dlg;
2080 dlg.m_PathList = list;
2082 if(dlg.DoModal()==IDOK)
2084 if(dlg.m_PathList.GetCount() == 0)
2085 return FALSE;
2087 CGitProgressDlg progDlg;
2089 theApp.m_pMainWnd = &progDlg;
2090 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2092 progDlg.SetAutoClose(autoclose);
2094 progDlg.SetPathList(dlg.m_PathList);
2095 //ProjectProperties props;
2096 //props.ReadPropsPathList(dlg.m_pathList);
2097 //progDlg.SetProjectProperties(props);
2098 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2100 DWORD flags =0;
2101 if(dlg.m_bAttachment)
2102 flags |= SENDMAIL_ATTACHMENT;
2103 if(dlg.m_bCombine)
2104 flags |= SENDMAIL_COMBINED;
2106 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2108 progDlg.DoModal();
2110 return true;
2112 return false;
2115 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2117 CTGitPathList list;
2118 CString log=formatpatchoutput;
2119 int start=log.Find(cmd);
2120 if(start >=0)
2121 CString one=log.Tokenize(_T("\n"),start);
2122 else
2123 start = 0;
2125 while(start>=0)
2127 CString one=log.Tokenize(_T("\n"),start);
2128 one=one.Trim();
2129 if(one.IsEmpty())
2130 continue;
2131 one.Replace(_T('/'),_T('\\'));
2132 CTGitPath path;
2133 path.SetFromWin(one);
2134 list.AddPath(path);
2136 return SendPatchMail(list,autoclose);
2140 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2142 CString cmd,output;
2143 int start=0;
2144 cmd=_T("git.exe config i18n.logOutputEncoding");
2145 if(pGit->Run(cmd,&output,CP_ACP))
2147 cmd=_T("git.exe config i18n.commitencoding");
2148 if(pGit->Run(cmd,&output,CP_ACP))
2149 return CP_UTF8;
2151 int start=0;
2152 output=output.Tokenize(_T("\n"),start);
2153 return CUnicodeUtils::GetCPCode(output);
2155 }else
2157 output=output.Tokenize(_T("\n"),start);
2158 return CUnicodeUtils::GetCPCode(output);
2161 int CAppUtils::GetCommitTemplate(CString &temp)
2163 CString cmd,output;
2164 cmd = _T("git.exe config commit.template");
2165 if( g_Git.Run(cmd,&output,CP_ACP) )
2166 return -1;
2168 if( output.GetLength()<1)
2169 return -1;
2171 if( output[0] == _T('/'))
2173 if(output.GetLength()>=3)
2174 if(output[2] == _T('/'))
2176 output.GetBuffer()[0] = output[1];
2177 output.GetBuffer()[1] = _T(':');
2181 int start=0;
2182 output=output.Tokenize(_T("\n"),start);
2184 output.Replace(_T('/'),_T('\\'));
2188 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2189 CString str;
2190 while(file.ReadString(str))
2192 temp+=str+_T("\n");
2195 }catch(...)
2197 return -1;
2199 return 0;
2203 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2205 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2206 CString cmd,output;
2207 int cp=CP_UTF8;
2209 cmd=_T("git.exe config i18n.commitencoding");
2210 if(g_Git.Run(cmd,&output,CP_ACP))
2211 cp=CP_UTF8;
2213 int start=0;
2214 output=output.Tokenize(_T("\n"),start);
2215 cp=CUnicodeUtils::GetCPCode(output);
2217 int len=message.GetLength();
2219 char * buf;
2220 buf = new char[len*4 + 4];
2221 SecureZeroMemory(buf, (len*4 + 4));
2223 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2225 file.Write(buf,lengthIncTerminator-1);
2226 file.Close();
2227 delete buf;
2228 return 0;
2231 bool CAppUtils::Push()
2233 CPushDlg dlg;
2234 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2235 CString error;
2236 DWORD exitcode = -1;
2237 CTGitPathList list;
2238 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2239 if (CHooks::Instance().PrePush(list,exitcode, error))
2241 if (exitcode)
2243 CString temp;
2244 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2245 //ReportError(temp);
2246 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2247 return false;
2251 if(dlg.DoModal()==IDOK)
2253 // CString dir=dlg.m_Directory;
2254 // CString url=dlg.m_URL;
2255 CString cmd;
2256 CString arg;
2258 if(dlg.m_bAutoLoad)
2260 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2263 if(dlg.m_bPack)
2264 arg +=_T("--thin ");
2265 if(dlg.m_bTags)
2266 arg +=_T("--tags ");
2267 if(dlg.m_bForce)
2268 arg +=_T("--force ");
2270 int ver = CAppUtils::GetMsysgitVersion();
2272 if(ver >= 0x01070203) //above 1.7.0.2
2273 arg += _T("--progress ");
2276 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2277 arg,
2278 dlg.m_URL,
2279 dlg.m_BranchSourceName);
2280 if (!dlg.m_BranchRemoteName.IsEmpty())
2282 cmd += _T(":") + dlg.m_BranchRemoteName;
2285 CProgressDlg progress;
2286 progress.m_GitCmd=cmd;
2287 progress.DoModal();
2289 if(!progress.m_GitStatus)
2291 if (CHooks::Instance().PostPush(list,exitcode, error))
2293 if (exitcode)
2295 CString temp;
2296 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2297 //ReportError(temp);
2298 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2299 return false;
2303 return TRUE;
2307 return FALSE;
2310 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2312 CString strDir(szPath);
2313 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2315 strDir.AppendChar(_T('\\'));
2317 std::vector<CString> vPath;
2318 CString strTemp;
2319 bool bSuccess = false;
2321 for (int i=0;i<strDir.GetLength();++i)
2323 if (strDir.GetAt(i) != _T('\\'))
2325 strTemp.AppendChar(strDir.GetAt(i));
2327 else
2329 vPath.push_back(strTemp);
2330 strTemp.AppendChar(_T('\\'));
2334 std::vector<CString>::const_iterator vIter;
2335 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2337 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2340 return bSuccess;
2343 void CAppUtils::RemoveTrailSlash(CString &path)
2345 if(path.IsEmpty())
2346 return ;
2348 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2350 path=path.Left(path.GetLength()-1);
2351 if(path.IsEmpty())
2352 return;
2356 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2357 CTGitPathList &pathList,
2358 CTGitPathList &selectedList,
2359 BOOL bSelectFilesForCommit)
2361 bool bFailed = true;
2363 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2365 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"),
2366 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2368 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&CTGitPath(g_Git.m_CurrentDir));
2369 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2370 dlg.SetTreeWidth(220);
2371 dlg.m_DefaultPage = _T("gitconfig");
2373 dlg.DoModal();
2374 dlg.HandleRestart();
2376 }else
2377 return false;
2380 while (bFailed)
2382 bFailed = false;
2383 CCommitDlg dlg;
2384 dlg.m_sBugID = bugid;
2386 dlg.m_bWholeProject = bWholeProject;
2388 dlg.m_sLogMessage = sLogMsg;
2389 dlg.m_pathList = pathList;
2390 dlg.m_checkedPathList = selectedList;
2391 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2392 if (dlg.DoModal() == IDOK)
2394 if (dlg.m_pathList.GetCount()==0)
2395 return false;
2396 // if the user hasn't changed the list of selected items
2397 // we don't use that list. Because if we would use the list
2398 // of pre-checked items, the dialog would show different
2399 // checked items on the next startup: it would only try
2400 // to check the parent folder (which might not even show)
2401 // instead, we simply use an empty list and let the
2402 // default checking do its job.
2403 if (!dlg.m_pathList.IsEqual(pathList))
2404 selectedList = dlg.m_pathList;
2405 pathList = dlg.m_updatedPathList;
2406 sLogMsg = dlg.m_sLogMessage;
2407 bSelectFilesForCommit = true;
2409 if( dlg.m_bPushAfterCommit )
2411 switch(dlg.m_PostCmd)
2413 case GIT_POST_CMD_DCOMMIT:
2414 CAppUtils::SVNDCommit();
2415 break;
2416 default:
2417 CAppUtils::Push();
2420 // CGitProgressDlg progDlg;
2421 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2422 // if (parser.HasVal(_T("closeonend")))
2423 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2424 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2425 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2426 // progDlg.SetPathList(dlg.m_pathList);
2427 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2428 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2429 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2430 // progDlg.SetItemCount(dlg.m_itemsCount);
2431 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2432 // progDlg.DoModal();
2433 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2434 // err = (DWORD)progDlg.DidErrorsOccur();
2435 // bFailed = progDlg.DidErrorsOccur();
2436 // bRet = progDlg.DidErrorsOccur();
2437 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2438 // if (DWORD(bFailRepeat)==0)
2439 // bFailed = false; // do not repeat if the user chose not to in the settings.
2442 return true;
2446 BOOL CAppUtils::SVNDCommit()
2448 BOOL IsStash = false;
2449 if(!g_Git.CheckCleanWorkTree())
2451 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2453 CString cmd,out;
2454 cmd=_T("git.exe stash");
2455 if(g_Git.Run(cmd,&out,CP_ACP))
2457 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2458 return false;
2460 IsStash =true;
2462 }else
2464 return false;
2468 CProgressDlg progress;
2469 progress.m_GitCmd=_T("git.exe svn dcommit");
2470 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2472 if( IsStash)
2474 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2476 CString cmd,out;
2477 cmd=_T("git.exe stash pop");
2478 if(g_Git.Run(cmd,&out,CP_ACP))
2480 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2481 return false;
2484 }else
2486 return false;
2489 return TRUE;
2491 return FALSE;
2494 BOOL CAppUtils::Merge(CString *commit, int mode)
2496 CMergeDlg dlg;
2497 if(commit)
2498 dlg.m_initialRefName = *commit;
2500 if(dlg.DoModal()==IDOK)
2502 CString cmd;
2503 CString noff;
2504 CString squash;
2505 CString nocommit;
2506 CString msg;
2508 if(dlg.m_bNoFF)
2509 noff=_T("--no-ff");
2511 if(dlg.m_bSquash)
2512 squash=_T("--squash");
2514 if(dlg.m_bNoCommit)
2515 nocommit=_T("--no-commit");
2517 if(!dlg.m_strLogMesage.IsEmpty())
2519 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2521 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2522 msg,
2523 noff,
2524 squash,
2525 nocommit,
2526 dlg.m_VersionName);
2528 CProgressDlg Prodlg;
2529 Prodlg.m_GitCmd = cmd;
2531 Prodlg.DoModal();
2533 return !Prodlg.m_GitStatus;
2535 return false;
2538 void CAppUtils::EditNote(GitRev *rev)
2540 CInputDlg dlg;
2541 dlg.m_sHintText=_T("Edit Notes");
2542 dlg.m_sInputText = rev->m_Notes;
2543 dlg.m_sTitle=_T("Edit Notes");
2544 //dlg.m_pProjectProperties = &m_ProjectProperties;
2545 dlg.m_bUseLogWidth = true;
2546 if(dlg.DoModal() == IDOK)
2548 CString cmd,output;
2549 cmd=_T("notes add -f -F \"");
2551 CString tempfile=::GetTempFile();
2552 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2553 cmd+=tempfile;
2554 cmd+=_T("\" ");
2555 cmd+=rev->m_CommitHash.ToString();
2559 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2561 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2564 else
2566 rev->m_Notes = dlg.m_sInputText;
2568 }catch(...)
2570 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2572 CFile::Remove(tempfile);
2577 int CAppUtils::GetMsysgitVersion()
2579 CString cmd;
2580 CString progressarg;
2581 CString version;
2582 cmd = _T("git.exe --version");
2583 if(g_Git.Run(cmd, &version, CP_ACP))
2585 CMessageBox::Show(NULL,_T("git have not installed"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2586 return false;
2589 int start=0;
2590 int ver;
2592 CString str=version.Tokenize(_T("."),start);
2593 int space = str.ReverseFind(_T(' '));
2594 str=str.Mid(space+1,start);
2595 ver = _ttol(str);
2596 ver <<=24;
2598 version = version.Mid(start);
2599 start = 0;
2600 str = version.Tokenize(_T("."),start);
2602 ver |= (_ttol(str)&0xFF)<<16;
2604 str = version.Tokenize(_T("."),start);
2605 ver |= (_ttol(str)&0xFF)<<8;
2607 str = version.Tokenize(_T("."),start);
2608 ver |= (_ttol(str)&0xFF);
2610 return ver;