Fixed issue #470: auto stash apply/pop for SVN dcommit
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob0cf0a5c8533a19e2542f8f70af5545bf235ddbd3
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"
54 CAppUtils::CAppUtils(void)
58 CAppUtils::~CAppUtils(void)
62 int CAppUtils::StashApply(CString ref)
64 CString cmd,out;
65 cmd=_T("git.exe stash apply ");
66 cmd+=ref;
68 if(g_Git.Run(cmd,&out,CP_ACP))
70 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
72 }else
74 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
75 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
77 CChangedDlg dlg;
78 dlg.m_pathList.AddPath(CTGitPath());
79 dlg.DoModal();
81 return 0;
83 return -1;
86 int CAppUtils::StashPop()
88 CString cmd,out;
89 cmd=_T("git.exe stash pop ");
91 if(g_Git.Run(cmd,&out,CP_ACP))
93 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
95 }else
97 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
98 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
100 CChangedDlg dlg;
101 dlg.m_pathList.AddPath(CTGitPath());
102 dlg.DoModal();
104 return 0;
106 return -1;
109 bool CAppUtils::GetMimeType(const CTGitPath& file, CString& mimetype)
111 #if 0
112 GitProperties props(file, GitRev::REV_WC, false);
113 for (int i = 0; i < props.GetCount(); ++i)
115 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
117 mimetype = props.GetItemValue(i).c_str();
118 return true;
121 #endif
122 return false;
125 BOOL CAppUtils::StartExtMerge(
126 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
127 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
130 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
131 CString ext = mergedfile.GetFileExtension();
132 CString com = regCom;
133 bool bInternal = false;
135 CString mimetype;
136 if (ext != "")
138 // is there an extension specific merge tool?
139 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
140 if (CString(mergetool) != "")
142 com = mergetool;
145 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
147 // is there a mime type specific merge tool?
148 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
149 if (CString(mergetool) != "")
151 com = mergetool;
155 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
157 // use TortoiseMerge
158 bInternal = true;
159 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
160 com = tortoiseMergePath;
161 if (com.IsEmpty())
163 com = CPathUtils::GetAppDirectory();
164 com += _T("TortoiseMerge.exe");
166 com = _T("\"") + com + _T("\"");
167 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
168 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
170 // check if the params are set. If not, just add the files to the command line
171 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
173 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
174 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
175 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
176 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
178 if (basefile.IsEmpty())
180 com.Replace(_T("/base:%base"), _T(""));
181 com.Replace(_T("%base"), _T(""));
183 else
184 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
185 if (theirfile.IsEmpty())
187 com.Replace(_T("/theirs:%theirs"), _T(""));
188 com.Replace(_T("%theirs"), _T(""));
190 else
191 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
192 if (yourfile.IsEmpty())
194 com.Replace(_T("/mine:%mine"), _T(""));
195 com.Replace(_T("%mine"), _T(""));
197 else
198 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
199 if (mergedfile.IsEmpty())
201 com.Replace(_T("/merged:%merged"), _T(""));
202 com.Replace(_T("%merged"), _T(""));
204 else
205 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
206 if (basename.IsEmpty())
208 if (basefile.IsEmpty())
210 com.Replace(_T("/basename:%bname"), _T(""));
211 com.Replace(_T("%bname"), _T(""));
213 else
215 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
218 else
219 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
220 if (theirname.IsEmpty())
222 if (theirfile.IsEmpty())
224 com.Replace(_T("/theirsname:%tname"), _T(""));
225 com.Replace(_T("%tname"), _T(""));
227 else
229 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
232 else
233 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
234 if (yourname.IsEmpty())
236 if (yourfile.IsEmpty())
238 com.Replace(_T("/minename:%yname"), _T(""));
239 com.Replace(_T("%yname"), _T(""));
241 else
243 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
246 else
247 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
248 if (mergedname.IsEmpty())
250 if (mergedfile.IsEmpty())
252 com.Replace(_T("/mergedname:%mname"), _T(""));
253 com.Replace(_T("%mname"), _T(""));
255 else
257 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
260 else
261 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
263 if ((bReadOnly)&&(bInternal))
264 com += _T(" /readonly");
266 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
268 return FALSE;
271 return TRUE;
274 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
276 CString viewer;
277 // use TortoiseMerge
278 viewer = CPathUtils::GetAppDirectory();
279 viewer += _T("TortoiseMerge.exe");
281 viewer = _T("\"") + viewer + _T("\"");
282 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
283 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
284 if (bReversed)
285 viewer += _T(" /reversedpatch");
286 if (!sOriginalDescription.IsEmpty())
287 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
288 if (!sPatchedDescription.IsEmpty())
289 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
290 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
292 return FALSE;
294 return TRUE;
297 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
299 // Is there a mime type specific diff tool?
300 CString mimetype;
301 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
303 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
304 if (!difftool.IsEmpty())
305 return difftool;
308 // Is there an extension specific diff tool?
309 CString ext = file2.GetFileExtension().MakeLower();
310 if (!ext.IsEmpty())
312 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
313 if (!difftool.IsEmpty())
314 return difftool;
315 // Maybe we should use TortoiseIDiff?
316 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
317 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
318 (ext == _T(".png")) || (ext == _T(".ico")) ||
319 (ext == _T(".dib")) || (ext == _T(".emf")))
321 return
322 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
323 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
327 // Finally, pick a generic external diff tool
328 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
329 return difftool;
332 bool CAppUtils::StartExtDiff(
333 const CString& file1, const CString& file2,
334 const CString& sName1, const CString& sName2,
335 const DiffFlags& flags)
337 CString viewer;
339 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
340 if (!flags.bBlame || !(DWORD)blamediff)
342 viewer = PickDiffTool(file1, file2);
343 // If registry entry for a diff program is commented out, use TortoiseMerge.
344 bool bCommentedOut = viewer.Left(1) == _T("#");
345 if (flags.bAlternativeTool)
347 // Invert external vs. internal diff tool selection.
348 if (bCommentedOut)
349 viewer.Delete(0); // uncomment
350 else
351 viewer = "";
353 else if (bCommentedOut)
354 viewer = "";
357 bool bInternal = viewer.IsEmpty();
358 if (bInternal)
360 viewer =
361 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
362 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
363 if (flags.bBlame)
364 viewer += _T(" /blame");
366 // check if the params are set. If not, just add the files to the command line
367 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
369 viewer += _T(" \"")+file1+_T("\"");
370 viewer += _T(" \"")+file2+_T("\"");
372 if (viewer.Find(_T("%base")) >= 0)
374 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
376 if (viewer.Find(_T("%mine")) >= 0)
378 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
381 if (sName1.IsEmpty())
382 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
383 else
384 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
386 if (sName2.IsEmpty())
387 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
388 else
389 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
391 if (flags.bReadOnly && bInternal)
392 viewer += _T(" /readonly");
394 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
397 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
399 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
400 CString viewer = diffpropsexe;
401 bool bInternal = false;
402 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
404 //no registry entry (or commented out) for a diff program
405 //use TortoiseMerge
406 bInternal = true;
407 viewer = CPathUtils::GetAppDirectory();
408 viewer += _T("TortoiseMerge.exe");
409 viewer = _T("\"") + viewer + _T("\"");
410 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
412 // check if the params are set. If not, just add the files to the command line
413 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
415 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
416 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
418 if (viewer.Find(_T("%base")) >= 0)
420 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
422 if (viewer.Find(_T("%mine")) >= 0)
424 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
427 if (sName1.IsEmpty())
428 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
429 else
430 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
432 if (sName2.IsEmpty())
433 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
434 else
435 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
437 if ((bReadOnly)&&(bInternal))
438 viewer += _T(" /readonly");
440 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
442 return FALSE;
444 return TRUE;
447 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
449 CString viewer;
450 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
451 viewer = v;
452 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
454 // use TortoiseUDiff
455 viewer = CPathUtils::GetAppDirectory();
456 viewer += _T("TortoiseUDiff.exe");
457 // enquote the path to TortoiseUDiff
458 viewer = _T("\"") + viewer + _T("\"");
459 // add the params
460 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
463 if (viewer.Find(_T("%1"))>=0)
465 if (viewer.Find(_T("\"%1\"")) >= 0)
466 viewer.Replace(_T("%1"), patchfile);
467 else
468 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
470 else
471 viewer += _T(" \"") + patchfile + _T("\"");
472 if (viewer.Find(_T("%title")) >= 0)
474 viewer.Replace(_T("%title"), title);
477 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
479 return FALSE;
481 return TRUE;
484 BOOL CAppUtils::StartTextViewer(CString file)
486 CString viewer;
487 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
488 viewer = txt;
489 viewer = viewer + _T("\\Shell\\Open\\Command\\");
490 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
491 viewer = txtexe;
493 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
494 TCHAR * buf = new TCHAR[len+1];
495 ExpandEnvironmentStrings(viewer, buf, len);
496 viewer = buf;
497 delete [] buf;
498 len = ExpandEnvironmentStrings(file, NULL, 0);
499 buf = new TCHAR[len+1];
500 ExpandEnvironmentStrings(file, buf, len);
501 file = buf;
502 delete [] buf;
503 file = _T("\"")+file+_T("\"");
504 if (viewer.IsEmpty())
506 OPENFILENAME ofn = {0}; // common dialog box structure
507 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
508 // Initialize OPENFILENAME
509 ofn.lStructSize = sizeof(OPENFILENAME);
510 ofn.hwndOwner = NULL;
511 ofn.lpstrFile = szFile;
512 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
513 CString sFilter;
514 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
515 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
516 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
517 // Replace '|' delimiters with '\0's
518 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
519 while (ptr != pszFilters)
521 if (*ptr == '|')
522 *ptr = '\0';
523 ptr--;
525 ofn.lpstrFilter = pszFilters;
526 ofn.nFilterIndex = 1;
527 ofn.lpstrFileTitle = NULL;
528 ofn.nMaxFileTitle = 0;
529 ofn.lpstrInitialDir = NULL;
530 CString temp;
531 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
532 CStringUtils::RemoveAccelerators(temp);
533 ofn.lpstrTitle = temp;
534 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
536 // Display the Open dialog box.
538 if (GetOpenFileName(&ofn)==TRUE)
540 delete [] pszFilters;
541 viewer = CString(ofn.lpstrFile);
543 else
545 delete [] pszFilters;
546 return FALSE;
549 if (viewer.Find(_T("\"%1\"")) >= 0)
551 viewer.Replace(_T("\"%1\""), file);
553 else if (viewer.Find(_T("%1")) >= 0)
555 viewer.Replace(_T("%1"), file);
557 else
559 viewer += _T(" ");
560 viewer += file;
563 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
565 return FALSE;
567 return TRUE;
570 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
572 DWORD length = 0;
573 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
574 if (hFile == INVALID_HANDLE_VALUE)
575 return TRUE;
576 length = ::GetFileSize(hFile, NULL);
577 ::CloseHandle(hFile);
578 if (length < 4)
579 return TRUE;
580 return FALSE;
584 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
586 LOGFONT logFont;
587 HDC hScreenDC = ::GetDC(NULL);
588 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
589 ::ReleaseDC(NULL, hScreenDC);
590 logFont.lfWidth = 0;
591 logFont.lfEscapement = 0;
592 logFont.lfOrientation = 0;
593 logFont.lfWeight = FW_NORMAL;
594 logFont.lfItalic = 0;
595 logFont.lfUnderline = 0;
596 logFont.lfStrikeOut = 0;
597 logFont.lfCharSet = DEFAULT_CHARSET;
598 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
599 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
600 logFont.lfQuality = DRAFT_QUALITY;
601 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
602 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
603 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
606 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
608 STARTUPINFO startup;
609 PROCESS_INFORMATION process;
610 memset(&startup, 0, sizeof(startup));
611 startup.cb = sizeof(startup);
612 memset(&process, 0, sizeof(process));
614 CString cleanCommandLine(sCommandLine);
616 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
618 if(idErrMessageFormat != 0)
620 LPVOID lpMsgBuf;
621 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
622 FORMAT_MESSAGE_FROM_SYSTEM |
623 FORMAT_MESSAGE_IGNORE_INSERTS,
624 NULL,
625 GetLastError(),
626 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
627 (LPTSTR) &lpMsgBuf,
629 NULL
631 CString temp;
632 temp.Format(idErrMessageFormat, lpMsgBuf);
633 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
634 LocalFree( lpMsgBuf );
636 return false;
639 if (bWaitForStartup)
641 WaitForInputIdle(process.hProcess, 10000);
644 CloseHandle(process.hThread);
645 CloseHandle(process.hProcess);
646 return true;
648 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
650 CString key,remote;
651 CString cmd,out;
652 if( pRemote == NULL)
654 remote=_T("origin");
655 }else
657 remote=*pRemote;
659 if(keyfile == NULL)
661 cmd.Format(_T("git.exe config remote.%s.puttykeyfile"),remote);
662 g_Git.Run(cmd,&key,CP_ACP);
663 int start=0;
664 key = key.Tokenize(_T("\n"),start);
666 else
667 key=*keyfile;
669 if(key.IsEmpty())
670 return false;
672 CString proc=CPathUtils::GetAppDirectory();
673 proc += _T("pageant.exe \"");
674 proc += key;
675 proc += _T("\"");
677 return LaunchApplication(proc, IDS_ERR_PAGEANT, false);
679 bool CAppUtils::LaunchRemoteSetting()
681 CString proc=CPathUtils::GetAppDirectory();
682 proc += _T("TortoiseProc.exe /command:settings");
683 proc += _T(" /path:\"");
684 proc += g_Git.m_CurrentDir;
685 proc += _T("\" /page:gitremote");
686 return LaunchApplication(proc, IDS_ERR_EXTDIFFSTART, false);
689 * Launch the external blame viewer
691 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
693 CString viewer = CPathUtils::GetAppDirectory();
694 viewer += _T("TortoiseGitBlame.exe");
695 viewer += _T(" \"") + sBlameFile + _T("\"");
696 //viewer += _T(" \"") + sLogFile + _T("\"");
697 //viewer += _T(" \"") + sOriginalFile + _T("\"");
698 if(!Rev.IsEmpty())
699 viewer += CString(_T(" /rev:"))+Rev;
700 viewer += _T(" ")+sParams;
702 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, false);
705 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
707 CString sText;
708 if (pWnd == NULL)
709 return false;
710 bool bStyled = false;
711 pWnd->GetWindowText(sText);
712 // the rich edit control doesn't count the CR char!
713 // to be exact: CRLF is treated as one char.
714 sText.Replace(_T("\r"), _T(""));
716 // style each line separately
717 int offset = 0;
718 int nNewlinePos;
721 nNewlinePos = sText.Find('\n', offset);
722 CString sLine = sText.Mid(offset);
723 if (nNewlinePos>=0)
724 sLine = sLine.Left(nNewlinePos-offset);
725 int start = 0;
726 int end = 0;
727 while (FindStyleChars(sLine, '*', start, end))
729 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
730 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
731 CHARFORMAT2 format;
732 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
733 format.cbSize = sizeof(CHARFORMAT2);
734 format.dwMask = CFM_BOLD;
735 format.dwEffects = CFE_BOLD;
736 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
737 bStyled = true;
738 start = end;
740 start = 0;
741 end = 0;
742 while (FindStyleChars(sLine, '^', start, end))
744 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
745 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
746 CHARFORMAT2 format;
747 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
748 format.cbSize = sizeof(CHARFORMAT2);
749 format.dwMask = CFM_ITALIC;
750 format.dwEffects = CFE_ITALIC;
751 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
752 bStyled = true;
753 start = end;
755 start = 0;
756 end = 0;
757 while (FindStyleChars(sLine, '_', start, end))
759 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
760 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
761 CHARFORMAT2 format;
762 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
763 format.cbSize = sizeof(CHARFORMAT2);
764 format.dwMask = CFM_UNDERLINE;
765 format.dwEffects = CFE_UNDERLINE;
766 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
767 bStyled = true;
768 start = end;
770 offset = nNewlinePos+1;
771 } while(nNewlinePos>=0);
772 return bStyled;
775 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
777 int i=start;
778 bool bFoundMarker = false;
779 // find a starting marker
780 while (sText[i] != 0)
782 if (sText[i] == stylechar)
784 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
785 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
787 start = i+1;
788 i++;
789 bFoundMarker = true;
790 break;
793 i++;
795 if (!bFoundMarker)
796 return false;
797 // find ending marker
798 bFoundMarker = false;
799 while (sText[i] != 0)
801 if (sText[i] == stylechar)
803 if ((IsCharAlphaNumeric(sText[i-1])) &&
804 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
806 end = i;
807 i++;
808 bFoundMarker = true;
809 break;
812 i++;
814 return bFoundMarker;
817 bool CAppUtils::BrowseRepository(CHistoryCombo& combo, CWnd * pParent, GitRev& rev)
819 #if 0
820 CString strUrl;
821 combo.GetWindowText(strUrl);
822 strUrl.Replace('\\', '/');
823 strUrl.Replace(_T("%"), _T("%25"));
824 strUrl = CUnicodeUtils::GetUnicode(CPathUtils::PathEscape(CUnicodeUtils::GetUTF8(strUrl)));
825 if (strUrl.Left(7) == _T("file://"))
827 CString strFile(strUrl);
828 Git::UrlToPath(strFile);
830 Git svn;
831 if (svn.IsRepository(CTGitPath(strFile)))
833 // browse repository - show repository browser
834 Git::preparePath(strUrl);
835 CRepositoryBrowser browser(strUrl, rev, pParent);
836 if (browser.DoModal() == IDOK)
838 combo.SetCurSel(-1);
839 combo.SetWindowText(browser.GetPath());
840 rev = browser.GetRevision();
841 return true;
844 else
846 // browse local directories
847 CBrowseFolder folderBrowser;
848 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
849 // remove the 'file:///' so the shell can recognize the local path
850 Git::UrlToPath(strUrl);
851 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
853 Git::PathToUrl(strUrl);
855 combo.SetCurSel(-1);
856 combo.SetWindowText(strUrl);
857 return true;
861 else if ((strUrl.Left(7) == _T("http://")
862 ||(strUrl.Left(8) == _T("https://"))
863 ||(strUrl.Left(6) == _T("svn://"))
864 ||(strUrl.Left(4) == _T("svn+"))) && strUrl.GetLength() > 6)
866 // browse repository - show repository browser
867 CRepositoryBrowser browser(strUrl, rev, pParent);
868 if (browser.DoModal() == IDOK)
870 combo.SetCurSel(-1);
871 combo.SetWindowText(browser.GetPath());
872 rev = browser.GetRevision();
873 return true;
876 else
878 // browse local directories
879 CBrowseFolder folderBrowser;
880 folderBrowser.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
881 if (folderBrowser.Show(pParent->GetSafeHwnd(), strUrl) == CBrowseFolder::OK)
883 Git::PathToUrl(strUrl);
885 combo.SetCurSel(-1);
886 combo.SetWindowText(strUrl);
887 return true;
890 #endif
891 return false;
894 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
896 OPENFILENAME ofn = {0}; // common dialog box structure
897 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
898 ofn.lStructSize = sizeof(OPENFILENAME);
899 ofn.hwndOwner = hwndOwner;
900 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
901 ofn.lpstrFile = szFile;
902 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
903 CString sFilter;
904 TCHAR * pszFilters = NULL;
905 if (filter)
907 sFilter.LoadString(filter);
908 pszFilters = new TCHAR[sFilter.GetLength()+4];
909 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
910 // Replace '|' delimiters with '\0's
911 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
912 while (ptr != pszFilters)
914 if (*ptr == '|')
915 *ptr = '\0';
916 ptr--;
918 ofn.lpstrFilter = pszFilters;
920 ofn.nFilterIndex = 1;
921 ofn.lpstrFileTitle = NULL;
922 ofn.nMaxFileTitle = 0;
923 ofn.lpstrInitialDir = NULL;
924 CString temp;
925 if (title)
927 temp.LoadString(title);
928 CStringUtils::RemoveAccelerators(temp);
930 ofn.lpstrTitle = temp;
931 if (bOpen)
932 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
933 else
934 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
937 // Display the Open dialog box.
938 bool bRet = false;
939 if (bOpen)
941 bRet = !!GetOpenFileName(&ofn);
943 else
945 bRet = !!GetSaveFileName(&ofn);
947 if (bRet)
949 if (pszFilters)
950 delete [] pszFilters;
951 path = CString(ofn.lpstrFile);
952 if (filterindex)
953 *filterindex = ofn.nFilterIndex;
954 return true;
956 if (pszFilters)
957 delete [] pszFilters;
958 return false;
961 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
963 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
964 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
965 // create a bitmap from the icon
966 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
967 if (!hIcon)
968 return false;
970 RECT rect = {0};
971 rect.right = width;
972 rect.bottom = height;
973 HBITMAP bmp = NULL;
975 HWND desktop = ::GetDesktopWindow();
976 if (desktop)
978 HDC screen_dev = ::GetDC(desktop);
979 if (screen_dev)
981 // Create a compatible DC
982 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
983 if (dst_hdc)
985 // Create a new bitmap of icon size
986 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
987 if (bmp)
989 // Select it into the compatible DC
990 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
991 // Fill the background of the compatible DC with the given color
992 ::SetBkColor(dst_hdc, bkColor);
993 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
995 // Draw the icon into the compatible DC
996 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
997 ::SelectObject(dst_hdc, old_dst_bmp);
999 ::DeleteDC(dst_hdc);
1002 ::ReleaseDC(desktop, screen_dev);
1005 // Restore settings
1006 DestroyIcon(hIcon);
1008 if (bmp == NULL)
1009 return false;
1011 LVBKIMAGE lv;
1012 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1013 lv.hbm = bmp;
1014 lv.xOffsetPercent = 100;
1015 lv.yOffsetPercent = 100;
1016 ListView_SetBkImage(hListCtrl, &lv);
1017 return true;
1020 CString CAppUtils::GetProjectNameFromURL(CString url)
1022 CString name;
1023 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1024 (name.CompareNoCase(_T("tags"))==0) ||
1025 (name.CompareNoCase(_T("trunk"))==0))
1027 name = url.Mid(url.ReverseFind('/')+1);
1028 url = url.Left(url.ReverseFind('/'));
1030 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1032 // a name of svn or svnroot indicates that it's not really the project name. In that
1033 // case, we try the first part of the URL
1034 // of course, this won't work in all cases (but it works for Google project hosting)
1035 url.Replace(_T("http://"), _T(""));
1036 url.Replace(_T("https://"), _T(""));
1037 url.Replace(_T("svn://"), _T(""));
1038 url.Replace(_T("svn+ssh://"), _T(""));
1039 url.TrimLeft(_T("/"));
1040 name = url.Left(url.Find('.'));
1042 return name;
1045 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd, const CTGitPath& url1, const git_revnum_t& rev1,
1046 const CTGitPath& url2, const git_revnum_t& rev2,
1047 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1048 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool /* blame = false */)
1051 CString tempfile=GetTempFile();
1052 CString cmd;
1053 if(rev1 == GitRev::GetWorkingCopy())
1055 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1056 }else
1058 cmd.Format(_T("git.exe diff-tree -r -p --stat %s %s"),rev1,rev2);
1061 if( !url1.IsEmpty() )
1063 cmd+=_T(" \"");
1064 cmd+=url1.GetGitPathString();
1065 cmd+=_T("\" ");
1067 g_Git.RunLogFile(cmd,tempfile);
1068 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1071 #if 0
1072 CString sCmd;
1073 sCmd.Format(_T("%s /command:showcompare /unified"),
1074 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1075 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1076 if (rev1.IsValid())
1077 sCmd += _T(" /revision1:") + rev1.ToString();
1078 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1079 if (rev2.IsValid())
1080 sCmd += _T(" /revision2:") + rev2.ToString();
1081 if (peg.IsValid())
1082 sCmd += _T(" /pegrevision:") + peg.ToString();
1083 if (headpeg.IsValid())
1084 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1086 if (bAlternateDiff)
1087 sCmd += _T(" /alternatediff");
1089 if (bIgnoreAncestry)
1090 sCmd += _T(" /ignoreancestry");
1092 if (hWnd)
1094 sCmd += _T(" /hwnd:");
1095 TCHAR buf[30];
1096 _stprintf_s(buf, 30, _T("%d"), hWnd);
1097 sCmd += buf;
1100 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1101 #endif
1102 return TRUE;
1105 bool CAppUtils::StartShowCompare(HWND hWnd, const CTGitPath& url1, const GitRev& rev1,
1106 const CTGitPath& url2, const GitRev& rev2,
1107 const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1108 bool bAlternateDiff /* = false */, bool bIgnoreAncestry /* = false */, bool blame /* = false */)
1110 #if 0
1111 CString sCmd;
1112 sCmd.Format(_T("%s /command:showcompare"),
1113 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1114 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1115 if (rev1.IsValid())
1116 sCmd += _T(" /revision1:") + rev1.ToString();
1117 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1118 if (rev2.IsValid())
1119 sCmd += _T(" /revision2:") + rev2.ToString();
1120 if (peg.IsValid())
1121 sCmd += _T(" /pegrevision:") + peg.ToString();
1122 if (headpeg.IsValid())
1123 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1124 if (bAlternateDiff)
1125 sCmd += _T(" /alternatediff");
1126 if (bIgnoreAncestry)
1127 sCmd += _T(" /ignoreancestry");
1128 if (blame)
1129 sCmd += _T(" /blame");
1131 if (hWnd)
1133 sCmd += _T(" /hwnd:");
1134 TCHAR buf[30];
1135 _stprintf_s(buf, 30, _T("%d"), hWnd);
1136 sCmd += buf;
1139 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1140 #endif
1141 return true;
1144 bool CAppUtils::Export(CString *BashHash)
1146 bool bRet = false;
1148 // ask from where the export has to be done
1149 CExportDlg dlg;
1150 if(BashHash)
1151 dlg.m_Revision=*BashHash;
1153 if (dlg.DoModal() == IDOK)
1155 CString cmd;
1156 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1157 dlg.m_VersionName);
1159 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1160 CProgressDlg pro;
1161 pro.m_GitCmd=cmd;
1162 pro.m_LogFile=dlg.m_strExportDirectory;
1163 pro.DoModal();
1164 return TRUE;
1166 return bRet;
1169 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash)
1171 CCreateBranchTagDlg dlg;
1172 dlg.m_bIsTag=IsTag;
1173 if(CommitHash)
1174 dlg.m_Base = *CommitHash;
1176 if(dlg.DoModal()==IDOK)
1178 CString cmd;
1179 CString force;
1180 CString track;
1181 if(dlg.m_bTrack)
1182 track=_T(" --track ");
1184 if(dlg.m_bForce)
1185 force=_T(" -f ");
1187 if(IsTag)
1189 cmd.Format(_T("git.exe tag %s %s %s %s"),
1190 track,
1191 force,
1192 dlg.m_BranchTagName,
1193 dlg.m_VersionName
1196 CString tempfile=::GetTempFile();
1197 if(!dlg.m_Message.Trim().IsEmpty())
1199 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1200 cmd += _T(" -F ")+tempfile;
1203 }else
1205 cmd.Format(_T("git.exe branch %s %s %s %s"),
1206 track,
1207 force,
1208 dlg.m_BranchTagName,
1209 dlg.m_VersionName
1212 CString out;
1213 if(g_Git.Run(cmd,&out,CP_UTF8))
1215 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1217 if( !IsTag && dlg.m_bSwitch )
1219 // it is a new branch and the user has requested to switch to it
1220 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1221 g_Git.Run(cmd,&out,CP_UTF8);
1222 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1225 return TRUE;
1228 return FALSE;
1231 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1233 CGitSwitchDlg dlg;
1234 if(CommitHash)
1235 dlg.m_Base=*CommitHash;
1236 if(!initialRefName.IsEmpty())
1237 dlg.m_initialRefName = initialRefName;
1239 if (dlg.DoModal() == IDOK)
1241 CString cmd;
1242 CString track;
1243 // CString base;
1244 CString force;
1245 CString branch;
1247 if(dlg.m_bBranch)
1248 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1249 if(dlg.m_bForce)
1250 force=_T("-f");
1251 if(dlg.m_bTrack)
1252 track=_T("--track");
1254 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1255 force,
1256 track,
1257 branch,
1258 dlg.m_VersionName);
1260 CProgressDlg progress;
1261 progress.m_GitCmd=cmd;
1262 if(progress.DoModal()==IDOK)
1263 return TRUE;
1266 return FALSE;
1269 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1271 CString ignorefile;
1272 ignorefile=g_Git.m_CurrentDir+_T("\\");
1274 if(IsMask)
1276 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1278 }else
1280 ignorefile+=_T("\\.gitignore");
1283 CStdioFile file;
1284 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1286 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1287 return FALSE;
1290 CString ignorelist;
1291 CString mask;
1294 //file.ReadString(ignorelist);
1295 file.SeekToEnd();
1296 for(int i=0;i<path.GetCount();i++)
1298 if(IsMask)
1300 mask=_T("*")+path[i].GetFileExtension();
1301 if(ignorelist.Find(mask)<0)
1302 ignorelist+=_T("\n")+mask;
1304 }else
1306 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1309 file.WriteString(ignorelist);
1311 file.Close();
1313 }catch(...)
1315 file.Close();
1316 return FALSE;
1319 return TRUE;
1323 bool CAppUtils::GitReset(CString *CommitHash,int type)
1325 CResetDlg dlg;
1326 dlg.m_ResetType=type;
1327 if (dlg.DoModal() == IDOK)
1329 CString cmd;
1330 CString type;
1331 switch(dlg.m_ResetType)
1333 case 0:
1334 type=_T("--soft");
1335 break;
1336 case 1:
1337 type=_T("--mixed");
1338 break;
1339 case 2:
1340 type=_T("--hard");
1341 break;
1342 default:
1343 type=_T("--mixed");
1344 break;
1346 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1348 CProgressDlg progress;
1349 progress.m_GitCmd=cmd;
1350 if(progress.DoModal()==IDOK)
1351 return TRUE;
1354 return FALSE;
1357 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1359 if(mode == FALSE)
1361 descript=_T("Deleted");
1362 return;
1364 if(base)
1366 descript=_T("Modified");
1367 return;
1369 descript=_T("Created");
1370 return;
1373 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1375 CString tempmergefile;
1378 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1379 CFile::Remove(tempmergefile);
1380 }catch(...)
1386 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1387 CFile::Remove(tempmergefile);
1388 }catch(...)
1394 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1395 CFile::Remove(tempmergefile);
1396 }catch(...)
1400 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1402 CString file;
1403 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1405 return file;
1408 bool CAppUtils::ConflictEdit(CTGitPath &path,bool bAlternativeTool,bool revertTheirMy)
1410 bool bRet = false;
1412 CTGitPath merge=path;
1413 CTGitPath directory = merge.GetDirectory();
1417 // we have the conflicted file (%merged)
1418 // now look for the other required files
1419 //GitStatus stat;
1420 //stat.GetStatus(merge);
1421 //if (stat.status == NULL)
1422 // return false;
1424 BYTE_VECTOR vector;
1426 CString cmd;
1427 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1429 if(g_Git.Run(cmd,&vector))
1431 return FALSE;
1434 CTGitPathList list;
1435 list.ParserFromLsFile(vector);
1437 if(list.GetCount() == 0)
1438 return FALSE;
1440 TCHAR szTempName[512];
1441 GetTempFileName(_T(""),_T(""),0,szTempName);
1442 CString temp(szTempName);
1443 temp=temp.Mid(1,temp.GetLength()-5);
1445 CTGitPath theirs;
1446 CTGitPath mine;
1447 CTGitPath base;
1450 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1451 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1452 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1454 CString format;
1456 //format=_T("git.exe cat-file blob \":%d:%s\"");
1457 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1458 CFile tempfile;
1459 //create a empty file, incase stage is not three
1460 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1461 tempfile.Close();
1462 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1463 tempfile.Close();
1464 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1465 tempfile.Close();
1467 bool b_base=false, b_local=false, b_remote=false;
1469 for(int i=0;i<list.GetCount();i++)
1471 CString cmd;
1472 CString outfile;
1473 cmd.Empty();
1474 outfile.Empty();
1476 if( list[i].m_Stage == 1)
1478 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1479 b_base = true;
1480 outfile = base.GetWinPathString();
1483 if( list[i].m_Stage == 2 )
1485 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1486 b_local = true;
1487 outfile = mine.GetWinPathString();
1490 if( list[i].m_Stage == 3 )
1492 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1493 b_remote = true;
1494 outfile = theirs.GetWinPathString();
1496 CString output;
1497 if(!outfile.IsEmpty())
1498 if(!g_Git.Run(cmd,&output,CP_ACP))
1500 CString file;
1501 int start =0 ;
1502 file = output.Tokenize(_T("\t"), start);
1503 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1505 else
1507 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1511 if(b_local && b_remote )
1513 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1514 if( revertTheirMy )
1515 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1516 else
1517 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1519 }else
1521 CFile::Remove(mine.GetWinPathString());
1522 CFile::Remove(theirs.GetWinPathString());
1523 CFile::Remove(base.GetWinPathString());
1525 CDeleteConflictDlg dlg;
1526 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1527 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1528 dlg.m_bShowModifiedButton=b_base;
1529 dlg.m_File=merge.GetGitPathString();
1530 if(dlg.DoModal() == IDOK)
1532 CString cmd,out;
1533 if(dlg.m_bIsDelete)
1535 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1536 }else
1537 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1539 if(g_Git.Run(cmd,&out,CP_ACP))
1541 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1542 return FALSE;
1544 return TRUE;
1546 else
1547 return FALSE;
1553 #if 0
1555 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1556 base, theirs, mine, merge);
1557 #endif
1558 #if 0
1559 if (stat.status->text_status == svn_wc_status_conflicted)
1561 // we have a text conflict, use our merge tool to resolve the conflict
1563 CTSVNPath theirs(directory);
1564 CTSVNPath mine(directory);
1565 CTSVNPath base(directory);
1566 bool bConflictData = false;
1568 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1570 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1571 bConflictData = true;
1573 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1575 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1576 bConflictData = true;
1578 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1580 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1581 bConflictData = true;
1583 else
1585 mine = merge;
1587 if (bConflictData)
1588 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1589 base, theirs, mine, merge);
1592 if (stat.status->prop_status == svn_wc_status_conflicted)
1594 // we have a property conflict
1595 CTSVNPath prej(directory);
1596 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1598 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1599 // there's a problem: the prej file contains a _description_ of the conflict, and
1600 // that description string might be translated. That means we have no way of parsing
1601 // the file to find out the conflicting values.
1602 // The only thing we can do: show a dialog with the conflict description, then
1603 // let the user either accept the existing property or open the property edit dialog
1604 // to manually change the properties and values. And a button to mark the conflict as
1605 // resolved.
1606 CEditPropConflictDlg dlg;
1607 dlg.SetPrejFile(prej);
1608 dlg.SetConflictedItem(merge);
1609 bRet = (dlg.DoModal() != IDCANCEL);
1613 if (stat.status->tree_conflict)
1615 // we have a tree conflict
1616 SVNInfo info;
1617 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1618 if (pInfoData)
1620 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1622 CTSVNPath theirs(directory);
1623 CTSVNPath mine(directory);
1624 CTSVNPath base(directory);
1625 bool bConflictData = false;
1627 if (pInfoData->treeconflict_theirfile)
1629 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1630 bConflictData = true;
1632 if (pInfoData->treeconflict_basefile)
1634 base.AppendPathString(pInfoData->treeconflict_basefile);
1635 bConflictData = true;
1637 if (pInfoData->treeconflict_myfile)
1639 mine.AppendPathString(pInfoData->treeconflict_myfile);
1640 bConflictData = true;
1642 else
1644 mine = merge;
1646 if (bConflictData)
1647 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1648 base, theirs, mine, merge);
1650 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1652 CString sConflictAction;
1653 CString sConflictReason;
1654 CString sResolveTheirs;
1655 CString sResolveMine;
1656 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1657 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1659 if (pInfoData->treeconflict_nodekind == svn_node_file)
1661 switch (pInfoData->treeconflict_operation)
1663 case svn_wc_operation_update:
1664 switch (pInfoData->treeconflict_action)
1666 case svn_wc_conflict_action_edit:
1667 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1668 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1669 break;
1670 case svn_wc_conflict_action_add:
1671 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1672 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1673 break;
1674 case svn_wc_conflict_action_delete:
1675 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1676 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1677 break;
1679 break;
1680 case svn_wc_operation_switch:
1681 switch (pInfoData->treeconflict_action)
1683 case svn_wc_conflict_action_edit:
1684 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1685 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1686 break;
1687 case svn_wc_conflict_action_add:
1688 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1689 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1690 break;
1691 case svn_wc_conflict_action_delete:
1692 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1693 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1694 break;
1696 break;
1697 case svn_wc_operation_merge:
1698 switch (pInfoData->treeconflict_action)
1700 case svn_wc_conflict_action_edit:
1701 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1702 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1703 break;
1704 case svn_wc_conflict_action_add:
1705 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1706 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1707 break;
1708 case svn_wc_conflict_action_delete:
1709 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1710 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1711 break;
1713 break;
1716 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1718 switch (pInfoData->treeconflict_operation)
1720 case svn_wc_operation_update:
1721 switch (pInfoData->treeconflict_action)
1723 case svn_wc_conflict_action_edit:
1724 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1725 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1726 break;
1727 case svn_wc_conflict_action_add:
1728 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1729 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1730 break;
1731 case svn_wc_conflict_action_delete:
1732 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1733 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1734 break;
1736 break;
1737 case svn_wc_operation_switch:
1738 switch (pInfoData->treeconflict_action)
1740 case svn_wc_conflict_action_edit:
1741 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1742 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1743 break;
1744 case svn_wc_conflict_action_add:
1745 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1746 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1747 break;
1748 case svn_wc_conflict_action_delete:
1749 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1750 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1751 break;
1753 break;
1754 case svn_wc_operation_merge:
1755 switch (pInfoData->treeconflict_action)
1757 case svn_wc_conflict_action_edit:
1758 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1759 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1760 break;
1761 case svn_wc_conflict_action_add:
1762 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1763 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1764 break;
1765 case svn_wc_conflict_action_delete:
1766 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1767 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1768 break;
1770 break;
1774 UINT uReasonID = 0;
1775 switch (pInfoData->treeconflict_reason)
1777 case svn_wc_conflict_reason_edited:
1778 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1779 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1780 break;
1781 case svn_wc_conflict_reason_obstructed:
1782 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1783 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1784 break;
1785 case svn_wc_conflict_reason_deleted:
1786 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1787 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1788 break;
1789 case svn_wc_conflict_reason_added:
1790 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1791 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1792 break;
1793 case svn_wc_conflict_reason_missing:
1794 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1795 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1796 break;
1797 case svn_wc_conflict_reason_unversioned:
1798 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1799 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1800 break;
1802 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1804 CTreeConflictEditorDlg dlg;
1805 dlg.SetConflictInfoText(sConflictReason);
1806 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1807 dlg.SetPath(treeConflictPath);
1808 INT_PTR dlgRet = dlg.DoModal();
1809 bRet = (dlgRet != IDCANCEL);
1813 #endif
1814 return bRet;
1818 * FUNCTION : FormatDateAndTime
1819 * DESCRIPTION : Generates a displayable string from a CTime object in
1820 * system short or long format or as a relative value
1821 * cTime - the time
1822 * option - DATE_SHORTDATE or DATE_LONGDATE
1823 * bIncluedeTime - whether to show time as well as date
1824 * bRelative - if true then relative time is shown if reasonable
1825 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1826 * rather than locale
1827 * RETURN : CString containing date/time
1829 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1830 bool bRelative /*=false*/)
1832 CString datetime;
1833 if ( bRelative )
1835 datetime = ToRelativeTimeString( cTime );
1837 else
1839 // should we use the locale settings for formatting the date/time?
1840 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1842 // yes
1843 SYSTEMTIME sysTime;
1844 cTime.GetAsSystemTime( sysTime );
1846 TCHAR buf[100];
1848 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1849 sizeof(buf)/sizeof(TCHAR)-1);
1850 datetime = buf;
1851 if ( bIncludeTime )
1853 datetime += _T(" ");
1854 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1855 datetime += buf;
1858 else
1860 // no, so fixed format
1861 if ( bIncludeTime )
1863 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1865 else
1867 datetime = cTime.Format(_T("%Y-%m-%d"));
1871 return datetime;
1875 * Converts a given time to a relative display string (relative to current time)
1876 * Given time must be in local timezone
1878 CString CAppUtils::ToRelativeTimeString(CTime time)
1880 CString answer;
1881 // convert to COleDateTime
1882 SYSTEMTIME sysTime;
1883 time.GetAsSystemTime( sysTime );
1884 COleDateTime oleTime( sysTime );
1885 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1886 return answer;
1890 * Generates a display string showing the relative time between the two given times as COleDateTimes
1892 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1894 CString answer;
1895 COleDateTimeSpan ts = RelativeTo - time;
1896 //years
1897 if(fabs(ts.GetTotalDays()) >= 3*365)
1899 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1901 //Months
1902 if(fabs(ts.GetTotalDays()) >= 60)
1904 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1905 return answer;
1907 //Weeks
1908 if(fabs(ts.GetTotalDays()) >= 14)
1910 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1911 return answer;
1913 //Days
1914 if(fabs(ts.GetTotalDays()) >= 2)
1916 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1917 return answer;
1919 //hours
1920 if(fabs(ts.GetTotalHours()) >= 2)
1922 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1923 return answer;
1925 //minutes
1926 if(fabs(ts.GetTotalMinutes()) >= 2)
1928 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1929 return answer;
1931 //seconds
1932 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1933 return answer;
1936 /**
1937 * Passed a value and two resource string ids
1938 * if count is 1 then FormatString is called with format_1 and the value
1939 * otherwise format_2 is used
1940 * the formatted string is returned
1942 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1944 CString answer;
1945 if ( count == 1 )
1947 answer.FormatMessage( format_1, count );
1949 else
1951 answer.FormatMessage( format_n, count );
1953 return answer;
1956 bool CAppUtils::IsSSHPutty()
1958 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1959 sshclient=sshclient.MakeLower();
1960 if(sshclient.Find(_T("plink.exe"),0)>=0)
1962 return true;
1964 return false;
1967 CString CAppUtils::GetClipboardLink()
1969 if (!OpenClipboard(NULL))
1970 return CString();
1972 CString sClipboardText;
1973 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1974 if (hglb)
1976 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1977 sClipboardText = CString(lpstr);
1978 GlobalUnlock(hglb);
1980 hglb = GetClipboardData(CF_UNICODETEXT);
1981 if (hglb)
1983 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1984 sClipboardText = lpstr;
1985 GlobalUnlock(hglb);
1987 CloseClipboard();
1989 if(!sClipboardText.IsEmpty())
1991 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1992 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1994 if(sClipboardText.Find( _T("http://")) == 0)
1995 return sClipboardText;
1997 if(sClipboardText.Find( _T("https://")) == 0)
1998 return sClipboardText;
2000 if(sClipboardText.Find( _T("git://")) == 0)
2001 return sClipboardText;
2003 if(sClipboardText.Find( _T("ssh://")) == 0)
2004 return sClipboardText;
2006 if(sClipboardText.GetLength()>=2)
2007 if( sClipboardText[1] == _T(':') )
2008 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2009 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2010 return sClipboardText;
2013 return CString(_T(""));
2016 CString CAppUtils::ChooseRepository(CString *path)
2018 CBrowseFolder browseFolder;
2019 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2021 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2022 CString strCloneDirectory;
2023 if(path)
2024 strCloneDirectory=*path;
2025 else
2027 strCloneDirectory = regLastResopitory;
2030 CString title;
2031 title.LoadString(IDS_CHOOSE_REPOSITORY);
2033 browseFolder.SetInfo(title);
2035 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2037 regLastResopitory = strCloneDirectory;
2038 return strCloneDirectory;
2040 }else
2042 return CString();
2047 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2049 CSendMailDlg dlg;
2051 dlg.m_PathList = list;
2053 if(dlg.DoModal()==IDOK)
2055 if(dlg.m_PathList.GetCount() == 0)
2056 return FALSE;
2058 CGitProgressDlg progDlg;
2060 theApp.m_pMainWnd = &progDlg;
2061 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2063 progDlg.SetAutoClose(autoclose);
2065 progDlg.SetPathList(dlg.m_PathList);
2066 //ProjectProperties props;
2067 //props.ReadPropsPathList(dlg.m_pathList);
2068 //progDlg.SetProjectProperties(props);
2069 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2071 DWORD flags =0;
2072 if(dlg.m_bAttachment)
2073 flags |= SENDMAIL_ATTACHMENT;
2074 if(dlg.m_bCombine)
2075 flags |= SENDMAIL_COMBINED;
2077 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2079 progDlg.DoModal();
2081 return true;
2083 return false;
2086 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2088 CTGitPathList list;
2089 CString log=formatpatchoutput;
2090 int start=log.Find(cmd);
2091 if(start >=0)
2092 CString one=log.Tokenize(_T("\n"),start);
2093 else
2094 start = 0;
2096 while(start>=0)
2098 CString one=log.Tokenize(_T("\n"),start);
2099 one=one.Trim();
2100 if(one.IsEmpty())
2101 continue;
2102 one.Replace(_T('/'),_T('\\'));
2103 CTGitPath path;
2104 path.SetFromWin(one);
2105 list.AddPath(path);
2107 return SendPatchMail(list,autoclose);
2111 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2113 CString cmd,output;
2114 int start=0;
2115 cmd=_T("git.exe config i18n.logOutputEncoding");
2116 if(pGit->Run(cmd,&output,CP_ACP))
2118 cmd=_T("git.exe config i18n.commitencoding");
2119 if(pGit->Run(cmd,&output,CP_ACP))
2120 return CP_UTF8;
2122 int start=0;
2123 output=output.Tokenize(_T("\n"),start);
2124 return CUnicodeUtils::GetCPCode(output);
2126 }else
2128 output=output.Tokenize(_T("\n"),start);
2129 return CUnicodeUtils::GetCPCode(output);
2132 int CAppUtils::GetCommitTemplate(CString &temp)
2134 CString cmd,output;
2135 cmd = _T("git.exe config commit.template");
2136 if( g_Git.Run(cmd,&output,CP_ACP) )
2137 return -1;
2139 if( output.GetLength()<1)
2140 return -1;
2142 if( output[0] == _T('/'))
2144 if(output.GetLength()>=3)
2145 if(output[2] == _T('/'))
2147 output.GetBuffer()[0] = output[1];
2148 output.GetBuffer()[1] = _T(':');
2152 int start=0;
2153 output=output.Tokenize(_T("\n"),start);
2155 output.Replace(_T('/'),_T('\\'));
2159 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2160 CString str;
2161 while(file.ReadString(str))
2163 temp+=str+_T("\n");
2166 }catch(...)
2168 return -1;
2170 return 0;
2174 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2176 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2177 CString cmd,output;
2178 int cp=CP_UTF8;
2180 cmd=_T("git.exe config i18n.commitencoding");
2181 if(g_Git.Run(cmd,&output,CP_ACP))
2182 cp=CP_UTF8;
2184 int start=0;
2185 output=output.Tokenize(_T("\n"),start);
2186 cp=CUnicodeUtils::GetCPCode(output);
2188 int len=message.GetLength();
2190 char * buf;
2191 buf = new char[len*4 + 4];
2192 SecureZeroMemory(buf, (len*4 + 4));
2194 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2196 file.Write(buf,lengthIncTerminator-1);
2197 file.Close();
2198 delete buf;
2199 return 0;
2202 bool CAppUtils::Push()
2204 CPushDlg dlg;
2205 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2206 CString error;
2207 DWORD exitcode = -1;
2208 CTGitPathList list;
2209 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2210 if (CHooks::Instance().PrePush(list,exitcode, error))
2212 if (exitcode)
2214 CString temp;
2215 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2216 //ReportError(temp);
2217 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2218 return false;
2222 if(dlg.DoModal()==IDOK)
2224 // CString dir=dlg.m_Directory;
2225 // CString url=dlg.m_URL;
2226 CString cmd;
2227 CString force;
2228 CString tags;
2229 CString thin;
2231 if(dlg.m_bAutoLoad)
2233 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2236 if(dlg.m_bPack)
2237 thin=_T("--thin");
2238 if(dlg.m_bTags)
2239 tags=_T("--tags");
2240 if(dlg.m_bForce)
2241 force=_T("--force");
2243 cmd.Format(_T("git.exe push %s %s %s \"%s\" %s"),
2244 thin,tags,force,
2245 dlg.m_URL,
2246 dlg.m_BranchSourceName);
2247 if (!dlg.m_BranchRemoteName.IsEmpty())
2249 cmd += _T(":") + dlg.m_BranchRemoteName;
2252 CProgressDlg progress;
2253 progress.m_GitCmd=cmd;
2254 progress.DoModal();
2256 if(!progress.m_GitStatus)
2258 if (CHooks::Instance().PostPush(list,exitcode, error))
2260 if (exitcode)
2262 CString temp;
2263 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2264 //ReportError(temp);
2265 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2266 return false;
2270 return TRUE;
2274 return FALSE;
2277 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2279 CString strDir(szPath);
2280 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2282 strDir.AppendChar(_T('\\'));
2284 std::vector<CString> vPath;
2285 CString strTemp;
2286 bool bSuccess = false;
2288 for (int i=0;i<strDir.GetLength();++i)
2290 if (strDir.GetAt(i) != _T('\\'))
2292 strTemp.AppendChar(strDir.GetAt(i));
2294 else
2296 vPath.push_back(strTemp);
2297 strTemp.AppendChar(_T('\\'));
2301 std::vector<CString>::const_iterator vIter;
2302 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2304 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2307 return bSuccess;
2310 void CAppUtils::RemoveTrailSlash(CString &path)
2312 if(path.IsEmpty())
2313 return ;
2315 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2317 path=path.Left(path.GetLength()-1);
2318 if(path.IsEmpty())
2319 return;
2323 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2324 CTGitPathList &pathList,
2325 CTGitPathList &selectedList,
2326 BOOL bSelectFilesForCommit)
2328 bool bFailed = true;
2330 while(g_Git.GetConfigValue(_T("user.name")).IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2332 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"),
2333 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2335 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&CTGitPath(g_Git.m_CurrentDir));
2336 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2337 dlg.SetTreeWidth(220);
2338 dlg.m_DefaultPage = _T("gitconfig");
2340 dlg.DoModal();
2341 dlg.HandleRestart();
2343 }else
2344 return false;
2347 while (bFailed)
2349 bFailed = false;
2350 CCommitDlg dlg;
2351 dlg.m_sBugID = bugid;
2353 dlg.m_bWholeProject = bWholeProject;
2355 dlg.m_sLogMessage = sLogMsg;
2356 dlg.m_pathList = pathList;
2357 dlg.m_checkedPathList = selectedList;
2358 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2359 if (dlg.DoModal() == IDOK)
2361 if (dlg.m_pathList.GetCount()==0)
2362 return false;
2363 // if the user hasn't changed the list of selected items
2364 // we don't use that list. Because if we would use the list
2365 // of pre-checked items, the dialog would show different
2366 // checked items on the next startup: it would only try
2367 // to check the parent folder (which might not even show)
2368 // instead, we simply use an empty list and let the
2369 // default checking do its job.
2370 if (!dlg.m_pathList.IsEqual(pathList))
2371 selectedList = dlg.m_pathList;
2372 pathList = dlg.m_updatedPathList;
2373 sLogMsg = dlg.m_sLogMessage;
2374 bSelectFilesForCommit = true;
2376 if( dlg.m_bPushAfterCommit )
2378 switch(dlg.m_PostCmd)
2380 case GIT_POST_CMD_DCOMMIT:
2381 CAppUtils::SVNDCommit();
2382 break;
2383 default:
2384 CAppUtils::Push();
2387 // CGitProgressDlg progDlg;
2388 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2389 // if (parser.HasVal(_T("closeonend")))
2390 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2391 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2392 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2393 // progDlg.SetPathList(dlg.m_pathList);
2394 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2395 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2396 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2397 // progDlg.SetItemCount(dlg.m_itemsCount);
2398 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2399 // progDlg.DoModal();
2400 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2401 // err = (DWORD)progDlg.DidErrorsOccur();
2402 // bFailed = progDlg.DidErrorsOccur();
2403 // bRet = progDlg.DidErrorsOccur();
2404 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2405 // if (DWORD(bFailRepeat)==0)
2406 // bFailed = false; // do not repeat if the user chose not to in the settings.
2409 return true;
2413 BOOL CAppUtils::SVNDCommit()
2415 BOOL IsStash = false;
2416 if(!g_Git.CheckCleanWorkTree())
2418 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2420 CString cmd,out;
2421 cmd=_T("git.exe stash");
2422 if(g_Git.Run(cmd,&out,CP_ACP))
2424 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2425 return false;
2427 IsStash =true;
2429 }else
2431 return false;
2435 CProgressDlg progress;
2436 progress.m_GitCmd=_T("git.exe svn dcommit");
2437 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2439 if( IsStash)
2441 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2443 CString cmd,out;
2444 cmd=_T("git.exe stash pop");
2445 if(g_Git.Run(cmd,&out,CP_ACP))
2447 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2448 return false;
2451 }else
2453 return false;
2456 return TRUE;
2458 return FALSE;
2461 BOOL CAppUtils::Merge(CString *commit, int mode)
2463 CMergeDlg dlg;
2464 if(commit)
2465 dlg.m_initialRefName = *commit;
2467 if(dlg.DoModal()==IDOK)
2469 CString cmd;
2470 CString noff;
2471 CString squash;
2472 CString nocommit;
2473 CString msg;
2475 if(dlg.m_bNoFF)
2476 noff=_T("--no-ff");
2478 if(dlg.m_bSquash)
2479 squash=_T("--squash");
2481 if(dlg.m_bNoCommit)
2482 nocommit=_T("--no-commit");
2484 if(!dlg.m_strLogMesage.IsEmpty())
2486 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2488 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2489 msg,
2490 noff,
2491 squash,
2492 nocommit,
2493 dlg.m_VersionName);
2495 CProgressDlg Prodlg;
2496 Prodlg.m_GitCmd = cmd;
2498 Prodlg.DoModal();
2500 return !Prodlg.m_GitStatus;
2502 return false;