tell user if there are conflicts after applying stash
[TortoiseGit.git] / src / TortoiseProc / AppUtils.cpp
blobaba2ed479b87f8dfa4de9d0de1956b6501d6415b
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 "GITProgressDlg.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"
60 #include "StashSave.h"
62 CAppUtils::CAppUtils(void)
66 CAppUtils::~CAppUtils(void)
70 bool CAppUtils::StashSave()
72 CStashSaveDlg dlg;
74 if (dlg.DoModal() == IDOK)
76 CString cmd, out;
77 cmd = _T("git.exe stash save");
79 if (dlg.m_bIncludeUntracked && CAppUtils::GetMsysgitVersion() >= 0x01070700)
80 cmd += _T(" --include-untracked");
82 if (!dlg.m_sMessage.IsEmpty())
84 CString message = dlg.m_sMessage;
85 message.Replace(_T("\""), _T("\"\""));
86 cmd += _T(" \"") + message + _T("\"");
89 if (g_Git.Run(cmd, &out, CP_ACP))
91 CMessageBox::Show(NULL, CString(_T("<ct=0x0000FF>Stash Fail!!!</ct>\n")) + out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
93 else
95 CMessageBox::Show(NULL, CString(_T("<ct=0xff0000>Stash Success</ct>\n")) + out, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
96 return true;
99 return false;
102 int CAppUtils::StashApply(CString ref, bool showChanges /* true */)
104 CString cmd,out;
105 cmd = _T("git.exe stash apply ");
106 if (ref.Find(_T("refs/")) == 0)
107 ref = ref.Mid(5);
108 if (ref.Find(_T("stash{")) == 0)
109 ref = _T("stash@") + ref.Mid(5);
110 cmd += ref;
112 int ret = g_Git.Run(cmd, &out, CP_ACP);
113 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
114 if (ret && !(ret == 1 && hasConflicts))
116 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash Apply Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
118 else
120 CString withConflicts;
121 if (hasConflicts)
122 withConflicts = _T(" with conflicts");
123 if (showChanges)
125 if(CMessageBox::Show(NULL,CString(_T("<ct=0xff0000>Stash Apply Success") + withConflicts + _T("</ct>\nDo you want to show change?"))
126 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
128 CChangedDlg dlg;
129 dlg.m_pathList.AddPath(CTGitPath());
130 dlg.DoModal();
132 return 0;
134 else
136 CMessageBox::Show(NULL, _T("<ct=0xff0000>Stash Apply Success") + withConflicts + _T("</ct>") ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
137 return 0;
140 return -1;
143 int CAppUtils::StashPop(bool showChanges /* true */)
145 CString cmd,out;
146 cmd=_T("git.exe stash pop ");
148 int ret = g_Git.Run(cmd, &out, CP_ACP);
149 bool hasConflicts = (out.Find(_T("CONFLICT")) >= 0);
150 if (ret && !(ret == 1 && hasConflicts))
152 CMessageBox::Show(NULL,CString(_T("<ct=0x0000FF>Stash POP Fail!!!</ct>\n"))+out,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
154 else
156 CString message = _T("<ct=0xff0000>Stash POP Success</ct>");
157 if (hasConflicts)
158 message = _T("<ct=0x000000ff>Stash POP Failed, there are conflicts</ct>");
159 if (showChanges)
161 if(CMessageBox::Show(NULL,CString(message + _T("\nDo you want to show change?"))
162 ,_T("TortoiseGit"),MB_YESNO|MB_ICONINFORMATION) == IDYES)
164 CChangedDlg dlg;
165 dlg.m_pathList.AddPath(CTGitPath());
166 dlg.DoModal();
168 return 0;
170 else
172 CMessageBox::Show(NULL, message ,_T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
173 return 0;
176 return -1;
179 bool CAppUtils::GetMimeType(const CTGitPath& /*file*/, CString& /*mimetype*/)
181 #if 0
182 GitProperties props(file, GitRev::REV_WC, false);
183 for (int i = 0; i < props.GetCount(); ++i)
185 if (props.GetItemName(i).compare(_T("svn:mime-type"))==0)
187 mimetype = props.GetItemValue(i).c_str();
188 return true;
191 #endif
192 return false;
195 BOOL CAppUtils::StartExtMerge(
196 const CTGitPath& basefile, const CTGitPath& theirfile, const CTGitPath& yourfile, const CTGitPath& mergedfile,
197 const CString& basename, const CString& theirname, const CString& yourname, const CString& mergedname, bool bReadOnly)
200 CRegString regCom = CRegString(_T("Software\\TortoiseGit\\Merge"));
201 CString ext = mergedfile.GetFileExtension();
202 CString com = regCom;
203 bool bInternal = false;
205 CString mimetype;
206 if (ext != "")
208 // is there an extension specific merge tool?
209 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext.MakeLower());
210 if (CString(mergetool) != "")
212 com = mergetool;
215 if (GetMimeType(yourfile, mimetype) || GetMimeType(theirfile, mimetype) || GetMimeType(basefile, mimetype))
217 // is there a mime type specific merge tool?
218 CRegString mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + mimetype);
219 if (CString(mergetool) != "")
221 com = mergetool;
225 if (com.IsEmpty()||(com.Left(1).Compare(_T("#"))==0))
227 // use TortoiseMerge
228 bInternal = true;
229 CRegString tortoiseMergePath(_T("Software\\TortoiseGit\\TMergePath"), _T(""), false, HKEY_LOCAL_MACHINE);
230 com = tortoiseMergePath;
231 if (com.IsEmpty())
233 com = CPathUtils::GetAppDirectory();
234 com += _T("TortoiseMerge.exe");
236 com = _T("\"") + com + _T("\"");
237 com = com + _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
238 com = com + _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
240 // check if the params are set. If not, just add the files to the command line
241 if ((com.Find(_T("%merged"))<0)&&(com.Find(_T("%base"))<0)&&(com.Find(_T("%theirs"))<0)&&(com.Find(_T("%mine"))<0))
243 com += _T(" \"")+basefile.GetWinPathString()+_T("\"");
244 com += _T(" \"")+theirfile.GetWinPathString()+_T("\"");
245 com += _T(" \"")+yourfile.GetWinPathString()+_T("\"");
246 com += _T(" \"")+mergedfile.GetWinPathString()+_T("\"");
248 if (basefile.IsEmpty())
250 com.Replace(_T("/base:%base"), _T(""));
251 com.Replace(_T("%base"), _T(""));
253 else
254 com.Replace(_T("%base"), _T("\"") + basefile.GetWinPathString() + _T("\""));
255 if (theirfile.IsEmpty())
257 com.Replace(_T("/theirs:%theirs"), _T(""));
258 com.Replace(_T("%theirs"), _T(""));
260 else
261 com.Replace(_T("%theirs"), _T("\"") + theirfile.GetWinPathString() + _T("\""));
262 if (yourfile.IsEmpty())
264 com.Replace(_T("/mine:%mine"), _T(""));
265 com.Replace(_T("%mine"), _T(""));
267 else
268 com.Replace(_T("%mine"), _T("\"") + yourfile.GetWinPathString() + _T("\""));
269 if (mergedfile.IsEmpty())
271 com.Replace(_T("/merged:%merged"), _T(""));
272 com.Replace(_T("%merged"), _T(""));
274 else
275 com.Replace(_T("%merged"), _T("\"") + mergedfile.GetWinPathString() + _T("\""));
276 if (basename.IsEmpty())
278 if (basefile.IsEmpty())
280 com.Replace(_T("/basename:%bname"), _T(""));
281 com.Replace(_T("%bname"), _T(""));
283 else
285 com.Replace(_T("%bname"), _T("\"") + basefile.GetUIFileOrDirectoryName() + _T("\""));
288 else
289 com.Replace(_T("%bname"), _T("\"") + basename + _T("\""));
290 if (theirname.IsEmpty())
292 if (theirfile.IsEmpty())
294 com.Replace(_T("/theirsname:%tname"), _T(""));
295 com.Replace(_T("%tname"), _T(""));
297 else
299 com.Replace(_T("%tname"), _T("\"") + theirfile.GetUIFileOrDirectoryName() + _T("\""));
302 else
303 com.Replace(_T("%tname"), _T("\"") + theirname + _T("\""));
304 if (yourname.IsEmpty())
306 if (yourfile.IsEmpty())
308 com.Replace(_T("/minename:%yname"), _T(""));
309 com.Replace(_T("%yname"), _T(""));
311 else
313 com.Replace(_T("%yname"), _T("\"") + yourfile.GetUIFileOrDirectoryName() + _T("\""));
316 else
317 com.Replace(_T("%yname"), _T("\"") + yourname + _T("\""));
318 if (mergedname.IsEmpty())
320 if (mergedfile.IsEmpty())
322 com.Replace(_T("/mergedname:%mname"), _T(""));
323 com.Replace(_T("%mname"), _T(""));
325 else
327 com.Replace(_T("%mname"), _T("\"") + mergedfile.GetUIFileOrDirectoryName() + _T("\""));
330 else
331 com.Replace(_T("%mname"), _T("\"") + mergedname + _T("\""));
333 if ((bReadOnly)&&(bInternal))
334 com += _T(" /readonly");
336 if(!LaunchApplication(com, IDS_ERR_EXTMERGESTART, false))
338 return FALSE;
341 return TRUE;
344 BOOL CAppUtils::StartExtPatch(const CTGitPath& patchfile, const CTGitPath& dir, const CString& sOriginalDescription, const CString& sPatchedDescription, BOOL bReversed, BOOL bWait)
346 CString viewer;
347 // use TortoiseMerge
348 viewer = CPathUtils::GetAppDirectory();
349 viewer += _T("TortoiseMerge.exe");
351 viewer = _T("\"") + viewer + _T("\"");
352 viewer = viewer + _T(" /diff:\"") + patchfile.GetWinPathString() + _T("\"");
353 viewer = viewer + _T(" /patchpath:\"") + dir.GetWinPathString() + _T("\"");
354 if (bReversed)
355 viewer += _T(" /reversedpatch");
356 if (!sOriginalDescription.IsEmpty())
357 viewer = viewer + _T(" /patchoriginal:\"") + sOriginalDescription + _T("\"");
358 if (!sPatchedDescription.IsEmpty())
359 viewer = viewer + _T(" /patchpatched:\"") + sPatchedDescription + _T("\"");
360 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
362 return FALSE;
364 return TRUE;
367 CString CAppUtils::PickDiffTool(const CTGitPath& file1, const CTGitPath& file2)
369 // Is there a mime type specific diff tool?
370 CString mimetype;
371 if (GetMimeType(file1, mimetype) || GetMimeType(file2, mimetype))
373 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + mimetype);
374 if (!difftool.IsEmpty())
375 return difftool;
378 // Is there an extension specific diff tool?
379 CString ext = file2.GetFileExtension().MakeLower();
380 if (!ext.IsEmpty())
382 CString difftool = CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext);
383 if (!difftool.IsEmpty())
384 return difftool;
385 // Maybe we should use TortoiseIDiff?
386 if ((ext == _T(".jpg")) || (ext == _T(".jpeg")) ||
387 (ext == _T(".bmp")) || (ext == _T(".gif")) ||
388 (ext == _T(".png")) || (ext == _T(".ico")) ||
389 (ext == _T(".dib")) || (ext == _T(".emf")))
391 return
392 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseIDiff.exe") + _T("\"") +
393 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname");
397 // Finally, pick a generic external diff tool
398 CString difftool = CRegString(_T("Software\\TortoiseGit\\Diff"));
399 return difftool;
402 bool CAppUtils::StartExtDiff(
403 const CString& file1, const CString& file2,
404 const CString& sName1, const CString& sName2,
405 const DiffFlags& flags)
407 CString viewer;
409 CRegDWORD blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE);
410 if (!flags.bBlame || !(DWORD)blamediff)
412 viewer = PickDiffTool(file1, file2);
413 // If registry entry for a diff program is commented out, use TortoiseMerge.
414 bool bCommentedOut = viewer.Left(1) == _T("#");
415 if (flags.bAlternativeTool)
417 // Invert external vs. internal diff tool selection.
418 if (bCommentedOut)
419 viewer.Delete(0); // uncomment
420 else
421 viewer = "";
423 else if (bCommentedOut)
424 viewer = "";
427 bool bInternal = viewer.IsEmpty();
428 if (bInternal)
430 viewer =
431 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseMerge.exe") + _T("\"") +
432 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
433 if (flags.bBlame)
434 viewer += _T(" /blame");
436 // check if the params are set. If not, just add the files to the command line
437 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
439 viewer += _T(" \"")+file1+_T("\"");
440 viewer += _T(" \"")+file2+_T("\"");
442 if (viewer.Find(_T("%base")) >= 0)
444 viewer.Replace(_T("%base"), _T("\"")+file1+_T("\""));
446 if (viewer.Find(_T("%mine")) >= 0)
448 viewer.Replace(_T("%mine"), _T("\"")+file2+_T("\""));
451 if (sName1.IsEmpty())
452 viewer.Replace(_T("%bname"), _T("\"") + file1 + _T("\""));
453 else
454 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
456 if (sName2.IsEmpty())
457 viewer.Replace(_T("%yname"), _T("\"") + file2 + _T("\""));
458 else
459 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
461 if (flags.bReadOnly && bInternal)
462 viewer += _T(" /readonly");
464 return LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, flags.bWait);
467 BOOL CAppUtils::StartExtDiffProps(const CTGitPath& file1, const CTGitPath& file2, const CString& sName1, const CString& sName2, BOOL bWait, BOOL bReadOnly)
469 CRegString diffpropsexe(_T("Software\\TortoiseGit\\DiffProps"));
470 CString viewer = diffpropsexe;
471 bool bInternal = false;
472 if (viewer.IsEmpty()||(viewer.Left(1).Compare(_T("#"))==0))
474 //no registry entry (or commented out) for a diff program
475 //use TortoiseMerge
476 bInternal = true;
477 viewer = CPathUtils::GetAppDirectory();
478 viewer += _T("TortoiseMerge.exe");
479 viewer = _T("\"") + viewer + _T("\"");
480 viewer = viewer + _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname");
482 // check if the params are set. If not, just add the files to the command line
483 if ((viewer.Find(_T("%base"))<0)&&(viewer.Find(_T("%mine"))<0))
485 viewer += _T(" \"")+file1.GetWinPathString()+_T("\"");
486 viewer += _T(" \"")+file2.GetWinPathString()+_T("\"");
488 if (viewer.Find(_T("%base")) >= 0)
490 viewer.Replace(_T("%base"), _T("\"")+file1.GetWinPathString()+_T("\""));
492 if (viewer.Find(_T("%mine")) >= 0)
494 viewer.Replace(_T("%mine"), _T("\"")+file2.GetWinPathString()+_T("\""));
497 if (sName1.IsEmpty())
498 viewer.Replace(_T("%bname"), _T("\"") + file1.GetUIFileOrDirectoryName() + _T("\""));
499 else
500 viewer.Replace(_T("%bname"), _T("\"") + sName1 + _T("\""));
502 if (sName2.IsEmpty())
503 viewer.Replace(_T("%yname"), _T("\"") + file2.GetUIFileOrDirectoryName() + _T("\""));
504 else
505 viewer.Replace(_T("%yname"), _T("\"") + sName2 + _T("\""));
507 if ((bReadOnly)&&(bInternal))
508 viewer += _T(" /readonly");
510 if(!LaunchApplication(viewer, IDS_ERR_EXTDIFFSTART, !!bWait))
512 return FALSE;
514 return TRUE;
517 BOOL CAppUtils::StartUnifiedDiffViewer(const CString& patchfile, const CString& title, BOOL bWait)
519 CString viewer;
520 CRegString v = CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
521 viewer = v;
522 if (viewer.IsEmpty() || (viewer.Left(1).Compare(_T("#"))==0))
524 // use TortoiseUDiff
525 viewer = CPathUtils::GetAppDirectory();
526 viewer += _T("TortoiseUDiff.exe");
527 // enquote the path to TortoiseUDiff
528 viewer = _T("\"") + viewer + _T("\"");
529 // add the params
530 viewer = viewer + _T(" /patchfile:%1 /title:\"%title\"");
533 if (viewer.Find(_T("%1"))>=0)
535 if (viewer.Find(_T("\"%1\"")) >= 0)
536 viewer.Replace(_T("%1"), patchfile);
537 else
538 viewer.Replace(_T("%1"), _T("\"") + patchfile + _T("\""));
540 else
541 viewer += _T(" \"") + patchfile + _T("\"");
542 if (viewer.Find(_T("%title")) >= 0)
544 viewer.Replace(_T("%title"), title);
547 if(!LaunchApplication(viewer, IDS_ERR_DIFFVIEWSTART, !!bWait))
549 return FALSE;
551 return TRUE;
554 BOOL CAppUtils::StartTextViewer(CString file)
556 CString viewer;
557 CRegString txt = CRegString(_T(".txt\\"), _T(""), FALSE, HKEY_CLASSES_ROOT);
558 viewer = txt;
559 viewer = viewer + _T("\\Shell\\Open\\Command\\");
560 CRegString txtexe = CRegString(viewer, _T(""), FALSE, HKEY_CLASSES_ROOT);
561 viewer = txtexe;
563 DWORD len = ExpandEnvironmentStrings(viewer, NULL, 0);
564 TCHAR * buf = new TCHAR[len+1];
565 ExpandEnvironmentStrings(viewer, buf, len);
566 viewer = buf;
567 delete [] buf;
568 len = ExpandEnvironmentStrings(file, NULL, 0);
569 buf = new TCHAR[len+1];
570 ExpandEnvironmentStrings(file, buf, len);
571 file = buf;
572 delete [] buf;
573 file = _T("\"")+file+_T("\"");
574 if (viewer.IsEmpty())
576 OPENFILENAME ofn = {0}; // common dialog box structure
577 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
578 // Initialize OPENFILENAME
579 ofn.lStructSize = sizeof(OPENFILENAME);
580 ofn.hwndOwner = NULL;
581 ofn.lpstrFile = szFile;
582 ofn.nMaxFile = _countof(szFile);
583 CString sFilter;
584 sFilter.LoadString(IDS_PROGRAMSFILEFILTER);
585 TCHAR * pszFilters = new TCHAR[sFilter.GetLength()+4];
586 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
587 // Replace '|' delimiters with '\0's
588 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
589 while (ptr != pszFilters)
591 if (*ptr == '|')
592 *ptr = '\0';
593 ptr--;
595 ofn.lpstrFilter = pszFilters;
596 ofn.nFilterIndex = 1;
597 ofn.lpstrFileTitle = NULL;
598 ofn.nMaxFileTitle = 0;
599 ofn.lpstrInitialDir = NULL;
600 CString temp;
601 temp.LoadString(IDS_UTILS_SELECTTEXTVIEWER);
602 CStringUtils::RemoveAccelerators(temp);
603 ofn.lpstrTitle = temp;
604 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY;
606 // Display the Open dialog box.
608 if (GetOpenFileName(&ofn)==TRUE)
610 delete [] pszFilters;
611 viewer = CString(ofn.lpstrFile);
613 else
615 delete [] pszFilters;
616 return FALSE;
619 if (viewer.Find(_T("\"%1\"")) >= 0)
621 viewer.Replace(_T("\"%1\""), file);
623 else if (viewer.Find(_T("%1")) >= 0)
625 viewer.Replace(_T("%1"), file);
627 else
629 viewer += _T(" ");
630 viewer += file;
633 if(!LaunchApplication(viewer, IDS_ERR_TEXTVIEWSTART, false))
635 return FALSE;
637 return TRUE;
640 BOOL CAppUtils::CheckForEmptyDiff(const CTGitPath& sDiffPath)
642 DWORD length = 0;
643 HANDLE hFile = ::CreateFile(sDiffPath.GetWinPath(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, NULL, NULL);
644 if (hFile == INVALID_HANDLE_VALUE)
645 return TRUE;
646 length = ::GetFileSize(hFile, NULL);
647 ::CloseHandle(hFile);
648 if (length < 4)
649 return TRUE;
650 return FALSE;
654 void CAppUtils::CreateFontForLogs(CFont& fontToCreate)
656 LOGFONT logFont;
657 HDC hScreenDC = ::GetDC(NULL);
658 logFont.lfHeight = -MulDiv((DWORD)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC, LOGPIXELSY), 72);
659 ::ReleaseDC(NULL, hScreenDC);
660 logFont.lfWidth = 0;
661 logFont.lfEscapement = 0;
662 logFont.lfOrientation = 0;
663 logFont.lfWeight = FW_NORMAL;
664 logFont.lfItalic = 0;
665 logFont.lfUnderline = 0;
666 logFont.lfStrikeOut = 0;
667 logFont.lfCharSet = DEFAULT_CHARSET;
668 logFont.lfOutPrecision = OUT_DEFAULT_PRECIS;
669 logFont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
670 logFont.lfQuality = DRAFT_QUALITY;
671 logFont.lfPitchAndFamily = FF_DONTCARE | FIXED_PITCH;
672 _tcscpy_s(logFont.lfFaceName, 32, (LPCTSTR)(CString)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
673 VERIFY(fontToCreate.CreateFontIndirect(&logFont));
676 bool CAppUtils::LaunchApplication(const CString& sCommandLine, UINT idErrMessageFormat, bool bWaitForStartup)
678 STARTUPINFO startup;
679 PROCESS_INFORMATION process;
680 memset(&startup, 0, sizeof(startup));
681 startup.cb = sizeof(startup);
682 memset(&process, 0, sizeof(process));
684 CString cleanCommandLine(sCommandLine);
686 if (CreateProcess(NULL, const_cast<TCHAR*>((LPCTSTR)cleanCommandLine), NULL, NULL, FALSE, 0, 0, g_Git.m_CurrentDir, &startup, &process)==0)
688 if(idErrMessageFormat != 0)
690 LPVOID lpMsgBuf;
691 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
692 FORMAT_MESSAGE_FROM_SYSTEM |
693 FORMAT_MESSAGE_IGNORE_INSERTS,
694 NULL,
695 GetLastError(),
696 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
697 (LPTSTR) &lpMsgBuf,
699 NULL
701 CString temp;
702 temp.Format(idErrMessageFormat, lpMsgBuf);
703 CMessageBox::Show(NULL, temp, _T("TortoiseGit"), MB_OK | MB_ICONINFORMATION);
704 LocalFree( lpMsgBuf );
706 return false;
709 if (bWaitForStartup)
711 WaitForInputIdle(process.hProcess, 10000);
714 CloseHandle(process.hThread);
715 CloseHandle(process.hProcess);
716 return true;
718 bool CAppUtils::LaunchPAgent(CString *keyfile,CString * pRemote)
720 CString key,remote;
721 CString cmd,out;
722 if( pRemote == NULL)
724 remote=_T("origin");
726 else
728 remote=*pRemote;
730 if(keyfile == NULL)
732 cmd.Format(_T("remote.%s.puttykeyfile"),remote);
733 key = g_Git.GetConfigValue(cmd);
734 int start=0;
735 key = key.Tokenize(_T("\n"),start);
737 else
738 key=*keyfile;
740 if(key.IsEmpty())
741 return false;
743 CString proc=CPathUtils::GetAppDirectory();
744 proc += _T("pageant.exe \"");
745 proc += key;
746 proc += _T("\"");
748 CString tempfile = GetTempFile();
749 ::DeleteFile(tempfile);
751 proc += _T(" -c \"");
752 proc += CPathUtils::GetAppDirectory();
753 proc += _T("touch.exe\"");
754 proc += _T(" \"");
755 proc += tempfile;
756 proc += _T("\"");
758 bool b = LaunchApplication(proc, IDS_ERR_PAGEANT, true);
759 if(!b)
760 return b;
762 int i=0;
763 while(!::PathFileExists(tempfile))
765 Sleep(100);
766 i++;
767 if(i>10*60*5)
768 break; //timeout 5 minutes
771 if( i== 10*60*5)
773 CMessageBox::Show(NULL, _T("Fail wait for pageant finish load key"),_T("TortoiseGit"),MB_OK|MB_ICONERROR);
775 ::DeleteFile(tempfile);
776 return true;
778 bool CAppUtils::LaunchAlternativeEditor(const CString& filename)
780 CString editTool = CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
781 if (editTool.IsEmpty() || (editTool.Left(1).Compare(_T("#"))==0)) {
782 editTool = CPathUtils::GetAppDirectory() + _T("notepad2.exe");
785 CString sCmd;
786 sCmd.Format(_T("\"%s\" \"%s\""), editTool, filename);
788 LaunchApplication(sCmd, NULL, false);
789 return true;
791 bool CAppUtils::LaunchRemoteSetting()
793 CTGitPath path(g_Git.m_CurrentDir);
794 CSettings dlg(IDS_PROC_SETTINGS_TITLE, &path);
795 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
796 //dlg.SetTreeWidth(220);
797 dlg.m_DefaultPage = _T("gitremote");
799 dlg.DoModal();
800 dlg.HandleRestart();
801 return true;
804 * Launch the external blame viewer
806 bool CAppUtils::LaunchTortoiseBlame(const CString& sBlameFile,CString Rev,const CString& sParams)
808 CString viewer = _T("\"") + CPathUtils::GetAppDirectory();
809 viewer += _T("TortoiseGitBlame.exe");
810 viewer += _T("\" \"") + sBlameFile + _T("\"");
811 //viewer += _T(" \"") + sLogFile + _T("\"");
812 //viewer += _T(" \"") + sOriginalFile + _T("\"");
813 if(!Rev.IsEmpty() && Rev != GIT_REV_ZERO)
814 viewer += CString(_T(" /rev:"))+Rev;
815 viewer += _T(" ")+sParams;
817 return LaunchApplication(viewer, IDS_ERR_TGITBLAME, false);
820 bool CAppUtils::FormatTextInRichEditControl(CWnd * pWnd)
822 CString sText;
823 if (pWnd == NULL)
824 return false;
825 bool bStyled = false;
826 pWnd->GetWindowText(sText);
827 // the rich edit control doesn't count the CR char!
828 // to be exact: CRLF is treated as one char.
829 sText.Remove('\r');
831 // style each line separately
832 int offset = 0;
833 int nNewlinePos;
836 nNewlinePos = sText.Find('\n', offset);
837 CString sLine = sText.Mid(offset);
838 if (nNewlinePos>=0)
839 sLine = sLine.Left(nNewlinePos-offset);
840 int start = 0;
841 int end = 0;
842 while (FindStyleChars(sLine, '*', start, end))
844 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
845 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
846 CHARFORMAT2 format;
847 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
848 format.cbSize = sizeof(CHARFORMAT2);
849 format.dwMask = CFM_BOLD;
850 format.dwEffects = CFE_BOLD;
851 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
852 bStyled = true;
853 start = end;
855 start = 0;
856 end = 0;
857 while (FindStyleChars(sLine, '^', start, end))
859 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
860 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
861 CHARFORMAT2 format;
862 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
863 format.cbSize = sizeof(CHARFORMAT2);
864 format.dwMask = CFM_ITALIC;
865 format.dwEffects = CFE_ITALIC;
866 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
867 bStyled = true;
868 start = end;
870 start = 0;
871 end = 0;
872 while (FindStyleChars(sLine, '_', start, end))
874 CHARRANGE range = {(LONG)start+offset, (LONG)end+offset};
875 pWnd->SendMessage(EM_EXSETSEL, NULL, (LPARAM)&range);
876 CHARFORMAT2 format;
877 SecureZeroMemory(&format, sizeof(CHARFORMAT2));
878 format.cbSize = sizeof(CHARFORMAT2);
879 format.dwMask = CFM_UNDERLINE;
880 format.dwEffects = CFE_UNDERLINE;
881 pWnd->SendMessage(EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM)&format);
882 bStyled = true;
883 start = end;
885 offset = nNewlinePos+1;
886 } while(nNewlinePos>=0);
887 return bStyled;
890 bool CAppUtils::FindStyleChars(const CString& sText, TCHAR stylechar, int& start, int& end)
892 int i=start;
893 bool bFoundMarker = false;
894 // find a starting marker
895 while (sText[i] != 0)
897 if (sText[i] == stylechar)
899 if (((i+1)<sText.GetLength())&&(IsCharAlphaNumeric(sText[i+1])) &&
900 (((i>0)&&(!IsCharAlphaNumeric(sText[i-1])))||(i==0)))
902 start = i+1;
903 i++;
904 bFoundMarker = true;
905 break;
908 i++;
910 if (!bFoundMarker)
911 return false;
912 // find ending marker
913 bFoundMarker = false;
914 while (sText[i] != 0)
916 if (sText[i] == stylechar)
918 if ((IsCharAlphaNumeric(sText[i-1])) &&
919 ((((i+1)<sText.GetLength())&&(!IsCharAlphaNumeric(sText[i+1])))||(i+1)==sText.GetLength()))
921 end = i;
922 i++;
923 bFoundMarker = true;
924 break;
927 i++;
929 return bFoundMarker;
932 bool CAppUtils::FileOpenSave(CString& path, int * filterindex, UINT title, UINT filter, bool bOpen, HWND hwndOwner)
934 OPENFILENAME ofn = {0}; // common dialog box structure
935 TCHAR szFile[MAX_PATH] = {0}; // buffer for file name. Explorer can't handle paths longer than MAX_PATH.
936 ofn.lStructSize = sizeof(OPENFILENAME);
937 ofn.hwndOwner = hwndOwner;
938 _tcscpy_s(szFile, MAX_PATH, (LPCTSTR)path);
939 ofn.lpstrFile = szFile;
940 ofn.nMaxFile = _countof(szFile);
941 CString sFilter;
942 TCHAR * pszFilters = NULL;
943 if (filter)
945 sFilter.LoadString(filter);
946 pszFilters = new TCHAR[sFilter.GetLength()+4];
947 _tcscpy_s (pszFilters, sFilter.GetLength()+4, sFilter);
948 // Replace '|' delimiters with '\0's
949 TCHAR *ptr = pszFilters + _tcslen(pszFilters); //set ptr at the NULL
950 while (ptr != pszFilters)
952 if (*ptr == '|')
953 *ptr = '\0';
954 ptr--;
956 ofn.lpstrFilter = pszFilters;
958 ofn.nFilterIndex = 1;
959 ofn.lpstrFileTitle = NULL;
960 ofn.nMaxFileTitle = 0;
961 ofn.lpstrInitialDir = NULL;
962 CString temp;
963 if (title)
965 temp.LoadString(title);
966 CStringUtils::RemoveAccelerators(temp);
968 ofn.lpstrTitle = temp;
969 if (bOpen)
970 ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY | OFN_EXPLORER;
971 else
972 ofn.Flags = OFN_OVERWRITEPROMPT | OFN_EXPLORER;
975 // Display the Open dialog box.
976 bool bRet = false;
977 if (bOpen)
979 bRet = !!GetOpenFileName(&ofn);
981 else
983 bRet = !!GetSaveFileName(&ofn);
985 if (bRet)
987 if (pszFilters)
988 delete [] pszFilters;
989 path = CString(ofn.lpstrFile);
990 if (filterindex)
991 *filterindex = ofn.nFilterIndex;
992 return true;
994 if (pszFilters)
995 delete [] pszFilters;
996 return false;
999 bool CAppUtils::SetListCtrlBackgroundImage(HWND hListCtrl, UINT nID, int width /* = 128 */, int height /* = 128 */)
1001 ListView_SetTextBkColor(hListCtrl, CLR_NONE);
1002 COLORREF bkColor = ListView_GetBkColor(hListCtrl);
1003 // create a bitmap from the icon
1004 HICON hIcon = (HICON)LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(nID), IMAGE_ICON, width, height, LR_DEFAULTCOLOR);
1005 if (!hIcon)
1006 return false;
1008 RECT rect = {0};
1009 rect.right = width;
1010 rect.bottom = height;
1011 HBITMAP bmp = NULL;
1013 HWND desktop = ::GetDesktopWindow();
1014 if (desktop)
1016 HDC screen_dev = ::GetDC(desktop);
1017 if (screen_dev)
1019 // Create a compatible DC
1020 HDC dst_hdc = ::CreateCompatibleDC(screen_dev);
1021 if (dst_hdc)
1023 // Create a new bitmap of icon size
1024 bmp = ::CreateCompatibleBitmap(screen_dev, rect.right, rect.bottom);
1025 if (bmp)
1027 // Select it into the compatible DC
1028 HBITMAP old_dst_bmp = (HBITMAP)::SelectObject(dst_hdc, bmp);
1029 // Fill the background of the compatible DC with the given color
1030 ::SetBkColor(dst_hdc, bkColor);
1031 ::ExtTextOut(dst_hdc, 0, 0, ETO_OPAQUE, &rect, NULL, 0, NULL);
1033 // Draw the icon into the compatible DC
1034 ::DrawIconEx(dst_hdc, 0, 0, hIcon, rect.right, rect.bottom, 0, NULL, DI_NORMAL);
1035 ::SelectObject(dst_hdc, old_dst_bmp);
1037 ::DeleteDC(dst_hdc);
1040 ::ReleaseDC(desktop, screen_dev);
1043 // Restore settings
1044 DestroyIcon(hIcon);
1046 if (bmp == NULL)
1047 return false;
1049 LVBKIMAGE lv;
1050 lv.ulFlags = LVBKIF_TYPE_WATERMARK;
1051 lv.hbm = bmp;
1052 lv.xOffsetPercent = 100;
1053 lv.yOffsetPercent = 100;
1054 ListView_SetBkImage(hListCtrl, &lv);
1055 return true;
1058 CString CAppUtils::GetProjectNameFromURL(CString url)
1060 CString name;
1061 while (name.IsEmpty() || (name.CompareNoCase(_T("branches"))==0) ||
1062 (name.CompareNoCase(_T("tags"))==0) ||
1063 (name.CompareNoCase(_T("trunk"))==0))
1065 name = url.Mid(url.ReverseFind('/')+1);
1066 url = url.Left(url.ReverseFind('/'));
1068 if ((name.Compare(_T("svn")) == 0)||(name.Compare(_T("svnroot")) == 0))
1070 // a name of svn or svnroot indicates that it's not really the project name. In that
1071 // case, we try the first part of the URL
1072 // of course, this won't work in all cases (but it works for Google project hosting)
1073 url.Replace(_T("http://"), _T(""));
1074 url.Replace(_T("https://"), _T(""));
1075 url.Replace(_T("svn://"), _T(""));
1076 url.Replace(_T("svn+ssh://"), _T(""));
1077 url.TrimLeft(_T("/"));
1078 name = url.Left(url.Find('.'));
1080 return name;
1083 bool CAppUtils::StartShowUnifiedDiff(HWND /*hWnd*/, const CTGitPath& url1, const git_revnum_t& rev1,
1084 const CTGitPath& /*url2*/, const git_revnum_t& rev2,
1085 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
1086 bool /*bAlternateDiff*/ /* = false */, bool /*bIgnoreAncestry*/ /* = false */, bool /* blame = false */, bool bMerge)
1089 CString tempfile=GetTempFile();
1090 CString cmd;
1091 if(rev1 == GitRev::GetWorkingCopy())
1093 cmd.Format(_T("git.exe diff --stat -p %s "),rev2);
1095 else
1097 CString merge;
1098 if(bMerge)
1099 merge = _T("-c");
1101 cmd.Format(_T("git.exe diff-tree -r -p %s --stat %s %s"),merge, rev1,rev2);
1104 if( !url1.IsEmpty() )
1106 cmd += _T(" \"");
1107 cmd += url1.GetGitPathString();
1108 cmd += _T("\" ");
1110 g_Git.RunLogFile(cmd,tempfile);
1111 CAppUtils::StartUnifiedDiffViewer(tempfile,rev1.Left(6)+_T(":")+rev2.Left(6));
1114 #if 0
1115 CString sCmd;
1116 sCmd.Format(_T("%s /command:showcompare /unified"),
1117 (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")));
1118 sCmd += _T(" /url1:\"") + url1.GetGitPathString() + _T("\"");
1119 if (rev1.IsValid())
1120 sCmd += _T(" /revision1:") + rev1.ToString();
1121 sCmd += _T(" /url2:\"") + url2.GetGitPathString() + _T("\"");
1122 if (rev2.IsValid())
1123 sCmd += _T(" /revision2:") + rev2.ToString();
1124 if (peg.IsValid())
1125 sCmd += _T(" /pegrevision:") + peg.ToString();
1126 if (headpeg.IsValid())
1127 sCmd += _T(" /headpegrevision:") + headpeg.ToString();
1129 if (bAlternateDiff)
1130 sCmd += _T(" /alternatediff");
1132 if (bIgnoreAncestry)
1133 sCmd += _T(" /ignoreancestry");
1135 if (hWnd)
1137 sCmd += _T(" /hwnd:");
1138 TCHAR buf[30];
1139 _stprintf_s(buf, 30, _T("%d"), hWnd);
1140 sCmd += buf;
1143 return CAppUtils::LaunchApplication(sCmd, NULL, false);
1144 #endif
1145 return TRUE;
1149 bool CAppUtils::Export(CString *BashHash)
1151 bool bRet = false;
1153 // ask from where the export has to be done
1154 CExportDlg dlg;
1155 if(BashHash)
1156 dlg.m_Revision=*BashHash;
1158 if (dlg.DoModal() == IDOK)
1160 CString cmd;
1161 cmd.Format(_T("git.exe archive --format=zip --verbose %s"),
1162 g_Git.FixBranchName(dlg.m_VersionName));
1164 //g_Git.RunLogFile(cmd,dlg.m_strExportDirectory);
1165 CProgressDlg pro;
1166 pro.m_GitCmd=cmd;
1167 pro.m_LogFile=dlg.m_strExportDirectory;
1168 pro.DoModal();
1169 return TRUE;
1171 return bRet;
1174 bool CAppUtils::CreateBranchTag(bool IsTag,CString *CommitHash, bool switch_new_brach)
1176 CCreateBranchTagDlg dlg;
1177 dlg.m_bIsTag=IsTag;
1178 dlg.m_bSwitch=switch_new_brach;
1180 if(CommitHash)
1181 dlg.m_Base = *CommitHash;
1183 if(dlg.DoModal()==IDOK)
1185 CString cmd;
1186 CString force;
1187 CString track;
1188 if(dlg.m_bTrack)
1189 track=_T(" --track ");
1191 if(dlg.m_bForce)
1192 force=_T(" -f ");
1194 if(IsTag)
1196 CString sign;
1197 if(dlg.m_bSign)
1198 sign=_T("-s");
1200 cmd.Format(_T("git.exe tag %s %s %s %s %s"),
1201 track,
1202 force,
1203 sign,
1204 dlg.m_BranchTagName,
1205 g_Git.FixBranchName(dlg.m_VersionName)
1208 CString tempfile=::GetTempFile();
1209 if(!dlg.m_Message.Trim().IsEmpty())
1211 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_Message);
1212 cmd += _T(" -F ")+tempfile;
1215 else
1217 cmd.Format(_T("git.exe branch %s %s %s %s"),
1218 track,
1219 force,
1220 dlg.m_BranchTagName,
1221 g_Git.FixBranchName(dlg.m_VersionName)
1224 CString out;
1225 if(g_Git.Run(cmd,&out,CP_UTF8))
1227 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1229 if( !IsTag && dlg.m_bSwitch )
1231 // it is a new branch and the user has requested to switch to it
1232 cmd.Format(_T("git.exe checkout %s"), dlg.m_BranchTagName);
1233 g_Git.Run(cmd,&out,CP_UTF8);
1234 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1237 return TRUE;
1239 return FALSE;
1242 bool CAppUtils::Switch(CString *CommitHash, CString initialRefName, bool autoclose)
1244 CGitSwitchDlg dlg;
1245 if(CommitHash)
1246 dlg.m_Base=*CommitHash;
1247 if(!initialRefName.IsEmpty())
1248 dlg.m_initialRefName = initialRefName;
1250 if (dlg.DoModal() == IDOK)
1252 CString branch;
1253 if (dlg.m_bBranch)
1254 branch = dlg.m_NewBranch;
1256 return PerformSwitch(dlg.m_VersionName, dlg.m_bForce == TRUE , branch, dlg.m_bBranchOverride == TRUE, dlg.m_bTrack == TRUE, autoclose);
1258 return FALSE;
1261 bool CAppUtils::PerformSwitch(CString ref, bool bForce /* false */, CString sNewBranch /* CString() */, bool bBranchOverride /* false */, bool bTrack /* false */, bool autoClose /* false */)
1263 CString cmd;
1264 CString track;
1265 CString force;
1266 CString branch;
1268 if(!sNewBranch.IsEmpty()){
1269 if (bBranchOverride)
1271 branch.Format(_T("-B %s"), sNewBranch);
1273 else
1275 branch.Format(_T("-b %s"), sNewBranch);
1277 if (bTrack)
1278 track = _T("--track");
1280 if (bForce)
1281 force = _T("-f");
1283 cmd.Format(_T("git.exe checkout %s %s %s %s"),
1284 force,
1285 track,
1286 branch,
1287 g_Git.FixBranchName(ref));
1289 CProgressDlg progress;
1290 progress.m_bAutoCloseOnSuccess = autoClose;
1291 progress.m_GitCmd = cmd;
1293 CTGitPath gitPath = g_Git.m_CurrentDir;
1294 if (gitPath.HasSubmodules())
1295 progress.m_PostCmdList.Add(_T("Update Submodules"));
1297 int ret = progress.DoModal();
1298 if (gitPath.HasSubmodules() && ret == IDC_PROGRESS_BUTTON1)
1300 CString sCmd;
1301 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1303 LaunchApplication(sCmd, NULL, false);
1304 return TRUE;
1306 else if (ret == IDOK)
1307 return TRUE;
1309 return FALSE;
1312 bool CAppUtils::IgnoreFile(CTGitPathList &path,bool IsMask)
1314 CString ignorefile;
1315 ignorefile=g_Git.m_CurrentDir+_T("\\");
1317 if(IsMask)
1319 ignorefile+=path.GetCommonRoot().GetDirectory().GetWinPathString()+_T("\\.gitignore");
1322 else
1324 ignorefile += _T("\\.gitignore");
1327 CStdioFile file;
1328 if(!file.Open(ignorefile,CFile::modeCreate|CFile::modeReadWrite|CFile::modeNoTruncate))
1330 CMessageBox::Show(NULL,ignorefile+_T(" Open Failure"),_T("TortoiseGit"),MB_OK);
1331 return FALSE;
1334 CString ignorelist;
1335 CString mask;
1338 //file.ReadString(ignorelist);
1339 file.SeekToEnd();
1340 for(int i=0;i<path.GetCount();i++)
1342 if(IsMask)
1344 mask=_T("*")+path[i].GetFileExtension();
1345 if(ignorelist.Find(mask)<0)
1346 ignorelist += _T("\n")+mask;
1348 else
1350 ignorelist += _T("\n/")+path[i].GetGitPathString();
1353 file.WriteString(ignorelist);
1355 file.Close();
1357 }catch(...)
1359 file.Close();
1360 return FALSE;
1363 return TRUE;
1367 bool CAppUtils::GitReset(CString *CommitHash,int type)
1369 CResetDlg dlg;
1370 dlg.m_ResetType=type;
1371 dlg.m_ResetToVersion=*CommitHash;
1372 if (dlg.DoModal() == IDOK)
1374 CString cmd;
1375 CString type;
1376 switch(dlg.m_ResetType)
1378 case 0:
1379 type=_T("--soft");
1380 break;
1381 case 1:
1382 type=_T("--mixed");
1383 break;
1384 case 2:
1385 type=_T("--hard");
1386 break;
1387 default:
1388 type=_T("--mixed");
1389 break;
1391 cmd.Format(_T("git.exe reset %s %s"),type, *CommitHash);
1393 CProgressDlg progress;
1394 progress.m_GitCmd=cmd;
1396 CTGitPath gitPath = g_Git.m_CurrentDir;
1397 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2)
1398 progress.m_PostCmdList.Add(_T("Update Submodules"));
1400 int ret = progress.DoModal();
1401 if (gitPath.HasSubmodules() && dlg.m_ResetType == 2 && ret == IDC_PROGRESS_BUTTON1)
1403 CString sCmd;
1404 sCmd.Format(_T("\"%s\" /command:subupdate /bkpath:\"%s\""), (LPCTSTR)(CPathUtils::GetAppDirectory()+_T("TortoiseProc.exe")), (LPCTSTR)g_Git.m_CurrentDir);
1406 LaunchApplication(sCmd, NULL, false);
1407 return TRUE;
1409 else if (ret == IDOK)
1410 return TRUE;
1413 return FALSE;
1416 void CAppUtils::DescribeFile(bool mode, bool base,CString &descript)
1418 if(mode == FALSE)
1420 descript=_T("Deleted");
1421 return;
1423 if(base)
1425 descript=_T("Modified");
1426 return;
1428 descript=_T("Created");
1429 return;
1432 void CAppUtils::RemoveTempMergeFile(CTGitPath &path)
1434 CString tempmergefile;
1437 tempmergefile = CAppUtils::GetMergeTempFile(_T("LOCAL"),path);
1438 CFile::Remove(tempmergefile);
1439 }catch(...)
1445 tempmergefile = CAppUtils::GetMergeTempFile(_T("REMOTE"),path);
1446 CFile::Remove(tempmergefile);
1447 }catch(...)
1453 tempmergefile = CAppUtils::GetMergeTempFile(_T("BASE"),path);
1454 CFile::Remove(tempmergefile);
1455 }catch(...)
1459 CString CAppUtils::GetMergeTempFile(CString type,CTGitPath &merge)
1461 CString file;
1462 file=g_Git.m_CurrentDir+_T("\\") + merge.GetWinPathString()+_T(".")+type+merge.GetFileExtension();
1464 return file;
1467 bool CAppUtils::ConflictEdit(CTGitPath &path,bool /*bAlternativeTool*/,bool revertTheirMy)
1469 bool bRet = false;
1471 CTGitPath merge=path;
1472 CTGitPath directory = merge.GetDirectory();
1474 // we have the conflicted file (%merged)
1475 // now look for the other required files
1476 //GitStatus stat;
1477 //stat.GetStatus(merge);
1478 //if (stat.status == NULL)
1479 // return false;
1481 BYTE_VECTOR vector;
1483 CString cmd;
1484 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),merge.GetGitPathString());
1486 if (g_Git.Run(cmd, &vector))
1488 return FALSE;
1491 CTGitPathList list;
1492 list.ParserFromLsFile(vector);
1494 if(list.GetCount() == 0)
1495 return FALSE;
1497 CTGitPath theirs;
1498 CTGitPath mine;
1499 CTGitPath base;
1501 mine.SetFromGit(GetMergeTempFile(_T("LOCAL"),merge));
1502 theirs.SetFromGit(GetMergeTempFile(_T("REMOTE"),merge));
1503 base.SetFromGit(GetMergeTempFile(_T("BASE"),merge));
1505 CString format;
1507 //format=_T("git.exe cat-file blob \":%d:%s\"");
1508 format = _T("git checkout-index --temp --stage=%d -- \"%s\"");
1509 CFile tempfile;
1510 //create a empty file, incase stage is not three
1511 tempfile.Open(mine.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1512 tempfile.Close();
1513 tempfile.Open(theirs.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1514 tempfile.Close();
1515 tempfile.Open(base.GetWinPathString(),CFile::modeCreate|CFile::modeReadWrite);
1516 tempfile.Close();
1518 bool b_base=false, b_local=false, b_remote=false;
1520 for(int i=0;i<list.GetCount();i++)
1522 CString cmd;
1523 CString outfile;
1524 cmd.Empty();
1525 outfile.Empty();
1527 if( list[i].m_Stage == 1)
1529 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1530 b_base = true;
1531 outfile = base.GetWinPathString();
1534 if( list[i].m_Stage == 2 )
1536 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1537 b_local = true;
1538 outfile = mine.GetWinPathString();
1541 if( list[i].m_Stage == 3 )
1543 cmd.Format(format, list[i].m_Stage, list[i].GetGitPathString());
1544 b_remote = true;
1545 outfile = theirs.GetWinPathString();
1547 CString output, err;
1548 if(!outfile.IsEmpty())
1549 if (!g_Git.Run(cmd, &output, &err, CP_ACP))
1551 CString file;
1552 int start =0 ;
1553 file = output.Tokenize(_T("\t"), start);
1554 ::MoveFileEx(file,outfile,MOVEFILE_REPLACE_EXISTING|MOVEFILE_COPY_ALLOWED);
1556 else
1558 CMessageBox::Show(NULL, output + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1562 if(b_local && b_remote )
1564 merge.SetFromWin(g_Git.m_CurrentDir+_T("\\")+merge.GetWinPathString());
1565 if( revertTheirMy )
1566 bRet = !!CAppUtils::StartExtMerge(base,mine, theirs, merge,_T("BASE"),_T("LOCAL"),_T("REMOTE"));
1567 else
1568 bRet = !!CAppUtils::StartExtMerge(base, theirs, mine, merge,_T("BASE"),_T("REMOTE"),_T("LOCAL"));
1571 else
1573 CFile::Remove(mine.GetWinPathString());
1574 CFile::Remove(theirs.GetWinPathString());
1575 CFile::Remove(base.GetWinPathString());
1577 CDeleteConflictDlg dlg;
1578 DescribeFile(b_local, b_base,dlg.m_LocalStatus);
1579 DescribeFile(b_remote,b_base,dlg.m_RemoteStatus);
1580 dlg.m_bShowModifiedButton=b_base;
1581 dlg.m_File=merge.GetGitPathString();
1582 if(dlg.DoModal() == IDOK)
1584 CString cmd,out;
1585 if(dlg.m_bIsDelete)
1587 cmd.Format(_T("git.exe rm -- \"%s\""),merge.GetGitPathString());
1589 else
1590 cmd.Format(_T("git.exe add -- \"%s\""),merge.GetGitPathString());
1592 if(g_Git.Run(cmd,&out,CP_ACP))
1594 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
1595 return FALSE;
1597 return TRUE;
1599 else
1600 return FALSE;
1603 #if 0
1604 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1605 base, theirs, mine, merge);
1606 #endif
1607 #if 0
1608 if (stat.status->text_status == svn_wc_status_conflicted)
1610 // we have a text conflict, use our merge tool to resolve the conflict
1612 CTSVNPath theirs(directory);
1613 CTSVNPath mine(directory);
1614 CTSVNPath base(directory);
1615 bool bConflictData = false;
1617 if ((stat.status->entry)&&(stat.status->entry->conflict_new))
1619 theirs.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_new));
1620 bConflictData = true;
1622 if ((stat.status->entry)&&(stat.status->entry->conflict_old))
1624 base.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_old));
1625 bConflictData = true;
1627 if ((stat.status->entry)&&(stat.status->entry->conflict_wrk))
1629 mine.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->conflict_wrk));
1630 bConflictData = true;
1632 else
1634 mine = merge;
1636 if (bConflictData)
1637 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1638 base, theirs, mine, merge);
1641 if (stat.status->prop_status == svn_wc_status_conflicted)
1643 // we have a property conflict
1644 CTSVNPath prej(directory);
1645 if ((stat.status->entry)&&(stat.status->entry->prejfile))
1647 prej.AppendPathString(CUnicodeUtils::GetUnicode(stat.status->entry->prejfile));
1648 // there's a problem: the prej file contains a _description_ of the conflict, and
1649 // that description string might be translated. That means we have no way of parsing
1650 // the file to find out the conflicting values.
1651 // The only thing we can do: show a dialog with the conflict description, then
1652 // let the user either accept the existing property or open the property edit dialog
1653 // to manually change the properties and values. And a button to mark the conflict as
1654 // resolved.
1655 CEditPropConflictDlg dlg;
1656 dlg.SetPrejFile(prej);
1657 dlg.SetConflictedItem(merge);
1658 bRet = (dlg.DoModal() != IDCANCEL);
1662 if (stat.status->tree_conflict)
1664 // we have a tree conflict
1665 SVNInfo info;
1666 const SVNInfoData * pInfoData = info.GetFirstFileInfo(merge, SVNRev(), SVNRev());
1667 if (pInfoData)
1669 if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_text)
1671 CTSVNPath theirs(directory);
1672 CTSVNPath mine(directory);
1673 CTSVNPath base(directory);
1674 bool bConflictData = false;
1676 if (pInfoData->treeconflict_theirfile)
1678 theirs.AppendPathString(pInfoData->treeconflict_theirfile);
1679 bConflictData = true;
1681 if (pInfoData->treeconflict_basefile)
1683 base.AppendPathString(pInfoData->treeconflict_basefile);
1684 bConflictData = true;
1686 if (pInfoData->treeconflict_myfile)
1688 mine.AppendPathString(pInfoData->treeconflict_myfile);
1689 bConflictData = true;
1691 else
1693 mine = merge;
1695 if (bConflictData)
1696 bRet = !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool),
1697 base, theirs, mine, merge);
1699 else if (pInfoData->treeconflict_kind == svn_wc_conflict_kind_tree)
1701 CString sConflictAction;
1702 CString sConflictReason;
1703 CString sResolveTheirs;
1704 CString sResolveMine;
1705 CTSVNPath treeConflictPath = CTSVNPath(pInfoData->treeconflict_path);
1706 CString sItemName = treeConflictPath.GetUIFileOrDirectoryName();
1708 if (pInfoData->treeconflict_nodekind == svn_node_file)
1710 switch (pInfoData->treeconflict_operation)
1712 case svn_wc_operation_update:
1713 switch (pInfoData->treeconflict_action)
1715 case svn_wc_conflict_action_edit:
1716 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEEDIT, (LPCTSTR)sItemName);
1717 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1718 break;
1719 case svn_wc_conflict_action_add:
1720 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEADD, (LPCTSTR)sItemName);
1721 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1722 break;
1723 case svn_wc_conflict_action_delete:
1724 sConflictAction.Format(IDS_TREECONFLICT_FILEUPDATEDELETE, (LPCTSTR)sItemName);
1725 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1726 break;
1728 break;
1729 case svn_wc_operation_switch:
1730 switch (pInfoData->treeconflict_action)
1732 case svn_wc_conflict_action_edit:
1733 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHEDIT, (LPCTSTR)sItemName);
1734 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1735 break;
1736 case svn_wc_conflict_action_add:
1737 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHADD, (LPCTSTR)sItemName);
1738 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1739 break;
1740 case svn_wc_conflict_action_delete:
1741 sConflictAction.Format(IDS_TREECONFLICT_FILESWITCHDELETE, (LPCTSTR)sItemName);
1742 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1743 break;
1745 break;
1746 case svn_wc_operation_merge:
1747 switch (pInfoData->treeconflict_action)
1749 case svn_wc_conflict_action_edit:
1750 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEEDIT, (LPCTSTR)sItemName);
1751 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1752 break;
1753 case svn_wc_conflict_action_add:
1754 sResolveTheirs.Format(IDS_TREECONFLICT_FILEMERGEADD, (LPCTSTR)sItemName);
1755 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE);
1756 break;
1757 case svn_wc_conflict_action_delete:
1758 sConflictAction.Format(IDS_TREECONFLICT_FILEMERGEDELETE, (LPCTSTR)sItemName);
1759 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1760 break;
1762 break;
1765 else if (pInfoData->treeconflict_nodekind == svn_node_dir)
1767 switch (pInfoData->treeconflict_operation)
1769 case svn_wc_operation_update:
1770 switch (pInfoData->treeconflict_action)
1772 case svn_wc_conflict_action_edit:
1773 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEEDIT, (LPCTSTR)sItemName);
1774 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1775 break;
1776 case svn_wc_conflict_action_add:
1777 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEADD, (LPCTSTR)sItemName);
1778 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1779 break;
1780 case svn_wc_conflict_action_delete:
1781 sConflictAction.Format(IDS_TREECONFLICT_DIRUPDATEDELETE, (LPCTSTR)sItemName);
1782 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1783 break;
1785 break;
1786 case svn_wc_operation_switch:
1787 switch (pInfoData->treeconflict_action)
1789 case svn_wc_conflict_action_edit:
1790 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHEDIT, (LPCTSTR)sItemName);
1791 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1792 break;
1793 case svn_wc_conflict_action_add:
1794 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHADD, (LPCTSTR)sItemName);
1795 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1796 break;
1797 case svn_wc_conflict_action_delete:
1798 sConflictAction.Format(IDS_TREECONFLICT_DIRSWITCHDELETE, (LPCTSTR)sItemName);
1799 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1800 break;
1802 break;
1803 case svn_wc_operation_merge:
1804 switch (pInfoData->treeconflict_action)
1806 case svn_wc_conflict_action_edit:
1807 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEEDIT, (LPCTSTR)sItemName);
1808 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1809 break;
1810 case svn_wc_conflict_action_add:
1811 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEADD, (LPCTSTR)sItemName);
1812 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR);
1813 break;
1814 case svn_wc_conflict_action_delete:
1815 sConflictAction.Format(IDS_TREECONFLICT_DIRMERGEDELETE, (LPCTSTR)sItemName);
1816 sResolveTheirs.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR);
1817 break;
1819 break;
1823 UINT uReasonID = 0;
1824 switch (pInfoData->treeconflict_reason)
1826 case svn_wc_conflict_reason_edited:
1827 uReasonID = IDS_TREECONFLICT_REASON_EDITED;
1828 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1829 break;
1830 case svn_wc_conflict_reason_obstructed:
1831 uReasonID = IDS_TREECONFLICT_REASON_OBSTRUCTED;
1832 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1833 break;
1834 case svn_wc_conflict_reason_deleted:
1835 uReasonID = IDS_TREECONFLICT_REASON_DELETED;
1836 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1837 break;
1838 case svn_wc_conflict_reason_added:
1839 uReasonID = IDS_TREECONFLICT_REASON_ADDED;
1840 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1841 break;
1842 case svn_wc_conflict_reason_missing:
1843 uReasonID = IDS_TREECONFLICT_REASON_MISSING;
1844 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_REMOVEDIR : IDS_TREECONFLICT_RESOLVE_REMOVEFILE);
1845 break;
1846 case svn_wc_conflict_reason_unversioned:
1847 uReasonID = IDS_TREECONFLICT_REASON_UNVERSIONED;
1848 sResolveMine.LoadString(pInfoData->treeconflict_nodekind == svn_node_dir ? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR : IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE);
1849 break;
1851 sConflictReason.Format(uReasonID, (LPCTSTR)sConflictAction);
1853 CTreeConflictEditorDlg dlg;
1854 dlg.SetConflictInfoText(sConflictReason);
1855 dlg.SetResolveTexts(sResolveTheirs, sResolveMine);
1856 dlg.SetPath(treeConflictPath);
1857 INT_PTR dlgRet = dlg.DoModal();
1858 bRet = (dlgRet != IDCANCEL);
1862 #endif
1863 return bRet;
1867 * FUNCTION : FormatDateAndTime
1868 * DESCRIPTION : Generates a displayable string from a CTime object in
1869 * system short or long format or as a relative value
1870 * cTime - the time
1871 * option - DATE_SHORTDATE or DATE_LONGDATE
1872 * bIncluedeTime - whether to show time as well as date
1873 * bRelative - if true then relative time is shown if reasonable
1874 * If HKCU\Software\TortoiseGit\UseSystemLocaleForDates is 0 then use fixed format
1875 * rather than locale
1876 * RETURN : CString containing date/time
1878 CString CAppUtils::FormatDateAndTime( const CTime& cTime, DWORD option, bool bIncludeTime /*=true*/,
1879 bool bRelative /*=false*/)
1881 CString datetime;
1882 if ( bRelative )
1884 datetime = ToRelativeTimeString( cTime );
1886 else
1888 // should we use the locale settings for formatting the date/time?
1889 if (CRegDWORD(_T("Software\\TortoiseGit\\UseSystemLocaleForDates"), TRUE))
1891 // yes
1892 SYSTEMTIME sysTime;
1893 cTime.GetAsSystemTime( sysTime );
1895 TCHAR buf[100];
1897 GetDateFormat(LOCALE_USER_DEFAULT, option, &sysTime, NULL, buf,
1898 _countof(buf) - 1);
1899 datetime = buf;
1900 if ( bIncludeTime )
1902 datetime += _T(" ");
1903 GetTimeFormat(LOCALE_USER_DEFAULT, 0, &sysTime, NULL, buf, _countof(buf) - 1);
1904 datetime += buf;
1907 else
1909 // no, so fixed format
1910 if ( bIncludeTime )
1912 datetime = cTime.Format(_T("%Y-%m-%d %H:%M:%S"));
1914 else
1916 datetime = cTime.Format(_T("%Y-%m-%d"));
1920 return datetime;
1924 * Converts a given time to a relative display string (relative to current time)
1925 * Given time must be in local timezone
1927 CString CAppUtils::ToRelativeTimeString(CTime time)
1929 CString answer;
1930 // convert to COleDateTime
1931 SYSTEMTIME sysTime;
1932 time.GetAsSystemTime( sysTime );
1933 COleDateTime oleTime( sysTime );
1934 answer = ToRelativeTimeString(oleTime, COleDateTime::GetCurrentTime());
1935 return answer;
1939 * Generates a display string showing the relative time between the two given times as COleDateTimes
1941 CString CAppUtils::ToRelativeTimeString(COleDateTime time,COleDateTime RelativeTo)
1943 CString answer;
1944 COleDateTimeSpan ts = RelativeTo - time;
1945 //years
1946 if(fabs(ts.GetTotalDays()) >= 3*365)
1948 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/365, IDS_YEAR_AGO, IDS_YEARS_AGO );
1950 //Months
1951 if(fabs(ts.GetTotalDays()) >= 60)
1953 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/30, IDS_MONTH_AGO, IDS_MONTHS_AGO );
1954 return answer;
1956 //Weeks
1957 if(fabs(ts.GetTotalDays()) >= 14)
1959 answer = ExpandRelativeTime( (int)ts.GetTotalDays()/7, IDS_WEEK_AGO, IDS_WEEKS_AGO );
1960 return answer;
1962 //Days
1963 if(fabs(ts.GetTotalDays()) >= 2)
1965 answer = ExpandRelativeTime( (int)ts.GetTotalDays(), IDS_DAY_AGO, IDS_DAYS_AGO );
1966 return answer;
1968 //hours
1969 if(fabs(ts.GetTotalHours()) >= 2)
1971 answer = ExpandRelativeTime( (int)ts.GetTotalHours(), IDS_HOUR_AGO, IDS_HOURS_AGO );
1972 return answer;
1974 //minutes
1975 if(fabs(ts.GetTotalMinutes()) >= 2)
1977 answer = ExpandRelativeTime( (int)ts.GetTotalMinutes(), IDS_MINUTE_AGO, IDS_MINUTES_AGO );
1978 return answer;
1980 //seconds
1981 answer = ExpandRelativeTime( (int)ts.GetTotalSeconds(), IDS_SECOND_AGO, IDS_SECONDS_AGO );
1982 return answer;
1986 * Passed a value and two resource string ids
1987 * if count is 1 then FormatString is called with format_1 and the value
1988 * otherwise format_2 is used
1989 * the formatted string is returned
1991 CString CAppUtils::ExpandRelativeTime( int count, UINT format_1, UINT format_n )
1993 CString answer;
1994 if ( count == 1 )
1996 answer.FormatMessage( format_1, count );
1998 else
2000 answer.FormatMessage( format_n, count );
2002 return answer;
2005 bool CAppUtils::IsSSHPutty()
2007 CString sshclient=g_Git.m_Environment.GetEnv(_T("GIT_SSH"));
2008 sshclient=sshclient.MakeLower();
2009 if(sshclient.Find(_T("plink.exe"),0)>=0)
2011 return true;
2013 return false;
2016 CString CAppUtils::GetClipboardLink()
2018 if (!OpenClipboard(NULL))
2019 return CString();
2021 CString sClipboardText;
2022 HGLOBAL hglb = GetClipboardData(CF_TEXT);
2023 if (hglb)
2025 LPCSTR lpstr = (LPCSTR)GlobalLock(hglb);
2026 sClipboardText = CString(lpstr);
2027 GlobalUnlock(hglb);
2029 hglb = GetClipboardData(CF_UNICODETEXT);
2030 if (hglb)
2032 LPCTSTR lpstr = (LPCTSTR)GlobalLock(hglb);
2033 sClipboardText = lpstr;
2034 GlobalUnlock(hglb);
2036 CloseClipboard();
2038 if(!sClipboardText.IsEmpty())
2040 if(sClipboardText[0] == _T('\"') && sClipboardText[sClipboardText.GetLength()-1] == _T('\"'))
2041 sClipboardText=sClipboardText.Mid(1,sClipboardText.GetLength()-2);
2043 if(sClipboardText.Find( _T("http://")) == 0)
2044 return sClipboardText;
2046 if(sClipboardText.Find( _T("https://")) == 0)
2047 return sClipboardText;
2049 if(sClipboardText.Find( _T("git://")) == 0)
2050 return sClipboardText;
2052 if(sClipboardText.Find( _T("ssh://")) == 0)
2053 return sClipboardText;
2055 if(sClipboardText.GetLength()>=2)
2056 if( sClipboardText[1] == _T(':') )
2057 if( (sClipboardText[0] >= 'A' && sClipboardText[0] <= 'Z')
2058 || (sClipboardText[0] >= 'a' && sClipboardText[0] <= 'z') )
2059 return sClipboardText;
2062 return CString(_T(""));
2065 CString CAppUtils::ChooseRepository(CString *path)
2067 CBrowseFolder browseFolder;
2068 CRegString regLastResopitory = CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2070 browseFolder.m_style = BIF_EDITBOX | BIF_NEWDIALOGSTYLE | BIF_RETURNFSANCESTORS | BIF_RETURNONLYFSDIRS;
2071 CString strCloneDirectory;
2072 if(path)
2073 strCloneDirectory=*path;
2074 else
2076 strCloneDirectory = regLastResopitory;
2079 CString title;
2080 title.LoadString(IDS_CHOOSE_REPOSITORY);
2082 browseFolder.SetInfo(title);
2084 if (browseFolder.Show(NULL, strCloneDirectory) == CBrowseFolder::OK)
2086 regLastResopitory = strCloneDirectory;
2087 return strCloneDirectory;
2089 else
2091 return CString();
2095 bool CAppUtils::SendPatchMail(CTGitPathList &list,bool autoclose)
2097 CSendMailDlg dlg;
2099 dlg.m_PathList = list;
2101 if(dlg.DoModal()==IDOK)
2103 if(dlg.m_PathList.GetCount() == 0)
2104 return FALSE;
2106 CGitProgressDlg progDlg;
2108 theApp.m_pMainWnd = &progDlg;
2109 progDlg.SetCommand(CGitProgressDlg::GitProgress_SendMail);
2111 progDlg.SetAutoClose(autoclose);
2113 progDlg.SetPathList(dlg.m_PathList);
2114 //ProjectProperties props;
2115 //props.ReadPropsPathList(dlg.m_pathList);
2116 //progDlg.SetProjectProperties(props);
2117 progDlg.SetItemCount(dlg.m_PathList.GetCount());
2119 DWORD flags =0;
2120 if(dlg.m_bAttachment)
2121 flags |= SENDMAIL_ATTACHMENT;
2122 if(dlg.m_bCombine)
2123 flags |= SENDMAIL_COMBINED;
2124 if(dlg.m_bUseMAPI)
2125 flags |= SENDMAIL_MAPI;
2127 progDlg.SetSendMailOption(dlg.m_To,dlg.m_CC,dlg.m_Subject,flags);
2129 progDlg.DoModal();
2131 return true;
2133 return false;
2136 bool CAppUtils::SendPatchMail(CString &cmd,CString &formatpatchoutput,bool autoclose)
2138 CTGitPathList list;
2139 CString log=formatpatchoutput;
2140 int start=log.Find(cmd);
2141 if(start >=0)
2142 CString one=log.Tokenize(_T("\n"),start);
2143 else
2144 start = 0;
2146 while(start>=0)
2148 CString one=log.Tokenize(_T("\n"),start);
2149 one=one.Trim();
2150 if(one.IsEmpty() || one == _T("Success"))
2151 continue;
2152 one.Replace(_T('/'),_T('\\'));
2153 CTGitPath path;
2154 path.SetFromWin(one);
2155 list.AddPath(path);
2157 if (list.GetCount() > 0)
2159 return SendPatchMail(list, autoclose);
2161 else
2163 CMessageBox::Show(NULL, _T("Not patches generated."), _T("TortoiseGit"), MB_ICONINFORMATION);
2164 return true;
2169 int CAppUtils::GetLogOutputEncode(CGit *pGit)
2171 CString cmd,output;
2172 int start=0;
2174 output = pGit->GetConfigValue(_T("i18n.logOutputEncoding"));
2175 if(output.IsEmpty())
2177 output = pGit->GetConfigValue(_T("i18n.commitencoding"));
2178 if(output.IsEmpty())
2179 return CP_UTF8;
2181 int start=0;
2182 output=output.Tokenize(_T("\n"),start);
2183 return CUnicodeUtils::GetCPCode(output);
2186 else
2188 output=output.Tokenize(_T("\n"),start);
2189 return CUnicodeUtils::GetCPCode(output);
2192 int CAppUtils::GetCommitTemplate(CString &temp)
2194 CString cmd,output;
2196 output= g_Git.GetConfigValue(_T("commit.template"),CP_ACP);
2197 if( output.IsEmpty() )
2198 return -1;
2200 if( output.GetLength()<1)
2201 return -1;
2203 if( output[0] == _T('/'))
2205 if(output.GetLength()>=3)
2206 if(output[2] == _T('/'))
2208 output.GetBuffer()[0] = output[1];
2209 output.GetBuffer()[1] = _T(':');
2213 int start=0;
2214 output=output.Tokenize(_T("\n"),start);
2216 output.Replace(_T('/'),_T('\\'));
2220 CStdioFile file(output,CFile::modeRead|CFile::typeText);
2221 CString str;
2222 while(file.ReadString(str))
2224 temp+=str+_T("\n");
2227 }catch(...)
2229 return -1;
2231 return 0;
2233 int CAppUtils::SaveCommitUnicodeFile(CString &filename, CString &message)
2235 CFile file(filename,CFile::modeReadWrite|CFile::modeCreate );
2236 CString cmd,output;
2237 int cp=CP_UTF8;
2239 output= g_Git.GetConfigValue(_T("i18n.commitencoding"));
2240 if(output.IsEmpty())
2241 cp=CP_UTF8;
2243 int start=0;
2244 output=output.Tokenize(_T("\n"),start);
2245 cp=CUnicodeUtils::GetCPCode(output);
2247 int len=message.GetLength();
2249 char * buf;
2250 buf = new char[len*4 + 4];
2251 SecureZeroMemory(buf, (len*4 + 4));
2253 int lengthIncTerminator = WideCharToMultiByte(cp, 0, message, -1, buf, len*4, NULL, NULL);
2255 file.Write(buf,lengthIncTerminator-1);
2256 file.Close();
2257 delete buf;
2258 return 0;
2261 bool CAppUtils::Fetch(CString remoteName, bool allowRebase, bool autoClose)
2263 CPullFetchDlg dlg;
2264 dlg.m_PreSelectRemote = remoteName;
2265 dlg.m_bAllowRebase = allowRebase;
2266 dlg.m_IsPull=FALSE;
2268 if(dlg.DoModal()==IDOK)
2270 if(dlg.m_bAutoLoad)
2272 CAppUtils::LaunchPAgent(NULL,&dlg.m_RemoteURL);
2275 CString url;
2276 url=dlg.m_RemoteURL;
2277 CString cmd;
2278 CString arg;
2280 int ver = CAppUtils::GetMsysgitVersion();
2282 if(ver >= 0x01070203) //above 1.7.0.2
2283 arg = _T("--progress ");
2285 if (dlg.m_bPrune) {
2286 arg += _T("--prune ");
2289 if (dlg.m_bFetchTags) {
2290 arg += _T("--tags ");
2293 cmd.Format(_T("git.exe fetch -v %s \"%s\" %s"),arg, url,dlg.m_RemoteBranchName);
2294 CProgressDlg progress;
2296 progress.m_bAutoCloseOnSuccess = autoClose;
2298 progress.m_PostCmdList.Add(_T("Show Log"));
2300 if(!dlg.m_bRebase)
2302 progress.m_PostCmdList.Add(_T("&Rebase"));
2305 progress.m_GitCmd=cmd;
2306 int userResponse=progress.DoModal();
2308 if (userResponse == IDC_PROGRESS_BUTTON1)
2310 CString cmd;
2311 cmd = CPathUtils::GetAppDirectory() + _T("TortoiseProc.exe");
2312 cmd += _T(" /command:log");
2313 cmd += _T(" /path:\"") + g_Git.m_CurrentDir + _T("\"");
2314 CAppUtils::LaunchApplication(cmd, IDS_ERR_PROC, false);
2315 return TRUE;
2317 else if ((userResponse == IDC_PROGRESS_BUTTON1 + 1) || (progress.m_GitStatus == 0 && dlg.m_bRebase))
2319 while(1)
2321 CRebaseDlg dlg;
2322 dlg.m_PostButtonTexts.Add(_T("Email &Patch..."));
2323 dlg.m_PostButtonTexts.Add(_T("Restart Rebase"));
2324 int response = dlg.DoModal();
2325 if(response == IDOK)
2327 return TRUE;
2329 if(response == IDC_REBASE_POST_BUTTON )
2331 CString cmd, out, err;
2332 cmd.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2333 g_Git.m_CurrentDir,
2334 g_Git.FixBranchName(dlg.m_Upstream),
2335 g_Git.FixBranchName(dlg.m_Branch));
2336 if (g_Git.Run(cmd, &out, &err, CP_ACP))
2338 CMessageBox::Show(NULL, out + L"\n" + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2339 return FALSE;
2342 CAppUtils::SendPatchMail(cmd,out);
2343 return TRUE;
2346 if(response == IDC_REBASE_POST_BUTTON +1 )
2347 continue;
2349 if(response == IDCANCEL)
2350 return FALSE;
2352 return TRUE;
2355 return FALSE;
2358 bool CAppUtils::Push(CString selectLocalBranch, bool autoClose)
2360 CPushDlg dlg;
2361 dlg.m_BranchSourceName = selectLocalBranch;
2362 CString error;
2363 DWORD exitcode = 0xFFFFFFFF;
2364 CTGitPathList list;
2365 list.AddPath(CTGitPath(g_Git.m_CurrentDir));
2366 if (CHooks::Instance().PrePush(list,exitcode, error))
2368 if (exitcode)
2370 CString temp;
2371 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2372 //ReportError(temp);
2373 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2374 return false;
2378 if(dlg.DoModal()==IDOK)
2380 CString cmd;
2381 CString arg;
2383 if(dlg.m_bAutoLoad)
2385 CAppUtils::LaunchPAgent(NULL,&dlg.m_URL);
2388 if(dlg.m_bPack)
2389 arg += _T("--thin ");
2390 if(dlg.m_bTags && !dlg.m_bPushAllBranches)
2391 arg += _T("--tags ");
2392 if(dlg.m_bForce)
2393 arg += _T("--force ");
2395 int ver = CAppUtils::GetMsysgitVersion();
2397 if(ver >= 0x01070203) //above 1.7.0.2
2398 arg += _T("--progress ");
2400 if (dlg.m_bPushAllBranches)
2402 cmd.Format(_T("git.exe push --all %s \"%s\""),
2403 arg,
2404 dlg.m_URL);
2406 else
2408 cmd.Format(_T("git.exe push %s \"%s\" %s"),
2409 arg,
2410 dlg.m_URL,
2411 dlg.m_BranchSourceName);
2412 if (!dlg.m_BranchRemoteName.IsEmpty())
2414 cmd += _T(":") + dlg.m_BranchRemoteName;
2418 CProgressDlg progress;
2419 progress.m_bAutoCloseOnSuccess=autoClose;
2420 progress.m_GitCmd=cmd;
2421 progress.m_PostCmdList.Add(_T("&Request pull"));
2422 progress.m_PostCmdList.Add(_T("Re&Push"));
2423 int ret = progress.DoModal();
2425 if(!progress.m_GitStatus)
2427 if (CHooks::Instance().PostPush(list,exitcode, error))
2429 if (exitcode)
2431 CString temp;
2432 temp.Format(IDS_ERR_HOOKFAILED, (LPCTSTR)error);
2433 //ReportError(temp);
2434 CMessageBox::Show(NULL,temp,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
2435 return false;
2438 if(ret == IDC_PROGRESS_BUTTON1)
2440 RequestPull(dlg.m_BranchRemoteName);
2442 else if(ret == IDC_PROGRESS_BUTTON1 + 1)
2444 Push();
2446 return TRUE;
2450 return FALSE;
2453 bool CAppUtils::RequestPull(CString endrevision, CString repositoryUrl)
2455 CRequestPullDlg dlg;
2456 dlg.m_RepositoryURL = repositoryUrl;
2457 dlg.m_EndRevision = endrevision;
2458 if (dlg.DoModal()==IDOK)
2460 CString cmd;
2461 cmd.Format(_T("git.exe request-pull %s \"%s\" %s"), dlg.m_StartRevision, dlg.m_RepositoryURL, dlg.m_EndRevision);
2463 CProgressDlg progress;
2464 progress.m_GitCmd=cmd;
2465 progress.DoModal();
2467 return true;
2470 bool CAppUtils::CreateMultipleDirectory(const CString& szPath)
2472 CString strDir(szPath);
2473 if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
2475 strDir.AppendChar(_T('\\'));
2477 std::vector<CString> vPath;
2478 CString strTemp;
2479 bool bSuccess = false;
2481 for (int i=0;i<strDir.GetLength();++i)
2483 if (strDir.GetAt(i) != _T('\\'))
2485 strTemp.AppendChar(strDir.GetAt(i));
2487 else
2489 vPath.push_back(strTemp);
2490 strTemp.AppendChar(_T('\\'));
2494 std::vector<CString>::const_iterator vIter;
2495 for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
2497 bSuccess = CreateDirectory(*vIter, NULL) ? true : false;
2500 return bSuccess;
2503 void CAppUtils::RemoveTrailSlash(CString &path)
2505 if(path.IsEmpty())
2506 return ;
2508 while(path[path.GetLength()-1] == _T('\\') || path[path.GetLength()-1] == _T('/' ) )
2510 path=path.Left(path.GetLength()-1);
2511 if(path.IsEmpty())
2512 return;
2516 BOOL CAppUtils::Commit(CString bugid,BOOL bWholeProject,CString &sLogMsg,
2517 CTGitPathList &pathList,
2518 CTGitPathList &selectedList,
2519 bool bSelectFilesForCommit,
2520 bool autoClose)
2522 bool bFailed = true;
2524 while(g_Git.GetUserName().IsEmpty() || g_Git.GetConfigValue(_T("user.email")).IsEmpty())
2526 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"),
2527 _T("TortoiseGit"),MB_YESNO| MB_ICONERROR) == IDYES)
2529 CTGitPath path(g_Git.m_CurrentDir);
2530 CSettings dlg(IDS_PROC_SETTINGS_TITLE,&path);
2531 dlg.SetTreeViewMode(TRUE, TRUE, TRUE);
2532 dlg.SetTreeWidth(220);
2533 dlg.m_DefaultPage = _T("gitconfig");
2535 dlg.DoModal();
2536 dlg.HandleRestart();
2539 else
2540 return false;
2543 while (bFailed)
2545 bFailed = false;
2546 CCommitDlg dlg;
2547 dlg.m_sBugID = bugid;
2549 dlg.m_bWholeProject = bWholeProject;
2551 dlg.m_sLogMessage = sLogMsg;
2552 dlg.m_pathList = pathList;
2553 dlg.m_checkedPathList = selectedList;
2554 dlg.m_bSelectFilesForCommit = bSelectFilesForCommit;
2555 dlg.m_bAutoClose = autoClose;
2556 if (dlg.DoModal() == IDOK)
2558 if (dlg.m_pathList.GetCount()==0)
2559 return false;
2560 // if the user hasn't changed the list of selected items
2561 // we don't use that list. Because if we would use the list
2562 // of pre-checked items, the dialog would show different
2563 // checked items on the next startup: it would only try
2564 // to check the parent folder (which might not even show)
2565 // instead, we simply use an empty list and let the
2566 // default checking do its job.
2567 if (!dlg.m_pathList.IsEqual(pathList))
2568 selectedList = dlg.m_pathList;
2569 pathList = dlg.m_updatedPathList;
2570 sLogMsg = dlg.m_sLogMessage;
2571 bSelectFilesForCommit = true;
2573 if( dlg.m_bPushAfterCommit )
2575 switch(dlg.m_PostCmd)
2577 case GIT_POST_CMD_DCOMMIT:
2578 CAppUtils::SVNDCommit();
2579 break;
2580 default:
2581 CAppUtils::Push();
2584 // CGitProgressDlg progDlg;
2585 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
2586 // if (parser.HasVal(_T("closeonend")))
2587 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
2588 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
2589 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
2590 // progDlg.SetPathList(dlg.m_pathList);
2591 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
2592 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
2593 // progDlg.SetSelectedList(dlg.m_selectedPathList);
2594 // progDlg.SetItemCount(dlg.m_itemsCount);
2595 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
2596 // progDlg.DoModal();
2597 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
2598 // err = (DWORD)progDlg.DidErrorsOccur();
2599 // bFailed = progDlg.DidErrorsOccur();
2600 // bRet = progDlg.DidErrorsOccur();
2601 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
2602 // if (DWORD(bFailRepeat)==0)
2603 // bFailed = false; // do not repeat if the user chose not to in the settings.
2606 return true;
2610 BOOL CAppUtils::SVNDCommit()
2612 CSVNDCommitDlg dcommitdlg;
2613 CString gitSetting = g_Git.GetConfigValue(_T("svn.rmdir"));
2614 if (gitSetting == _T("")) {
2615 if (dcommitdlg.DoModal() != IDOK)
2617 return false;
2619 else
2621 if (dcommitdlg.m_remember)
2623 if (dcommitdlg.m_rmdir)
2625 gitSetting = _T("true");
2627 else
2629 gitSetting = _T("false");
2631 if(g_Git.SetConfigValue(_T("svn.rmdir"),gitSetting))
2633 CMessageBox::Show(NULL,_T("Fail to set config"),_T("TortoiseGit"),MB_OK);
2639 BOOL IsStash = false;
2640 if(!g_Git.CheckCleanWorkTree())
2642 if(CMessageBox::Show(NULL, IDS_ERROR_NOCLEAN_STASH,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2644 CString cmd,out;
2645 cmd=_T("git.exe stash");
2646 if(g_Git.Run(cmd,&out,CP_ACP))
2648 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2649 return false;
2651 IsStash =true;
2654 else
2656 return false;
2660 CProgressDlg progress;
2661 if (dcommitdlg.m_rmdir)
2663 progress.m_GitCmd=_T("git.exe svn dcommit --rmdir");
2665 else
2667 progress.m_GitCmd=_T("git.exe svn dcommit");
2669 if(progress.DoModal()==IDOK && progress.m_GitStatus == 0)
2671 if( IsStash)
2673 if(CMessageBox::Show(NULL,IDS_DCOMMIT_STASH_POP,IDS_APPNAME,MB_YESNO|MB_ICONINFORMATION)==IDYES)
2675 CString cmd,out;
2676 cmd=_T("git.exe stash pop");
2677 if(g_Git.Run(cmd,&out,CP_ACP))
2679 CMessageBox::Show(NULL,out,_T("TortoiseGit"),MB_OK);
2680 return false;
2684 else
2686 return false;
2689 return TRUE;
2691 return FALSE;
2694 BOOL CAppUtils::Merge(CString *commit)
2696 CMergeDlg dlg;
2697 if(commit)
2698 dlg.m_initialRefName = *commit;
2700 if(dlg.DoModal()==IDOK)
2702 CString cmd;
2703 CString noff;
2704 CString squash;
2705 CString nocommit;
2706 CString msg;
2708 if(dlg.m_bNoFF)
2709 noff=_T("--no-ff");
2711 if(dlg.m_bSquash)
2712 squash=_T("--squash");
2714 if(dlg.m_bNoCommit)
2715 nocommit=_T("--no-commit");
2717 if(!dlg.m_strLogMesage.IsEmpty())
2719 msg += _T("-m \"")+dlg.m_strLogMesage+_T("\"");
2721 cmd.Format(_T("git.exe merge %s %s %s %s %s"),
2722 msg,
2723 noff,
2724 squash,
2725 nocommit,
2726 g_Git.FixBranchName(dlg.m_VersionName));
2728 CProgressDlg Prodlg;
2729 Prodlg.m_GitCmd = cmd;
2731 if (dlg.m_bNoCommit)
2732 Prodlg.m_PostCmdList.Add(_T("Commit"));
2734 int ret = Prodlg.DoModal();
2736 if (ret == IDC_PROGRESS_BUTTON1)
2737 return Commit(_T(""), TRUE, CString(), CTGitPathList(), CTGitPathList(), true);
2739 return !Prodlg.m_GitStatus;
2741 return false;
2744 void CAppUtils::EditNote(GitRev *rev)
2746 CInputDlg dlg;
2747 dlg.m_sHintText=_T("Edit Notes");
2748 dlg.m_sInputText = rev->m_Notes;
2749 dlg.m_sTitle=_T("Edit Notes");
2750 //dlg.m_pProjectProperties = &m_ProjectProperties;
2751 dlg.m_bUseLogWidth = true;
2752 if(dlg.DoModal() == IDOK)
2754 CString cmd,output;
2755 cmd=_T("notes add -f -F \"");
2757 CString tempfile=::GetTempFile();
2758 CAppUtils::SaveCommitUnicodeFile(tempfile,dlg.m_sInputText);
2759 cmd += tempfile;
2760 cmd += _T("\" ");
2761 cmd += rev->m_CommitHash.ToString();
2765 if(git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd,CP_ACP).GetBuffer()))
2767 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2770 else
2772 rev->m_Notes = dlg.m_sInputText;
2774 }catch(...)
2776 CMessageBox::Show(NULL,_T("Edit Note Fail"), _T("TortoiseGit"),MB_OK|MB_ICONERROR);
2778 CFile::Remove(tempfile);
2783 int CAppUtils::GetMsysgitVersion(CString *versionstr)
2785 CString cmd;
2786 CString progressarg;
2787 CString version;
2789 CRegDWORD regTime = CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
2790 CRegDWORD regVersion = CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
2792 CString gitpath = CGit::ms_LastMsysGitDir+_T("\\git.exe");
2794 __int64 time=0;
2795 if(!g_Git.GetFileModifyTime(gitpath, &time) && !versionstr)
2797 if((DWORD)time == regTime)
2799 return regVersion;
2803 if(versionstr)
2804 version = *versionstr;
2805 else
2807 CString err;
2808 cmd = _T("git.exe --version");
2809 if(g_Git.Run(cmd, &version, &err, CP_ACP))
2811 CMessageBox::Show(NULL, _T("git have not installed (") + err + _T(")"), _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2812 return false;
2816 int start=0;
2817 int ver;
2819 CString str=version.Tokenize(_T("."),start);
2820 int space = str.ReverseFind(_T(' '));
2821 str=str.Mid(space+1,start);
2822 ver = _ttol(str);
2823 ver <<=24;
2825 version = version.Mid(start);
2826 start = 0;
2827 str = version.Tokenize(_T("."),start);
2829 ver |= (_ttol(str)&0xFF)<<16;
2831 str = version.Tokenize(_T("."),start);
2832 ver |= (_ttol(str)&0xFF)<<8;
2834 str = version.Tokenize(_T("."),start);
2835 ver |= (_ttol(str)&0xFF);
2837 regTime = time&0xFFFFFFFF;
2838 regVersion = ver;
2840 return ver;
2843 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd)
2845 typedef HRESULT (WINAPI *SHGPSFW) (HWND hwnd,REFIID riid,void** ppv);
2847 HMODULE hShell = LoadLibrary(_T("Shell32.dll"));
2849 if (hShell) {
2850 SHGPSFW pfnSHGPSFW = (SHGPSFW)::GetProcAddress(hShell, "SHGetPropertyStoreForWindow");
2851 if (pfnSHGPSFW) {
2852 IPropertyStore *pps;
2853 HRESULT hr = pfnSHGPSFW(hWnd, IID_PPV_ARGS(&pps));
2854 if (SUCCEEDED(hr)) {
2855 PROPVARIANT var;
2856 var.vt = VT_BOOL;
2857 var.boolVal = VARIANT_TRUE;
2858 hr = pps->SetValue(PKEY_AppUserModel_PreventPinning, var);
2859 pps->Release();
2862 FreeLibrary(hShell);
2866 void CAppUtils::SetWindowTitle(HWND hWnd, const CString& urlorpath, const CString& dialogname)
2868 ASSERT(dialogname.GetLength() < 70);
2869 ASSERT(urlorpath.GetLength() < MAX_PATH);
2870 WCHAR pathbuf[MAX_PATH] = {0};
2872 PathCompactPathEx(pathbuf, urlorpath, 70 - dialogname.GetLength(), 0);
2874 wcscat_s(pathbuf, L" - ");
2875 wcscat_s(pathbuf, dialogname);
2876 wcscat_s(pathbuf, L" - ");
2877 wcscat_s(pathbuf, CString(MAKEINTRESOURCE(IDS_APPNAME)));
2878 SetWindowText(hWnd, pathbuf);