Enable security checks and features
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobbefee810ca6c1fd91924e30f40ad8af2f38a86f2
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - TortoiseGit
4 // Copyright (C) 2003-2010 - 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"
60 CAppUtils::CAppUtils(void)
64 CAppUtils::~CAppUtils(void)
68 int CAppUtils::StashApply(CString ref)
70 CString cmd,out;
71 cmd=_T("git.exe stash apply ");
72 cmd+=ref;
74 if(g_Git.Run(cmd,&out,CP_ACP))
76 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
78 }else
80 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success</ct>\nDo you want to show change?"))
81 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
83 CChangedDlg dlg;
84 dlg.m_pathList.AddPath(CTGitPath());
85 dlg.DoModal();
87 return 0;
89 return -1;
92 int CAppUtils::StashPop()
94 CString cmd,out;
95 cmd=_T("git.exe stash pop ");
97 if(g_Git.Run(cmd,&out,CP_ACP))
99 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
101 }else
103 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash POP Success</ct>\nDo you want to show change?"))
104 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
106 CChangedDlg dlg;
107 dlg.m_pathList.AddPath(CTGitPath());
108 dlg.DoModal();
110 return 0;
112 return -1;
115 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
117 #if 0
118 GitProperties props(file, GitRev::REV_WC, false);
119 for (int i = 0; i < props.GetCount(); ++i)
121 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
123 mimetype = props.GetItemValue(i).c_str();
124 return true;
127 #endif
128 return false;
131 BOOL CAppUtils::StartExtMerge(
132 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
133 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
136 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
137 CString ext = mergedfile.GetFileExtension();
138 CString com = regCom;
139 bool bInternal = false;
141 CString mimetype;
142 if (ext != "")
144 // is there an extension specific merge tool?
145 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
146 if (CString(mergetool) != "")
148 com = mergetool;
151 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
153 // is there a mime type specific merge tool?
154 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
155 if (CString(mergetool) != "")
157 com = mergetool;
161 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
163 // use TortoiseMerge
164 bInternal = true;
165 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
166 com = tortoiseMergePath;
167 if (com.IsEmpty())
169 com = CPathUtils::GetAppDirectory();
170 com += _T("TortoiseMerge.exe");
172 com = _T("\"") + com + _T("\"");
173 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
174 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
176 // check if the params are set. If not, just add the files to the command line
177 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
179 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
180 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
181 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
182 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
184 if (basefile.IsEmpty())
186 com.Replace(_T("/base:%base"), _T(""));
187 com.Replace(_T("%base"), _T(""));
189 else
190 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
191 if (theirfile.IsEmpty())
193 com.Replace(_T("/theirs:%theirs"), _T(""));
194 com.Replace(_T("%theirs"), _T(""));
196 else
197 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
198 if (yourfile.IsEmpty())
200 com.Replace(_T("/mine:%mine"), _T(""));
201 com.Replace(_T("%mine"), _T(""));
203 else
204 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
205 if (mergedfile.IsEmpty())
207 com.Replace(_T("/merged:%merged"), _T(""));
208 com.Replace(_T("%merged"), _T(""));
210 else
211 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
212 if (basename.IsEmpty())
214 if (basefile.IsEmpty())
216 com.Replace(_T("/basename:%bname"), _T(""));
217 com.Replace(_T("%bname"), _T(""));
219 else
221 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
224 else
225 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
226 if (theirname.IsEmpty())
228 if (theirfile.IsEmpty())
230 com.Replace(_T("/theirsname:%tname"), _T(""));
231 com.Replace(_T("%tname"), _T(""));
233 else
235 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
238 else
239 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
240 if (yourname.IsEmpty())
242 if (yourfile.IsEmpty())
244 com.Replace(_T("/minename:%yname"), _T(""));
245 com.Replace(_T("%yname"), _T(""));
247 else
249 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
252 else
253 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
254 if (mergedname.IsEmpty())
256 if (mergedfile.IsEmpty())
258 com.Replace(_T("/mergedname:%mname"), _T(""));
259 com.Replace(_T("%mname"), _T(""));
261 else
263 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
266 else
267 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
269 if ((bReadOnly)&&(bInternal))
270 com += _T(" /readonly");
272 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
274 return FALSE;
277 return TRUE;
280 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
282 CString viewer;
283 // use TortoiseMerge
284 viewer = CPathUtils::GetAppDirectory();
285 viewer += _T("TortoiseMerge.exe");
287 viewer = _T("\"") + viewer + _T("\"");
288 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
289 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
290 if (bReversed)
291 viewer += _T(" /reversedpatch");
292 if (!sOriginalDescription.IsEmpty())
293 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
294 if (!sPatchedDescription.IsEmpty())
295 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
296 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
298 return FALSE;
300 return TRUE;
303 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
305 // Is there a mime type specific diff tool?
306 CString mimetype;
307 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
309 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
310 if (!difftool.IsEmpty())
311 return difftool;
314 // Is there an extension specific diff tool?
315 CString ext = file2.GetFileExtension().MakeLower();
316 if (!ext.IsEmpty())
318 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
319 if (!difftool.IsEmpty())
320 return difftool;
321 // Maybe we should use TortoiseIDiff?
322 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
323 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
324 (ext == _T(".png")) || (ext == _T(".ico")) ||
325 (ext == _T(".dib")) || (ext == _T(".emf")))
327 return
328 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
329 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
333 // Finally, pick a generic external diff tool
334 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
335 return difftool;
338 bool CAppUtils::StartExtDiff(
339 const CString& file1, const CString& file2,
340 const CString& sName1, const CString& sName2,
341 const DiffFlags& flags)
343 CString viewer;
345 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
346 if (!flags.bBlame || !(DWORD)blamediff)
348 viewer = PickDiffTool(file1, file2);
349 // If registry entry for a diff program is commented out, use TortoiseMerge.
350 bool bCommentedOut = viewer.Left(1) == _T("#");
351 if (flags.bAlternativeTool)
353 // Invert external vs. internal diff tool selection.
354 if (bCommentedOut)
355 viewer.Delete(0); // uncomment
356 else
357 viewer = "";
359 else if (bCommentedOut)
360 viewer = "";
363 bool bInternal = viewer.IsEmpty();
364 if (bInternal)
366 viewer =
367 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
368 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
369 if (flags.bBlame)
370 viewer += _T(" /blame");
372 // check if the params are set. If not, just add the files to the command line
373 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
375 viewer += _T(" \"")+file1+_T("\"");
376 viewer += _T(" \"")+file2+_T("\"");
378 if (viewer.Find(_T("%base")) >= 0)
380 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
382 if (viewer.Find(_T("%mine")) >= 0)
384 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
387 if (sName1.IsEmpty())
388 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
389 else
390 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
392 if (sName2.IsEmpty())
393 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
394 else
395 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
397 if (flags.bReadOnly && bInternal)
398 viewer += _T(" /readonly");
400 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
403 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
405 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
406 CString viewer = diffpropsexe;
407 bool bInternal = false;
408 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
410 //no registry entry (or commented out) for a diff program
411 //use TortoiseMerge
412 bInternal = true;
413 viewer = CPathUtils::GetAppDirectory();
414 viewer += _T("TortoiseMerge.exe");
415 viewer = _T("\"") + viewer + _T("\"");
416 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
418 // check if the params are set. If not, just add the files to the command line
419 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
421 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
422 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
424 if (viewer.Find(_T("%base")) >= 0)
426 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
428 if (viewer.Find(_T("%mine")) >= 0)
430 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
433 if (sName1.IsEmpty())
434 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
435 else
436 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
438 if (sName2.IsEmpty())
439 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
440 else
441 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
443 if ((bReadOnly)&&(bInternal))
444 viewer += _T(" /readonly");
446 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
448 return FALSE;
450 return TRUE;
453 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
455 CString viewer;
456 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
457 viewer = v;
458 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
460 // use TortoiseUDiff
461 viewer = CPathUtils::GetAppDirectory();
462 viewer += _T("TortoiseUDiff.exe");
463 // enquote the path to TortoiseUDiff
464 viewer = _T("\"") + viewer + _T("\"");
465 // add the params
466 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
469 if (viewer.Find(_T("%1"))>=0)
471 if (viewer.Find(_T("\"%1\"")) >= 0)
472 viewer.Replace(_T("%1"), patchfile);
473 else
474 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
476 else
477 viewer += _T(" \"") + patchfile + _T("\"");
478 if (viewer.Find(_T("%title")) >= 0)
480 viewer.Replace(_T("%title"), title);
483 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
485 return FALSE;
487 return TRUE;
490 BOOL CAppUtils::StartTextViewer(CString file)
492 CString viewer;
493 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
494 viewer = txt;
495 viewer = viewer + _T("\\Shell\\Open\\Command\\");
496 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
497 viewer = txtexe;
499 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
500 TCHAR * buf = new TCHAR[len+1];
501 ExpandEnvironmentStrings(viewer, buf, len);
502 viewer = buf;
503 delete [] buf;
504 len = ExpandEnvironmentStrings(file, NULL, 0);
505 buf = new TCHAR[len+1];
506 ExpandEnvironmentStrings(file, buf, len);
507 file = buf;
508 delete [] buf;
509 file = _T("\"")+file+_T("\"");
510 if (viewer.IsEmpty())
512 OPENFILENAME ofn = {0}; // common dialog box structure
513 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
514 // Initialize OPENFILENAME
515 ofn.lStructSize = sizeof(OPENFILENAME);
516 ofn.hwndOwner = NULL;
517 ofn.lpstrFile = szFile;
518 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
519 CString sFilter;
520 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
521 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
522 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
523 // Replace '|' delimiters with '\0's
524 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
525 while (ptr != pszFilters)
527 if (*ptr == '|')
528 *ptr = '\0';
529 ptr--;
531 ofn.lpstrFilter = pszFilters;
532 ofn.nFilterIndex = 1;
533 ofn.lpstrFileTitle = NULL;
534 ofn.nMaxFileTitle = 0;
535 ofn.lpstrInitialDir = NULL;
536 CString temp;
537 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
538 CStringUtils::RemoveAccelerators(temp);
539 ofn.lpstrTitle = temp;
540 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
542 // Display the Open dialog box.
544 if (GetOpenFileName(&ofn)==TRUE)
546 delete [] pszFilters;
547 viewer = CString(ofn.lpstrFile);
549 else
551 delete [] pszFilters;
552 return FALSE;
555 if (viewer.Find(_T("\"%1\"")) >= 0)
557 viewer.Replace(_T("\"%1\""), file);
559 else if (viewer.Find(_T("%1")) >= 0)
561 viewer.Replace(_T("%1"), file);
563 else
565 viewer += _T(" ");
566 viewer += file;
569 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
571 return FALSE;
573 return TRUE;
576 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
578 DWORD length = 0;
579 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
580 if (hFile == INVALID_HANDLE_VALUE)
581 return TRUE;
582 length = ::GetFileSize(hFile, NULL);
583 ::CloseHandle(hFile);
584 if (length < 4)
585 return TRUE;
586 return FALSE;
590 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
592 LOGFONT logFont;
593 HDC hScreenDC = ::GetDC(NULL);
594 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
595 ::ReleaseDC(NULL, hScreenDC);
596 logFont.lfWidth = 0;
597 logFont.lfEscapement = 0;
598 logFont.lfOrientation = 0;
599 logFont.lfWeight = FW_NORMAL;
600 logFont.lfItalic = 0;
601 logFont.lfUnderline = 0;
602 logFont.lfStrikeOut = 0;
603 logFont.lfCharSet = DEFAULT_CHARSET;
604 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
605 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
606 logFont.lfQuality = DRAFT_QUALITY;
607 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
608 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
609 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
612 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
614 STARTUPINFO startup;
615 PROCESS_INFORMATION process;
616 memset(&startup, 0, sizeof(startup));
617 startup.cb = sizeof(startup);
618 memset(&process, 0, sizeof(process));
620 CString cleanCommandLine(sCommandLine);
622 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
624 if(idErrMessageFormat != 0)
626 LPVOID lpMsgBuf;
627 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
628 FORMAT_MESSAGE_FROM_SYSTEM |
629 FORMAT_MESSAGE_IGNORE_INSERTS,
630 NULL,
631 GetLastError(),
632 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
633 (LPTSTR) &lpMsgBuf,
635 NULL
637 CString temp;
638 temp.Format(idErrMessageFormat, lpMsgBuf);
639 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
640 LocalFree( lpMsgBuf );
642 return false;
645 if (bWaitForStartup)
647 WaitForInputIdle(process.hProcess, 10000);
650 CloseHandle(process.hThread);
651 CloseHandle(process.hProcess);
652 return true;
654 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
656 CString key,remote;
657 CString cmd,out;
658 if( pRemote == NULL)
660 remote=_T("origin");
661 }else
663 remote=*pRemote;
665 if(keyfile == NULL)
667 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
668 key = g_Git.GetConfigValue(cmd);
669 int start=0;
670 key = key.Tokenize(_T("\n"),start);
672 else
673 key=*keyfile;
675 if(key.IsEmpty())
676 return false;
678 CString proc=CPathUtils::GetAppDirectory();
679 proc += _T("pageant.exe \"");
680 proc += key;
681 proc += _T("\"");
683 CString tempfile = GetTempFile();
684 ::DeleteFile(tempfile);
686 proc +=_T(" -c \"");
687 proc += CPathUtils::GetAppDirectory();
688 proc += _T("touch.exe\"");
689 proc +=_T(" \"");
690 proc +=tempfile;
691 proc +=_T("\"");
693 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
694 if(!b)
695 return b;
697 int i=0;
698 while(!::PathFileExists(tempfile))
700 Sleep(100);
701 i++;
702 if(i>10*60*5)
703 break; //timeout 5 minutes
706 if( i== 10*60*5)
708 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
710 ::DeleteFile(tempfile);
711 return true;
713 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
715 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
716 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
717 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
720 CString sCmd;
721 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
723 LaunchApplication(sCmd, NULL, false);
724 return true;
726 bool CAppUtils::LaunchRemoteSetting()
728 CTGitPath path(g_Git.m_CurrentDir);
729 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
730 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
731 //dlg.SetTreeWidth(220);
732 dlg.m_DefaultPage = _T("gitremote");
734 dlg.DoModal();
735 dlg.HandleRestart();
736 return true;
739 * Launch the external blame viewer
741 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
743 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
744 viewer += _T("TortoiseGitBlame.exe");
745 viewer += _T("\" \"") + sBlameFile + _T("\"");
746 //viewer += _T(" \"") + sLogFile + _T("\"");
747 //viewer += _T(" \"") + sOriginalFile + _T("\"");
748 if(!Rev.IsEmpty())
749 viewer += CString(_T(" /rev:"))+Rev;
750 viewer += _T(" ")+sParams;
752 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
755 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
757 CString sText;
758 if (pWnd == NULL)
759 return false;
760 bool bStyled = false;
761 pWnd->GetWindowText(sText);
762 // the rich edit control doesn't count the CR char!
763 // to be exact: CRLF is treated as one char.
764 sText.Replace(_T("\r"), _T(""));
766 // style each line separately
767 int offset = 0;
768 int nNewlinePos;
771 nNewlinePos = sText.Find('\n', offset);
772 CString sLine = sText.Mid(offset);
773 if (nNewlinePos>=0)
774 sLine = sLine.Left(nNewlinePos-offset);
775 int start = 0;
776 int end = 0;
777 while (FindStyleChars(sLine, '*', start, end))
779 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
780 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
781 CHARFORMAT2 format;
782 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
783 format.cbSize = sizeof(CHARFORMAT2);
784 format.dwMask = CFM_BOLD;
785 format.dwEffects = CFE_BOLD;
786 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
787 bStyled = true;
788 start = end;
790 start = 0;
791 end = 0;
792 while (FindStyleChars(sLine, '^', start, end))
794 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
795 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
796 CHARFORMAT2 format;
797 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
798 format.cbSize = sizeof(CHARFORMAT2);
799 format.dwMask = CFM_ITALIC;
800 format.dwEffects = CFE_ITALIC;
801 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
802 bStyled = true;
803 start = end;
805 start = 0;
806 end = 0;
807 while (FindStyleChars(sLine, '_', start, end))
809 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
810 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
811 CHARFORMAT2 format;
812 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
813 format.cbSize = sizeof(CHARFORMAT2);
814 format.dwMask = CFM_UNDERLINE;
815 format.dwEffects = CFE_UNDERLINE;
816 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
817 bStyled = true;
818 start = end;
820 offset = nNewlinePos+1;
821 } while(nNewlinePos>=0);
822 return bStyled;
825 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
827 int i=start;
828 bool bFoundMarker = false;
829 // find a starting marker
830 while (sText[i] != 0)
832 if (sText[i] == stylechar)
834 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
835 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
837 start = i+1;
838 i++;
839 bFoundMarker = true;
840 break;
843 i++;
845 if (!bFoundMarker)
846 return false;
847 // find ending marker
848 bFoundMarker = false;
849 while (sText[i] != 0)
851 if (sText[i] == stylechar)
853 if ((IsCharAlphaNumeric(sText[i-1])) &&
854 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
856 end = i;
857 i++;
858 bFoundMarker = true;
859 break;
862 i++;
864 return bFoundMarker;
867 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
869 OPENFILENAME ofn = {0}; // common dialog box structure
870 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
871 ofn.lStructSize = sizeof(OPENFILENAME);
872 ofn.hwndOwner = hwndOwner;
873 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
874 ofn.lpstrFile = szFile;
875 ofn.nMaxFile = sizeof(szFile)/sizeof(TCHAR);
876 CString sFilter;
877 TCHAR * pszFilters = NULL;
878 if (filter)
880 sFilter.LoadString(filter);
881 pszFilters = new TCHAR[sFilter.GetLength()+4];
882 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
883 // Replace '|' delimiters with '\0's
884 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
885 while (ptr != pszFilters)
887 if (*ptr == '|')
888 *ptr = '\0';
889 ptr--;
891 ofn.lpstrFilter = pszFilters;
893 ofn.nFilterIndex = 1;
894 ofn.lpstrFileTitle = NULL;
895 ofn.nMaxFileTitle = 0;
896 ofn.lpstrInitialDir = NULL;
897 CString temp;
898 if (title)
900 temp.LoadString(title);
901 CStringUtils::RemoveAccelerators(temp);
903 ofn.lpstrTitle = temp;
904 if (bOpen)
905 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
906 else
907 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
910 // Display the Open dialog box.
911 bool bRet = false;
912 if (bOpen)
914 bRet = !!GetOpenFileName(&ofn);
916 else
918 bRet = !!GetSaveFileName(&ofn);
920 if (bRet)
922 if (pszFilters)
923 delete [] pszFilters;
924 path = CString(ofn.lpstrFile);
925 if (filterindex)
926 *filterindex = ofn.nFilterIndex;
927 return true;
929 if (pszFilters)
930 delete [] pszFilters;
931 return false;
934 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
936 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
937 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
938 // create a bitmap from the icon
939 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
940 if (!hIcon)
941 return false;
943 RECT rect = {0};
944 rect.right = width;
945 rect.bottom = height;
946 HBITMAP bmp = NULL;
948 HWND desktop = ::GetDesktopWindow();
949 if (desktop)
951 HDC screen_dev = ::GetDC(desktop);
952 if (screen_dev)
954 // Create a compatible DC
955 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
956 if (dst_hdc)
958 // Create a new bitmap of icon size
959 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
960 if (bmp)
962 // Select it into the compatible DC
963 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
964 // Fill the background of the compatible DC with the given color
965 ::SetBkColor(dst_hdc, bkColor);
966 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
968 // Draw the icon into the compatible DC
969 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
970 ::SelectObject(dst_hdc, old_dst_bmp);
972 ::DeleteDC(dst_hdc);
975 ::ReleaseDC(desktop, screen_dev);
978 // Restore settings
979 DestroyIcon(hIcon);
981 if (bmp == NULL)
982 return false;
984 LVBKIMAGE lv;
985 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
986 lv.hbm = bmp;
987 lv.xOffsetPercent = 100;
988 lv.yOffsetPercent = 100;
989 ListView_SetBkImage(hListCtrl, &lv);
990 return true;
993 CString CAppUtils::GetProjectNameFromURL(CString url)
995 CString name;
996 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
997 (name.CompareNoCase(_T("tags"))==0) ||
998 (name.CompareNoCase(_T("trunk"))==0))
1000 name = url.Mid(url.ReverseFind('/')+1);
1001 url = url.Left(url.ReverseFind('/'));
1003 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1005 // a name of svn or svnroot indicates that it's not really the project name. In that
1006 // case, we try the first part of the URL
1007 // of course, this won't work in all cases (but it works for Google project hosting)
1008 url.Replace(_T("http://"), _T(""));
1009 url.Replace(_T("https://"), _T(""));
1010 url.Replace(_T("svn://"), _T(""));
1011 url.Replace(_T("svn+ssh://"), _T(""));
1012 url.TrimLeft(_T("/"));
1013 name = url.Left(url.Find('.'));
1015 return name;
1018 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1019 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1020 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1021 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1024 CString tempfile=GetTempFile();
1025 CString cmd;
1026 if(rev1 == GitRev::GetWorkingCopy())
1028 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1029 }else
1031 CString merge;
1032 if(bMerge)
1033 merge = _T("-c");
1035 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1038 if( !url1.IsEmpty() )
1040 cmd+=_T(" \"");
1041 cmd+=url1.GetGitPathString();
1042 cmd+=_T("\" ");
1044 g_Git.RunLogFile(cmd,tempfile);
1045 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1048 #if 0
1049 CString sCmd;
1050 sCmd.Format(_T("%s /command:showcompare /unified"),
1051 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1052 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1053 if (rev1.IsValid())
1054 sCmd += _T(" /revision1:") + rev1.ToString();
1055 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1056 if (rev2.IsValid())
1057 sCmd += _T(" /revision2:") + rev2.ToString();
1058 if (peg.IsValid())
1059 sCmd += _T(" /pegrevision:") + peg.ToString();
1060 if (headpeg.IsValid())
1061 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1063 if (bAlternateDiff)
1064 sCmd += _T(" /alternatediff");
1066 if (bIgnoreAncestry)
1067 sCmd += _T(" /ignoreancestry");
1069 if (hWnd)
1071 sCmd += _T(" /hwnd:");
1072 TCHAR buf[30];
1073 _stprintf_s(buf, 30, _T("%d"), hWnd);
1074 sCmd += buf;
1077 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1078 #endif
1079 return TRUE;
1083 bool CAppUtils::Export(CString *BashHash)
1085 bool bRet = false;
1087 // ask from where the export has to be done
1088 CExportDlg dlg;
1089 if(BashHash)
1090 dlg.m_Revision=*BashHash;
1092 if (dlg.DoModal() == IDOK)
1094 CString cmd;
1095 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1096 dlg.m_VersionName);
1098 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1099 CProgressDlg pro;
1100 pro.m_GitCmd=cmd;
1101 pro.m_LogFile=dlg.m_strExportDirectory;
1102 pro.DoModal();
1103 return TRUE;
1105 return bRet;
1108 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1110 CCreateBranchTagDlg dlg;
1111 dlg.m_bIsTag=IsTag;
1112 dlg.m_bSwitch=switch_new_brach;
1114 if(CommitHash)
1115 dlg.m_Base = *CommitHash;
1117 if(dlg.DoModal()==IDOK)
1119 CString cmd;
1120 CString force;
1121 CString track;
1122 if(dlg.m_bTrack)
1123 track=_T(" --track ");
1125 if(dlg.m_bForce)
1126 force=_T(" -f ");
1128 if(IsTag)
1130 CString sign;
1131 if(dlg.m_bSign)
1132 sign=_T("-s");
1134 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1135 track,
1136 force,
1137 sign,
1138 dlg.m_BranchTagName,
1139 dlg.m_VersionName
1142 CString tempfile=::GetTempFile();
1143 if(!dlg.m_Message.Trim().IsEmpty())
1145 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1146 cmd += _T(" -F ")+tempfile;
1149 else
1151 cmd.Format(_T("git.exe branch %s %s %s %s"),
1152 track,
1153 force,
1154 dlg.m_BranchTagName,
1155 dlg.m_VersionName
1158 CString out;
1159 if(g_Git.Run(cmd,&out,CP_UTF8))
1161 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1163 if( !IsTag && dlg.m_bSwitch )
1165 // it is a new branch and the user has requested to switch to it
1166 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1167 g_Git.Run(cmd,&out,CP_UTF8);
1168 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1171 return TRUE;
1173 return FALSE;
1176 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName)
1178 CGitSwitchDlg dlg;
1179 if(CommitHash)
1180 dlg.m_Base=*CommitHash;
1181 if(!initialRefName.IsEmpty())
1182 dlg.m_initialRefName = initialRefName;
1184 if (dlg.DoModal() == IDOK)
1186 CString cmd;
1187 CString track;
1188 // CString base;
1189 CString force;
1190 CString branch;
1192 if(dlg.m_bBranch){
1193 if (dlg.m_bBranchOverride) {
1194 branch.Format(_T("-B %s"),dlg.m_NewBranch);
1195 } else {
1196 branch.Format(_T("-b %s"),dlg.m_NewBranch);
1199 if(dlg.m_bForce)
1200 force=_T("-f");
1201 if(dlg.m_bTrack)
1202 track=_T("--track");
1204 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1205 force,
1206 track,
1207 branch,
1208 dlg.m_VersionName);
1210 CProgressDlg progress;
1211 progress.m_GitCmd=cmd;
1212 if(progress.DoModal()==IDOK)
1213 return TRUE;
1216 return FALSE;
1219 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1221 CString ignorefile;
1222 ignorefile=g_Git.m_CurrentDir+_T("\\");
1224 if(IsMask)
1226 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1228 }else
1230 ignorefile+=_T("\\.gitignore");
1233 CStdioFile file;
1234 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1236 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1237 return FALSE;
1240 CString ignorelist;
1241 CString mask;
1244 //file.ReadString(ignorelist);
1245 file.SeekToEnd();
1246 for(int i=0;i<path.GetCount();i++)
1248 if(IsMask)
1250 mask=_T("*")+path[i].GetFileExtension();
1251 if(ignorelist.Find(mask)<0)
1252 ignorelist+=_T("\n")+mask;
1254 else
1256 ignorelist+=_T("\n/")+path[i].GetGitPathString();
1259 file.WriteString(ignorelist);
1261 file.Close();
1263 }catch(...)
1265 file.Close();
1266 return FALSE;
1269 return TRUE;
1273 bool CAppUtils::GitReset(CString *CommitHash,int type)
1275 CResetDlg dlg;
1276 dlg.m_ResetType=type;
1277 dlg.m_ResetToVersion=*CommitHash;
1278 if (dlg.DoModal() == IDOK)
1280 CString cmd;
1281 CString type;
1282 switch(dlg.m_ResetType)
1284 case 0:
1285 type=_T("--soft");
1286 break;
1287 case 1:
1288 type=_T("--mixed");
1289 break;
1290 case 2:
1291 type=_T("--hard");
1292 break;
1293 default:
1294 type=_T("--mixed");
1295 break;
1297 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1299 CProgressDlg progress;
1300 progress.m_GitCmd=cmd;
1301 if(progress.DoModal()==IDOK)
1302 return TRUE;
1305 return FALSE;
1308 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1310 if(mode == FALSE)
1312 descript=_T("Deleted");
1313 return;
1315 if(base)
1317 descript=_T("Modified");
1318 return;
1320 descript=_T("Created");
1321 return;
1324 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1326 CString tempmergefile;
1329 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1330 CFile::Remove(tempmergefile);
1331 }catch(...)
1337 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1338 CFile::Remove(tempmergefile);
1339 }catch(...)
1345 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1346 CFile::Remove(tempmergefile);
1347 }catch(...)
1351 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1353 CString file;
1354 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1356 return file;
1359 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1361 bool bRet = false;
1363 CTGitPath merge=path;
1364 CTGitPath directory = merge.GetDirectory();
1366 // we have the conflicted file (%merged)
1367 // now look for the other required files
1368 //GitStatus stat;
1369 //stat.GetStatus(merge);
1370 //if (stat.status == NULL)
1371 // return false;
1373 BYTE_VECTOR vector;
1375 CString cmd;
1376 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1378 if(g_Git.Run(cmd,&vector))
1380 return FALSE;
1383 CTGitPathList list;
1384 list.ParserFromLsFile(vector);
1386 if(list.GetCount() == 0)
1387 return FALSE;
1389 CTGitPath theirs;
1390 CTGitPath mine;
1391 CTGitPath base;
1393 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1394 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1395 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1397 CString format;
1399 //format=_T("git.exe cat-file blob \":%d:%s\"");
1400 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1401 CFile tempfile;
1402 //create a empty file, incase stage is not three
1403 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1404 tempfile.Close();
1405 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1406 tempfile.Close();
1407 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1408 tempfile.Close();
1410 bool b_base=false, b_local=false, b_remote=false;
1412 for(int i=0;i<list.GetCount();i++)
1414 CString cmd;
1415 CString outfile;
1416 cmd.Empty();
1417 outfile.Empty();
1419 if( list[i].m_Stage == 1)
1421 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1422 b_base = true;
1423 outfile = base.GetWinPathString();
1426 if( list[i].m_Stage == 2 )
1428 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1429 b_local = true;
1430 outfile = mine.GetWinPathString();
1433 if( list[i].m_Stage == 3 )
1435 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1436 b_remote = true;
1437 outfile = theirs.GetWinPathString();
1439 CString output;
1440 if(!outfile.IsEmpty())
1441 if(!g_Git.Run(cmd,&output,CP_ACP))
1443 CString file;
1444 int start =0 ;
1445 file = output.Tokenize(_T("\t"), start);
1446 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1448 else
1450 CMessageBox::Show(NULL,output,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1454 if(b_local && b_remote )
1456 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1457 if( revertTheirMy )
1458 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1459 else
1460 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1463 else
1465 CFile::Remove(mine.GetWinPathString());
1466 CFile::Remove(theirs.GetWinPathString());
1467 CFile::Remove(base.GetWinPathString());
1469 CDeleteConflictDlg dlg;
1470 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1471 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1472 dlg.m_bShowModifiedButton=b_base;
1473 dlg.m_File=merge.GetGitPathString();
1474 if(dlg.DoModal() == IDOK)
1476 CString cmd,out;
1477 if(dlg.m_bIsDelete)
1479 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1480 }else
1481 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1483 if(g_Git.Run(cmd,&out,CP_ACP))
1485 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1486 return FALSE;
1488 return TRUE;
1490 else
1491 return FALSE;
1494 #if 0
1495 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1496 base, theirs, mine, merge);
1497 #endif
1498 #if 0
1499 if (stat.status->text_status == svn_wc_status_conflicted)
1501 // we have a text conflict, use our merge tool to resolve the conflict
1503 CTSVNPath theirs(directory);
1504 CTSVNPath mine(directory);
1505 CTSVNPath base(directory);
1506 bool bConflictData = false;
1508 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1510 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1511 bConflictData = true;
1513 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1515 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1516 bConflictData = true;
1518 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1520 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1521 bConflictData = true;
1523 else
1525 mine = merge;
1527 if (bConflictData)
1528 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1529 base, theirs, mine, merge);
1532 if (stat.status->prop_status == svn_wc_status_conflicted)
1534 // we have a property conflict
1535 CTSVNPath prej(directory);
1536 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1538 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1539 // there's a problem: the prej file contains a _description_ of the conflict, and
1540 // that description string might be translated. That means we have no way of parsing
1541 // the file to find out the conflicting values.
1542 // The only thing we can do: show a dialog with the conflict description, then
1543 // let the user either accept the existing property or open the property edit dialog
1544 // to manually change the properties and values. And a button to mark the conflict as
1545 // resolved.
1546 CEditPropConflictDlg dlg;
1547 dlg.SetPrejFile(prej);
1548 dlg.SetConflictedItem(merge);
1549 bRet = (dlg.DoModal() != IDCANCEL);
1553 if (stat.status->tree_conflict)
1555 // we have a tree conflict
1556 SVNInfo info;
1557 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1558 if (pInfoData)
1560 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1562 CTSVNPath theirs(directory);
1563 CTSVNPath mine(directory);
1564 CTSVNPath base(directory);
1565 bool bConflictData = false;
1567 if (pInfoData->treeconflict_theirfile)
1569 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1570 bConflictData = true;
1572 if (pInfoData->treeconflict_basefile)
1574 base.AppendPathString(pInfoData->treeconflict_basefile);
1575 bConflictData = true;
1577 if (pInfoData->treeconflict_myfile)
1579 mine.AppendPathString(pInfoData->treeconflict_myfile);
1580 bConflictData = true;
1582 else
1584 mine = merge;
1586 if (bConflictData)
1587 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1588 base, theirs, mine, merge);
1590 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1592 CString sConflictAction;
1593 CString sConflictReason;
1594 CString sResolveTheirs;
1595 CString sResolveMine;
1596 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1597 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1599 if (pInfoData->treeconflict_nodekind == svn_node_file)
1601 switch (pInfoData->treeconflict_operation)
1603 case svn_wc_operation_update:
1604 switch (pInfoData->treeconflict_action)
1606 case svn_wc_conflict_action_edit:
1607 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1608 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1609 break;
1610 case svn_wc_conflict_action_add:
1611 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1612 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1613 break;
1614 case svn_wc_conflict_action_delete:
1615 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1616 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1617 break;
1619 break;
1620 case svn_wc_operation_switch:
1621 switch (pInfoData->treeconflict_action)
1623 case svn_wc_conflict_action_edit:
1624 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1625 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1626 break;
1627 case svn_wc_conflict_action_add:
1628 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1629 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1630 break;
1631 case svn_wc_conflict_action_delete:
1632 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1633 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1634 break;
1636 break;
1637 case svn_wc_operation_merge:
1638 switch (pInfoData->treeconflict_action)
1640 case svn_wc_conflict_action_edit:
1641 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1642 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1643 break;
1644 case svn_wc_conflict_action_add:
1645 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1646 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1647 break;
1648 case svn_wc_conflict_action_delete:
1649 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1650 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1651 break;
1653 break;
1656 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1658 switch (pInfoData->treeconflict_operation)
1660 case svn_wc_operation_update:
1661 switch (pInfoData->treeconflict_action)
1663 case svn_wc_conflict_action_edit:
1664 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1665 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1666 break;
1667 case svn_wc_conflict_action_add:
1668 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1669 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1670 break;
1671 case svn_wc_conflict_action_delete:
1672 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1673 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1674 break;
1676 break;
1677 case svn_wc_operation_switch:
1678 switch (pInfoData->treeconflict_action)
1680 case svn_wc_conflict_action_edit:
1681 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1682 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1683 break;
1684 case svn_wc_conflict_action_add:
1685 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1686 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1687 break;
1688 case svn_wc_conflict_action_delete:
1689 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1690 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1691 break;
1693 break;
1694 case svn_wc_operation_merge:
1695 switch (pInfoData->treeconflict_action)
1697 case svn_wc_conflict_action_edit:
1698 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1699 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1700 break;
1701 case svn_wc_conflict_action_add:
1702 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1703 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1704 break;
1705 case svn_wc_conflict_action_delete:
1706 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1707 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1708 break;
1710 break;
1714 UINT uReasonID = 0;
1715 switch (pInfoData->treeconflict_reason)
1717 case svn_wc_conflict_reason_edited:
1718 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1719 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1720 break;
1721 case svn_wc_conflict_reason_obstructed:
1722 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1723 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1724 break;
1725 case svn_wc_conflict_reason_deleted:
1726 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1727 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1728 break;
1729 case svn_wc_conflict_reason_added:
1730 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1731 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1732 break;
1733 case svn_wc_conflict_reason_missing:
1734 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1735 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1736 break;
1737 case svn_wc_conflict_reason_unversioned:
1738 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1739 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1740 break;
1742 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1744 CTreeConflictEditorDlg dlg;
1745 dlg.SetConflictInfoText(sConflictReason);
1746 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1747 dlg.SetPath(treeConflictPath);
1748 INT_PTR dlgRet = dlg.DoModal();
1749 bRet = (dlgRet != IDCANCEL);
1753 #endif
1754 return bRet;
1758 * FUNCTION : FormatDateAndTime
1759 * DESCRIPTION : Generates a displayable string from a CTime object in
1760 * system short or long format or as a relative value
1761 * cTime - the time
1762 * option - DATE_SHORTDATE or DATE_LONGDATE
1763 * bIncluedeTime - whether to show time as well as date
1764 * bRelative - if true then relative time is shown if reasonable
1765 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1766 * rather than locale
1767 * RETURN : CString containing date/time
1769 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1770 bool bRelative /*=false*/)
1772 CString datetime;
1773 if ( bRelative )
1775 datetime = ToRelativeTimeString( cTime );
1777 else
1779 // should we use the locale settings for formatting the date/time?
1780 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1782 // yes
1783 SYSTEMTIME sysTime;
1784 cTime.GetAsSystemTime( sysTime );
1786 TCHAR buf[100];
1788 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1789 sizeof(buf)/sizeof(TCHAR)-1);
1790 datetime = buf;
1791 if ( bIncludeTime )
1793 datetime += _T(" ");
1794 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, sizeof(buf)/sizeof(TCHAR)-1);
1795 datetime += buf;
1798 else
1800 // no, so fixed format
1801 if ( bIncludeTime )
1803 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1805 else
1807 datetime = cTime.Format(_T("%Y-%m-%d"));
1811 return datetime;
1815 * Converts a given time to a relative display string (relative to current time)
1816 * Given time must be in local timezone
1818 CString CAppUtils::ToRelativeTimeString(CTime time)
1820 CString answer;
1821 // convert to COleDateTime
1822 SYSTEMTIME sysTime;
1823 time.GetAsSystemTime( sysTime );
1824 COleDateTime oleTime( sysTime );
1825 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1826 return answer;
1830 * Generates a display string showing the relative time between the two given times as COleDateTimes
1832 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1834 CString answer;
1835 COleDateTimeSpan ts = RelativeTo - time;
1836 //years
1837 if(fabs(ts.GetTotalDays()) >= 3*365)
1839 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1841 //Months
1842 if(fabs(ts.GetTotalDays()) >= 60)
1844 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1845 return answer;
1847 //Weeks
1848 if(fabs(ts.GetTotalDays()) >= 14)
1850 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1851 return answer;
1853 //Days
1854 if(fabs(ts.GetTotalDays()) >= 2)
1856 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1857 return answer;
1859 //hours
1860 if(fabs(ts.GetTotalHours()) >= 2)
1862 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1863 return answer;
1865 //minutes
1866 if(fabs(ts.GetTotalMinutes()) >= 2)
1868 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1869 return answer;
1871 //seconds
1872 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1873 return answer;
1877 * Passed a value and two resource string ids
1878 * if count is 1 then FormatString is called with format_1 and the value
1879 * otherwise format_2 is used
1880 * the formatted string is returned
1882 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1884 CString answer;
1885 if ( count == 1 )
1887 answer.FormatMessage( format_1, count );
1889 else
1891 answer.FormatMessage( format_n, count );
1893 return answer;
1896 bool CAppUtils::IsSSHPutty()
1898 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
1899 sshclient=sshclient.MakeLower();
1900 if(sshclient.Find(_T("plink.exe"),0)>=0)
1902 return true;
1904 return false;
1907 CString CAppUtils::GetClipboardLink()
1909 if (!OpenClipboard(NULL))
1910 return CString();
1912 CString sClipboardText;
1913 HGLOBAL hglb = GetClipboardData(CF_TEXT);
1914 if (hglb)
1916 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
1917 sClipboardText = CString(lpstr);
1918 GlobalUnlock(hglb);
1920 hglb = GetClipboardData(CF_UNICODETEXT);
1921 if (hglb)
1923 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
1924 sClipboardText = lpstr;
1925 GlobalUnlock(hglb);
1927 CloseClipboard();
1929 if(!sClipboardText.IsEmpty())
1931 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
1932 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
1934 if(sClipboardText.Find( _T("http://")) == 0)
1935 return sClipboardText;
1937 if(sClipboardText.Find( _T("https://")) == 0)
1938 return sClipboardText;
1940 if(sClipboardText.Find( _T("git://")) == 0)
1941 return sClipboardText;
1943 if(sClipboardText.Find( _T("ssh://")) == 0)
1944 return sClipboardText;
1946 if(sClipboardText.GetLength()>=2)
1947 if( sClipboardText[1] == _T(':') )
1948 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
1949 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
1950 return sClipboardText;
1953 return CString(_T(""));
1956 CString CAppUtils::ChooseRepository(CString *path)
1958 CBrowseFolder browseFolder;
1959 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
1961 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
1962 CString strCloneDirectory;
1963 if(path)
1964 strCloneDirectory=*path;
1965 else
1967 strCloneDirectory = regLastResopitory;
1970 CString title;
1971 title.LoadString(IDS_CHOOSE_REPOSITORY);
1973 browseFolder.SetInfo(title);
1975 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
1977 regLastResopitory = strCloneDirectory;
1978 return strCloneDirectory;
1980 else
1982 return CString();
1986 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
1988 CSendMailDlg dlg;
1990 dlg.m_PathList = list;
1992 if(dlg.DoModal()==IDOK)
1994 if(dlg.m_PathList.GetCount() == 0)
1995 return FALSE;
1997 CGitProgressDlg progDlg;
1999 theApp.m_pMainWnd = &progDlg;
2000 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2002 progDlg.SetAutoClose(autoclose);
2004 progDlg.SetPathList(dlg.m_PathList);
2005 //ProjectProperties props;
2006 //props.ReadPropsPathList(dlg.m_pathList);
2007 //progDlg.SetProjectProperties(props);
2008 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2010 DWORD flags =0;
2011 if(dlg.m_bAttachment)
2012 flags |= SENDMAIL_ATTACHMENT;
2013 if(dlg.m_bCombine)
2014 flags |= SENDMAIL_COMBINED;
2015 if(dlg.m_bUseMAPI)
2016 flags |= SENDMAIL_MAPI;
2018 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2020 progDlg.DoModal();
2022 return true;
2024 return false;
2027 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2029 CTGitPathList list;
2030 CString log=formatpatchoutput;
2031 int start=log.Find(cmd);
2032 if(start >=0)
2033 CString one=log.Tokenize(_T("\n"),start);
2034 else
2035 start = 0;
2037 while(start>=0)
2039 CString one=log.Tokenize(_T("\n"),start);
2040 one=one.Trim();
2041 if(one.IsEmpty() || one == _T("Success"))
2042 continue;
2043 one.Replace(_T('/'),_T('\\'));
2044 CTGitPath path;
2045 path.SetFromWin(one);
2046 list.AddPath(path);
2048 if (list.GetCount() > 0) {
2049 return SendPatchMail(list, autoclose);
2050 } else {
2051 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2052 return true;
2057 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2059 CString cmd,output;
2060 int start=0;
2062 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2063 if(output.IsEmpty())
2065 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2066 if(output.IsEmpty())
2067 return CP_UTF8;
2069 int start=0;
2070 output=output.Tokenize(_T("\n"),start);
2071 return CUnicodeUtils::GetCPCode(output);
2073 }else
2075 output=output.Tokenize(_T("\n"),start);
2076 return CUnicodeUtils::GetCPCode(output);
2079 int CAppUtils::GetCommitTemplate(CString &temp)
2081 CString cmd,output;
2083 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2084 if( output.IsEmpty() )
2085 return -1;
2087 if( output.GetLength()<1)
2088 return -1;
2090 if( output[0] == _T('/'))
2092 if(output.GetLength()>=3)
2093 if(output[2] == _T('/'))
2095 output.GetBuffer()[0] = output[1];
2096 output.GetBuffer()[1] = _T(':');
2100 int start=0;
2101 output=output.Tokenize(_T("\n"),start);
2103 output.Replace(_T('/'),_T('\\'));
2107 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2108 CString str;
2109 while(file.ReadString(str))
2111 temp+=str+_T("\n");
2114 }catch(...)
2116 return -1;
2118 return 0;
2120 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2122 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2123 CString cmd,output;
2124 int cp=CP_UTF8;
2126 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2127 if(output.IsEmpty())
2128 cp=CP_UTF8;
2130 int start=0;
2131 output=output.Tokenize(_T("\n"),start);
2132 cp=CUnicodeUtils::GetCPCode(output);
2134 int len=message.GetLength();
2136 char * buf;
2137 buf = new char[len*4 + 4];
2138 SecureZeroMemory(buf, (len*4 + 4));
2140 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2142 file.Write(buf,lengthIncTerminator-1);
2143 file.Close();
2144 delete buf;
2145 return 0;
2148 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2150 CPullFetchDlg dlg;
2151 dlg.m_PreSelectRemote = remoteName;
2152 dlg.m_bAllowRebase = allowRebase;
2153 dlg.m_IsPull=FALSE;
2155 if(dlg.DoModal()==IDOK)
2157 if(dlg.m_bAutoLoad)
2159 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2162 CString url;
2163 url=dlg.m_RemoteURL;
2164 CString cmd;
2165 CString arg;
2167 int ver = CAppUtils::GetMsysgitVersion();
2169 if(ver >= 0x01070203) //above 1.7.0.2
2170 arg = _T("--progress ");
2172 if (dlg.m_bPrune) {
2173 arg += _T("--prune ");
2176 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2177 CProgressDlg progress;
2179 progress.m_bAutoCloseOnSuccess = autoClose;
2181 if(!dlg.m_bRebase)
2183 progress.m_PostCmdList.Add(_T("&Rebase"));
2186 progress.m_GitCmd=cmd;
2187 int userResponse=progress.DoModal();
2189 if( (userResponse==IDC_PROGRESS_BUTTON1) || ( progress.m_GitStatus ==0 && dlg.m_bRebase) )
2191 while(1)
2193 CRebaseDlg dlg;
2194 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2195 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2196 int response = dlg.DoModal();
2197 if(response == IDOK)
2199 return TRUE;
2201 if(response == IDC_REBASE_POST_BUTTON )
2203 CString cmd,out;
2204 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2205 g_Git.m_CurrentDir,
2206 dlg.m_Upstream,dlg.m_Branch);
2207 if(g_Git.Run(cmd,&out,CP_ACP))
2209 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2210 return FALSE;
2213 CAppUtils::SendPatchMail(cmd,out);
2214 return TRUE;
2217 if(response == IDC_REBASE_POST_BUTTON +1 )
2218 continue;
2220 if(response == IDCANCEL)
2221 return FALSE;
2223 return TRUE;
2226 return FALSE;
2229 bool CAppUtils::Push(bool autoClose)
2231 CPushDlg dlg;
2232 // dlg.m_Directory=this->orgCmdLinePath.GetWinPathString();
2233 CString error;
2234 DWORD exitcode = 0xFFFFFFFF;
2235 CTGitPathList list;
2236 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2237 if (CHooks::Instance().PrePush(list,exitcode, error))
2239 if (exitcode)
2241 CString temp;
2242 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2243 //ReportError(temp);
2244 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2245 return false;
2249 if(dlg.DoModal()==IDOK)
2251 // CString dir=dlg.m_Directory;
2252 // CString url=dlg.m_URL;
2253 CString cmd;
2254 CString arg;
2256 if(dlg.m_bAutoLoad)
2258 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2261 if(dlg.m_bPack)
2262 arg +=_T("--thin ");
2263 if(dlg.m_bTags)
2264 arg +=_T("--tags ");
2265 if(dlg.m_bForce)
2266 arg +=_T("--force ");
2268 int ver = CAppUtils::GetMsysgitVersion();
2270 if(ver >= 0x01070203) //above 1.7.0.2
2271 arg += _T("--progress ");
2274 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2275 arg,
2276 dlg.m_URL,
2277 dlg.m_BranchSourceName);
2278 if (!dlg.m_BranchRemoteName.IsEmpty())
2280 cmd += _T(":") + dlg.m_BranchRemoteName;
2283 CProgressDlg progress;
2284 progress.m_bAutoCloseOnSuccess=autoClose;
2285 progress.m_GitCmd=cmd;
2286 progress.m_PostCmdList.Add(_T("&Request pull"));
2287 int ret = progress.DoModal();
2289 if(!progress.m_GitStatus)
2291 if (CHooks::Instance().PostPush(list,exitcode, error))
2293 if (exitcode)
2295 CString temp;
2296 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2297 //ReportError(temp);
2298 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2299 return false;
2302 if(ret == IDC_PROGRESS_BUTTON1)
2304 RequestPull(dlg.m_BranchRemoteName);
2306 return TRUE;
2310 return FALSE;
2313 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2315 CRequestPullDlg dlg;
2316 dlg.m_RepositoryURL = repositoryUrl;
2317 dlg.m_EndRevision = endrevision;
2318 if (dlg.DoModal()==IDOK)
2320 CString cmd;
2321 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2323 CProgressDlg progress;
2324 progress.m_GitCmd=cmd;
2325 progress.DoModal();
2327 return true;
2330 bool CAppUtils::CreateMultipleDirectory(CString& szPath)
2332 CString strDir(szPath);
2333 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2335 strDir.AppendChar(_T('\\'));
2337 std::vector<CString> vPath;
2338 CString strTemp;
2339 bool bSuccess = false;
2341 for (int i=0;i<strDir.GetLength();++i)
2343 if (strDir.GetAt(i) != _T('\\'))
2345 strTemp.AppendChar(strDir.GetAt(i));
2347 else
2349 vPath.push_back(strTemp);
2350 strTemp.AppendChar(_T('\\'));
2354 std::vector<CString>::const_iterator vIter;
2355 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2357 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2360 return bSuccess;
2363 void CAppUtils::RemoveTrailSlash(CString &path)
2365 if(path.IsEmpty())
2366 return ;
2368 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2370 path=path.Left(path.GetLength()-1);
2371 if(path.IsEmpty())
2372 return;
2376 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2377 CTGitPathList &pathList,
2378 CTGitPathList &selectedList,
2379 bool bSelectFilesForCommit)
2381 bool bFailed = true;
2383 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2385 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"),
2386 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2388 CTGitPath path(g_Git.m_CurrentDir);
2389 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2390 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2391 dlg.SetTreeWidth(220);
2392 dlg.m_DefaultPage = _T("gitconfig");
2394 dlg.DoModal();
2395 dlg.HandleRestart();
2397 }else
2398 return false;
2401 while (bFailed)
2403 bFailed = false;
2404 CCommitDlg dlg;
2405 dlg.m_sBugID = bugid;
2407 dlg.m_bWholeProject = bWholeProject;
2409 dlg.m_sLogMessage = sLogMsg;
2410 dlg.m_pathList = pathList;
2411 dlg.m_checkedPathList = selectedList;
2412 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2413 if (dlg.DoModal() == IDOK)
2415 if (dlg.m_pathList.GetCount()==0)
2416 return false;
2417 // if the user hasn't changed the list of selected items
2418 // we don't use that list. Because if we would use the list
2419 // of pre-checked items, the dialog would show different
2420 // checked items on the next startup: it would only try
2421 // to check the parent folder (which might not even show)
2422 // instead, we simply use an empty list and let the
2423 // default checking do its job.
2424 if (!dlg.m_pathList.IsEqual(pathList))
2425 selectedList = dlg.m_pathList;
2426 pathList = dlg.m_updatedPathList;
2427 sLogMsg = dlg.m_sLogMessage;
2428 bSelectFilesForCommit = true;
2430 if( dlg.m_bPushAfterCommit )
2432 switch(dlg.m_PostCmd)
2434 case GIT_POST_CMD_DCOMMIT:
2435 CAppUtils::SVNDCommit();
2436 break;
2437 default:
2438 CAppUtils::Push();
2441 // CGitProgressDlg progDlg;
2442 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2443 // if (parser.HasVal(_T("closeonend")))
2444 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2445 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2446 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2447 // progDlg.SetPathList(dlg.m_pathList);
2448 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2449 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2450 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2451 // progDlg.SetItemCount(dlg.m_itemsCount);
2452 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2453 // progDlg.DoModal();
2454 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2455 // err = (DWORD)progDlg.DidErrorsOccur();
2456 // bFailed = progDlg.DidErrorsOccur();
2457 // bRet = progDlg.DidErrorsOccur();
2458 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2459 // if (DWORD(bFailRepeat)==0)
2460 // bFailed = false; // do not repeat if the user chose not to in the settings.
2463 return true;
2467 BOOL CAppUtils::SVNDCommit()
2469 CSVNDCommitDlg dcommitdlg;
2470 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2471 if (gitSetting == _T("")) {
2472 if (dcommitdlg.DoModal() != IDOK) {
2473 return false;
2474 } else {
2475 if (dcommitdlg.m_remember) {
2476 if (dcommitdlg.m_rmdir) {
2477 gitSetting = _T("true");
2478 } else {
2479 gitSetting = _T("false");
2481 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2483 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2489 BOOL IsStash = false;
2490 if(!g_Git.CheckCleanWorkTree())
2492 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2494 CString cmd,out;
2495 cmd=_T("git.exe stash");
2496 if(g_Git.Run(cmd,&out,CP_ACP))
2498 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2499 return false;
2501 IsStash =true;
2503 }else
2505 return false;
2509 CProgressDlg progress;
2510 if (dcommitdlg.m_rmdir) {
2511 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2512 } else {
2513 progress.m_GitCmd=_T("git.exe svn dcommit");
2515 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2517 if( IsStash)
2519 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2521 CString cmd,out;
2522 cmd=_T("git.exe stash pop");
2523 if(g_Git.Run(cmd,&out,CP_ACP))
2525 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2526 return false;
2529 }else
2531 return false;
2534 return TRUE;
2536 return FALSE;
2539 BOOL CAppUtils::Merge(CString *commit)
2541 CMergeDlg dlg;
2542 if(commit)
2543 dlg.m_initialRefName = *commit;
2545 if(dlg.DoModal()==IDOK)
2547 CString cmd;
2548 CString noff;
2549 CString squash;
2550 CString nocommit;
2551 CString msg;
2553 if(dlg.m_bNoFF)
2554 noff=_T("--no-ff");
2556 if(dlg.m_bSquash)
2557 squash=_T("--squash");
2559 if(dlg.m_bNoCommit)
2560 nocommit=_T("--no-commit");
2562 if(!dlg.m_strLogMesage.IsEmpty())
2564 msg+=_T("-m \"")+dlg.m_strLogMesage+_T("\"");
2566 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2567 msg,
2568 noff,
2569 squash,
2570 nocommit,
2571 dlg.m_VersionName);
2573 CProgressDlg Prodlg;
2574 Prodlg.m_GitCmd = cmd;
2576 Prodlg.DoModal();
2578 return !Prodlg.m_GitStatus;
2580 return false;
2583 void CAppUtils::EditNote(GitRev *rev)
2585 CInputDlg dlg;
2586 dlg.m_sHintText=_T("Edit Notes");
2587 dlg.m_sInputText = rev->m_Notes;
2588 dlg.m_sTitle=_T("Edit Notes");
2589 //dlg.m_pProjectProperties = &m_ProjectProperties;
2590 dlg.m_bUseLogWidth = true;
2591 if(dlg.DoModal() == IDOK)
2593 CString cmd,output;
2594 cmd=_T("notes add -f -F \"");
2596 CString tempfile=::GetTempFile();
2597 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2598 cmd+=tempfile;
2599 cmd+=_T("\" ");
2600 cmd+=rev->m_CommitHash.ToString();
2604 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2606 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2609 else
2611 rev->m_Notes = dlg.m_sInputText;
2613 }catch(...)
2615 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2617 CFile::Remove(tempfile);
2622 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2624 CString cmd;
2625 CString progressarg;
2626 CString version;
2628 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2629 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2631 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2633 __int64 time=0;
2634 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2636 if((DWORD)time == regTime)
2638 return regVersion;
2642 if(versionstr)
2643 version = *versionstr;
2644 else
2646 cmd = _T("git.exe --version");
2647 if(g_Git.Run(cmd, &version, CP_ACP))
2649 CMessageBox::Show(NULL,_T("git have not installed"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2650 return false;
2654 int start=0;
2655 int ver;
2657 CString str=version.Tokenize(_T("."),start);
2658 int space = str.ReverseFind(_T(' '));
2659 str=str.Mid(space+1,start);
2660 ver = _ttol(str);
2661 ver <<=24;
2663 version = version.Mid(start);
2664 start = 0;
2665 str = version.Tokenize(_T("."),start);
2667 ver |= (_ttol(str)&0xFF)<<16;
2669 str = version.Tokenize(_T("."),start);
2670 ver |= (_ttol(str)&0xFF)<<8;
2672 str = version.Tokenize(_T("."),start);
2673 ver |= (_ttol(str)&0xFF);
2675 regTime = time&0xFFFFFFFF;
2676 regVersion = ver;
2678 return ver;