Fixed issue #151: need "stash pop" function and clear HasAdminDir HasGitSVN HashSubmo...
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob99360169fb90dfd8e5f5f093cfe94b89d37b6d3e
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"
50 CAppUtils::CAppUtils(void)
54 CAppUtils::~CAppUtils(void)
58 int CAppUtils::StashApply(CString ref)
60 CString cmd,out;
61 cmd=_T("git.exe stash apply ");
62 cmd+=ref;
64 if(g_Git.Run(cmd,&out,CP_ACP))
66 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
68 }else
70 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
71 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
73 CChangedDlg dlg;
74 dlg.m_pathList.AddPath(CTGitPath());
75 dlg.DoModal();
77 return 0;
79 return -1;
82 int CAppUtils::StashPop()
84 CString cmd,out;
85 cmd=_T("git.exe stash pop ");
87 if(g_Git.Run(cmd,&out,CP_ACP))
89 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
91 }else
93 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
94 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
96 CChangedDlg dlg;
97 dlg.m_pathList.AddPath(CTGitPath());
98 dlg.DoModal();
100 return 0;
102 return -1;
105 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
107 #if 0
108 GitProperties props(file, GitRev::REV_WC, false);
109 for (int i = 0; i < props.GetCount(); ++i)
111 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
113 mimetype = props.GetItemValue(i).c_str();
114 return true;
117 #endif
118 return false;
121 BOOL CAppUtils::StartExtMerge(
122 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
123 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
126 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
127 CString ext = mergedfile.GetFileExtension();
128 CString com = regCom;
129 bool bInternal = false;
131 CString mimetype;
132 if (ext != "")
134 // is there an extension specific merge tool?
135 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
136 if (CString(mergetool) != "")
138 com = mergetool;
141 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
143 // is there a mime type specific merge tool?
144 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
145 if (CString(mergetool) != "")
147 com = mergetool;
151 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
153 // use TortoiseMerge
154 bInternal = true;
155 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
156 com = tortoiseMergePath;
157 if (com.IsEmpty())
159 com = CPathUtils::GetAppDirectory();
160 com += _T("TortoiseMerge.exe");
162 com = _T("\"") + com + _T("\"");
163 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
164 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
166 // check if the params are set. If not, just add the files to the command line
167 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
169 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
170 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
171 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
172 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
174 if (basefile.IsEmpty())
176 com.Replace(_T("/base:%base"), _T(""));
177 com.Replace(_T("%base"), _T(""));
179 else
180 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
181 if (theirfile.IsEmpty())
183 com.Replace(_T("/theirs:%theirs"), _T(""));
184 com.Replace(_T("%theirs"), _T(""));
186 else
187 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
188 if (yourfile.IsEmpty())
190 com.Replace(_T("/mine:%mine"), _T(""));
191 com.Replace(_T("%mine"), _T(""));
193 else
194 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
195 if (mergedfile.IsEmpty())
197 com.Replace(_T("/merged:%merged"), _T(""));
198 com.Replace(_T("%merged"), _T(""));
200 else
201 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
202 if (basename.IsEmpty())
204 if (basefile.IsEmpty())
206 com.Replace(_T("/basename:%bname"), _T(""));
207 com.Replace(_T("%bname"), _T(""));
209 else
211 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
214 else
215 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
216 if (theirname.IsEmpty())
218 if (theirfile.IsEmpty())
220 com.Replace(_T("/theirsname:%tname"), _T(""));
221 com.Replace(_T("%tname"), _T(""));
223 else
225 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
228 else
229 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
230 if (yourname.IsEmpty())
232 if (yourfile.IsEmpty())
234 com.Replace(_T("/minename:%yname"), _T(""));
235 com.Replace(_T("%yname"), _T(""));
237 else
239 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
242 else
243 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
244 if (mergedname.IsEmpty())
246 if (mergedfile.IsEmpty())
248 com.Replace(_T("/mergedname:%mname"), _T(""));
249 com.Replace(_T("%mname"), _T(""));
251 else
253 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
256 else
257 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
259 if ((bReadOnly)&&(bInternal))
260 com += _T(" /readonly");
262 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
264 return FALSE;
267 return TRUE;
270 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
272 CString viewer;
273 // use TortoiseMerge
274 viewer = CPathUtils::GetAppDirectory();
275 viewer += _T("TortoiseMerge.exe");
277 viewer = _T("\"") + viewer + _T("\"");
278 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
279 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
280 if (bReversed)
281 viewer += _T(" /reversedpatch");
282 if (!sOriginalDescription.IsEmpty())
283 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
284 if (!sPatchedDescription.IsEmpty())
285 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
286 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
288 return FALSE;
290 return TRUE;
293 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
295 // Is there a mime type specific diff tool?
296 CString mimetype;
297 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
299 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
300 if (!difftool.IsEmpty())
301 return difftool;
304 // Is there an extension specific diff tool?
305 CString ext = file2.GetFileExtension().MakeLower();
306 if (!ext.IsEmpty())
308 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
309 if (!difftool.IsEmpty())
310 return difftool;
311 // Maybe we should use TortoiseIDiff?
312 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
313 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
314 (ext == _T(".png")) || (ext == _T(".ico")) ||
315 (ext == _T(".dib")) || (ext == _T(".emf")))
317 return
318 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
319 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
323 // Finally, pick a generic external diff tool
324 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
325 return difftool;
328 bool CAppUtils::StartExtDiff(
329 const CString& file1, const CString& file2,
330 const CString& sName1, const CString& sName2,
331 const DiffFlags& flags)
333 CString viewer;
335 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
336 if (!flags.bBlame || !(DWORD)blamediff)
338 viewer = PickDiffTool(file1, file2);
339 // If registry entry for a diff program is commented out, use TortoiseMerge.
340 bool bCommentedOut = viewer.Left(1) == _T("#");
341 if (flags.bAlternativeTool)
343 // Invert external vs. internal diff tool selection.
344 if (bCommentedOut)
345 viewer.Delete(0); // uncomment
346 else
347 viewer = "";
349 else if (bCommentedOut)
350 viewer = "";
353 bool bInternal = viewer.IsEmpty();
354 if (bInternal)
356 viewer =
357 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
358 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
359 if (flags.bBlame)
360 viewer += _T(" /blame");
362 // check if the params are set. If not, just add the files to the command line
363 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
365 viewer += _T(" \"")+file1+_T("\"");
366 viewer += _T(" \"")+file2+_T("\"");
368 if (viewer.Find(_T("%base")) >= 0)
370 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
372 if (viewer.Find(_T("%mine")) >= 0)
374 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
377 if (sName1.IsEmpty())
378 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
379 else
380 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
382 if (sName2.IsEmpty())
383 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
384 else
385 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
387 if (flags.bReadOnly && bInternal)
388 viewer += _T(" /readonly");
390 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
393 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
395 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
396 CString viewer = diffpropsexe;
397 bool bInternal = false;
398 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
400 //no registry entry (or commented out) for a diff program
401 //use TortoiseMerge
402 bInternal = true;
403 viewer = CPathUtils::GetAppDirectory();
404 viewer += _T("TortoiseMerge.exe");
405 viewer = _T("\"") + viewer + _T("\"");
406 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
408 // check if the params are set. If not, just add the files to the command line
409 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
411 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
412 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
414 if (viewer.Find(_T("%base")) >= 0)
416 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
418 if (viewer.Find(_T("%mine")) >= 0)
420 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
423 if (sName1.IsEmpty())
424 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
425 else
426 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
428 if (sName2.IsEmpty())
429 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
430 else
431 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
433 if ((bReadOnly)&&(bInternal))
434 viewer += _T(" /readonly");
436 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
438 return FALSE;
440 return TRUE;
443 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
445 CString viewer;
446 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
447 viewer = v;
448 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
450 // use TortoiseUDiff
451 viewer = CPathUtils::GetAppDirectory();
452 viewer += _T("TortoiseUDiff.exe");
453 // enquote the path to TortoiseUDiff
454 viewer = _T("\"") + viewer + _T("\"");
455 // add the params
456 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
459 if (viewer.Find(_T("%1"))>=0)
461 if (viewer.Find(_T("\"%1\"")) >= 0)
462 viewer.Replace(_T("%1"), patchfile);
463 else
464 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
466 else
467 viewer += _T(" \"") + patchfile + _T("\"");
468 if (viewer.Find(_T("%title")) >= 0)
470 viewer.Replace(_T("%title"), title);
473 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
475 return FALSE;
477 return TRUE;
480 BOOL CAppUtils::StartTextViewer(CString file)
482 CString viewer;
483 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
484 viewer = txt;
485 viewer = viewer + _T("\\Shell\\Open\\Command\\");
486 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
487 viewer = txtexe;
489 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
490 TCHAR * buf = new TCHAR[len+1];
491 ExpandEnvironmentStrings(viewer, buf, len);
492 viewer = buf;
493 delete [] buf;
494 len = ExpandEnvironmentStrings(file, NULL, 0);
495 buf = new TCHAR[len+1];
496 ExpandEnvironmentStrings(file, buf, len);
497 file = buf;
498 delete [] buf;
499 file = _T("\"")+file+_T("\"");
500 if (viewer.IsEmpty())
502 OPENFILENAME ofn = {0}; // common dialog box structure
503 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
504 // Initialize OPENFILENAME
505 ofn.lStructSize = sizeof(OPENFILENAME);
506 ofn.hwndOwner = NULL;
507 ofn.lpstrFile = szFile;
508 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
509 CString sFilter;
510 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
511 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
512 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
513 // Replace '|' delimiters with '\0's
514 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
515 while (ptr != pszFilters)
517 if (*ptr == '|')
518 *ptr = '\0';
519 ptr--;
521 ofn.lpstrFilter = pszFilters;
522 ofn.nFilterIndex = 1;
523 ofn.lpstrFileTitle = NULL;
524 ofn.nMaxFileTitle = 0;
525 ofn.lpstrInitialDir = NULL;
526 CString temp;
527 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
528 CStringUtils::RemoveAccelerators(temp);
529 ofn.lpstrTitle = temp;
530 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
532 // Display the Open dialog box.
534 if (GetOpenFileName(&ofn)==TRUE)
536 delete [] pszFilters;
537 viewer = CString(ofn.lpstrFile);
539 else
541 delete [] pszFilters;
542 return FALSE;
545 if (viewer.Find(_T("\"%1\"")) >= 0)
547 viewer.Replace(_T("\"%1\""), file);
549 else if (viewer.Find(_T("%1")) >= 0)
551 viewer.Replace(_T("%1"), file);
553 else
555 viewer += _T(" ");
556 viewer += file;
559 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
561 return FALSE;
563 return TRUE;
566 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
568 DWORD length = 0;
569 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
570 if (hFile == INVALID_HANDLE_VALUE)
571 return TRUE;
572 length = ::GetFileSize(hFile, NULL);
573 ::CloseHandle(hFile);
574 if (length < 4)
575 return TRUE;
576 return FALSE;
580 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
582 LOGFONT logFont;
583 HDC hScreenDC = ::GetDC(NULL);
584 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
585 ::ReleaseDC(NULL, hScreenDC);
586 logFont.lfWidth = 0;
587 logFont.lfEscapement = 0;
588 logFont.lfOrientation = 0;
589 logFont.lfWeight = FW_NORMAL;
590 logFont.lfItalic = 0;
591 logFont.lfUnderline = 0;
592 logFont.lfStrikeOut = 0;
593 logFont.lfCharSet = DEFAULT_CHARSET;
594 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
595 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
596 logFont.lfQuality = DRAFT_QUALITY;
597 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
598 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
599 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
602 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
604 STARTUPINFO startup;
605 PROCESS_INFORMATION process;
606 memset(&startup, 0, sizeof(startup));
607 startup.cb = sizeof(startup);
608 memset(&process, 0, sizeof(process));
610 CString cleanCommandLine(sCommandLine);
612 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, sOrigCWD, &startup, &process)==0)
614 if(idErrMessageFormat != 0)
616 LPVOID lpMsgBuf;
617 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
618 FORMAT_MESSAGE_FROM_SYSTEM |
619 FORMAT_MESSAGE_IGNORE_INSERTS,
620 NULL,
621 GetLastError(),
622 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
623 (LPTSTR) &lpMsgBuf,
625 NULL
627 CString temp;
628 temp.Format(idErrMessageFormat, lpMsgBuf);
629 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
630 LocalFree( lpMsgBuf );
632 return false;
635 if (bWaitForStartup)
637 WaitForInputIdle(process.hProcess, 10000);
640 CloseHandle(process.hThread);
641 CloseHandle(process.hProcess);
642 return true;
644 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
646 CString key,remote;
647 CString cmd,out;
648 if( pRemote == NULL)
650 remote=_T("origin");
651 }else
653 remote=*pRemote;
655 if(keyfile == NULL)
657 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
658 g_Git.Run(cmd,&key,CP_ACP);
659 int start=0;
660 key = key.Tokenize(_T("\n"),start);
662 else
663 key=*keyfile;
665 if(key.IsEmpty())
666 return false;
668 CString proc=CPathUtils::GetAppDirectory();
669 proc += _T("pageant.exe \"");
670 proc += key;
671 proc += _T("\"");
673 return LaunchApplication(proc, IDS_ERR_PAGEANT, false);
675 bool CAppUtils::LaunchRemoteSetting()
677 CString proc=CPathUtils::GetAppDirectory();
678 proc += _T("TortoiseProc.exe /command:settings");
679 proc += _T(" /path:\"");
680 proc += g_Git.m_CurrentDir;
681 proc += _T("\" /page:gitremote");
682 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
685 * Launch the external blame viewer
687 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
689 CString viewer = CPathUtils::GetAppDirectory();
690 viewer += _T("TortoiseGitBlame.exe");
691 viewer += _T(" \"") + sBlameFile + _T("\"");
692 //viewer += _T(" \"") + sLogFile + _T("\"");
693 //viewer += _T(" \"") + sOriginalFile + _T("\"");
694 if(!Rev.IsEmpty())
695 viewer += CString(_T(" /rev:"))+Rev;
696 viewer += _T(" ")+sParams;
698 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
701 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
703 CString sText;
704 if (pWnd == NULL)
705 return false;
706 bool bStyled = false;
707 pWnd->GetWindowText(sText);
708 // the rich edit control doesn't count the CR char!
709 // to be exact: CRLF is treated as one char.
710 sText.Replace(_T("\r"), _T(""));
712 // style each line separately
713 int offset = 0;
714 int nNewlinePos;
717 nNewlinePos = sText.Find('\n', offset);
718 CString sLine = sText.Mid(offset);
719 if (nNewlinePos>=0)
720 sLine = sLine.Left(nNewlinePos-offset);
721 int start = 0;
722 int end = 0;
723 while (FindStyleChars(sLine, '*', start, end))
725 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
726 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
727 CHARFORMAT2 format;
728 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
729 format.cbSize = sizeof(CHARFORMAT2);
730 format.dwMask = CFM_BOLD;
731 format.dwEffects = CFE_BOLD;
732 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
733 bStyled = true;
734 start = end;
736 start = 0;
737 end = 0;
738 while (FindStyleChars(sLine, '^', start, end))
740 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
741 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
742 CHARFORMAT2 format;
743 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
744 format.cbSize = sizeof(CHARFORMAT2);
745 format.dwMask = CFM_ITALIC;
746 format.dwEffects = CFE_ITALIC;
747 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
748 bStyled = true;
749 start = end;
751 start = 0;
752 end = 0;
753 while (FindStyleChars(sLine, '_', start, end))
755 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
756 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
757 CHARFORMAT2 format;
758 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
759 format.cbSize = sizeof(CHARFORMAT2);
760 format.dwMask = CFM_UNDERLINE;
761 format.dwEffects = CFE_UNDERLINE;
762 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
763 bStyled = true;
764 start = end;
766 offset = nNewlinePos+1;
767 } while(nNewlinePos>=0);
768 return bStyled;
771 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
773 int i=start;
774 bool bFoundMarker = false;
775 // find a starting marker
776 while (sText[i] != 0)
778 if (sText[i] == stylechar)
780 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
781 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
783 start = i+1;
784 i++;
785 bFoundMarker = true;
786 break;
789 i++;
791 if (!bFoundMarker)
792 return false;
793 // find ending marker
794 bFoundMarker = false;
795 while (sText[i] != 0)
797 if (sText[i] == stylechar)
799 if ((IsCharAlphaNumeric(sText[i-1])) &&
800 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
802 end = i;
803 i++;
804 bFoundMarker = true;
805 break;
808 i++;
810 return bFoundMarker;
813 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
815 #if 0
816 CString strUrl;
817 combo.GetWindowText(strUrl);
818 strUrl.Replace('\\', '/');
819 strUrl.Replace(_T("%"), _T("%25"));
820 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
821 if (strUrl.Left(7) == _T("file://"))
823 CString strFile(strUrl);
824 Git::UrlToPath(strFile);
826 Git svn;
827 if (svn.IsRepository(CTGitPath(strFile)))
829 // browse repository - show repository browser
830 Git::preparePath(strUrl);
831 CRepositoryBrowser browser(strUrl, rev, pParent);
832 if (browser.DoModal() == IDOK)
834 combo.SetCurSel(-1);
835 combo.SetWindowText(browser.GetPath());
836 rev = browser.GetRevision();
837 return true;
840 else
842 // browse local directories
843 CBrowseFolder folderBrowser;
844 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
845 // remove the 'file:///' so the shell can recognize the local path
846 Git::UrlToPath(strUrl);
847 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
849 Git::PathToUrl(strUrl);
851 combo.SetCurSel(-1);
852 combo.SetWindowText(strUrl);
853 return true;
857 else if ((strUrl.Left(7) == _T("http://")
858 ||(strUrl.Left(8) == _T("https://"))
859 ||(strUrl.Left(6) == _T("svn://"))
860 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
862 // browse repository - show repository browser
863 CRepositoryBrowser browser(strUrl, rev, pParent);
864 if (browser.DoModal() == IDOK)
866 combo.SetCurSel(-1);
867 combo.SetWindowText(browser.GetPath());
868 rev = browser.GetRevision();
869 return true;
872 else
874 // browse local directories
875 CBrowseFolder folderBrowser;
876 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
877 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
879 Git::PathToUrl(strUrl);
881 combo.SetCurSel(-1);
882 combo.SetWindowText(strUrl);
883 return true;
886 #endif
887 return false;
890 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
892 OPENFILENAME ofn = {0}; // common dialog box structure
893 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
894 ofn.lStructSize = sizeof(OPENFILENAME);
895 ofn.hwndOwner = hwndOwner;
896 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
897 ofn.lpstrFile = szFile;
898 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
899 CString sFilter;
900 TCHAR * pszFilters = NULL;
901 if (filter)
903 sFilter.LoadString(filter);
904 pszFilters = new TCHAR[sFilter.GetLength()+4];
905 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
906 // Replace '|' delimiters with '\0's
907 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
908 while (ptr != pszFilters)
910 if (*ptr == '|')
911 *ptr = '\0';
912 ptr--;
914 ofn.lpstrFilter = pszFilters;
916 ofn.nFilterIndex = 1;
917 ofn.lpstrFileTitle = NULL;
918 ofn.nMaxFileTitle = 0;
919 ofn.lpstrInitialDir = NULL;
920 CString temp;
921 if (title)
923 temp.LoadString(title);
924 CStringUtils::RemoveAccelerators(temp);
926 ofn.lpstrTitle = temp;
927 if (bOpen)
928 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
929 else
930 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
933 // Display the Open dialog box.
934 bool bRet = false;
935 if (bOpen)
937 bRet = !!GetOpenFileName(&ofn);
939 else
941 bRet = !!GetSaveFileName(&ofn);
943 if (bRet)
945 if (pszFilters)
946 delete [] pszFilters;
947 path = CString(ofn.lpstrFile);
948 if (filterindex)
949 *filterindex = ofn.nFilterIndex;
950 return true;
952 if (pszFilters)
953 delete [] pszFilters;
954 return false;
957 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
959 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
960 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
961 // create a bitmap from the icon
962 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
963 if (!hIcon)
964 return false;
966 RECT rect = {0};
967 rect.right = width;
968 rect.bottom = height;
969 HBITMAP bmp = NULL;
971 HWND desktop = ::GetDesktopWindow();
972 if (desktop)
974 HDC screen_dev = ::GetDC(desktop);
975 if (screen_dev)
977 // Create a compatible DC
978 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
979 if (dst_hdc)
981 // Create a new bitmap of icon size
982 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
983 if (bmp)
985 // Select it into the compatible DC
986 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
987 // Fill the background of the compatible DC with the given color
988 ::SetBkColor(dst_hdc, bkColor);
989 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
991 // Draw the icon into the compatible DC
992 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
993 ::SelectObject(dst_hdc, old_dst_bmp);
995 ::DeleteDC(dst_hdc);
998 ::ReleaseDC(desktop, screen_dev);
1001 // Restore settings
1002 DestroyIcon(hIcon);
1004 if (bmp == NULL)
1005 return false;
1007 LVBKIMAGE lv;
1008 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1009 lv.hbm = bmp;
1010 lv.xOffsetPercent = 100;
1011 lv.yOffsetPercent = 100;
1012 ListView_SetBkImage(hListCtrl, &lv);
1013 return true;
1016 CString CAppUtils::GetProjectNameFromURL(CString url)
1018 CString name;
1019 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1020 (name.CompareNoCase(_T("tags"))==0) ||
1021 (name.CompareNoCase(_T("trunk"))==0))
1023 name = url.Mid(url.ReverseFind('/')+1);
1024 url = url.Left(url.ReverseFind('/'));
1026 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1028 // a name of svn or svnroot indicates that it's not really the project name. In that
1029 // case, we try the first part of the URL
1030 // of course, this won't work in all cases (but it works for Google project hosting)
1031 url.Replace(_T("http://"), _T(""));
1032 url.Replace(_T("https://"), _T(""));
1033 url.Replace(_T("svn://"), _T(""));
1034 url.Replace(_T("svn+ssh://"), _T(""));
1035 url.TrimLeft(_T("/"));
1036 name = url.Left(url.Find('.'));
1038 return name;
1041 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1042 const CTGitPath& url2, const git_revnum_t& rev2,
1043 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1044 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1047 CString tempfile=GetTempFile();
1048 CString cmd;
1049 if(rev1 == GitRev::GetWorkingCopy())
1051 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1052 }else
1054 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1057 if( !url1.IsEmpty() )
1059 cmd+=_T(" \"");
1060 cmd+=url1.GetGitPathString();
1061 cmd+=_T("\" ");
1063 g_Git.RunLogFile(cmd,tempfile);
1064 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1067 #if 0
1068 CString sCmd;
1069 sCmd.Format(_T("%s /command:showcompare /unified"),
1070 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1071 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1072 if (rev1.IsValid())
1073 sCmd += _T(" /revision1:") + rev1.ToString();
1074 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1075 if (rev2.IsValid())
1076 sCmd += _T(" /revision2:") + rev2.ToString();
1077 if (peg.IsValid())
1078 sCmd += _T(" /pegrevision:") + peg.ToString();
1079 if (headpeg.IsValid())
1080 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1082 if (bAlternateDiff)
1083 sCmd += _T(" /alternatediff");
1085 if (bIgnoreAncestry)
1086 sCmd += _T(" /ignoreancestry");
1088 if (hWnd)
1090 sCmd += _T(" /hwnd:");
1091 TCHAR buf[30];
1092 _stprintf_s(buf, 30, _T("%d"), hWnd);
1093 sCmd += buf;
1096 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1097 #endif
1098 return TRUE;
1101 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1102 const CTGitPath& url2, const GitRev& rev2,
1103 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1104 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1106 #if 0
1107 CString sCmd;
1108 sCmd.Format(_T("%s /command:showcompare"),
1109 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1110 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1111 if (rev1.IsValid())
1112 sCmd += _T(" /revision1:") + rev1.ToString();
1113 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1114 if (rev2.IsValid())
1115 sCmd += _T(" /revision2:") + rev2.ToString();
1116 if (peg.IsValid())
1117 sCmd += _T(" /pegrevision:") + peg.ToString();
1118 if (headpeg.IsValid())
1119 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1120 if (bAlternateDiff)
1121 sCmd += _T(" /alternatediff");
1122 if (bIgnoreAncestry)
1123 sCmd += _T(" /ignoreancestry");
1124 if (blame)
1125 sCmd += _T(" /blame");
1127 if (hWnd)
1129 sCmd += _T(" /hwnd:");
1130 TCHAR buf[30];
1131 _stprintf_s(buf, 30, _T("%d"), hWnd);
1132 sCmd += buf;
1135 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1136 #endif
1137 return true;
1140 bool CAppUtils::Export(CString *BashHash)
1142 bool bRet = false;
1144 // ask from where the export has to be done
1145 CExportDlg dlg;
1146 if(BashHash)
1147 dlg.m_Revision=*BashHash;
1149 if (dlg.DoModal() == IDOK)
1151 CString cmd;
1152 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1153 dlg.m_VersionName);
1155 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1156 CProgressDlg pro;
1157 pro.m_GitCmd=cmd;
1158 pro.m_LogFile=dlg.m_strExportDirectory;
1159 pro.DoModal();
1160 return TRUE;
1162 return bRet;
1165 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1167 CCreateBranchTagDlg dlg;
1168 dlg.m_bIsTag=IsTag;
1169 if(CommitHash)
1170 dlg.m_Base = *CommitHash;
1172 if(dlg.DoModal()==IDOK)
1174 CString cmd;
1175 CString force;
1176 CString track;
1177 if(dlg.m_bTrack)
1178 track=_T(" --track ");
1180 if(dlg.m_bForce)
1181 force=_T(" -f ");
1183 if(IsTag)
1185 cmd.Format(_T("git.exe tag %s %s %s %s"),
1186 track,
1187 force,
1188 dlg.m_BranchTagName,
1189 dlg.m_VersionName
1193 }else
1195 cmd.Format(_T("git.exe branch %s %s %s %s"),
1196 track,
1197 force,
1198 dlg.m_BranchTagName,
1199 dlg.m_VersionName
1202 CString out;
1203 if(g_Git.Run(cmd,&out,CP_UTF8))
1205 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1207 if( !IsTag && dlg.m_bSwitch )
1209 // it is a new branch and the user has requested to switch to it
1210 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1211 g_Git.Run(cmd,&out,CP_UTF8);
1212 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1215 return TRUE;
1218 return FALSE;
1221 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1223 CGitSwitchDlg dlg;
1224 if(CommitHash)
1225 dlg.m_Base=*CommitHash;
1226 if(!initialRefName.IsEmpty())
1227 dlg.m_initialRefName = initialRefName;
1229 if (dlg.DoModal() == IDOK)
1231 CString cmd;
1232 CString track;
1233 // CString base;
1234 CString force;
1235 CString branch;
1237 if(dlg.m_bBranch)
1238 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1239 if(dlg.m_bForce)
1240 force=_T("-f");
1241 if(dlg.m_bTrack)
1242 track=_T("--track");
1244 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1245 force,
1246 track,
1247 branch,
1248 dlg.m_VersionName);
1250 CProgressDlg progress;
1251 progress.m_GitCmd=cmd;
1252 if(progress.DoModal()==IDOK)
1253 return TRUE;
1256 return FALSE;
1259 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1261 CString ignorefile;
1262 ignorefile=g_Git.m_CurrentDir+_T("\\");
1264 if(IsMask)
1266 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1268 }else
1270 ignorefile+=_T("\\.gitignore");
1273 CStdioFile file;
1274 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1276 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1277 return FALSE;
1280 CString ignorelist;
1281 CString mask;
1284 //file.ReadString(ignorelist);
1285 file.SeekToEnd();
1286 for(int i=0;i<path.GetCount();i++)
1288 if(IsMask)
1290 mask=_T("*")+path[i].GetFileExtension();
1291 if(ignorelist.Find(mask)<0)
1292 ignorelist+=_T("\n")+mask;
1294 }else
1296 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1299 file.WriteString(ignorelist);
1301 file.Close();
1303 }catch(...)
1305 file.Close();
1306 return FALSE;
1309 return TRUE;
1313 bool CAppUtils::GitReset(CString *CommitHash,int type)
1315 CResetDlg dlg;
1316 dlg.m_ResetType=type;
1317 if (dlg.DoModal() == IDOK)
1319 CString cmd;
1320 CString type;
1321 switch(dlg.m_ResetType)
1323 case 0:
1324 type=_T("--soft");
1325 break;
1326 case 1:
1327 type=_T("--mixed");
1328 break;
1329 case 2:
1330 type=_T("--hard");
1331 break;
1332 default:
1333 type=_T("--mixed");
1334 break;
1336 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1338 CProgressDlg progress;
1339 progress.m_GitCmd=cmd;
1340 if(progress.DoModal()==IDOK)
1341 return TRUE;
1344 return FALSE;
1347 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1349 if(mode == FALSE)
1351 descript=_T("Deleted");
1352 return;
1354 if(base)
1356 descript=_T("Modified");
1357 return;
1359 descript=_T("Created");
1360 return;
1363 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1365 CString file;
1366 file=g_Git.m_CurrentDir+_T("\\")+merge.GetDirectory().GetWinPathString()+_T("\\")+merge.GetFilename()+_T(".")+type+merge.GetFileExtension();
1368 return file;
1371 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool)
1373 bool bRet = false;
1375 CTGitPath merge=path;
1376 CTGitPath directory = merge.GetDirectory();
1380 // we have the conflicted file (%merged)
1381 // now look for the other required files
1382 //GitStatus stat;
1383 //stat.GetStatus(merge);
1384 //if (stat.status == NULL)
1385 // return false;
1387 BYTE_VECTOR vector;
1389 CString cmd;
1390 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1392 if(g_Git.Run(cmd,&vector))
1394 return FALSE;
1397 CTGitPathList list;
1398 list.ParserFromLsFile(vector);
1400 if(list.GetCount() == 0)
1401 return FALSE;
1403 TCHAR szTempName[512];
1404 GetTempFileName(_T(""),_T(""),0,szTempName);
1405 CString temp(szTempName);
1406 temp=temp.Mid(1,temp.GetLength()-5);
1408 CTGitPath theirs;
1409 CTGitPath mine;
1410 CTGitPath base;
1413 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1414 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1415 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1417 CString format;
1419 format=_T("git.exe cat-file blob \":%d:%s\"");
1420 CFile tempfile;
1421 //create a empty file, incase stage is not three
1422 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1423 tempfile.Close();
1424 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1425 tempfile.Close();
1426 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1427 tempfile.Close();
1429 bool b_base=false, b_local=false, b_remote=false;
1431 for(int i=0;i<list.GetCount();i++)
1433 CString cmd;
1434 CString outfile;
1435 cmd.Format(format,list[i].m_Stage,list[i].GetGitPathString());
1437 if( list[i].m_Stage == 1)
1439 b_base = true;
1440 outfile=base.GetWinPathString();
1442 if( list[i].m_Stage == 2 )
1444 b_local = true;
1445 outfile=mine.GetWinPathString();
1447 if( list[i].m_Stage == 3 )
1449 b_remote = true;
1450 outfile=theirs.GetWinPathString();
1452 g_Git.RunLogFile(cmd,outfile);
1455 if(b_local && b_remote )
1457 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1458 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1460 }else
1462 CFile::Remove(mine.GetWinPathString());
1463 CFile::Remove(theirs.GetWinPathString());
1464 CFile::Remove(base.GetWinPathString());
1466 CDeleteConflictDlg dlg;
1467 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1468 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1469 dlg.m_bShowModifiedButton=b_base;
1470 dlg.m_File=merge.GetGitPathString();
1471 if(dlg.DoModal() == IDOK)
1473 CString cmd,out;
1474 if(dlg.m_bIsDelete)
1476 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1477 }else
1478 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1480 if(g_Git.Run(cmd,&out,CP_ACP))
1482 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1483 return FALSE;
1485 return TRUE;
1487 else
1488 return FALSE;
1494 #if 0
1496 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1497 base, theirs, mine, merge);
1498 #endif
1499 #if 0
1500 if (stat.status->text_status == svn_wc_status_conflicted)
1502 // we have a text conflict, use our merge tool to resolve the conflict
1504 CTSVNPath theirs(directory);
1505 CTSVNPath mine(directory);
1506 CTSVNPath base(directory);
1507 bool bConflictData = false;
1509 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1511 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1512 bConflictData = true;
1514 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1516 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1517 bConflictData = true;
1519 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1521 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1522 bConflictData = true;
1524 else
1526 mine = merge;
1528 if (bConflictData)
1529 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1530 base, theirs, mine, merge);
1533 if (stat.status->prop_status == svn_wc_status_conflicted)
1535 // we have a property conflict
1536 CTSVNPath prej(directory);
1537 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1539 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1540 // there's a problem: the prej file contains a _description_ of the conflict, and
1541 // that description string might be translated. That means we have no way of parsing
1542 // the file to find out the conflicting values.
1543 // The only thing we can do: show a dialog with the conflict description, then
1544 // let the user either accept the existing property or open the property edit dialog
1545 // to manually change the properties and values. And a button to mark the conflict as
1546 // resolved.
1547 CEditPropConflictDlg dlg;
1548 dlg.SetPrejFile(prej);
1549 dlg.SetConflictedItem(merge);
1550 bRet = (dlg.DoModal() != IDCANCEL);
1554 if (stat.status->tree_conflict)
1556 // we have a tree conflict
1557 SVNInfo info;
1558 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1559 if (pInfoData)
1561 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1563 CTSVNPath theirs(directory);
1564 CTSVNPath mine(directory);
1565 CTSVNPath base(directory);
1566 bool bConflictData = false;
1568 if (pInfoData->treeconflict_theirfile)
1570 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1571 bConflictData = true;
1573 if (pInfoData->treeconflict_basefile)
1575 base.AppendPathString(pInfoData->treeconflict_basefile);
1576 bConflictData = true;
1578 if (pInfoData->treeconflict_myfile)
1580 mine.AppendPathString(pInfoData->treeconflict_myfile);
1581 bConflictData = true;
1583 else
1585 mine = merge;
1587 if (bConflictData)
1588 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1589 base, theirs, mine, merge);
1591 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1593 CString sConflictAction;
1594 CString sConflictReason;
1595 CString sResolveTheirs;
1596 CString sResolveMine;
1597 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1598 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1600 if (pInfoData->treeconflict_nodekind == svn_node_file)
1602 switch (pInfoData->treeconflict_operation)
1604 case svn_wc_operation_update:
1605 switch (pInfoData->treeconflict_action)
1607 case svn_wc_conflict_action_edit:
1608 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1609 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1610 break;
1611 case svn_wc_conflict_action_add:
1612 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1613 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1614 break;
1615 case svn_wc_conflict_action_delete:
1616 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1617 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1618 break;
1620 break;
1621 case svn_wc_operation_switch:
1622 switch (pInfoData->treeconflict_action)
1624 case svn_wc_conflict_action_edit:
1625 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1626 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1627 break;
1628 case svn_wc_conflict_action_add:
1629 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1630 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1631 break;
1632 case svn_wc_conflict_action_delete:
1633 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1634 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1635 break;
1637 break;
1638 case svn_wc_operation_merge:
1639 switch (pInfoData->treeconflict_action)
1641 case svn_wc_conflict_action_edit:
1642 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1643 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1644 break;
1645 case svn_wc_conflict_action_add:
1646 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1647 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1648 break;
1649 case svn_wc_conflict_action_delete:
1650 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1651 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1652 break;
1654 break;
1657 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1659 switch (pInfoData->treeconflict_operation)
1661 case svn_wc_operation_update:
1662 switch (pInfoData->treeconflict_action)
1664 case svn_wc_conflict_action_edit:
1665 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1666 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1667 break;
1668 case svn_wc_conflict_action_add:
1669 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1670 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1671 break;
1672 case svn_wc_conflict_action_delete:
1673 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1674 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1675 break;
1677 break;
1678 case svn_wc_operation_switch:
1679 switch (pInfoData->treeconflict_action)
1681 case svn_wc_conflict_action_edit:
1682 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1683 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1684 break;
1685 case svn_wc_conflict_action_add:
1686 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1687 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1688 break;
1689 case svn_wc_conflict_action_delete:
1690 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1691 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1692 break;
1694 break;
1695 case svn_wc_operation_merge:
1696 switch (pInfoData->treeconflict_action)
1698 case svn_wc_conflict_action_edit:
1699 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1700 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1701 break;
1702 case svn_wc_conflict_action_add:
1703 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1704 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1705 break;
1706 case svn_wc_conflict_action_delete:
1707 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1708 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1709 break;
1711 break;
1715 UINT uReasonID = 0;
1716 switch (pInfoData->treeconflict_reason)
1718 case svn_wc_conflict_reason_edited:
1719 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1720 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1721 break;
1722 case svn_wc_conflict_reason_obstructed:
1723 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
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_deleted:
1727 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1728 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1729 break;
1730 case svn_wc_conflict_reason_added:
1731 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1732 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1733 break;
1734 case svn_wc_conflict_reason_missing:
1735 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1736 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1737 break;
1738 case svn_wc_conflict_reason_unversioned:
1739 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1740 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1741 break;
1743 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1745 CTreeConflictEditorDlg dlg;
1746 dlg.SetConflictInfoText(sConflictReason);
1747 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1748 dlg.SetPath(treeConflictPath);
1749 INT_PTR dlgRet = dlg.DoModal();
1750 bRet = (dlgRet != IDCANCEL);
1754 #endif
1755 return bRet;
1759 * FUNCTION : FormatDateAndTime
1760 * DESCRIPTION : Generates a displayable string from a CTime object in
1761 * system short or long format or as a relative value
1762 * cTime - the time
1763 * option - DATE_SHORTDATE or DATE_LONGDATE
1764 * bIncluedeTime - whether to show time as well as date
1765 * bRelative - if true then relative time is shown if reasonable
1766 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1767 * rather than locale
1768 * RETURN : CString containing date/time
1770 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1771 bool bRelative /*=false*/)
1773 CString datetime;
1774 if ( bRelative )
1776 datetime = ToRelativeTimeString( cTime );
1778 else
1780 // should we use the locale settings for formatting the date/time?
1781 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1783 // yes
1784 SYSTEMTIME sysTime;
1785 cTime.GetAsSystemTime( sysTime );
1787 TCHAR buf[100];
1789 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1790 sizeof(buf)/sizeof(TCHAR)-1);
1791 datetime = buf;
1792 if ( bIncludeTime )
1794 datetime += _T(" ");
1795 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1796 datetime += buf;
1799 else
1801 // no, so fixed format
1802 if ( bIncludeTime )
1804 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1806 else
1808 datetime = cTime.Format(_T("%Y-%m-%d"));
1812 return datetime;
1816 * Converts a given time to a relative display string (relative to current time)
1817 * Given time must be in local timezone
1819 CString CAppUtils::ToRelativeTimeString(CTime time)
1821 CString answer;
1822 // convert to COleDateTime
1823 SYSTEMTIME sysTime;
1824 time.GetAsSystemTime( sysTime );
1825 COleDateTime oleTime( sysTime );
1826 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1827 return answer;
1831 * Generates a display string showing the relative time between the two given times as COleDateTimes
1833 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1835 CString answer;
1836 COleDateTimeSpan ts = RelativeTo - time;
1837 //years
1838 if(fabs(ts.GetTotalDays()) >= 3*365)
1840 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1842 //Months
1843 if(fabs(ts.GetTotalDays()) >= 60)
1845 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1846 return answer;
1848 //Weeks
1849 if(fabs(ts.GetTotalDays()) >= 14)
1851 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1852 return answer;
1854 //Days
1855 if(fabs(ts.GetTotalDays()) >= 2)
1857 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1858 return answer;
1860 //hours
1861 if(fabs(ts.GetTotalHours()) >= 2)
1863 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1864 return answer;
1866 //minutes
1867 if(fabs(ts.GetTotalMinutes()) >= 2)
1869 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1870 return answer;
1872 //seconds
1873 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1874 return answer;
1877 /**
1878 * Passed a value and two resource string ids
1879 * if count is 1 then FormatString is called with format_1 and the value
1880 * otherwise format_2 is used
1881 * the formatted string is returned
1883 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1885 CString answer;
1886 if ( count == 1 )
1888 answer.FormatMessage( format_1, count );
1890 else
1892 answer.FormatMessage( format_n, count );
1894 return answer;
1897 bool CAppUtils::IsSSHPutty()
1899 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1900 sshclient=sshclient.MakeLower();
1901 if(sshclient.Find(_T("plink.exe"),0)>=0)
1903 return true;
1905 return false;
1908 CString CAppUtils::GetClipboardLink()
1910 if (!OpenClipboard(NULL))
1911 return CString();
1913 CString sClipboardText;
1914 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1915 if (hglb)
1917 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1918 sClipboardText = CString(lpstr);
1919 GlobalUnlock(hglb);
1921 hglb = GetClipboardData(CF_UNICODETEXT);
1922 if (hglb)
1924 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1925 sClipboardText = lpstr;
1926 GlobalUnlock(hglb);
1928 CloseClipboard();
1930 if(!sClipboardText.IsEmpty())
1932 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1933 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1935 if(sClipboardText.Find( _T("http://")) == 0)
1936 return sClipboardText;
1938 if(sClipboardText.Find( _T("https://")) == 0)
1939 return sClipboardText;
1941 if(sClipboardText.Find( _T("git://")) == 0)
1942 return sClipboardText;
1944 if(sClipboardText.Find( _T("ssh://")) == 0)
1945 return sClipboardText;
1947 if(sClipboardText.GetLength()>=2)
1948 if( sClipboardText[1] == _T(':') )
1949 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1950 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1951 return sClipboardText;
1954 return CString(_T(""));
1957 CString CAppUtils::ChooseRepository(CString *path)
1959 CBrowseFolder browseFolder;
1960 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1961 CString strCloneDirectory;
1962 if(path)
1963 strCloneDirectory=*path;
1965 CString title;
1966 title.LoadString(IDS_CHOOSE_REPOSITORY);
1968 browseFolder.SetInfo(title);
1970 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1972 return strCloneDirectory;
1974 }else
1976 return CString();
1981 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1983 CSendMailDlg dlg;
1985 dlg.m_PathList = list;
1987 if(dlg.DoModal()==IDOK)
1989 if(dlg.m_PathList.GetCount() == 0)
1990 return FALSE;
1992 CGitProgressDlg progDlg;
1994 theApp.m_pMainWnd = &progDlg;
1995 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
1997 progDlg.SetAutoClose(autoclose);
1999 progDlg.SetPathList(dlg.m_PathList);
2000 //ProjectProperties props;
2001 //props.ReadPropsPathList(dlg.m_pathList);
2002 //progDlg.SetProjectProperties(props);
2003 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2005 DWORD flags =0;
2006 if(dlg.m_bAttachment)
2007 flags |= SENDMAIL_ATTACHMENT;
2008 if(dlg.m_bCombine)
2009 flags |= SENDMAIL_COMBINED;
2011 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2013 progDlg.DoModal();
2015 return true;
2017 return false;
2020 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2022 CTGitPathList list;
2023 CString log=formatpatchoutput;
2024 int start=log.Find(cmd);
2025 if(start >=0)
2026 CString one=log.Tokenize(_T("\n"),start);
2027 else
2028 start = 0;
2030 while(start>=0)
2032 CString one=log.Tokenize(_T("\n"),start);
2033 one=one.Trim();
2034 if(one.IsEmpty())
2035 continue;
2036 one.Replace(_T('/'),_T('\\'));
2037 CTGitPath path;
2038 path.SetFromWin(one);
2039 list.AddPath(path);
2041 return SendPatchMail(list,autoclose);
2045 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2047 CString cmd,output;
2048 int start=0;
2049 cmd=_T("git.exe config i18n.logOutputEncoding");
2050 if(pGit->Run(cmd,&output,CP_ACP))
2052 cmd=_T("git.exe config i18n.commitencoding");
2053 if(pGit->Run(cmd,&output,CP_ACP))
2054 return CP_UTF8;
2056 int start=0;
2057 output=output.Tokenize(_T("\n"),start);
2058 return CUnicodeUtils::GetCPCode(output);
2060 }else
2062 output=output.Tokenize(_T("\n"),start);
2063 return CUnicodeUtils::GetCPCode(output);
2066 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2068 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2069 CString cmd,output;
2070 int cp=CP_UTF8;
2072 cmd=_T("git.exe config i18n.commitencoding");
2073 if(g_Git.Run(cmd,&output,CP_ACP))
2074 cp=CP_UTF8;
2076 int start=0;
2077 output=output.Tokenize(_T("\n"),start);
2078 cp=CUnicodeUtils::GetCPCode(output);
2080 int len=message.GetLength();
2082 char * buf;
2083 buf = new char[len*4 + 4];
2084 SecureZeroMemory(buf, (len*4 + 4));
2086 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2088 file.Write(buf,lengthIncTerminator-1);
2089 file.Close();
2090 delete buf;
2091 return 0;
2094 bool CAppUtils::Push()
2096 CPushDlg dlg;
2097 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2098 if(dlg.DoModal()==IDOK)
2100 // CString dir=dlg.m_Directory;
2101 // CString url=dlg.m_URL;
2102 CString cmd;
2103 CString force;
2104 CString tags;
2105 CString thin;
2107 if(dlg.m_bAutoLoad)
2109 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2112 if(dlg.m_bPack)
2113 thin=_T("--thin");
2114 if(dlg.m_bTags)
2115 tags=_T("--tags");
2116 if(dlg.m_bForce)
2117 force=_T("--force");
2119 cmd.Format(_T("git.exe push %s %s %s \"%s\" %s"),
2120 thin,tags,force,
2121 dlg.m_URL,
2122 dlg.m_BranchSourceName);
2123 if (!dlg.m_BranchRemoteName.IsEmpty())
2125 cmd += _T(":") + dlg.m_BranchRemoteName;
2128 CProgressDlg progress;
2129 progress.m_GitCmd=cmd;
2130 if(progress.DoModal()==IDOK)
2131 return TRUE;
2134 return FALSE;
2137 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2139 CString strDir(szPath);
2140 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2142 strDir.AppendChar(_T('\\'));
2144 std::vector<CString> vPath;
2145 CString strTemp;
2146 bool bSuccess = false;
2148 for (int i=0;i<strDir.GetLength();++i)
2150 if (strDir.GetAt(i) != _T('\\'))
2152 strTemp.AppendChar(strDir.GetAt(i));
2154 else
2156 vPath.push_back(strTemp);
2157 strTemp.AppendChar(_T('\\'));
2161 std::vector<CString>::const_iterator vIter;
2162 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2164 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2167 return bSuccess;
2170 void CAppUtils::RemoveTrailSlash(CString &path)
2172 if(path.IsEmpty())
2173 return ;
2175 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2177 path=path.Left(path.GetLength()-1);
2178 if(path.IsEmpty())
2179 return;