allow do open commit dialog on merge w/o commit
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blob4170df1a8e08718290a3a9d3d7c841d96384371b
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - TortoiseGit
4 // Copyright (C) 2003-2011 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "StdAfx.h"
21 #include "resource.h"
22 #include "TortoiseProc.h"
23 #include "PathUtils.h"
24 #include "AppUtils.h"
25 //#include "GitProperties.h"
26 #include "StringUtils.h"
27 #include "MessageBox.h"
28 #include "Registry.h"
29 #include "TGitPath.h"
30 #include "Git.h"
31 //#include "RepositoryBrowser.h"
32 //#include "BrowseFolder.h"
33 #include "UnicodeUtils.h"
34 #include "ExportDlg.h"
35 #include "ProgressDlg.h"
36 #include "GitAdminDir.h"
37 #include "ProgressDlg.h"
38 #include "BrowseFolder.h"
39 #include "DirFileEnum.h"
40 #include "MessageBox.h"
41 #include "GitStatus.h"
42 #include "CreateBranchTagDlg.h"
43 #include "GitSwitchDlg.h"
44 #include "ResetDlg.h"
45 #include "DeleteConflictDlg.h"
46 #include "ChangedDlg.h"
47 #include "SendMailDlg.h"
48 #include "SVNProgressDlg.h"
49 #include "PushDlg.h"
50 #include "CommitDlg.h"
51 #include "MergeDlg.h"
52 #include "hooks.h"
53 #include "..\Settings\Settings.h"
54 #include "InputDlg.h"
55 #include "SVNDCommitDlg.h"
56 #include "requestpulldlg.h"
57 #include "PullFetchDlg.h"
58 #include "RebaseDlg.h"
59 #include "PropKey.h"
61 CAppUtils::CAppUtils(void)
65 CAppUtils::~CAppUtils(void)
69 int CAppUtils::StashApply(CString ref)
71 CString cmd,out;
72 cmd=_T("git.exe stash apply ");
73 cmd+=ref;
75 if(g_Git.Run(cmd,&out,CP_ACP))
77 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
80 else
82 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
83 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
85 CChangedDlg dlg;
86 dlg.m_pathList.AddPath(CTGitPath());
87 dlg.DoModal();
89 return 0;
91 return -1;
94 int CAppUtils::StashPop()
96 CString cmd,out;
97 cmd=_T("git.exe stash pop ");
99 if(g_Git.Run(cmd,&out,CP_ACP))
101 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
104 else
106 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
107 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
109 CChangedDlg dlg;
110 dlg.m_pathList.AddPath(CTGitPath());
111 dlg.DoModal();
113 return 0;
115 return -1;
118 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
120 #if 0
121 GitProperties props(file, GitRev::REV_WC, false);
122 for (int i = 0; i < props.GetCount(); ++i)
124 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
126 mimetype = props.GetItemValue(i).c_str();
127 return true;
130 #endif
131 return false;
134 BOOL CAppUtils::StartExtMerge(
135 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
136 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
139 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
140 CString ext = mergedfile.GetFileExtension();
141 CString com = regCom;
142 bool bInternal = false;
144 CString mimetype;
145 if (ext != "")
147 // is there an extension specific merge tool?
148 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
149 if (CString(mergetool) != "")
151 com = mergetool;
154 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
156 // is there a mime type specific merge tool?
157 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
158 if (CString(mergetool) != "")
160 com = mergetool;
164 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
166 // use TortoiseMerge
167 bInternal = true;
168 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
169 com = tortoiseMergePath;
170 if (com.IsEmpty())
172 com = CPathUtils::GetAppDirectory();
173 com += _T("TortoiseMerge.exe");
175 com = _T("\"") + com + _T("\"");
176 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
177 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
179 // check if the params are set. If not, just add the files to the command line
180 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
182 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
183 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
184 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
185 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
187 if (basefile.IsEmpty())
189 com.Replace(_T("/base:%base"), _T(""));
190 com.Replace(_T("%base"), _T(""));
192 else
193 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
194 if (theirfile.IsEmpty())
196 com.Replace(_T("/theirs:%theirs"), _T(""));
197 com.Replace(_T("%theirs"), _T(""));
199 else
200 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
201 if (yourfile.IsEmpty())
203 com.Replace(_T("/mine:%mine"), _T(""));
204 com.Replace(_T("%mine"), _T(""));
206 else
207 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
208 if (mergedfile.IsEmpty())
210 com.Replace(_T("/merged:%merged"), _T(""));
211 com.Replace(_T("%merged"), _T(""));
213 else
214 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
215 if (basename.IsEmpty())
217 if (basefile.IsEmpty())
219 com.Replace(_T("/basename:%bname"), _T(""));
220 com.Replace(_T("%bname"), _T(""));
222 else
224 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
227 else
228 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
229 if (theirname.IsEmpty())
231 if (theirfile.IsEmpty())
233 com.Replace(_T("/theirsname:%tname"), _T(""));
234 com.Replace(_T("%tname"), _T(""));
236 else
238 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
241 else
242 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
243 if (yourname.IsEmpty())
245 if (yourfile.IsEmpty())
247 com.Replace(_T("/minename:%yname"), _T(""));
248 com.Replace(_T("%yname"), _T(""));
250 else
252 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
255 else
256 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
257 if (mergedname.IsEmpty())
259 if (mergedfile.IsEmpty())
261 com.Replace(_T("/mergedname:%mname"), _T(""));
262 com.Replace(_T("%mname"), _T(""));
264 else
266 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
269 else
270 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
272 if ((bReadOnly)&&(bInternal))
273 com += _T(" /readonly");
275 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
277 return FALSE;
280 return TRUE;
283 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
285 CString viewer;
286 // use TortoiseMerge
287 viewer = CPathUtils::GetAppDirectory();
288 viewer += _T("TortoiseMerge.exe");
290 viewer = _T("\"") + viewer + _T("\"");
291 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
292 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
293 if (bReversed)
294 viewer += _T(" /reversedpatch");
295 if (!sOriginalDescription.IsEmpty())
296 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
297 if (!sPatchedDescription.IsEmpty())
298 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
299 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
301 return FALSE;
303 return TRUE;
306 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
308 // Is there a mime type specific diff tool?
309 CString mimetype;
310 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
312 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
313 if (!difftool.IsEmpty())
314 return difftool;
317 // Is there an extension specific diff tool?
318 CString ext = file2.GetFileExtension().MakeLower();
319 if (!ext.IsEmpty())
321 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
322 if (!difftool.IsEmpty())
323 return difftool;
324 // Maybe we should use TortoiseIDiff?
325 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
326 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
327 (ext == _T(".png")) || (ext == _T(".ico")) ||
328 (ext == _T(".dib")) || (ext == _T(".emf")))
330 return
331 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
332 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
336 // Finally, pick a generic external diff tool
337 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
338 return difftool;
341 bool CAppUtils::StartExtDiff(
342 const CString& file1, const CString& file2,
343 const CString& sName1, const CString& sName2,
344 const DiffFlags& flags)
346 CString viewer;
348 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
349 if (!flags.bBlame || !(DWORD)blamediff)
351 viewer = PickDiffTool(file1, file2);
352 // If registry entry for a diff program is commented out, use TortoiseMerge.
353 bool bCommentedOut = viewer.Left(1) == _T("#");
354 if (flags.bAlternativeTool)
356 // Invert external vs. internal diff tool selection.
357 if (bCommentedOut)
358 viewer.Delete(0); // uncomment
359 else
360 viewer = "";
362 else if (bCommentedOut)
363 viewer = "";
366 bool bInternal = viewer.IsEmpty();
367 if (bInternal)
369 viewer =
370 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
371 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
372 if (flags.bBlame)
373 viewer += _T(" /blame");
375 // check if the params are set. If not, just add the files to the command line
376 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
378 viewer += _T(" \"")+file1+_T("\"");
379 viewer += _T(" \"")+file2+_T("\"");
381 if (viewer.Find(_T("%base")) >= 0)
383 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
385 if (viewer.Find(_T("%mine")) >= 0)
387 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
390 if (sName1.IsEmpty())
391 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
392 else
393 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
395 if (sName2.IsEmpty())
396 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
397 else
398 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
400 if (flags.bReadOnly && bInternal)
401 viewer += _T(" /readonly");
403 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
406 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
408 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
409 CString viewer = diffpropsexe;
410 bool bInternal = false;
411 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
413 //no registry entry (or commented out) for a diff program
414 //use TortoiseMerge
415 bInternal = true;
416 viewer = CPathUtils::GetAppDirectory();
417 viewer += _T("TortoiseMerge.exe");
418 viewer = _T("\"") + viewer + _T("\"");
419 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
421 // check if the params are set. If not, just add the files to the command line
422 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
424 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
425 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
427 if (viewer.Find(_T("%base")) >= 0)
429 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
431 if (viewer.Find(_T("%mine")) >= 0)
433 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
436 if (sName1.IsEmpty())
437 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
438 else
439 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
441 if (sName2.IsEmpty())
442 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
443 else
444 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
446 if ((bReadOnly)&&(bInternal))
447 viewer += _T(" /readonly");
449 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
451 return FALSE;
453 return TRUE;
456 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
458 CString viewer;
459 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
460 viewer = v;
461 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
463 // use TortoiseUDiff
464 viewer = CPathUtils::GetAppDirectory();
465 viewer += _T("TortoiseUDiff.exe");
466 // enquote the path to TortoiseUDiff
467 viewer = _T("\"") + viewer + _T("\"");
468 // add the params
469 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
472 if (viewer.Find(_T("%1"))>=0)
474 if (viewer.Find(_T("\"%1\"")) >= 0)
475 viewer.Replace(_T("%1"), patchfile);
476 else
477 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
479 else
480 viewer += _T(" \"") + patchfile + _T("\"");
481 if (viewer.Find(_T("%title")) >= 0)
483 viewer.Replace(_T("%title"), title);
486 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
488 return FALSE;
490 return TRUE;
493 BOOL CAppUtils::StartTextViewer(CString file)
495 CString viewer;
496 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
497 viewer = txt;
498 viewer = viewer + _T("\\Shell\\Open\\Command\\");
499 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
500 viewer = txtexe;
502 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
503 TCHAR * buf = new TCHAR[len+1];
504 ExpandEnvironmentStrings(viewer, buf, len);
505 viewer = buf;
506 delete [] buf;
507 len = ExpandEnvironmentStrings(file, NULL, 0);
508 buf = new TCHAR[len+1];
509 ExpandEnvironmentStrings(file, buf, len);
510 file = buf;
511 delete [] buf;
512 file = _T("\"")+file+_T("\"");
513 if (viewer.IsEmpty())
515 OPENFILENAME ofn = {0}; // common dialog box structure
516 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
517 // Initialize OPENFILENAME
518 ofn.lStructSize = sizeof(OPENFILENAME);
519 ofn.hwndOwner = NULL;
520 ofn.lpstrFile = szFile;
521 ofn.nMaxFile = _countof(szFile);
522 CString sFilter;
523 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
524 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
525 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
526 // Replace '|' delimiters with '\0's
527 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
528 while (ptr != pszFilters)
530 if (*ptr == '|')
531 *ptr = '\0';
532 ptr--;
534 ofn.lpstrFilter = pszFilters;
535 ofn.nFilterIndex = 1;
536 ofn.lpstrFileTitle = NULL;
537 ofn.nMaxFileTitle = 0;
538 ofn.lpstrInitialDir = NULL;
539 CString temp;
540 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
541 CStringUtils::RemoveAccelerators(temp);
542 ofn.lpstrTitle = temp;
543 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
545 // Display the Open dialog box.
547 if (GetOpenFileName(&ofn)==TRUE)
549 delete [] pszFilters;
550 viewer = CString(ofn.lpstrFile);
552 else
554 delete [] pszFilters;
555 return FALSE;
558 if (viewer.Find(_T("\"%1\"")) >= 0)
560 viewer.Replace(_T("\"%1\""), file);
562 else if (viewer.Find(_T("%1")) >= 0)
564 viewer.Replace(_T("%1"), file);
566 else
568 viewer += _T(" ");
569 viewer += file;
572 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
574 return FALSE;
576 return TRUE;
579 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
581 DWORD length = 0;
582 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
583 if (hFile == INVALID_HANDLE_VALUE)
584 return TRUE;
585 length = ::GetFileSize(hFile, NULL);
586 ::CloseHandle(hFile);
587 if (length < 4)
588 return TRUE;
589 return FALSE;
593 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
595 LOGFONT logFont;
596 HDC hScreenDC = ::GetDC(NULL);
597 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
598 ::ReleaseDC(NULL, hScreenDC);
599 logFont.lfWidth = 0;
600 logFont.lfEscapement = 0;
601 logFont.lfOrientation = 0;
602 logFont.lfWeight = FW_NORMAL;
603 logFont.lfItalic = 0;
604 logFont.lfUnderline = 0;
605 logFont.lfStrikeOut = 0;
606 logFont.lfCharSet = DEFAULT_CHARSET;
607 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
608 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
609 logFont.lfQuality = DRAFT_QUALITY;
610 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
611 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
612 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
615 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
617 STARTUPINFO startup;
618 PROCESS_INFORMATION process;
619 memset(&startup, 0, sizeof(startup));
620 startup.cb = sizeof(startup);
621 memset(&process, 0, sizeof(process));
623 CString cleanCommandLine(sCommandLine);
625 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
627 if(idErrMessageFormat != 0)
629 LPVOID lpMsgBuf;
630 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
631 FORMAT_MESSAGE_FROM_SYSTEM |
632 FORMAT_MESSAGE_IGNORE_INSERTS,
633 NULL,
634 GetLastError(),
635 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
636 (LPTSTR) &lpMsgBuf,
638 NULL
640 CString temp;
641 temp.Format(idErrMessageFormat, lpMsgBuf);
642 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
643 LocalFree( lpMsgBuf );
645 return false;
648 if (bWaitForStartup)
650 WaitForInputIdle(process.hProcess, 10000);
653 CloseHandle(process.hThread);
654 CloseHandle(process.hProcess);
655 return true;
657 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
659 CString key,remote;
660 CString cmd,out;
661 if( pRemote == NULL)
663 remote=_T("origin");
665 else
667 remote=*pRemote;
669 if(keyfile == NULL)
671 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
672 key = g_Git.GetConfigValue(cmd);
673 int start=0;
674 key = key.Tokenize(_T("\n"),start);
676 else
677 key=*keyfile;
679 if(key.IsEmpty())
680 return false;
682 CString proc=CPathUtils::GetAppDirectory();
683 proc += _T("pageant.exe \"");
684 proc += key;
685 proc += _T("\"");
687 CString tempfile = GetTempFile();
688 ::DeleteFile(tempfile);
690 proc += _T(" -c \"");
691 proc += CPathUtils::GetAppDirectory();
692 proc += _T("touch.exe\"");
693 proc += _T(" \"");
694 proc += tempfile;
695 proc += _T("\"");
697 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
698 if(!b)
699 return b;
701 int i=0;
702 while(!::PathFileExists(tempfile))
704 Sleep(100);
705 i++;
706 if(i>10*60*5)
707 break; //timeout 5 minutes
710 if( i== 10*60*5)
712 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
714 ::DeleteFile(tempfile);
715 return true;
717 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
719 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
720 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
721 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
724 CString sCmd;
725 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
727 LaunchApplication(sCmd, NULL, false);
728 return true;
730 bool CAppUtils::LaunchRemoteSetting()
732 CTGitPath path(g_Git.m_CurrentDir);
733 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
734 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
735 //dlg.SetTreeWidth(220);
736 dlg.m_DefaultPage = _T("gitremote");
738 dlg.DoModal();
739 dlg.HandleRestart();
740 return true;
743 * Launch the external blame viewer
745 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
747 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
748 viewer += _T("TortoiseGitBlame.exe");
749 viewer += _T("\" \"") + sBlameFile + _T("\"");
750 //viewer += _T(" \"") + sLogFile + _T("\"");
751 //viewer += _T(" \"") + sOriginalFile + _T("\"");
752 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
753 viewer += CString(_T(" /rev:"))+Rev;
754 viewer += _T(" ")+sParams;
756 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
759 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
761 CString sText;
762 if (pWnd == NULL)
763 return false;
764 bool bStyled = false;
765 pWnd->GetWindowText(sText);
766 // the rich edit control doesn't count the CR char!
767 // to be exact: CRLF is treated as one char.
768 sText.Remove('\r');
770 // style each line separately
771 int offset = 0;
772 int nNewlinePos;
775 nNewlinePos = sText.Find('\n', offset);
776 CString sLine = sText.Mid(offset);
777 if (nNewlinePos>=0)
778 sLine = sLine.Left(nNewlinePos-offset);
779 int start = 0;
780 int end = 0;
781 while (FindStyleChars(sLine, '*', start, end))
783 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
784 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
785 CHARFORMAT2 format;
786 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
787 format.cbSize = sizeof(CHARFORMAT2);
788 format.dwMask = CFM_BOLD;
789 format.dwEffects = CFE_BOLD;
790 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
791 bStyled = true;
792 start = end;
794 start = 0;
795 end = 0;
796 while (FindStyleChars(sLine, '^', start, end))
798 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
799 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
800 CHARFORMAT2 format;
801 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
802 format.cbSize = sizeof(CHARFORMAT2);
803 format.dwMask = CFM_ITALIC;
804 format.dwEffects = CFE_ITALIC;
805 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
806 bStyled = true;
807 start = end;
809 start = 0;
810 end = 0;
811 while (FindStyleChars(sLine, '_', start, end))
813 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
814 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
815 CHARFORMAT2 format;
816 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
817 format.cbSize = sizeof(CHARFORMAT2);
818 format.dwMask = CFM_UNDERLINE;
819 format.dwEffects = CFE_UNDERLINE;
820 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
821 bStyled = true;
822 start = end;
824 offset = nNewlinePos+1;
825 } while(nNewlinePos>=0);
826 return bStyled;
829 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
831 int i=start;
832 bool bFoundMarker = false;
833 // find a starting marker
834 while (sText[i] != 0)
836 if (sText[i] == stylechar)
838 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
839 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
841 start = i+1;
842 i++;
843 bFoundMarker = true;
844 break;
847 i++;
849 if (!bFoundMarker)
850 return false;
851 // find ending marker
852 bFoundMarker = false;
853 while (sText[i] != 0)
855 if (sText[i] == stylechar)
857 if ((IsCharAlphaNumeric(sText[i-1])) &&
858 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
860 end = i;
861 i++;
862 bFoundMarker = true;
863 break;
866 i++;
868 return bFoundMarker;
871 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
873 OPENFILENAME ofn = {0}; // common dialog box structure
874 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
875 ofn.lStructSize = sizeof(OPENFILENAME);
876 ofn.hwndOwner = hwndOwner;
877 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
878 ofn.lpstrFile = szFile;
879 ofn.nMaxFile = _countof(szFile);
880 CString sFilter;
881 TCHAR * pszFilters = NULL;
882 if (filter)
884 sFilter.LoadString(filter);
885 pszFilters = new TCHAR[sFilter.GetLength()+4];
886 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
887 // Replace '|' delimiters with '\0's
888 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
889 while (ptr != pszFilters)
891 if (*ptr == '|')
892 *ptr = '\0';
893 ptr--;
895 ofn.lpstrFilter = pszFilters;
897 ofn.nFilterIndex = 1;
898 ofn.lpstrFileTitle = NULL;
899 ofn.nMaxFileTitle = 0;
900 ofn.lpstrInitialDir = NULL;
901 CString temp;
902 if (title)
904 temp.LoadString(title);
905 CStringUtils::RemoveAccelerators(temp);
907 ofn.lpstrTitle = temp;
908 if (bOpen)
909 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
910 else
911 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
914 // Display the Open dialog box.
915 bool bRet = false;
916 if (bOpen)
918 bRet = !!GetOpenFileName(&ofn);
920 else
922 bRet = !!GetSaveFileName(&ofn);
924 if (bRet)
926 if (pszFilters)
927 delete [] pszFilters;
928 path = CString(ofn.lpstrFile);
929 if (filterindex)
930 *filterindex = ofn.nFilterIndex;
931 return true;
933 if (pszFilters)
934 delete [] pszFilters;
935 return false;
938 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
940 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
941 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
942 // create a bitmap from the icon
943 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
944 if (!hIcon)
945 return false;
947 RECT rect = {0};
948 rect.right = width;
949 rect.bottom = height;
950 HBITMAP bmp = NULL;
952 HWND desktop = ::GetDesktopWindow();
953 if (desktop)
955 HDC screen_dev = ::GetDC(desktop);
956 if (screen_dev)
958 // Create a compatible DC
959 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
960 if (dst_hdc)
962 // Create a new bitmap of icon size
963 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
964 if (bmp)
966 // Select it into the compatible DC
967 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
968 // Fill the background of the compatible DC with the given color
969 ::SetBkColor(dst_hdc, bkColor);
970 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
972 // Draw the icon into the compatible DC
973 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
974 ::SelectObject(dst_hdc, old_dst_bmp);
976 ::DeleteDC(dst_hdc);
979 ::ReleaseDC(desktop, screen_dev);
982 // Restore settings
983 DestroyIcon(hIcon);
985 if (bmp == NULL)
986 return false;
988 LVBKIMAGE lv;
989 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
990 lv.hbm = bmp;
991 lv.xOffsetPercent = 100;
992 lv.yOffsetPercent = 100;
993 ListView_SetBkImage(hListCtrl, &lv);
994 return true;
997 CString CAppUtils::GetProjectNameFromURL(CString url)
999 CString name;
1000 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1001 (name.CompareNoCase(_T("tags"))==0) ||
1002 (name.CompareNoCase(_T("trunk"))==0))
1004 name = url.Mid(url.ReverseFind('/')+1);
1005 url = url.Left(url.ReverseFind('/'));
1007 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1009 // a name of svn or svnroot indicates that it's not really the project name. In that
1010 // case, we try the first part of the URL
1011 // of course, this won't work in all cases (but it works for Google project hosting)
1012 url.Replace(_T("http://"), _T(""));
1013 url.Replace(_T("https://"), _T(""));
1014 url.Replace(_T("svn://"), _T(""));
1015 url.Replace(_T("svn+ssh://"), _T(""));
1016 url.TrimLeft(_T("/"));
1017 name = url.Left(url.Find('.'));
1019 return name;
1022 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1023 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1024 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1025 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1028 CString tempfile=GetTempFile();
1029 CString cmd;
1030 if(rev1 == GitRev::GetWorkingCopy())
1032 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1034 else
1036 CString merge;
1037 if(bMerge)
1038 merge = _T("-c");
1040 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1043 if( !url1.IsEmpty() )
1045 cmd += _T(" \"");
1046 cmd += url1.GetGitPathString();
1047 cmd += _T("\" ");
1049 g_Git.RunLogFile(cmd,tempfile);
1050 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1053 #if 0
1054 CString sCmd;
1055 sCmd.Format(_T("%s /command:showcompare /unified"),
1056 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1057 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1058 if (rev1.IsValid())
1059 sCmd += _T(" /revision1:") + rev1.ToString();
1060 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1061 if (rev2.IsValid())
1062 sCmd += _T(" /revision2:") + rev2.ToString();
1063 if (peg.IsValid())
1064 sCmd += _T(" /pegrevision:") + peg.ToString();
1065 if (headpeg.IsValid())
1066 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1068 if (bAlternateDiff)
1069 sCmd += _T(" /alternatediff");
1071 if (bIgnoreAncestry)
1072 sCmd += _T(" /ignoreancestry");
1074 if (hWnd)
1076 sCmd += _T(" /hwnd:");
1077 TCHAR buf[30];
1078 _stprintf_s(buf, 30, _T("%d"), hWnd);
1079 sCmd += buf;
1082 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1083 #endif
1084 return TRUE;
1088 bool CAppUtils::Export(CString *BashHash)
1090 bool bRet = false;
1092 // ask from where the export has to be done
1093 CExportDlg dlg;
1094 if(BashHash)
1095 dlg.m_Revision=*BashHash;
1097 if (dlg.DoModal() == IDOK)
1099 CString cmd;
1100 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1101 g_Git.FixBranchName(dlg.m_VersionName));
1103 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1104 CProgressDlg pro;
1105 pro.m_GitCmd=cmd;
1106 pro.m_LogFile=dlg.m_strExportDirectory;
1107 pro.DoModal();
1108 return TRUE;
1110 return bRet;
1113 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1115 CCreateBranchTagDlg dlg;
1116 dlg.m_bIsTag=IsTag;
1117 dlg.m_bSwitch=switch_new_brach;
1119 if(CommitHash)
1120 dlg.m_Base = *CommitHash;
1122 if(dlg.DoModal()==IDOK)
1124 CString cmd;
1125 CString force;
1126 CString track;
1127 if(dlg.m_bTrack)
1128 track=_T(" --track ");
1130 if(dlg.m_bForce)
1131 force=_T(" -f ");
1133 if(IsTag)
1135 CString sign;
1136 if(dlg.m_bSign)
1137 sign=_T("-s");
1139 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1140 track,
1141 force,
1142 sign,
1143 dlg.m_BranchTagName,
1144 g_Git.FixBranchName(dlg.m_VersionName)
1147 CString tempfile=::GetTempFile();
1148 if(!dlg.m_Message.Trim().IsEmpty())
1150 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1151 cmd += _T(" -F ")+tempfile;
1154 else
1156 cmd.Format(_T("git.exe branch %s %s %s %s"),
1157 track,
1158 force,
1159 dlg.m_BranchTagName,
1160 g_Git.FixBranchName(dlg.m_VersionName)
1163 CString out;
1164 if(g_Git.Run(cmd,&out,CP_UTF8))
1166 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1168 if( !IsTag && dlg.m_bSwitch )
1170 // it is a new branch and the user has requested to switch to it
1171 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1172 g_Git.Run(cmd,&out,CP_UTF8);
1173 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1176 return TRUE;
1178 return FALSE;
1181 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1183 CGitSwitchDlg dlg;
1184 if(CommitHash)
1185 dlg.m_Base=*CommitHash;
1186 if(!initialRefName.IsEmpty())
1187 dlg.m_initialRefName = initialRefName;
1189 if (dlg.DoModal() == IDOK)
1191 CString cmd;
1192 CString track;
1193 // CString base;
1194 CString force;
1195 CString branch;
1197 if(dlg.m_bBranch){
1198 if (dlg.m_bBranchOverride)
1200 branch.Format(_T("-B %s"),dlg.m_NewBranch);
1202 else
1204 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1207 if(dlg.m_bForce)
1208 force=_T("-f");
1209 if(dlg.m_bTrack)
1210 track=_T("--track");
1212 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1213 force,
1214 track,
1215 branch,
1216 g_Git.FixBranchName(dlg.m_VersionName));
1218 CProgressDlg progress;
1219 progress.m_bAutoCloseOnSuccess = autoclose;
1220 progress.m_GitCmd=cmd;
1221 if(progress.DoModal()==IDOK)
1222 return TRUE;
1225 return FALSE;
1228 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1230 CString ignorefile;
1231 ignorefile=g_Git.m_CurrentDir+_T("\\");
1233 if(IsMask)
1235 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1238 else
1240 ignorefile += _T("\\.gitignore");
1243 CStdioFile file;
1244 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1246 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1247 return FALSE;
1250 CString ignorelist;
1251 CString mask;
1254 //file.ReadString(ignorelist);
1255 file.SeekToEnd();
1256 for(int i=0;i<path.GetCount();i++)
1258 if(IsMask)
1260 mask=_T("*")+path[i].GetFileExtension();
1261 if(ignorelist.Find(mask)<0)
1262 ignorelist += _T("\n")+mask;
1264 else
1266 ignorelist += _T("\n/")+path[i].GetGitPathString();
1269 file.WriteString(ignorelist);
1271 file.Close();
1273 }catch(...)
1275 file.Close();
1276 return FALSE;
1279 return TRUE;
1283 bool CAppUtils::GitReset(CString *CommitHash,int type)
1285 CResetDlg dlg;
1286 dlg.m_ResetType=type;
1287 dlg.m_ResetToVersion=*CommitHash;
1288 if (dlg.DoModal() == IDOK)
1290 CString cmd;
1291 CString type;
1292 switch(dlg.m_ResetType)
1294 case 0:
1295 type=_T("--soft");
1296 break;
1297 case 1:
1298 type=_T("--mixed");
1299 break;
1300 case 2:
1301 type=_T("--hard");
1302 break;
1303 default:
1304 type=_T("--mixed");
1305 break;
1307 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1309 CProgressDlg progress;
1310 progress.m_GitCmd=cmd;
1311 if(progress.DoModal()==IDOK)
1312 return TRUE;
1315 return FALSE;
1318 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1320 if(mode == FALSE)
1322 descript=_T("Deleted");
1323 return;
1325 if(base)
1327 descript=_T("Modified");
1328 return;
1330 descript=_T("Created");
1331 return;
1334 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1336 CString tempmergefile;
1339 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1340 CFile::Remove(tempmergefile);
1341 }catch(...)
1347 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1348 CFile::Remove(tempmergefile);
1349 }catch(...)
1355 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1356 CFile::Remove(tempmergefile);
1357 }catch(...)
1361 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1363 CString file;
1364 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1366 return file;
1369 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1371 bool bRet = false;
1373 CTGitPath merge=path;
1374 CTGitPath directory = merge.GetDirectory();
1376 // we have the conflicted file (%merged)
1377 // now look for the other required files
1378 //GitStatus stat;
1379 //stat.GetStatus(merge);
1380 //if (stat.status == NULL)
1381 // return false;
1383 BYTE_VECTOR vector;
1385 CString cmd;
1386 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1388 if(g_Git.Run(cmd,&vector))
1390 return FALSE;
1393 CTGitPathList list;
1394 list.ParserFromLsFile(vector);
1396 if(list.GetCount() == 0)
1397 return FALSE;
1399 CTGitPath theirs;
1400 CTGitPath mine;
1401 CTGitPath base;
1403 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1404 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1405 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1407 CString format;
1409 //format=_T("git.exe cat-file blob \":%d:%s\"");
1410 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1411 CFile tempfile;
1412 //create a empty file, incase stage is not three
1413 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1414 tempfile.Close();
1415 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1416 tempfile.Close();
1417 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1418 tempfile.Close();
1420 bool b_base=false, b_local=false, b_remote=false;
1422 for(int i=0;i<list.GetCount();i++)
1424 CString cmd;
1425 CString outfile;
1426 cmd.Empty();
1427 outfile.Empty();
1429 if( list[i].m_Stage == 1)
1431 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1432 b_base = true;
1433 outfile = base.GetWinPathString();
1436 if( list[i].m_Stage == 2 )
1438 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1439 b_local = true;
1440 outfile = mine.GetWinPathString();
1443 if( list[i].m_Stage == 3 )
1445 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1446 b_remote = true;
1447 outfile = theirs.GetWinPathString();
1449 CString output;
1450 if(!outfile.IsEmpty())
1451 if(!g_Git.Run(cmd,&output,CP_ACP))
1453 CString file;
1454 int start =0 ;
1455 file = output.Tokenize(_T("\t"), start);
1456 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1458 else
1460 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1464 if(b_local && b_remote )
1466 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1467 if( revertTheirMy )
1468 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1469 else
1470 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1473 else
1475 CFile::Remove(mine.GetWinPathString());
1476 CFile::Remove(theirs.GetWinPathString());
1477 CFile::Remove(base.GetWinPathString());
1479 CDeleteConflictDlg dlg;
1480 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1481 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1482 dlg.m_bShowModifiedButton=b_base;
1483 dlg.m_File=merge.GetGitPathString();
1484 if(dlg.DoModal() == IDOK)
1486 CString cmd,out;
1487 if(dlg.m_bIsDelete)
1489 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1491 else
1492 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1494 if(g_Git.Run(cmd,&out,CP_ACP))
1496 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1497 return FALSE;
1499 return TRUE;
1501 else
1502 return FALSE;
1505 #if 0
1506 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1507 base, theirs, mine, merge);
1508 #endif
1509 #if 0
1510 if (stat.status->text_status == svn_wc_status_conflicted)
1512 // we have a text conflict, use our merge tool to resolve the conflict
1514 CTSVNPath theirs(directory);
1515 CTSVNPath mine(directory);
1516 CTSVNPath base(directory);
1517 bool bConflictData = false;
1519 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1521 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1522 bConflictData = true;
1524 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1526 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1527 bConflictData = true;
1529 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1531 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1532 bConflictData = true;
1534 else
1536 mine = merge;
1538 if (bConflictData)
1539 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1540 base, theirs, mine, merge);
1543 if (stat.status->prop_status == svn_wc_status_conflicted)
1545 // we have a property conflict
1546 CTSVNPath prej(directory);
1547 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1549 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1550 // there's a problem: the prej file contains a _description_ of the conflict, and
1551 // that description string might be translated. That means we have no way of parsing
1552 // the file to find out the conflicting values.
1553 // The only thing we can do: show a dialog with the conflict description, then
1554 // let the user either accept the existing property or open the property edit dialog
1555 // to manually change the properties and values. And a button to mark the conflict as
1556 // resolved.
1557 CEditPropConflictDlg dlg;
1558 dlg.SetPrejFile(prej);
1559 dlg.SetConflictedItem(merge);
1560 bRet = (dlg.DoModal() != IDCANCEL);
1564 if (stat.status->tree_conflict)
1566 // we have a tree conflict
1567 SVNInfo info;
1568 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1569 if (pInfoData)
1571 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1573 CTSVNPath theirs(directory);
1574 CTSVNPath mine(directory);
1575 CTSVNPath base(directory);
1576 bool bConflictData = false;
1578 if (pInfoData->treeconflict_theirfile)
1580 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1581 bConflictData = true;
1583 if (pInfoData->treeconflict_basefile)
1585 base.AppendPathString(pInfoData->treeconflict_basefile);
1586 bConflictData = true;
1588 if (pInfoData->treeconflict_myfile)
1590 mine.AppendPathString(pInfoData->treeconflict_myfile);
1591 bConflictData = true;
1593 else
1595 mine = merge;
1597 if (bConflictData)
1598 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1599 base, theirs, mine, merge);
1601 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1603 CString sConflictAction;
1604 CString sConflictReason;
1605 CString sResolveTheirs;
1606 CString sResolveMine;
1607 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1608 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1610 if (pInfoData->treeconflict_nodekind == svn_node_file)
1612 switch (pInfoData->treeconflict_operation)
1614 case svn_wc_operation_update:
1615 switch (pInfoData->treeconflict_action)
1617 case svn_wc_conflict_action_edit:
1618 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1619 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1620 break;
1621 case svn_wc_conflict_action_add:
1622 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1623 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1624 break;
1625 case svn_wc_conflict_action_delete:
1626 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1627 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1628 break;
1630 break;
1631 case svn_wc_operation_switch:
1632 switch (pInfoData->treeconflict_action)
1634 case svn_wc_conflict_action_edit:
1635 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1636 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1637 break;
1638 case svn_wc_conflict_action_add:
1639 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1640 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1641 break;
1642 case svn_wc_conflict_action_delete:
1643 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1644 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1645 break;
1647 break;
1648 case svn_wc_operation_merge:
1649 switch (pInfoData->treeconflict_action)
1651 case svn_wc_conflict_action_edit:
1652 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1653 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1654 break;
1655 case svn_wc_conflict_action_add:
1656 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1657 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1658 break;
1659 case svn_wc_conflict_action_delete:
1660 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1661 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1662 break;
1664 break;
1667 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1669 switch (pInfoData->treeconflict_operation)
1671 case svn_wc_operation_update:
1672 switch (pInfoData->treeconflict_action)
1674 case svn_wc_conflict_action_edit:
1675 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1676 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1677 break;
1678 case svn_wc_conflict_action_add:
1679 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1680 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1681 break;
1682 case svn_wc_conflict_action_delete:
1683 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1684 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1685 break;
1687 break;
1688 case svn_wc_operation_switch:
1689 switch (pInfoData->treeconflict_action)
1691 case svn_wc_conflict_action_edit:
1692 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1693 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1694 break;
1695 case svn_wc_conflict_action_add:
1696 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1697 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1698 break;
1699 case svn_wc_conflict_action_delete:
1700 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1701 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1702 break;
1704 break;
1705 case svn_wc_operation_merge:
1706 switch (pInfoData->treeconflict_action)
1708 case svn_wc_conflict_action_edit:
1709 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1710 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1711 break;
1712 case svn_wc_conflict_action_add:
1713 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1714 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1715 break;
1716 case svn_wc_conflict_action_delete:
1717 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1718 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1719 break;
1721 break;
1725 UINT uReasonID = 0;
1726 switch (pInfoData->treeconflict_reason)
1728 case svn_wc_conflict_reason_edited:
1729 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1730 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1731 break;
1732 case svn_wc_conflict_reason_obstructed:
1733 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1734 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1735 break;
1736 case svn_wc_conflict_reason_deleted:
1737 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1738 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1739 break;
1740 case svn_wc_conflict_reason_added:
1741 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1742 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1743 break;
1744 case svn_wc_conflict_reason_missing:
1745 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1746 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1747 break;
1748 case svn_wc_conflict_reason_unversioned:
1749 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1750 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1751 break;
1753 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1755 CTreeConflictEditorDlg dlg;
1756 dlg.SetConflictInfoText(sConflictReason);
1757 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1758 dlg.SetPath(treeConflictPath);
1759 INT_PTR dlgRet = dlg.DoModal();
1760 bRet = (dlgRet != IDCANCEL);
1764 #endif
1765 return bRet;
1769 * FUNCTION : FormatDateAndTime
1770 * DESCRIPTION : Generates a displayable string from a CTime object in
1771 * system short or long format or as a relative value
1772 * cTime - the time
1773 * option - DATE_SHORTDATE or DATE_LONGDATE
1774 * bIncluedeTime - whether to show time as well as date
1775 * bRelative - if true then relative time is shown if reasonable
1776 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1777 * rather than locale
1778 * RETURN : CString containing date/time
1780 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1781 bool bRelative /*=false*/)
1783 CString datetime;
1784 if ( bRelative )
1786 datetime = ToRelativeTimeString( cTime );
1788 else
1790 // should we use the locale settings for formatting the date/time?
1791 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1793 // yes
1794 SYSTEMTIME sysTime;
1795 cTime.GetAsSystemTime( sysTime );
1797 TCHAR buf[100];
1799 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1800 _countof(buf) - 1);
1801 datetime = buf;
1802 if ( bIncludeTime )
1804 datetime += _T(" ");
1805 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1806 datetime += buf;
1809 else
1811 // no, so fixed format
1812 if ( bIncludeTime )
1814 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1816 else
1818 datetime = cTime.Format(_T("%Y-%m-%d"));
1822 return datetime;
1826 * Converts a given time to a relative display string (relative to current time)
1827 * Given time must be in local timezone
1829 CString CAppUtils::ToRelativeTimeString(CTime time)
1831 CString answer;
1832 // convert to COleDateTime
1833 SYSTEMTIME sysTime;
1834 time.GetAsSystemTime( sysTime );
1835 COleDateTime oleTime( sysTime );
1836 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1837 return answer;
1841 * Generates a display string showing the relative time between the two given times as COleDateTimes
1843 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1845 CString answer;
1846 COleDateTimeSpan ts = RelativeTo - time;
1847 //years
1848 if(fabs(ts.GetTotalDays()) >= 3*365)
1850 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1852 //Months
1853 if(fabs(ts.GetTotalDays()) >= 60)
1855 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1856 return answer;
1858 //Weeks
1859 if(fabs(ts.GetTotalDays()) >= 14)
1861 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1862 return answer;
1864 //Days
1865 if(fabs(ts.GetTotalDays()) >= 2)
1867 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1868 return answer;
1870 //hours
1871 if(fabs(ts.GetTotalHours()) >= 2)
1873 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1874 return answer;
1876 //minutes
1877 if(fabs(ts.GetTotalMinutes()) >= 2)
1879 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1880 return answer;
1882 //seconds
1883 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1884 return answer;
1888 * Passed a value and two resource string ids
1889 * if count is 1 then FormatString is called with format_1 and the value
1890 * otherwise format_2 is used
1891 * the formatted string is returned
1893 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1895 CString answer;
1896 if ( count == 1 )
1898 answer.FormatMessage( format_1, count );
1900 else
1902 answer.FormatMessage( format_n, count );
1904 return answer;
1907 bool CAppUtils::IsSSHPutty()
1909 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1910 sshclient=sshclient.MakeLower();
1911 if(sshclient.Find(_T("plink.exe"),0)>=0)
1913 return true;
1915 return false;
1918 CString CAppUtils::GetClipboardLink()
1920 if (!OpenClipboard(NULL))
1921 return CString();
1923 CString sClipboardText;
1924 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1925 if (hglb)
1927 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1928 sClipboardText = CString(lpstr);
1929 GlobalUnlock(hglb);
1931 hglb = GetClipboardData(CF_UNICODETEXT);
1932 if (hglb)
1934 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1935 sClipboardText = lpstr;
1936 GlobalUnlock(hglb);
1938 CloseClipboard();
1940 if(!sClipboardText.IsEmpty())
1942 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1943 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1945 if(sClipboardText.Find( _T("http://")) == 0)
1946 return sClipboardText;
1948 if(sClipboardText.Find( _T("https://")) == 0)
1949 return sClipboardText;
1951 if(sClipboardText.Find( _T("git://")) == 0)
1952 return sClipboardText;
1954 if(sClipboardText.Find( _T("ssh://")) == 0)
1955 return sClipboardText;
1957 if(sClipboardText.GetLength()>=2)
1958 if( sClipboardText[1] == _T(':') )
1959 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1960 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1961 return sClipboardText;
1964 return CString(_T(""));
1967 CString CAppUtils::ChooseRepository(CString *path)
1969 CBrowseFolder browseFolder;
1970 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1972 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1973 CString strCloneDirectory;
1974 if(path)
1975 strCloneDirectory=*path;
1976 else
1978 strCloneDirectory = regLastResopitory;
1981 CString title;
1982 title.LoadString(IDS_CHOOSE_REPOSITORY);
1984 browseFolder.SetInfo(title);
1986 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1988 regLastResopitory = strCloneDirectory;
1989 return strCloneDirectory;
1991 else
1993 return CString();
1997 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1999 CSendMailDlg dlg;
2001 dlg.m_PathList = list;
2003 if(dlg.DoModal()==IDOK)
2005 if(dlg.m_PathList.GetCount() == 0)
2006 return FALSE;
2008 CGitProgressDlg progDlg;
2010 theApp.m_pMainWnd = &progDlg;
2011 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2013 progDlg.SetAutoClose(autoclose);
2015 progDlg.SetPathList(dlg.m_PathList);
2016 //ProjectProperties props;
2017 //props.ReadPropsPathList(dlg.m_pathList);
2018 //progDlg.SetProjectProperties(props);
2019 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2021 DWORD flags =0;
2022 if(dlg.m_bAttachment)
2023 flags |= SENDMAIL_ATTACHMENT;
2024 if(dlg.m_bCombine)
2025 flags |= SENDMAIL_COMBINED;
2026 if(dlg.m_bUseMAPI)
2027 flags |= SENDMAIL_MAPI;
2029 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2031 progDlg.DoModal();
2033 return true;
2035 return false;
2038 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2040 CTGitPathList list;
2041 CString log=formatpatchoutput;
2042 int start=log.Find(cmd);
2043 if(start >=0)
2044 CString one=log.Tokenize(_T("\n"),start);
2045 else
2046 start = 0;
2048 while(start>=0)
2050 CString one=log.Tokenize(_T("\n"),start);
2051 one=one.Trim();
2052 if(one.IsEmpty() || one == _T("Success"))
2053 continue;
2054 one.Replace(_T('/'),_T('\\'));
2055 CTGitPath path;
2056 path.SetFromWin(one);
2057 list.AddPath(path);
2059 if (list.GetCount() > 0)
2061 return SendPatchMail(list, autoclose);
2063 else
2065 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2066 return true;
2071 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2073 CString cmd,output;
2074 int start=0;
2076 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2077 if(output.IsEmpty())
2079 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2080 if(output.IsEmpty())
2081 return CP_UTF8;
2083 int start=0;
2084 output=output.Tokenize(_T("\n"),start);
2085 return CUnicodeUtils::GetCPCode(output);
2088 else
2090 output=output.Tokenize(_T("\n"),start);
2091 return CUnicodeUtils::GetCPCode(output);
2094 int CAppUtils::GetCommitTemplate(CString &temp)
2096 CString cmd,output;
2098 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2099 if( output.IsEmpty() )
2100 return -1;
2102 if( output.GetLength()<1)
2103 return -1;
2105 if( output[0] == _T('/'))
2107 if(output.GetLength()>=3)
2108 if(output[2] == _T('/'))
2110 output.GetBuffer()[0] = output[1];
2111 output.GetBuffer()[1] = _T(':');
2115 int start=0;
2116 output=output.Tokenize(_T("\n"),start);
2118 output.Replace(_T('/'),_T('\\'));
2122 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2123 CString str;
2124 while(file.ReadString(str))
2126 temp+=str+_T("\n");
2129 }catch(...)
2131 return -1;
2133 return 0;
2135 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2137 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2138 CString cmd,output;
2139 int cp=CP_UTF8;
2141 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2142 if(output.IsEmpty())
2143 cp=CP_UTF8;
2145 int start=0;
2146 output=output.Tokenize(_T("\n"),start);
2147 cp=CUnicodeUtils::GetCPCode(output);
2149 int len=message.GetLength();
2151 char * buf;
2152 buf = new char[len*4 + 4];
2153 SecureZeroMemory(buf, (len*4 + 4));
2155 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2157 file.Write(buf,lengthIncTerminator-1);
2158 file.Close();
2159 delete buf;
2160 return 0;
2163 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2165 CPullFetchDlg dlg;
2166 dlg.m_PreSelectRemote = remoteName;
2167 dlg.m_bAllowRebase = allowRebase;
2168 dlg.m_IsPull=FALSE;
2170 if(dlg.DoModal()==IDOK)
2172 if(dlg.m_bAutoLoad)
2174 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2177 CString url;
2178 url=dlg.m_RemoteURL;
2179 CString cmd;
2180 CString arg;
2182 int ver = CAppUtils::GetMsysgitVersion();
2184 if(ver >= 0x01070203) //above 1.7.0.2
2185 arg = _T("--progress ");
2187 if (dlg.m_bPrune) {
2188 arg += _T("--prune ");
2191 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2192 CProgressDlg progress;
2194 progress.m_bAutoCloseOnSuccess = autoClose;
2196 if(!dlg.m_bRebase)
2198 progress.m_PostCmdList.Add(_T("&Rebase"));
2201 progress.m_GitCmd=cmd;
2202 int userResponse=progress.DoModal();
2204 if( (userResponse==IDC_PROGRESS_BUTTON1) || ( progress.m_GitStatus ==0 && dlg.m_bRebase) )
2206 while(1)
2208 CRebaseDlg dlg;
2209 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2210 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2211 int response = dlg.DoModal();
2212 if(response == IDOK)
2214 return TRUE;
2216 if(response == IDC_REBASE_POST_BUTTON )
2218 CString cmd,out;
2219 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2220 g_Git.m_CurrentDir,
2221 g_Git.FixBranchName(dlg.m_Upstream),
2222 g_Git.FixBranchName(dlg.m_Branch));
2223 if(g_Git.Run(cmd,&out,CP_ACP))
2225 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2226 return FALSE;
2229 CAppUtils::SendPatchMail(cmd,out);
2230 return TRUE;
2233 if(response == IDC_REBASE_POST_BUTTON +1 )
2234 continue;
2236 if(response == IDCANCEL)
2237 return FALSE;
2239 return TRUE;
2242 return FALSE;
2245 bool CAppUtils::Push(bool autoClose)
2247 CPushDlg dlg;
2248 CString error;
2249 DWORD exitcode = 0xFFFFFFFF;
2250 CTGitPathList list;
2251 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2252 if (CHooks::Instance().PrePush(list,exitcode, error))
2254 if (exitcode)
2256 CString temp;
2257 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2258 //ReportError(temp);
2259 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2260 return false;
2264 if(dlg.DoModal()==IDOK)
2266 CString cmd;
2267 CString arg;
2269 if(dlg.m_bAutoLoad)
2271 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2274 if(dlg.m_bPack)
2275 arg += _T("--thin ");
2276 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2277 arg += _T("--tags ");
2278 if(dlg.m_bForce)
2279 arg += _T("--force ");
2281 int ver = CAppUtils::GetMsysgitVersion();
2283 if(ver >= 0x01070203) //above 1.7.0.2
2284 arg += _T("--progress ");
2286 if (dlg.m_bPushAllBranches)
2288 cmd.Format(_T("git.exe push --all %s \"%s\""),
2289 arg,
2290 dlg.m_URL);
2292 else
2294 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2295 arg,
2296 dlg.m_URL,
2297 dlg.m_BranchSourceName);
2298 if (!dlg.m_BranchRemoteName.IsEmpty())
2300 cmd += _T(":") + dlg.m_BranchRemoteName;
2304 CProgressDlg progress;
2305 progress.m_bAutoCloseOnSuccess=autoClose;
2306 progress.m_GitCmd=cmd;
2307 progress.m_PostCmdList.Add(_T("&Request pull"));
2308 progress.m_PostCmdList.Add(_T("Re&Push"));
2309 int ret = progress.DoModal();
2311 if(!progress.m_GitStatus)
2313 if (CHooks::Instance().PostPush(list,exitcode, error))
2315 if (exitcode)
2317 CString temp;
2318 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2319 //ReportError(temp);
2320 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2321 return false;
2324 if(ret == IDC_PROGRESS_BUTTON1)
2326 RequestPull(dlg.m_BranchRemoteName);
2328 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2330 Push();
2332 return TRUE;
2336 return FALSE;
2339 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2341 CRequestPullDlg dlg;
2342 dlg.m_RepositoryURL = repositoryUrl;
2343 dlg.m_EndRevision = endrevision;
2344 if (dlg.DoModal()==IDOK)
2346 CString cmd;
2347 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2349 CProgressDlg progress;
2350 progress.m_GitCmd=cmd;
2351 progress.DoModal();
2353 return true;
2356 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2358 CString strDir(szPath);
2359 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2361 strDir.AppendChar(_T('\\'));
2363 std::vector<CString> vPath;
2364 CString strTemp;
2365 bool bSuccess = false;
2367 for (int i=0;i<strDir.GetLength();++i)
2369 if (strDir.GetAt(i) != _T('\\'))
2371 strTemp.AppendChar(strDir.GetAt(i));
2373 else
2375 vPath.push_back(strTemp);
2376 strTemp.AppendChar(_T('\\'));
2380 std::vector<CString>::const_iterator vIter;
2381 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2383 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2386 return bSuccess;
2389 void CAppUtils::RemoveTrailSlash(CString &path)
2391 if(path.IsEmpty())
2392 return ;
2394 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2396 path=path.Left(path.GetLength()-1);
2397 if(path.IsEmpty())
2398 return;
2402 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2403 CTGitPathList &pathList,
2404 CTGitPathList &selectedList,
2405 bool bSelectFilesForCommit,
2406 bool autoClose)
2408 bool bFailed = true;
2410 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2412 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"),
2413 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2415 CTGitPath path(g_Git.m_CurrentDir);
2416 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2417 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2418 dlg.SetTreeWidth(220);
2419 dlg.m_DefaultPage = _T("gitconfig");
2421 dlg.DoModal();
2422 dlg.HandleRestart();
2425 else
2426 return false;
2429 while (bFailed)
2431 bFailed = false;
2432 CCommitDlg dlg;
2433 dlg.m_sBugID = bugid;
2435 dlg.m_bWholeProject = bWholeProject;
2437 dlg.m_sLogMessage = sLogMsg;
2438 dlg.m_pathList = pathList;
2439 dlg.m_checkedPathList = selectedList;
2440 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2441 dlg.m_bAutoClose = autoClose;
2442 if (dlg.DoModal() == IDOK)
2444 if (dlg.m_pathList.GetCount()==0)
2445 return false;
2446 // if the user hasn't changed the list of selected items
2447 // we don't use that list. Because if we would use the list
2448 // of pre-checked items, the dialog would show different
2449 // checked items on the next startup: it would only try
2450 // to check the parent folder (which might not even show)
2451 // instead, we simply use an empty list and let the
2452 // default checking do its job.
2453 if (!dlg.m_pathList.IsEqual(pathList))
2454 selectedList = dlg.m_pathList;
2455 pathList = dlg.m_updatedPathList;
2456 sLogMsg = dlg.m_sLogMessage;
2457 bSelectFilesForCommit = true;
2459 if( dlg.m_bPushAfterCommit )
2461 switch(dlg.m_PostCmd)
2463 case GIT_POST_CMD_DCOMMIT:
2464 CAppUtils::SVNDCommit();
2465 break;
2466 default:
2467 CAppUtils::Push();
2470 // CGitProgressDlg progDlg;
2471 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2472 // if (parser.HasVal(_T("closeonend")))
2473 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2474 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2475 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2476 // progDlg.SetPathList(dlg.m_pathList);
2477 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2478 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2479 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2480 // progDlg.SetItemCount(dlg.m_itemsCount);
2481 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2482 // progDlg.DoModal();
2483 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2484 // err = (DWORD)progDlg.DidErrorsOccur();
2485 // bFailed = progDlg.DidErrorsOccur();
2486 // bRet = progDlg.DidErrorsOccur();
2487 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2488 // if (DWORD(bFailRepeat)==0)
2489 // bFailed = false; // do not repeat if the user chose not to in the settings.
2492 return true;
2496 BOOL CAppUtils::SVNDCommit()
2498 CSVNDCommitDlg dcommitdlg;
2499 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2500 if (gitSetting == _T("")) {
2501 if (dcommitdlg.DoModal() != IDOK)
2503 return false;
2505 else
2507 if (dcommitdlg.m_remember)
2509 if (dcommitdlg.m_rmdir)
2511 gitSetting = _T("true");
2513 else
2515 gitSetting = _T("false");
2517 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2519 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2525 BOOL IsStash = false;
2526 if(!g_Git.CheckCleanWorkTree())
2528 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2530 CString cmd,out;
2531 cmd=_T("git.exe stash");
2532 if(g_Git.Run(cmd,&out,CP_ACP))
2534 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2535 return false;
2537 IsStash =true;
2540 else
2542 return false;
2546 CProgressDlg progress;
2547 if (dcommitdlg.m_rmdir)
2549 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2551 else
2553 progress.m_GitCmd=_T("git.exe svn dcommit");
2555 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2557 if( IsStash)
2559 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2561 CString cmd,out;
2562 cmd=_T("git.exe stash pop");
2563 if(g_Git.Run(cmd,&out,CP_ACP))
2565 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2566 return false;
2570 else
2572 return false;
2575 return TRUE;
2577 return FALSE;
2580 BOOL CAppUtils::Merge(CString *commit)
2582 CMergeDlg dlg;
2583 if(commit)
2584 dlg.m_initialRefName = *commit;
2586 if(dlg.DoModal()==IDOK)
2588 CString cmd;
2589 CString noff;
2590 CString squash;
2591 CString nocommit;
2592 CString msg;
2594 if(dlg.m_bNoFF)
2595 noff=_T("--no-ff");
2597 if(dlg.m_bSquash)
2598 squash=_T("--squash");
2600 if(dlg.m_bNoCommit)
2601 nocommit=_T("--no-commit");
2603 if(!dlg.m_strLogMesage.IsEmpty())
2605 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2607 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2608 msg,
2609 noff,
2610 squash,
2611 nocommit,
2612 g_Git.FixBranchName(dlg.m_VersionName));
2614 CProgressDlg Prodlg;
2615 Prodlg.m_GitCmd = cmd;
2617 if (dlg.m_bNoCommit)
2618 Prodlg.m_PostCmdList.Add(_T("Commit"));
2620 int ret = Prodlg.DoModal();
2622 if (ret == IDC_PROGRESS_BUTTON1)
2623 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2625 return !Prodlg.m_GitStatus;
2627 return false;
2630 void CAppUtils::EditNote(GitRev *rev)
2632 CInputDlg dlg;
2633 dlg.m_sHintText=_T("Edit Notes");
2634 dlg.m_sInputText = rev->m_Notes;
2635 dlg.m_sTitle=_T("Edit Notes");
2636 //dlg.m_pProjectProperties = &m_ProjectProperties;
2637 dlg.m_bUseLogWidth = true;
2638 if(dlg.DoModal() == IDOK)
2640 CString cmd,output;
2641 cmd=_T("notes add -f -F \"");
2643 CString tempfile=::GetTempFile();
2644 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2645 cmd += tempfile;
2646 cmd += _T("\" ");
2647 cmd += rev->m_CommitHash.ToString();
2651 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2653 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2656 else
2658 rev->m_Notes = dlg.m_sInputText;
2660 }catch(...)
2662 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2664 CFile::Remove(tempfile);
2669 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2671 CString cmd;
2672 CString progressarg;
2673 CString version;
2675 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2676 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2678 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2680 __int64 time=0;
2681 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2683 if((DWORD)time == regTime)
2685 return regVersion;
2689 if(versionstr)
2690 version = *versionstr;
2691 else
2693 cmd = _T("git.exe --version");
2694 if(g_Git.Run(cmd, &version, CP_ACP))
2696 CMessageBox::Show(NULL,_T("git have not installed"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2697 return false;
2701 int start=0;
2702 int ver;
2704 CString str=version.Tokenize(_T("."),start);
2705 int space = str.ReverseFind(_T(' '));
2706 str=str.Mid(space+1,start);
2707 ver = _ttol(str);
2708 ver <<=24;
2710 version = version.Mid(start);
2711 start = 0;
2712 str = version.Tokenize(_T("."),start);
2714 ver |= (_ttol(str)&0xFF)<<16;
2716 str = version.Tokenize(_T("."),start);
2717 ver |= (_ttol(str)&0xFF)<<8;
2719 str = version.Tokenize(_T("."),start);
2720 ver |= (_ttol(str)&0xFF);
2722 regTime = time&0xFFFFFFFF;
2723 regVersion = ver;
2725 return ver;
2728 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2730 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2732 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2734 if (hShell) {
2735 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2736 if (pfnSHGPSFW) {
2737 IPropertyStore *pps;
2738 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2739 if (SUCCEEDED(hr)) {
2740 PROPVARIANT var;
2741 var.vt = VT_BOOL;
2742 var.boolVal = VARIANT_TRUE;
2743 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2744 pps->Release();
2747 FreeLibrary(hShell);
2751 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2753 ASSERT(dialogname.GetLength() < 70);
2754 ASSERT(urlorpath.GetLength() < MAX_PATH);
2755 WCHAR pathbuf[MAX_PATH] = {0};
2757 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2759 wcscat_s(pathbuf, L" - ");
2760 wcscat_s(pathbuf, dialogname);
2761 wcscat_s(pathbuf, L" - ");
2762 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2763 SetWindowText(hWnd, pathbuf);