1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - TortoiseGit
4 // Copyright (C) 2003-2011, 2013-2014 - 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.
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
24 #include "MessageBox.h"
28 #include "UnicodeUtils.h"
29 #include "ExportDlg.h"
30 #include "ProgressDlg.h"
31 #include "GitAdminDir.h"
32 #include "ProgressDlg.h"
33 #include "BrowseFolder.h"
34 #include "DirFileEnum.h"
35 #include "MessageBox.h"
36 #include "GitStatus.h"
37 #include "CreateBranchTagDlg.h"
38 #include "GitSwitchDlg.h"
40 #include "DeleteConflictDlg.h"
41 #include "ChangedDlg.h"
42 #include "SendMailDlg.h"
43 #include "GitProgressDlg.h"
45 #include "CommitDlg.h"
47 #include "MergeAbortDlg.h"
49 #include "..\Settings\Settings.h"
51 #include "SVNDCommitDlg.h"
52 #include "requestpulldlg.h"
53 #include "PullFetchDlg.h"
54 #include "FileDiffDlg.h"
55 #include "RebaseDlg.h"
57 #include "StashSave.h"
58 #include "IgnoreDlg.h"
59 #include "FormatMessageWrapper.h"
60 #include "SmartHandle.h"
61 #include "BisectStartDlg.h"
62 #include "SysProgressDlg.h"
63 #include "UserPassword.h"
64 #include "SendmailPatch.h"
66 #include "ProgressCommands/ResetProgressCommand.h"
67 #include "ProgressCommands/FetchProgressCommand.h"
68 #include "ProgressCommands/SendMailProgressCommand.h"
69 #include "CertificateValidationHelper.h"
70 #include "CheckCertificateDlg.h"
71 #include "SubmoduleResolveConflictDlg.h"
73 #include "../TGitCache/CacheInterface.h"
75 static struct last_accepted_cert
{
88 boolean
cmp(git_cert_x509
* cert
)
90 return len
> 0 && len
== cert
->len
&& memcmp(data
, cert
->data
, len
) == 0;
92 void set(git_cert_x509
* cert
)
101 data
= new BYTE
[len
];
102 memcpy(data
, cert
->data
, len
);
104 } last_accepted_cert
;
106 static bool DoFetch(const CString
& url
, const bool fetchAllRemotes
, const bool loadPuttyAgent
, const int prune
, const bool bDepth
, const int nDepth
, const int fetchTags
, const CString
& remoteBranch
, int runRebase
, const bool rebasePreserveMerges
);
108 CAppUtils::CAppUtils(void)
112 CAppUtils::~CAppUtils(void)
116 bool CAppUtils::StashSave(const CString
& msg
, bool showPull
, bool pullShowPush
, bool showMerge
, const CString
& mergeRev
)
119 dlg
.m_sMessage
= msg
;
120 if (dlg
.DoModal() == IDOK
)
123 cmd
= _T("git.exe stash save");
125 if (dlg
.m_bIncludeUntracked
)
126 cmd
+= L
" --include-untracked";
130 if (!dlg
.m_sMessage
.IsEmpty())
132 CString message
= dlg
.m_sMessage
;
133 message
.Replace(_T("\""), _T("\"\""));
134 cmd
+= _T(" -- \"") + message
+ _T("\"");
137 CProgressDlg progress
;
138 progress
.m_GitCmd
= cmd
;
139 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
145 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(pullShowPush
, true); });
147 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ CAppUtils::Merge(&mergeRev
, true); });
149 return (progress
.DoModal() == IDOK
);
154 bool CAppUtils::StashApply(CString ref
, bool showChanges
/* true */)
157 cmd
= _T("git.exe stash apply ");
158 if (CStringUtils::StartsWith(ref
, L
"refs/"))
160 if (CStringUtils::StartsWith(ref
, L
"stash{"))
161 ref
= _T("stash@") + ref
.Mid(5);
164 CSysProgressDlg sysProgressDlg
;
165 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
166 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
167 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
168 sysProgressDlg
.SetShowProgressBar(false);
169 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
170 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
172 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
174 sysProgressDlg
.Stop();
176 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
177 if (ret
&& !(ret
== 1 && hasConflicts
))
178 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
182 message
.LoadString(IDS_PROC_STASHAPPLYSUCCESS
);
184 message
.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS
);
187 if (CMessageBox::Show(nullptr, message
+ _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES
)), _T("TortoiseGit"), MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
190 dlg
.m_pathList
.AddPath(CTGitPath());
197 CMessageBox::Show(nullptr, message
,_T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
204 bool CAppUtils::StashPop(int showChanges
/* = 1 */)
207 cmd
=_T("git.exe stash pop ");
209 CSysProgressDlg sysProgressDlg
;
210 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
211 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
212 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
213 sysProgressDlg
.SetShowProgressBar(false);
214 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
215 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
217 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
219 sysProgressDlg
.Stop();
221 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
222 if (ret
&& !(ret
== 1 && hasConflicts
))
223 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
227 message
.LoadString(IDS_PROC_STASHPOPSUCCESS
);
229 message
.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS
);
230 if (showChanges
== 1 || (showChanges
== 0 && hasConflicts
))
232 if (CMessageBox::Show(nullptr, CString(message
+ _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES
))), _T("TortoiseGit"), MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
235 dlg
.m_pathList
.AddPath(CTGitPath());
240 else if (showChanges
> 1)
242 CMessageBox::Show(nullptr, message
, _T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
245 else if (showChanges
== 0)
251 BOOL
CAppUtils::StartExtMerge(bool bAlternative
,
252 const CTGitPath
& basefile
, const CTGitPath
& theirfile
, const CTGitPath
& yourfile
, const CTGitPath
& mergedfile
,
253 const CString
& basename
, const CString
& theirname
, const CString
& yourname
, const CString
& mergedname
, bool bReadOnly
,
254 HWND resolveMsgHwnd
, bool bDeleteBaseTheirsMineOnClose
)
256 CRegString regCom
= CRegString(_T("Software\\TortoiseGit\\Merge"));
257 CString ext
= mergedfile
.GetFileExtension();
258 CString com
= regCom
;
259 bool bInternal
= false;
263 // is there an extension specific merge tool?
264 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext
.MakeLower());
265 if (!CString(mergetool
).IsEmpty())
268 // is there a filename specific merge tool?
269 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile
.GetFilename().MakeLower());
270 if (!CString(mergetool
).IsEmpty())
273 if (bAlternative
&& !com
.IsEmpty())
275 if (com
.Left(1).Compare(L
"#") == 0)
281 if (com
.IsEmpty()||(com
.Left(1).Compare(_T("#"))==0))
283 // Maybe we should use TortoiseIDiff?
284 if ((ext
== _T(".jpg")) || (ext
== _T(".jpeg")) ||
285 (ext
== _T(".bmp")) || (ext
== _T(".gif")) ||
286 (ext
== _T(".png")) || (ext
== _T(".ico")) ||
287 (ext
== _T(".tif")) || (ext
== _T(".tiff")) ||
288 (ext
== _T(".dib")) || (ext
== _T(".emf")) ||
291 com
= CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
292 com
= _T("\"") + com
+ _T("\"");
293 com
= com
+ _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
294 com
= com
+ _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
296 com
.AppendFormat(L
" /resolvemsghwnd:%I64d", (__int64
)resolveMsgHwnd
);
300 // use TortoiseGitMerge
302 com
= CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
303 com
= _T("\"") + com
+ _T("\"");
304 com
= com
+ _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
305 com
= com
+ _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
306 com
+= _T(" /saverequired");
308 com
.AppendFormat(L
" /resolvemsghwnd:%I64d", (__int64
)resolveMsgHwnd
);
309 if (bDeleteBaseTheirsMineOnClose
)
310 com
+= _T(" /deletebasetheirsmineonclose");
312 if (!g_sGroupingUUID
.IsEmpty())
314 com
+= L
" /groupuuid:\"";
315 com
+= g_sGroupingUUID
;
319 // check if the params are set. If not, just add the files to the command line
320 if ((com
.Find(_T("%merged"))<0)&&(com
.Find(_T("%base"))<0)&&(com
.Find(_T("%theirs"))<0)&&(com
.Find(_T("%mine"))<0))
322 com
+= _T(" \"")+basefile
.GetWinPathString()+_T("\"");
323 com
+= _T(" \"")+theirfile
.GetWinPathString()+_T("\"");
324 com
+= _T(" \"")+yourfile
.GetWinPathString()+_T("\"");
325 com
+= _T(" \"")+mergedfile
.GetWinPathString()+_T("\"");
327 if (basefile
.IsEmpty())
329 com
.Replace(_T("/base:%base"), _T(""));
330 com
.Replace(_T("%base"), _T(""));
333 com
.Replace(_T("%base"), _T("\"") + basefile
.GetWinPathString() + _T("\""));
334 if (theirfile
.IsEmpty())
336 com
.Replace(_T("/theirs:%theirs"), _T(""));
337 com
.Replace(_T("%theirs"), _T(""));
340 com
.Replace(_T("%theirs"), _T("\"") + theirfile
.GetWinPathString() + _T("\""));
341 if (yourfile
.IsEmpty())
343 com
.Replace(_T("/mine:%mine"), _T(""));
344 com
.Replace(_T("%mine"), _T(""));
347 com
.Replace(_T("%mine"), _T("\"") + yourfile
.GetWinPathString() + _T("\""));
348 if (mergedfile
.IsEmpty())
350 com
.Replace(_T("/merged:%merged"), _T(""));
351 com
.Replace(_T("%merged"), _T(""));
354 com
.Replace(_T("%merged"), _T("\"") + mergedfile
.GetWinPathString() + _T("\""));
355 if (basename
.IsEmpty())
357 if (basefile
.IsEmpty())
359 com
.Replace(_T("/basename:%bname"), _T(""));
360 com
.Replace(_T("%bname"), _T(""));
363 com
.Replace(_T("%bname"), _T("\"") + basefile
.GetUIFileOrDirectoryName() + _T("\""));
366 com
.Replace(_T("%bname"), _T("\"") + basename
+ _T("\""));
367 if (theirname
.IsEmpty())
369 if (theirfile
.IsEmpty())
371 com
.Replace(_T("/theirsname:%tname"), _T(""));
372 com
.Replace(_T("%tname"), _T(""));
375 com
.Replace(_T("%tname"), _T("\"") + theirfile
.GetUIFileOrDirectoryName() + _T("\""));
378 com
.Replace(_T("%tname"), _T("\"") + theirname
+ _T("\""));
379 if (yourname
.IsEmpty())
381 if (yourfile
.IsEmpty())
383 com
.Replace(_T("/minename:%yname"), _T(""));
384 com
.Replace(_T("%yname"), _T(""));
387 com
.Replace(_T("%yname"), _T("\"") + yourfile
.GetUIFileOrDirectoryName() + _T("\""));
390 com
.Replace(_T("%yname"), _T("\"") + yourname
+ _T("\""));
391 if (mergedname
.IsEmpty())
393 if (mergedfile
.IsEmpty())
395 com
.Replace(_T("/mergedname:%mname"), _T(""));
396 com
.Replace(_T("%mname"), _T(""));
399 com
.Replace(_T("%mname"), _T("\"") + mergedfile
.GetUIFileOrDirectoryName() + _T("\""));
402 com
.Replace(_T("%mname"), _T("\"") + mergedname
+ _T("\""));
404 if ((bReadOnly
)&&(bInternal
))
405 com
+= _T(" /readonly");
407 if(!LaunchApplication(com
, IDS_ERR_EXTMERGESTART
, false))
415 BOOL
CAppUtils::StartExtPatch(const CTGitPath
& patchfile
, const CTGitPath
& dir
, const CString
& sOriginalDescription
, const CString
& sPatchedDescription
, BOOL bReversed
, BOOL bWait
)
418 // use TortoiseGitMerge
419 viewer
= CPathUtils::GetAppDirectory();
420 viewer
+= _T("TortoiseGitMerge.exe");
422 viewer
= _T("\"") + viewer
+ _T("\"");
423 viewer
= viewer
+ _T(" /diff:\"") + patchfile
.GetWinPathString() + _T("\"");
424 viewer
= viewer
+ _T(" /patchpath:\"") + dir
.GetWinPathString() + _T("\"");
426 viewer
+= _T(" /reversedpatch");
427 if (!sOriginalDescription
.IsEmpty())
428 viewer
= viewer
+ _T(" /patchoriginal:\"") + sOriginalDescription
+ _T("\"");
429 if (!sPatchedDescription
.IsEmpty())
430 viewer
= viewer
+ _T(" /patchpatched:\"") + sPatchedDescription
+ _T("\"");
431 if (!g_sGroupingUUID
.IsEmpty())
433 viewer
+= L
" /groupuuid:\"";
434 viewer
+= g_sGroupingUUID
;
437 if(!LaunchApplication(viewer
, IDS_ERR_DIFFVIEWSTART
, !!bWait
))
442 CString
CAppUtils::PickDiffTool(const CTGitPath
& file1
, const CTGitPath
& file2
)
444 CString difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file2
.GetFilename().MakeLower());
445 if (!difftool
.IsEmpty())
447 difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file1
.GetFilename().MakeLower());
448 if (!difftool
.IsEmpty())
451 // Is there an extension specific diff tool?
452 CString ext
= file2
.GetFileExtension().MakeLower();
455 difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext
);
456 if (!difftool
.IsEmpty())
458 // Maybe we should use TortoiseIDiff?
459 if ((ext
== _T(".jpg")) || (ext
== _T(".jpeg")) ||
460 (ext
== _T(".bmp")) || (ext
== _T(".gif")) ||
461 (ext
== _T(".png")) || (ext
== _T(".ico")) ||
462 (ext
== _T(".tif")) || (ext
== _T(".tiff")) ||
463 (ext
== _T(".dib")) || (ext
== _T(".emf")) ||
467 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
468 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
469 L
" /groupuuid:\"" + g_sGroupingUUID
+ L
"\"";
473 // Finally, pick a generic external diff tool
474 difftool
= CRegString(_T("Software\\TortoiseGit\\Diff"));
478 bool CAppUtils::StartExtDiff(
479 const CString
& file1
, const CString
& file2
,
480 const CString
& sName1
, const CString
& sName2
,
481 const CString
& originalFile1
, const CString
& originalFile2
,
482 const git_revnum_t
& hash1
, const git_revnum_t
& hash2
,
483 const DiffFlags
& flags
, int jumpToLine
)
487 CRegDWORD
blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE
);
488 if (!flags
.bBlame
|| !(DWORD
)blamediff
)
490 viewer
= PickDiffTool(file1
, file2
);
491 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
492 bool bCommentedOut
= viewer
.Left(1) == _T("#");
493 if (flags
.bAlternativeTool
)
495 // Invert external vs. internal diff tool selection.
497 viewer
.Delete(0); // uncomment
501 else if (bCommentedOut
)
505 bool bInternal
= viewer
.IsEmpty();
509 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
510 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
511 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
512 if (!g_sGroupingUUID
.IsEmpty())
514 viewer
+= L
" /groupuuid:\"";
515 viewer
+= g_sGroupingUUID
;
519 viewer
+= _T(" /blame");
521 // check if the params are set. If not, just add the files to the command line
522 if ((viewer
.Find(_T("%base"))<0)&&(viewer
.Find(_T("%mine"))<0))
524 viewer
+= _T(" \"")+file1
+_T("\"");
525 viewer
+= _T(" \"")+file2
+_T("\"");
527 if (viewer
.Find(_T("%base")) >= 0)
528 viewer
.Replace(_T("%base"), _T("\"")+file1
+_T("\""));
529 if (viewer
.Find(_T("%mine")) >= 0)
530 viewer
.Replace(_T("%mine"), _T("\"")+file2
+_T("\""));
532 if (sName1
.IsEmpty())
533 viewer
.Replace(_T("%bname"), _T("\"") + file1
+ _T("\""));
535 viewer
.Replace(_T("%bname"), _T("\"") + sName1
+ _T("\""));
537 if (sName2
.IsEmpty())
538 viewer
.Replace(_T("%yname"), _T("\"") + file2
+ _T("\""));
540 viewer
.Replace(_T("%yname"), _T("\"") + sName2
+ _T("\""));
542 viewer
.Replace(_T("%bpath"), _T("\"") + originalFile1
+ _T("\""));
543 viewer
.Replace(_T("%ypath"), _T("\"") + originalFile2
+ _T("\""));
545 viewer
.Replace(_T("%brev"), _T("\"") + hash1
+ _T("\""));
546 viewer
.Replace(_T("%yrev"), _T("\"") + hash2
+ _T("\""));
548 if (flags
.bReadOnly
&& bInternal
)
549 viewer
+= _T(" /readonly");
552 viewer
.AppendFormat(L
" /line:%d", jumpToLine
);
554 return LaunchApplication(viewer
, IDS_ERR_EXTDIFFSTART
, flags
.bWait
);
557 BOOL
CAppUtils::StartUnifiedDiffViewer(const CString
& patchfile
, const CString
& title
, BOOL bWait
, bool bAlternativeTool
)
560 CRegString v
= CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
563 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
564 bool bCommentedOut
= viewer
.Left(1) == _T("#");
565 if (bAlternativeTool
)
567 // Invert external vs. internal diff tool selection.
569 viewer
.Delete(0); // uncomment
573 else if (bCommentedOut
)
576 if (viewer
.IsEmpty())
578 // use TortoiseGitUDiff
579 viewer
= CPathUtils::GetAppDirectory();
580 viewer
+= _T("TortoiseGitUDiff.exe");
581 // enquote the path to TortoiseGitUDiff
582 viewer
= _T("\"") + viewer
+ _T("\"");
584 viewer
= viewer
+ _T(" /patchfile:%1 /title:\"%title\"");
585 if (!g_sGroupingUUID
.IsEmpty())
587 viewer
+= L
" /groupuuid:\"";
588 viewer
+= g_sGroupingUUID
;
592 if (viewer
.Find(_T("%1"))>=0)
594 if (viewer
.Find(_T("\"%1\"")) >= 0)
595 viewer
.Replace(_T("%1"), patchfile
);
597 viewer
.Replace(_T("%1"), _T("\"") + patchfile
+ _T("\""));
600 viewer
+= _T(" \"") + patchfile
+ _T("\"");
601 if (viewer
.Find(_T("%title")) >= 0)
602 viewer
.Replace(_T("%title"), title
);
604 if(!LaunchApplication(viewer
, IDS_ERR_DIFFVIEWSTART
, !!bWait
))
609 BOOL
CAppUtils::StartTextViewer(CString file
)
612 CRegString txt
= CRegString(_T(".txt\\"), _T(""), FALSE
, HKEY_CLASSES_ROOT
);
614 viewer
= viewer
+ _T("\\Shell\\Open\\Command\\");
615 CRegString txtexe
= CRegString(viewer
, _T(""), FALSE
, HKEY_CLASSES_ROOT
);
618 DWORD len
= ExpandEnvironmentStrings(viewer
, nullptr, 0);
619 auto buf
= std::make_unique
<TCHAR
[]>(len
+ 1);
620 ExpandEnvironmentStrings(viewer
, buf
.get(), len
);
622 len
= ExpandEnvironmentStrings(file
, nullptr, 0);
623 auto buf2
= std::make_unique
<TCHAR
[]>(len
+ 1);
624 ExpandEnvironmentStrings(file
, buf2
.get(), len
);
626 file
= _T("\"")+file
+_T("\"");
627 if (viewer
.IsEmpty())
628 return CAppUtils::ShowOpenWithDialog(file
) ? TRUE
: FALSE
;
629 if (viewer
.Find(_T("\"%1\"")) >= 0)
630 viewer
.Replace(_T("\"%1\""), file
);
631 else if (viewer
.Find(_T("%1")) >= 0)
632 viewer
.Replace(_T("%1"), file
);
637 if(!LaunchApplication(viewer
, IDS_ERR_TEXTVIEWSTART
, false))
642 BOOL
CAppUtils::CheckForEmptyDiff(const CTGitPath
& sDiffPath
)
645 CAutoFile hFile
= ::CreateFile(sDiffPath
.GetWinPath(), GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, nullptr, OPEN_EXISTING
, 0, nullptr);
648 length
= ::GetFileSize(hFile
, nullptr);
654 void CAppUtils::CreateFontForLogs(CFont
& fontToCreate
)
657 HDC hScreenDC
= ::GetDC(nullptr);
658 logFont
.lfHeight
= -MulDiv((DWORD
)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC
, LOGPIXELSY
), 72);
659 ::ReleaseDC(nullptr, hScreenDC
);
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::LaunchPAgent(const CString
* keyfile
, const CString
* pRemote
)
687 cmd
.Format(_T("remote.%s.puttykeyfile"), (LPCTSTR
)remote
);
688 key
= g_Git
.GetConfigValue(cmd
);
696 CString proc
=CPathUtils::GetAppDirectory();
697 proc
+= _T("pageant.exe \"");
701 CString tempfile
= GetTempFile();
702 ::DeleteFile(tempfile
);
704 proc
+= _T(" -c \"");
705 proc
+= CPathUtils::GetAppDirectory();
706 proc
+= _T("tgittouch.exe\"");
711 CString appDir
= CPathUtils::GetAppDirectory();
712 bool b
= LaunchApplication(proc
, IDS_ERR_PAGEANT
, true, &appDir
);
717 while(!::PathFileExists(tempfile
))
722 break; //timeout 5 minutes
726 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
727 ::DeleteFile(tempfile
);
730 bool CAppUtils::LaunchAlternativeEditor(const CString
& filename
, bool uac
)
732 CString editTool
= CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
733 if (editTool
.IsEmpty() || (editTool
.Left(1).Compare(_T("#"))==0)) {
734 editTool
= CPathUtils::GetAppDirectory() + _T("notepad2.exe");
738 sCmd
.Format(_T("\"%s\" \"%s\""), (LPCTSTR
)editTool
, (LPCTSTR
)filename
);
740 LaunchApplication(sCmd
, 0, false, nullptr, uac
);
743 bool CAppUtils::LaunchRemoteSetting()
745 CTGitPath
path(g_Git
.m_CurrentDir
);
746 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
, &path
);
747 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
748 dlg
.SetTreeWidth(220);
749 dlg
.m_DefaultPage
= _T("gitremote");
756 * Launch the external blame viewer
758 bool CAppUtils::LaunchTortoiseBlame(const CString
& sBlameFile
, const CString
& Rev
, const CString
& sParams
)
760 CString viewer
= _T("\"") + CPathUtils::GetAppDirectory();
761 viewer
+= _T("TortoiseGitBlame.exe");
762 viewer
+= _T("\" \"") + sBlameFile
+ _T("\"");
763 //viewer += _T(" \"") + sLogFile + _T("\"");
764 //viewer += _T(" \"") + sOriginalFile + _T("\"");
765 if(!Rev
.IsEmpty() && Rev
!= GIT_REV_ZERO
)
766 viewer
+= CString(_T(" /rev:"))+Rev
;
767 if (!g_sGroupingUUID
.IsEmpty())
769 viewer
+= L
" /groupuuid:\"";
770 viewer
+= g_sGroupingUUID
;
773 viewer
+= _T(" ")+sParams
;
775 return LaunchApplication(viewer
, IDS_ERR_TGITBLAME
, false);
778 bool CAppUtils::FormatTextInRichEditControl(CWnd
* pWnd
)
783 bool bStyled
= false;
784 pWnd
->GetWindowText(sText
);
785 // the rich edit control doesn't count the CR char!
786 // to be exact: CRLF is treated as one char.
787 sText
.Remove(_T('\r'));
789 // style each line separately
794 nNewlinePos
= sText
.Find('\n', offset
);
795 CString sLine
= nNewlinePos
>= 0 ? sText
.Mid(offset
, nNewlinePos
- offset
) : sText
.Mid(offset
);
799 while (FindStyleChars(sLine
, '*', start
, end
))
801 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
802 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
803 SetCharFormat(pWnd
, CFM_BOLD
, CFE_BOLD
);
809 while (FindStyleChars(sLine
, '^', start
, end
))
811 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
812 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
813 SetCharFormat(pWnd
, CFM_ITALIC
, CFE_ITALIC
);
819 while (FindStyleChars(sLine
, '_', start
, end
))
821 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
822 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
823 SetCharFormat(pWnd
, CFM_UNDERLINE
, CFE_UNDERLINE
);
827 offset
= nNewlinePos
+1;
828 } while(nNewlinePos
>=0);
832 bool CAppUtils::FindStyleChars(const CString
& sText
, TCHAR stylechar
, int& start
, int& end
)
835 int last
= sText
.GetLength() - 1;
836 bool bFoundMarker
= false;
837 TCHAR c
= i
== 0 ? _T('\0') : sText
[i
- 1];
838 TCHAR nextChar
= i
>= last
? _T('\0') : sText
[i
+ 1];
840 // find a starting marker
845 nextChar
= sText
[i
+ 1];
847 // IsCharAlphaNumeric can be somewhat expensive.
848 // Long lines of "*****" or "----" will be pre-empted efficiently
849 // by the (c != nextChar) condition.
851 if ((c
== stylechar
) && (c
!= nextChar
))
853 if (IsCharAlphaNumeric(nextChar
) && !IsCharAlphaNumeric(prevChar
))
865 // find ending marker
868 bFoundMarker
= false;
875 if ((i
== last
) || (!IsCharAlphaNumeric(sText
[i
+ 1]) && IsCharAlphaNumeric(prevChar
)))
890 bool IsValidURLChar(wchar_t ch
)
892 return iswalnum(ch
) ||
893 ch
== L
'_' || ch
== L
'/' || ch
== L
';' || ch
== L
'?' || ch
== L
'&' || ch
== L
'=' ||
894 ch
== L
'%' || ch
== L
':' || ch
== L
'.' || ch
== L
'#' || ch
== L
'-' || ch
== L
'+' ||
895 ch
== L
'|' || ch
== L
'>' || ch
== L
'<';
898 bool IsUrl(const CString
& sText
)
900 if (!PathIsURLW(sText
))
902 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ftp://", L
"file://", L
"mailto:" })
904 if (CStringUtils::StartsWith(sText
, prefix
) && sText
.GetLength() != prefix
.GetLength())
911 BOOL
CAppUtils::StyleURLs(const CString
& msg
, CWnd
* pWnd
)
913 std::vector
<CHARRANGE
> positions
= FindURLMatches(msg
);
914 CAppUtils::SetCharFormat(pWnd
, CFM_LINK
, CFE_LINK
, positions
);
916 return positions
.empty() ? FALSE
: TRUE
;
920 * implements URL searching with the same logic as CSciEdit::StyleURLs
922 std::vector
<CHARRANGE
> CAppUtils::FindURLMatches(const CString
& msg
)
924 std::vector
<CHARRANGE
> result
;
926 int len
= msg
.GetLength();
929 for (int i
= 0; i
<= msg
.GetLength(); ++i
)
931 if ((i
< len
) && IsValidURLChar(msg
[i
]))
941 if (msg
[starturl
] == '<' && i
< len
) // try to detect and do not strip URLs put within <>
943 while (starturl
<= i
&& msg
[starturl
] == '<') // strip leading '<'
947 while (i
< len
&& msg
[i
] != '\r' && msg
[i
] != '\n' && msg
[i
] != '>') // find first '>' or new line after resetting i to start position
950 if (!IsUrl(msg
.Mid(starturl
, i
- starturl
)))
956 int skipTrailing
= 0;
957 while (strip
&& i
- skipTrailing
- 1 > starturl
&& (msg
[i
- skipTrailing
- 1] == '.' || msg
[i
- skipTrailing
- 1] == '-' || msg
[i
- skipTrailing
- 1] == '?' || msg
[i
- skipTrailing
- 1] == ';' || msg
[i
- skipTrailing
- 1] == ':' || msg
[i
- skipTrailing
- 1] == '>' || msg
[i
- skipTrailing
- 1] == '<'))
960 CHARRANGE range
= { starturl
, i
- skipTrailing
};
961 result
.push_back(range
);
970 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd
, const CTGitPath
& url1
, const git_revnum_t
& rev1
,
971 const CTGitPath
& /*url2*/, const git_revnum_t
& rev2
,
972 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
973 bool bAlternateDiff
/* = false */, bool /*bIgnoreAncestry*/ /* = false */,
974 bool /* blame = false */,
979 int diffContext
= g_Git
.GetConfigValueInt32(L
"diff.context", -1);
980 CString tempfile
=GetTempFile();
981 if (g_Git
.GetUnifiedDiff(url1
, rev1
, rev2
, tempfile
, bMerge
, bCombine
, diffContext
, bNoPrefix
))
983 CMessageBox::Show(hWnd
, g_Git
.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF
), _T("TortoiseGit"), MB_OK
);
986 CAppUtils::StartUnifiedDiffViewer(tempfile
, rev1
+ L
":" + rev2
, FALSE
, bAlternateDiff
);
990 sCmd
.Format(_T("%s /command:showcompare /unified"),
991 (LPCTSTR
)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
992 sCmd
+= _T(" /url1:\"") + url1
.GetGitPathString() + _T("\"");
994 sCmd
+= _T(" /revision1:") + rev1
.ToString();
995 sCmd
+= _T(" /url2:\"") + url2
.GetGitPathString() + _T("\"");
997 sCmd
+= _T(" /revision2:") + rev2
.ToString();
999 sCmd
+= _T(" /pegrevision:") + peg
.ToString();
1000 if (headpeg
.IsValid())
1001 sCmd
+= _T(" /headpegrevision:") + headpeg
.ToString();
1004 sCmd
+= _T(" /alternatediff");
1006 if (bIgnoreAncestry
)
1007 sCmd
+= _T(" /ignoreancestry");
1011 sCmd
+= _T(" /hwnd:");
1013 _stprintf_s(buf
, 30, _T("%p"), (void*)hWnd
);
1017 return CAppUtils::LaunchApplication(sCmd
, 0, false);
1022 bool CAppUtils::SetupDiffScripts(bool force
, const CString
& type
)
1024 CString scriptsdir
= CPathUtils::GetAppParentDirectory();
1025 scriptsdir
+= _T("Diff-Scripts");
1026 CSimpleFileFind
files(scriptsdir
);
1027 while (files
.FindNextFileNoDirectories())
1029 CString file
= files
.GetFilePath();
1030 CString filename
= files
.GetFileName();
1031 CString ext
= file
.Mid(file
.ReverseFind('-') + 1);
1032 ext
= _T(".") + ext
.Left(ext
.ReverseFind('.'));
1033 std::set
<CString
> extensions
;
1034 extensions
.insert(ext
);
1036 if (file
.Right(3).CompareNoCase(_T("vbs"))==0)
1037 kind
= _T(" //E:vbscript");
1038 if (file
.Right(2).CompareNoCase(_T("js"))==0)
1039 kind
= _T(" //E:javascript");
1040 // open the file, read the first line and find possible extensions
1041 // this script can handle
1044 CStdioFile
f(file
, CFile::modeRead
| CFile::shareDenyNone
);
1046 if (f
.ReadString(extline
))
1048 if ((extline
.GetLength() > 15 ) &&
1049 ((extline
.Left(15).Compare(_T("// extensions: ")) == 0) ||
1050 (extline
.Left(14).Compare(_T("' extensions: ")) == 0)))
1052 if (extline
[0] == '/')
1053 extline
= extline
.Mid(15);
1055 extline
= extline
.Mid(14);
1058 sToken
= extline
.Tokenize(_T(";"), curPos
);
1059 while (!sToken
.IsEmpty())
1061 if (!sToken
.IsEmpty())
1063 if (sToken
[0] != '.')
1064 sToken
= _T(".") + sToken
;
1065 extensions
.insert(sToken
);
1067 sToken
= extline
.Tokenize(_T(";"), curPos
);
1073 catch (CFileException
* e
)
1078 for (const auto& extension
: extensions
)
1080 if (type
.IsEmpty() || (type
.Compare(_T("Diff")) == 0))
1082 if (filename
.Left(5).CompareNoCase(_T("diff-")) == 0)
1084 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension
);
1085 CString diffregstring
= diffreg
;
1086 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1087 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %base %mine") + kind
;
1090 if (type
.IsEmpty() || (type
.Compare(_T("Merge"))==0))
1092 if (filename
.Left(6).CompareNoCase(_T("merge-"))==0)
1094 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension
);
1095 CString diffregstring
= diffreg
;
1096 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1097 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %merged %theirs %mine %base") + kind
;
1106 bool CAppUtils::Export(const CString
* BashHash
, const CTGitPath
* orgPath
)
1108 // ask from where the export has to be done
1111 dlg
.m_initialRefName
=*BashHash
;
1114 if (PathIsRelative(orgPath
->GetWinPath()))
1115 dlg
.m_orgPath
= g_Git
.CombinePath(orgPath
);
1117 dlg
.m_orgPath
= *orgPath
;
1120 if (dlg
.DoModal() == IDOK
)
1123 cmd
.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1124 (LPCTSTR
)dlg
.m_strFile
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
1128 pro
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1132 postCmdList
.emplace_back(IDI_EXPLORER
, IDS_STATUSLIST_CONTEXT_EXPLORE
, [&]{ CAppUtils::ExploreTo(hWndExplorer
, dlg
.m_strFile
); });
1136 if (!dlg
.m_bWholeProject
&& !dlg
.m_orgPath
.IsEmpty() && PathIsDirectory(dlg
.m_orgPath
.GetWinPathString()))
1138 git
.m_CurrentDir
= dlg
.m_orgPath
.GetWinPathString();
1141 return (pro
.DoModal() == IDOK
);
1146 bool CAppUtils::UpdateBranchDescription(const CString
& branch
, CString description
)
1148 if (branch
.IsEmpty())
1152 key
.Format(L
"branch.%s.description", (LPCTSTR
)branch
);
1153 description
.Replace(L
"\r", L
"");
1155 if (description
.IsEmpty())
1156 g_Git
.UnsetConfigValue(key
);
1158 g_Git
.SetConfigValue(key
, description
);
1163 bool CAppUtils::CreateBranchTag(bool isTag
/*true*/, const CString
* commitHash
/*nullptr*/, bool switchNewBranch
/*false*/, LPCTSTR name
/*nullptr*/)
1165 CCreateBranchTagDlg dlg
;
1166 dlg
.m_bIsTag
= isTag
;
1167 dlg
.m_bSwitch
= switchNewBranch
;
1170 dlg
.m_initialRefName
= *commitHash
;
1173 dlg
.m_BranchTagName
= name
;
1175 if(dlg
.DoModal()==IDOK
)
1180 if(dlg
.m_bTrack
== TRUE
)
1181 track
=_T(" --track ");
1182 else if(dlg
.m_bTrack
== FALSE
)
1183 track
=_T(" --no-track");
1194 cmd
.Format(_T("git.exe tag %s %s %s %s"),
1197 (LPCTSTR
)dlg
.m_BranchTagName
,
1198 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1201 if(!dlg
.m_Message
.Trim().IsEmpty())
1203 CString tempfile
= ::GetTempFile();
1204 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_Message
))
1206 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1209 cmd
+= _T(" -F ")+tempfile
;
1214 cmd
.Format(_T("git.exe branch %s %s %s %s"),
1217 (LPCTSTR
)dlg
.m_BranchTagName
,
1218 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1222 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1224 CMessageBox::Show(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1227 if (!isTag
&& dlg
.m_bSwitch
)
1229 // it is a new branch and the user has requested to switch to it
1230 PerformSwitch(dlg
.m_BranchTagName
);
1232 if (!isTag
&& !dlg
.m_Message
.IsEmpty())
1233 UpdateBranchDescription(dlg
.m_BranchTagName
, dlg
.m_Message
);
1240 bool CAppUtils::Switch(const CString
& initialRefName
)
1243 if(!initialRefName
.IsEmpty())
1244 dlg
.m_initialRefName
= initialRefName
;
1246 if (dlg
.DoModal() == IDOK
)
1250 branch
= dlg
.m_NewBranch
;
1252 // if refs/heads/ is not stripped, checkout will detach HEAD
1253 // checkout prefers branches on name clashes (with tags)
1254 if (dlg
.m_VersionName
.Left(11) ==_T("refs/heads/") && dlg
.m_bBranchOverride
!= TRUE
)
1255 dlg
.m_VersionName
= dlg
.m_VersionName
.Mid(11);
1257 return PerformSwitch(dlg
.m_VersionName
, dlg
.m_bForce
== TRUE
, branch
, dlg
.m_bBranchOverride
== TRUE
, dlg
.m_bTrack
, dlg
.m_bMerge
== TRUE
);
1262 bool CAppUtils::PerformSwitch(const CString
& ref
, bool bForce
/* false */, const CString
& sNewBranch
/* CString() */, bool bBranchOverride
/* false */, BOOL bTrack
/* 2 */, bool bMerge
/* false */)
1270 if(!sNewBranch
.IsEmpty()){
1271 if (bBranchOverride
)
1272 branch
.Format(_T("-B %s "), (LPCTSTR
)sNewBranch
);
1274 branch
.Format(_T("-b %s "), (LPCTSTR
)sNewBranch
);
1276 track
= _T("--track ");
1277 else if (bTrack
== FALSE
)
1278 track
= _T("--no-track ");
1283 merge
= _T("--merge ");
1285 cmd
.Format(_T("git.exe checkout %s%s%s%s%s --"),
1290 (LPCTSTR
)g_Git
.FixBranchName(ref
));
1292 CProgressDlg progress
;
1293 progress
.m_GitCmd
= cmd
;
1295 CString currentBranch
;
1296 bool hasBranch
= CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
) == 0;
1297 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1301 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1302 if (gitPath
.HasSubmodules())
1304 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1307 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1308 RunTortoiseGitProc(sCmd
);
1312 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ Merge(¤tBranch
); });
1316 if (!CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, newBranch
))
1317 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
1319 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []{
1320 CTGitPathList pathlist
;
1321 CTGitPathList selectedlist
;
1322 pathlist
.AddPath(CTGitPath());
1323 bool bSelectFilesForCommit
= !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE
));
1325 Commit(CString(), false, str
, pathlist
, selectedlist
, bSelectFilesForCommit
);
1330 if (bMerge
&& g_Git
.HasWorkingTreeConflicts() > 0)
1332 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
1335 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1336 CAppUtils::RunTortoiseGitProc(sCmd
);
1339 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, bMerge
); });
1341 postCmdList
.emplace_back(IDI_SWITCH
, IDS_SWITCH_WITH_MERGE
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, true); });
1344 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
& extraMsg
)
1346 if (bMerge
&& !exitCode
&& g_Git
.HasWorkingTreeConflicts() > 0)
1348 exitCode
= 1; // Treat it as failure
1349 extraMsg
= _T("Has merge conflict");
1353 INT_PTR ret
= progress
.DoModal();
1358 class CIgnoreFile
: public CStdioFile
1361 STRING_VECTOR m_Items
;
1364 virtual BOOL
ReadString(CString
& rString
)
1366 if (GetPosition() == 0)
1368 unsigned char utf8bom
[] = { 0xEF, 0xBB, 0xBF };
1369 char buf
[3] = { 0, 0, 0 };
1371 if (memcpy(buf
, utf8bom
, sizeof(utf8bom
)))
1376 char lastChar
= '\0';
1377 for (char c
= '\0'; Read(&c
, 1) == 1; lastChar
= c
)
1383 m_eol
= lastChar
== '\r' ? _T("\r\n") : _T("\n");
1391 rString
= CUnicodeUtils::GetUnicode(strA
);
1402 bool CAppUtils::OpenIgnoreFile(CIgnoreFile
&file
, const CString
& filename
)
1405 if (!file
.Open(filename
, CFile::modeCreate
| CFile::modeReadWrite
| CFile::modeNoTruncate
| CFile::typeBinary
))
1407 CMessageBox::Show(nullptr, filename
+ _T(" Open Failure"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1411 if (file
.GetLength() > 0)
1414 while (file
.ReadString(fileText
))
1415 file
.m_Items
.push_back(fileText
);
1416 file
.Seek(file
.GetLength() - 1, 0);
1417 char lastchar
[1] = { 0 };
1418 file
.Read(lastchar
, 1);
1420 if (lastchar
[0] != '\n')
1422 CStringA eol
= CStringA(file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
);
1423 file
.Write(eol
, eol
.GetLength());
1432 bool CAppUtils::IgnoreFile(const CTGitPathList
& path
,bool IsMask
)
1434 CIgnoreDlg ignoreDlg
;
1435 if (ignoreDlg
.DoModal() == IDOK
)
1438 ignorefile
= g_Git
.m_CurrentDir
+ _T("\\");
1440 switch (ignoreDlg
.m_IgnoreFile
)
1443 ignorefile
+= _T(".gitignore");
1446 GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, ignorefile
);
1447 ignorefile
+= _T("info");
1448 if (!PathFileExists(ignorefile
))
1449 CreateDirectory(ignorefile
, nullptr);
1450 ignorefile
+= _T("\\exclude");
1457 if (ignoreDlg
.m_IgnoreFile
!= 1 && !OpenIgnoreFile(file
, ignorefile
))
1460 for (int i
= 0; i
< path
.GetCount(); ++i
)
1462 if (ignoreDlg
.m_IgnoreFile
== 1)
1464 ignorefile
= g_Git
.CombinePath(path
[i
].GetContainingDirectory()) + _T("\\.gitignore");
1465 if (!OpenIgnoreFile(file
, ignorefile
))
1469 CString ignorePattern
;
1470 if (ignoreDlg
.m_IgnoreType
== 0)
1472 if (ignoreDlg
.m_IgnoreFile
!= 1 && !path
[i
].GetContainingDirectory().GetGitPathString().IsEmpty())
1473 ignorePattern
+= _T("/") + path
[i
].GetContainingDirectory().GetGitPathString();
1475 ignorePattern
+= _T("/");
1478 ignorePattern
+= _T("*") + path
[i
].GetFileExtension();
1480 ignorePattern
+= path
[i
].GetFileOrDirectoryName();
1482 // escape [ and ] so that files get ignored correctly
1483 ignorePattern
.Replace(_T("["), _T("\\["));
1484 ignorePattern
.Replace(_T("]"), _T("\\]"));
1487 for (size_t j
= 0; j
< file
.m_Items
.size(); ++j
)
1489 if (file
.m_Items
[j
] == ignorePattern
)
1497 file
.m_Items
.push_back(ignorePattern
);
1498 ignorePattern
+= file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
;
1499 CStringA ignorePatternA
= CUnicodeUtils::GetUTF8(ignorePattern
);
1500 file
.Write(ignorePatternA
, ignorePatternA
.GetLength());
1503 if (ignoreDlg
.m_IgnoreFile
== 1)
1507 if (ignoreDlg
.m_IgnoreFile
!= 1)
1521 static bool Reset(const CString
& resetTo
, int resetType
)
1528 type
= _T("--soft");
1531 type
= _T("--mixed");
1534 type
= _T("--hard");
1538 type
= _T("--mixed");
1541 cmd
.Format(_T("git.exe reset %s %s --"), (LPCTSTR
)type
, (LPCTSTR
)resetTo
);
1543 CProgressDlg progress
;
1544 progress
.m_GitCmd
= cmd
;
1546 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1550 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ Reset(resetTo
, resetType
); });
1554 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1555 if (gitPath
.HasSubmodules() && resetType
== 2)
1557 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1560 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1561 CAppUtils::RunTortoiseGitProc(sCmd
);
1567 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_RESET
))
1569 CGitProgressDlg gitdlg
;
1570 ResetProgressCommand resetProgressCommand
;
1571 gitdlg
.SetCommand(&resetProgressCommand
);
1572 resetProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
1573 resetProgressCommand
.SetRevision(resetTo
);
1574 resetProgressCommand
.SetResetType(resetType
);
1575 ret
= gitdlg
.DoModal();
1578 ret
= progress
.DoModal();
1583 bool CAppUtils::GitReset(const CString
* CommitHash
, int type
)
1586 dlg
.m_ResetType
=type
;
1587 dlg
.m_ResetToVersion
=*CommitHash
;
1588 dlg
.m_initialRefName
= *CommitHash
;
1589 if (dlg
.DoModal() == IDOK
)
1590 return Reset(dlg
.m_ResetToVersion
, dlg
.m_ResetType
);
1595 void CAppUtils::DescribeConflictFile(bool mode
, bool base
,CString
&descript
)
1599 descript
.LoadString(IDS_SVNACTION_DELETE
);
1604 descript
.LoadString(IDS_SVNACTION_MODIFIED
);
1607 descript
.LoadString(IDS_PROC_CREATED
);
1610 void CAppUtils::RemoveTempMergeFile(const CTGitPath
& path
)
1612 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path
));
1613 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path
));
1614 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path
));
1616 CString
CAppUtils::GetMergeTempFile(const CString
& type
, const CTGitPath
&merge
)
1619 file
= g_Git
.CombinePath(merge
.GetWinPathString() + _T(".") + type
+ merge
.GetFileExtension());
1624 bool ParseHashesFromLsFile(const BYTE_VECTOR
& out
, CString
& hash1
, CString
& hash2
, CString
& hash3
)
1630 while (pos
>= 0 && pos
< (int)out
.size())
1634 CGit::StringAppend(&one
, &out
[pos
], CP_UTF8
);
1636 one
.Tokenize(_T("\t"), tabstart
);
1639 part
= one
.Tokenize(_T(" "), tabstart
); //Tag
1640 part
= one
.Tokenize(_T(" "), tabstart
); //Mode
1641 part
= one
.Tokenize(_T(" "), tabstart
); //Hash
1642 CString hash
= part
;
1643 part
= one
.Tokenize(_T("\t"), tabstart
); //Stage
1644 int stage
= _ttol(part
);
1647 else if (stage
== 2)
1649 else if (stage
== 3)
1655 pos
= out
.findNextString(pos
);
1661 bool CAppUtils::ConflictEdit(const CTGitPath
& path
, bool bAlternativeTool
/*= false*/, bool revertTheirMy
/*= false*/, HWND resolveMsgHwnd
/*= nullptr*/)
1665 CTGitPath merge
=path
;
1666 CTGitPath directory
= merge
.GetDirectory();
1668 // we have the conflicted file (%merged)
1669 // now look for the other required files
1671 //stat.GetStatus(merge);
1672 //if (stat.status == nullptr)
1678 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1680 if (g_Git
.Run(cmd
, &vector
))
1683 if (merge
.IsDirectory())
1685 CString baseHash
, realBaseHash(GIT_REV_ZERO
), localHash(GIT_REV_ZERO
), remoteHash(GIT_REV_ZERO
);
1686 if (merge
.HasAdminDir()) {
1688 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1690 subgit
.GetHash(hash
, _T("HEAD"));
1693 if (ParseHashesFromLsFile(vector
, realBaseHash
, localHash
, remoteHash
)) // in base no submodule, but in remote submodule
1694 baseHash
= realBaseHash
;
1696 CGitDiff::ChangeType changeTypeMine
= CGitDiff::Unknown
;
1697 CGitDiff::ChangeType changeTypeTheirs
= CGitDiff::Unknown
;
1699 bool baseOK
= false, mineOK
= false, theirsOK
= false;
1700 CString baseSubject
, mineSubject
, theirsSubject
;
1701 if (merge
.HasAdminDir())
1704 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1705 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, localHash
, baseOK
, mineOK
, changeTypeMine
, baseSubject
, mineSubject
);
1706 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, remoteHash
, baseOK
, theirsOK
, changeTypeTheirs
, baseSubject
, theirsSubject
);
1708 else if (baseHash
== GIT_REV_ZERO
&& localHash
== GIT_REV_ZERO
&& remoteHash
!= GIT_REV_ZERO
) // merge conflict with no submodule, but submodule in merged revision (not initialized)
1710 changeTypeMine
= CGitDiff::Identical
;
1711 changeTypeTheirs
= CGitDiff::NewSubmodule
;
1712 baseSubject
= _T("no submodule");
1713 mineSubject
= baseSubject
;
1714 theirsSubject
= _T("not initialized");
1716 else if (baseHash
.IsEmpty() && localHash
!= GIT_REV_ZERO
&& remoteHash
== GIT_REV_ZERO
) // merge conflict with no submodule initialized, but submodule exists in base and folder with no submodule is merged
1718 baseHash
= localHash
;
1719 baseSubject
= _T("not initialized");
1720 mineSubject
= baseSubject
;
1721 theirsSubject
= _T("not initialized");
1722 changeTypeMine
= CGitDiff::Identical
;
1723 changeTypeTheirs
= CGitDiff::DeleteSubmodule
;
1725 else if (baseHash
!= GIT_REV_ZERO
&& localHash
!= GIT_REV_ZERO
&& remoteHash
!= GIT_REV_ZERO
) // base has submodule, mine has submodule and theirs also, but not initialized
1727 baseSubject
= _T("not initialized");
1728 mineSubject
= baseSubject
;
1729 theirsSubject
= baseSubject
;
1730 if (baseHash
== localHash
)
1731 changeTypeMine
= CGitDiff::Identical
;
1736 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog
;
1737 resolveSubmoduleConflictDialog
.SetDiff(merge
.GetGitPathString(), revertTheirMy
, baseHash
, baseSubject
, baseOK
, localHash
, mineSubject
, mineOK
, changeTypeMine
, remoteHash
, theirsSubject
, theirsOK
, changeTypeTheirs
);
1738 resolveSubmoduleConflictDialog
.DoModal();
1739 if (resolveSubmoduleConflictDialog
.m_bResolved
&& resolveMsgHwnd
)
1741 static UINT WM_REVERTMSG
= RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1742 ::PostMessage(resolveMsgHwnd
, WM_REVERTMSG
, NULL
, NULL
);
1749 if (list
.ParserFromLsFile(vector
))
1751 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1764 mine
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1765 theirs
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1769 mine
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1770 theirs
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1772 base
.SetFromGit(GetMergeTempFile(_T("BASE"),merge
));
1776 //format=_T("git.exe cat-file blob \":%d:%s\"");
1777 format
= _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1779 //create a empty file, incase stage is not three
1780 tempfile
.Open(mine
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1782 tempfile
.Open(theirs
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1784 tempfile
.Open(base
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1787 bool b_base
=false, b_local
=false, b_remote
=false;
1789 for (int i
= 0; i
< list
.GetCount(); ++i
)
1795 if( list
[i
].m_Stage
== 1)
1797 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1799 outfile
= base
.GetWinPathString();
1802 if( list
[i
].m_Stage
== 2 )
1804 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1806 outfile
= mine
.GetWinPathString();
1809 if( list
[i
].m_Stage
== 3 )
1811 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1813 outfile
= theirs
.GetWinPathString();
1815 CString output
, err
;
1816 if(!outfile
.IsEmpty())
1817 if (!g_Git
.Run(cmd
, &output
, &err
, CP_UTF8
))
1821 file
= output
.Tokenize(_T("\t"), start
);
1822 ::MoveFileEx(file
,outfile
,MOVEFILE_REPLACE_EXISTING
|MOVEFILE_COPY_ALLOWED
);
1825 CMessageBox::Show(nullptr, output
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1828 if(b_local
&& b_remote
)
1830 merge
.SetFromWin(g_Git
.CombinePath(merge
));
1832 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, mine
, theirs
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1834 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, theirs
, mine
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1838 ::DeleteFile(mine
.GetWinPathString());
1839 ::DeleteFile(theirs
.GetWinPathString());
1840 ::DeleteFile(base
.GetWinPathString());
1842 CDeleteConflictDlg dlg
;
1843 DescribeConflictFile(b_local
, b_base
,dlg
.m_LocalStatus
);
1844 DescribeConflictFile(b_remote
,b_base
,dlg
.m_RemoteStatus
);
1845 CGitHash localHash
, remoteHash
;
1846 if (!g_Git
.GetHash(localHash
, _T("HEAD")))
1847 dlg
.m_LocalHash
= localHash
.ToString();
1848 if (!g_Git
.GetHash(remoteHash
, _T("MERGE_HEAD")))
1849 dlg
.m_RemoteHash
= remoteHash
.ToString();
1850 else if (!g_Git
.GetHash(remoteHash
, _T("rebase-apply/original-commit")))
1851 dlg
.m_RemoteHash
= remoteHash
.ToString();
1852 else if (!g_Git
.GetHash(remoteHash
, _T("CHERRY_PICK_HEAD")))
1853 dlg
.m_RemoteHash
= remoteHash
.ToString();
1854 else if (!g_Git
.GetHash(remoteHash
, _T("REVERT_HEAD")))
1855 dlg
.m_RemoteHash
= remoteHash
.ToString();
1856 dlg
.m_bShowModifiedButton
=b_base
;
1857 dlg
.m_File
=merge
.GetGitPathString();
1858 if(dlg
.DoModal() == IDOK
)
1862 cmd
.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1864 cmd
.Format(_T("git.exe add -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1866 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1868 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1878 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1879 base
, theirs
, mine
, merge
);
1882 if (stat
.status
->text_status
== svn_wc_status_conflicted
)
1884 // we have a text conflict, use our merge tool to resolve the conflict
1886 CTSVNPath
theirs(directory
);
1887 CTSVNPath
mine(directory
);
1888 CTSVNPath
base(directory
);
1889 bool bConflictData
= false;
1891 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_new
))
1893 theirs
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_new
));
1894 bConflictData
= true;
1896 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_old
))
1898 base
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_old
));
1899 bConflictData
= true;
1901 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_wrk
))
1903 mine
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_wrk
));
1904 bConflictData
= true;
1909 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1910 base
, theirs
, mine
, merge
);
1913 if (stat
.status
->prop_status
== svn_wc_status_conflicted
)
1915 // we have a property conflict
1916 CTSVNPath
prej(directory
);
1917 if ((stat
.status
->entry
)&&(stat
.status
->entry
->prejfile
))
1919 prej
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->prejfile
));
1920 // there's a problem: the prej file contains a _description_ of the conflict, and
1921 // that description string might be translated. That means we have no way of parsing
1922 // the file to find out the conflicting values.
1923 // The only thing we can do: show a dialog with the conflict description, then
1924 // let the user either accept the existing property or open the property edit dialog
1925 // to manually change the properties and values. And a button to mark the conflict as
1927 CEditPropConflictDlg dlg
;
1928 dlg
.SetPrejFile(prej
);
1929 dlg
.SetConflictedItem(merge
);
1930 bRet
= (dlg
.DoModal() != IDCANCEL
);
1934 if (stat
.status
->tree_conflict
)
1936 // we have a tree conflict
1938 const SVNInfoData
* pInfoData
= info
.GetFirstFileInfo(merge
, SVNRev(), SVNRev());
1941 if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_text
)
1943 CTSVNPath
theirs(directory
);
1944 CTSVNPath
mine(directory
);
1945 CTSVNPath
base(directory
);
1946 bool bConflictData
= false;
1948 if (pInfoData
->treeconflict_theirfile
)
1950 theirs
.AppendPathString(pInfoData
->treeconflict_theirfile
);
1951 bConflictData
= true;
1953 if (pInfoData
->treeconflict_basefile
)
1955 base
.AppendPathString(pInfoData
->treeconflict_basefile
);
1956 bConflictData
= true;
1958 if (pInfoData
->treeconflict_myfile
)
1960 mine
.AppendPathString(pInfoData
->treeconflict_myfile
);
1961 bConflictData
= true;
1966 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1967 base
, theirs
, mine
, merge
);
1969 else if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_tree
)
1971 CString sConflictAction
;
1972 CString sConflictReason
;
1973 CString sResolveTheirs
;
1974 CString sResolveMine
;
1975 CTSVNPath treeConflictPath
= CTSVNPath(pInfoData
->treeconflict_path
);
1976 CString sItemName
= treeConflictPath
.GetUIFileOrDirectoryName();
1978 if (pInfoData
->treeconflict_nodekind
== svn_node_file
)
1980 switch (pInfoData
->treeconflict_operation
)
1982 case svn_wc_operation_update
:
1983 switch (pInfoData
->treeconflict_action
)
1985 case svn_wc_conflict_action_edit
:
1986 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEEDIT
, (LPCTSTR
)sItemName
);
1987 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1989 case svn_wc_conflict_action_add
:
1990 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEADD
, (LPCTSTR
)sItemName
);
1991 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1993 case svn_wc_conflict_action_delete
:
1994 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEDELETE
, (LPCTSTR
)sItemName
);
1995 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
1999 case svn_wc_operation_switch
:
2000 switch (pInfoData
->treeconflict_action
)
2002 case svn_wc_conflict_action_edit
:
2003 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHEDIT
, (LPCTSTR
)sItemName
);
2004 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2006 case svn_wc_conflict_action_add
:
2007 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHADD
, (LPCTSTR
)sItemName
);
2008 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2010 case svn_wc_conflict_action_delete
:
2011 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHDELETE
, (LPCTSTR
)sItemName
);
2012 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2016 case svn_wc_operation_merge
:
2017 switch (pInfoData
->treeconflict_action
)
2019 case svn_wc_conflict_action_edit
:
2020 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEEDIT
, (LPCTSTR
)sItemName
);
2021 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2023 case svn_wc_conflict_action_add
:
2024 sResolveTheirs
.Format(IDS_TREECONFLICT_FILEMERGEADD
, (LPCTSTR
)sItemName
);
2025 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2027 case svn_wc_conflict_action_delete
:
2028 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEDELETE
, (LPCTSTR
)sItemName
);
2029 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2035 else if (pInfoData
->treeconflict_nodekind
== svn_node_dir
)
2037 switch (pInfoData
->treeconflict_operation
)
2039 case svn_wc_operation_update
:
2040 switch (pInfoData
->treeconflict_action
)
2042 case svn_wc_conflict_action_edit
:
2043 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEEDIT
, (LPCTSTR
)sItemName
);
2044 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2046 case svn_wc_conflict_action_add
:
2047 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEADD
, (LPCTSTR
)sItemName
);
2048 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2050 case svn_wc_conflict_action_delete
:
2051 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEDELETE
, (LPCTSTR
)sItemName
);
2052 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2056 case svn_wc_operation_switch
:
2057 switch (pInfoData
->treeconflict_action
)
2059 case svn_wc_conflict_action_edit
:
2060 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHEDIT
, (LPCTSTR
)sItemName
);
2061 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2063 case svn_wc_conflict_action_add
:
2064 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHADD
, (LPCTSTR
)sItemName
);
2065 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2067 case svn_wc_conflict_action_delete
:
2068 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHDELETE
, (LPCTSTR
)sItemName
);
2069 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2073 case svn_wc_operation_merge
:
2074 switch (pInfoData
->treeconflict_action
)
2076 case svn_wc_conflict_action_edit
:
2077 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEEDIT
, (LPCTSTR
)sItemName
);
2078 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2080 case svn_wc_conflict_action_add
:
2081 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEADD
, (LPCTSTR
)sItemName
);
2082 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2084 case svn_wc_conflict_action_delete
:
2085 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEDELETE
, (LPCTSTR
)sItemName
);
2086 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2094 switch (pInfoData
->treeconflict_reason
)
2096 case svn_wc_conflict_reason_edited
:
2097 uReasonID
= IDS_TREECONFLICT_REASON_EDITED
;
2098 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2100 case svn_wc_conflict_reason_obstructed
:
2101 uReasonID
= IDS_TREECONFLICT_REASON_OBSTRUCTED
;
2102 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2104 case svn_wc_conflict_reason_deleted
:
2105 uReasonID
= IDS_TREECONFLICT_REASON_DELETED
;
2106 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2108 case svn_wc_conflict_reason_added
:
2109 uReasonID
= IDS_TREECONFLICT_REASON_ADDED
;
2110 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2112 case svn_wc_conflict_reason_missing
:
2113 uReasonID
= IDS_TREECONFLICT_REASON_MISSING
;
2114 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2116 case svn_wc_conflict_reason_unversioned
:
2117 uReasonID
= IDS_TREECONFLICT_REASON_UNVERSIONED
;
2118 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2121 sConflictReason
.Format(uReasonID
, (LPCTSTR
)sConflictAction
);
2123 CTreeConflictEditorDlg dlg
;
2124 dlg
.SetConflictInfoText(sConflictReason
);
2125 dlg
.SetResolveTexts(sResolveTheirs
, sResolveMine
);
2126 dlg
.SetPath(treeConflictPath
);
2127 INT_PTR dlgRet
= dlg
.DoModal();
2128 bRet
= (dlgRet
!= IDCANCEL
);
2136 bool CAppUtils::IsSSHPutty()
2138 CString sshclient
=g_Git
.m_Environment
.GetEnv(_T("GIT_SSH"));
2139 sshclient
=sshclient
.MakeLower();
2140 if(sshclient
.Find(_T("plink.exe"),0)>=0)
2145 CString
CAppUtils::GetClipboardLink(const CString
&skipGitPrefix
, int paramsCount
)
2147 if (!OpenClipboard(nullptr))
2150 CString sClipboardText
;
2151 HGLOBAL hglb
= GetClipboardData(CF_TEXT
);
2154 LPCSTR lpstr
= (LPCSTR
)GlobalLock(hglb
);
2155 sClipboardText
= CString(lpstr
);
2158 hglb
= GetClipboardData(CF_UNICODETEXT
);
2161 LPCTSTR lpstr
= (LPCTSTR
)GlobalLock(hglb
);
2162 sClipboardText
= lpstr
;
2167 if(!sClipboardText
.IsEmpty())
2169 if(sClipboardText
[0] == _T('\"') && sClipboardText
[sClipboardText
.GetLength()-1] == _T('\"'))
2170 sClipboardText
=sClipboardText
.Mid(1,sClipboardText
.GetLength()-2);
2172 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ssh://", L
"git@" })
2174 if (CStringUtils::StartsWith(sClipboardText
, prefix
) && sClipboardText
.GetLength() != prefix
.GetLength())
2175 return sClipboardText
;
2178 if(sClipboardText
.GetLength()>=2)
2179 if( sClipboardText
[1] == _T(':') )
2180 if( (sClipboardText
[0] >= 'A' && sClipboardText
[0] <= 'Z')
2181 || (sClipboardText
[0] >= 'a' && sClipboardText
[0] <= 'z') )
2182 return sClipboardText
;
2184 // trim prefixes like "git clone "
2185 if (!skipGitPrefix
.IsEmpty() && CStringUtils::StartsWith(sClipboardText
, skipGitPrefix
))
2187 sClipboardText
= sClipboardText
.Mid(skipGitPrefix
.GetLength()).Trim();
2189 while (paramsCount
>= 0)
2192 spacePos
= sClipboardText
.Find(_T(' '), spacePos
+ 1);
2196 if (spacePos
> 0 && paramsCount
< 0)
2197 sClipboardText
= sClipboardText
.Left(spacePos
);
2198 return sClipboardText
;
2205 CString
CAppUtils::ChooseRepository(const CString
* path
)
2207 CBrowseFolder browseFolder
;
2208 CRegString regLastResopitory
= CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2210 browseFolder
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
2211 CString strCloneDirectory
;
2213 strCloneDirectory
=*path
;
2215 strCloneDirectory
= regLastResopitory
;
2218 title
.LoadString(IDS_CHOOSE_REPOSITORY
);
2220 browseFolder
.SetInfo(title
);
2222 if (browseFolder
.Show(nullptr, strCloneDirectory
) == CBrowseFolder::OK
)
2224 regLastResopitory
= strCloneDirectory
;
2225 return strCloneDirectory
;
2231 bool CAppUtils::SendPatchMail(CTGitPathList
& list
, bool bIsMainWnd
)
2235 dlg
.m_PathList
= list
;
2237 if(dlg
.DoModal()==IDOK
)
2239 if (dlg
.m_PathList
.IsEmpty())
2242 CGitProgressDlg progDlg
;
2244 theApp
.m_pMainWnd
= &progDlg
;
2245 SendMailProgressCommand sendMailProgressCommand
;
2246 progDlg
.SetCommand(&sendMailProgressCommand
);
2248 sendMailProgressCommand
.SetPathList(dlg
.m_PathList
);
2249 progDlg
.SetItemCount(dlg
.m_PathList
.GetCount());
2251 CSendMailPatch
sendMailPatch(dlg
.m_To
, dlg
.m_CC
, dlg
.m_Subject
, !!dlg
.m_bAttachment
, !!dlg
.m_bCombine
);
2252 sendMailProgressCommand
.SetSendMailOption(&sendMailPatch
);
2261 bool CAppUtils::SendPatchMail(const CString
& cmd
, const CString
& formatpatchoutput
, bool bIsMainWnd
)
2264 CString log
=formatpatchoutput
;
2265 int start
=log
.Find(cmd
);
2267 CString one
=log
.Tokenize(_T("\n"),start
);
2273 CString one
=log
.Tokenize(_T("\n"),start
);
2275 if (one
.IsEmpty() || one
.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS
))) == 0)
2277 one
.Replace(_T('/'),_T('\\'));
2279 path
.SetFromWin(one
);
2282 if (!list
.IsEmpty())
2283 return SendPatchMail(list
, bIsMainWnd
);
2286 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES
, IDS_APPNAME
, MB_ICONINFORMATION
);
2292 int CAppUtils::GetLogOutputEncode(CGit
*pGit
)
2295 output
= pGit
->GetConfigValue(_T("i18n.logOutputEncoding"));
2296 if(output
.IsEmpty())
2297 return CUnicodeUtils::GetCPCode(pGit
->GetConfigValue(_T("i18n.commitencoding")));
2299 return CUnicodeUtils::GetCPCode(output
);
2301 int CAppUtils::SaveCommitUnicodeFile(const CString
& filename
, CString
&message
)
2305 CFile
file(filename
, CFile::modeReadWrite
| CFile::modeCreate
);
2306 int cp
= CUnicodeUtils::GetCPCode(g_Git
.GetConfigValue(_T("i18n.commitencoding")));
2308 bool stripComments
= (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE
) == TRUE
);
2309 TCHAR commentChar
= L
'#';
2312 CString commentCharValue
= g_Git
.GetConfigValue(L
"core.commentchar");
2313 if (!commentCharValue
.IsEmpty())
2314 commentChar
= commentCharValue
[0];
2317 bool sanitize
= (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE
) == TRUE
);
2319 message
.Trim(L
" \r\n");
2321 int len
= message
.GetLength();
2323 int emptyLineCnt
= 0;
2324 while (start
>= 0 && start
< len
)
2326 int oldStart
= start
;
2327 start
= message
.Find(L
"\n", oldStart
);
2328 CString line
= message
.Mid(oldStart
);
2331 line
= line
.Left(start
- oldStart
);
2332 ++start
; // move forward so we don't find the same char again
2334 if (stripComments
&& (!line
.IsEmpty() && line
.GetAt(0) == commentChar
) || (start
< 0 && line
.IsEmpty()))
2336 line
.TrimRight(L
" \r");
2344 if (emptyLineCnt
) // squash multiple newlines
2345 file
.Write("\n", 1);
2348 CStringA lineA
= CUnicodeUtils::GetMulti(line
+ L
"\n", cp
);
2349 file
.Write((LPCSTR
)lineA
, lineA
.GetLength());
2354 catch (CFileException
*e
)
2361 bool CAppUtils::Pull(bool showPush
, bool showStashPop
)
2363 if (IsTGitRebaseActive())
2367 dlg
.m_IsPull
= TRUE
;
2368 if (dlg
.DoModal() == IDOK
)
2370 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2372 return DoFetch(dlg
.m_RemoteURL
,
2373 FALSE
, // Fetch all remotes
2374 dlg
.m_bAutoLoad
== BST_CHECKED
,
2376 dlg
.m_bDepth
== BST_CHECKED
,
2379 dlg
.m_RemoteBranchName
,
2380 dlg
.m_bRebaseActivatedInConfigForPull
? 2 : 1, // Rebase after fetching
2381 dlg
.m_bRebasePreserveMerges
== TRUE
); // Preserve merges on rebase
2383 CString url
= dlg
.m_RemoteURL
;
2385 if (dlg
.m_bAutoLoad
)
2386 CAppUtils::LaunchPAgent(nullptr, &dlg
.m_RemoteURL
);
2390 if (g_Git
.GetHash(hashOld
, _T("HEAD")))
2392 MessageBox(nullptr, g_Git
.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR
);
2404 if (!dlg
.m_bFetchTags
)
2405 notags
= _T("--no-tags ");
2407 if (dlg
.m_bFetchTags
== TRUE
)
2408 notags
= _T("--tags ");
2411 noff
=_T("--no-ff ");
2414 ffonly
= _T("--ff-only ");
2417 squash
= _T("--squash ");
2419 if (dlg
.m_bNoCommit
)
2420 nocommit
= _T("--no-commit ");
2423 depth
.Format(_T("--depth %d "), dlg
.m_nDepth
);
2425 if (dlg
.m_bPrune
== TRUE
)
2426 prune
= _T("--prune ");
2427 else if (dlg
.m_bPrune
== FALSE
)
2428 prune
= _T("--no-prune ");
2430 cmd
.Format(_T("git.exe pull --progress%s -v %s%s%s%s%s%s%s\"%s\" %s"), CRegDWORD(L
"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE
) == FALSE
? L
" --no-rebase" : L
"", (LPCTSTR
)noff
, (LPCTSTR
)ffonly
, (LPCTSTR
)squash
, (LPCTSTR
)nocommit
, (LPCTSTR
)depth
, (LPCTSTR
)notags
, (LPCTSTR
)prune
, (LPCTSTR
)url
, (LPCTSTR
)dlg
.m_RemoteBranchName
);
2431 CProgressDlg progress
;
2432 progress
.m_GitCmd
= cmd
;
2434 CGitHash hashNew
; // declare outside lambda, because it is captured by reference
2435 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2439 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
2440 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ StashSave(_T(""), true); });
2445 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ StashPop(); });
2447 if (g_Git
.GetHash(hashNew
, _T("HEAD")))
2448 MessageBox(nullptr, g_Git
.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR
);
2451 postCmdList
.emplace_back(IDI_DIFF
, IDS_PROC_PULL_DIFFS
, [&]
2454 dlg
.SetDiff(nullptr, hashOld
.ToString(), hashNew
.ToString());
2457 postCmdList
.emplace_back(IDI_LOG
, IDS_PROC_PULL_LOG
, [&]
2460 dlg
.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld
.ToString() + _T("..") + hashNew
.ToString(), 0);
2466 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ Push(); });
2468 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
2469 if (gitPath
.HasSubmodules())
2471 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
2474 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
2475 CAppUtils::RunTortoiseGitProc(sCmd
);
2480 INT_PTR ret
= progress
.DoModal();
2482 if (ret
== IDOK
&& progress
.m_GitStatus
== 1 && progress
.m_LogText
.Find(_T("CONFLICT")) >= 0 && CMessageBox::Show(nullptr, IDS_SEECHANGES
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
2484 CChangedDlg changeddlg
;
2485 changeddlg
.m_pathList
.AddPath(CTGitPath());
2486 changeddlg
.DoModal();
2497 bool CAppUtils::RebaseAfterFetch(const CString
& upstream
, int rebase
, bool preserveMerges
)
2502 if (!upstream
.IsEmpty())
2503 dlg
.m_Upstream
= upstream
;
2504 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENULOG
)));
2505 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH
)));
2506 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL
)));
2507 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE
)));
2508 dlg
.m_bRebaseAutoStart
= (rebase
== 2);
2509 dlg
.m_bPreserveMerges
= preserveMerges
;
2510 INT_PTR response
= dlg
.DoModal();
2511 if (response
== IDOK
)
2513 else if (response
== IDC_REBASE_POST_BUTTON
)
2515 CString cmd
= _T("/command:log");
2516 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2517 CAppUtils::RunTortoiseGitProc(cmd
);
2520 else if (response
== IDC_REBASE_POST_BUTTON
+ 1)
2522 else if (response
== IDC_REBASE_POST_BUTTON
+ 2)
2524 CString cmd
, out
, err
;
2525 cmd
.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2526 (LPCTSTR
)g_Git
.m_CurrentDir
,
2527 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Upstream
),
2528 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Branch
));
2529 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
2531 CMessageBox::Show(nullptr, out
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2534 CAppUtils::SendPatchMail(cmd
, out
);
2537 else if (response
== IDC_REBASE_POST_BUTTON
+ 3)
2539 else if (response
== IDCANCEL
)
2545 static bool DoFetch(const CString
& url
, const bool fetchAllRemotes
, const bool loadPuttyAgent
, const int prune
, const bool bDepth
, const int nDepth
, const int fetchTags
, const CString
& remoteBranch
, int runRebase
, const bool rebasePreserveMerges
)
2549 if (fetchAllRemotes
)
2552 g_Git
.GetRemoteList(list
);
2554 for (const auto& remote
: list
)
2555 CAppUtils::LaunchPAgent(nullptr, &remote
);
2558 CAppUtils::LaunchPAgent(nullptr, &url
);
2561 CString upstream
= _T("FETCH_HEAD");
2562 CGitHash oldUpstreamHash
;
2566 g_Git
.GetRemoteList(list
);
2567 for (auto it
= list
.cbegin(); it
!= list
.cend(); ++it
)
2571 CString remote
, trackedBranch
;
2572 g_Git
.GetRemoteTrackedBranchForHEAD(remote
, trackedBranch
);
2573 if (!remote
.IsEmpty() && !trackedBranch
.IsEmpty())
2575 upstream
= L
"remotes/" + remote
+ L
"/" + trackedBranch
;
2576 g_Git
.GetHash(oldUpstreamHash
, upstream
);
2584 arg
= _T(" --progress");
2587 arg
.AppendFormat(_T(" --depth %d"), nDepth
);
2590 arg
+= _T(" --prune");
2591 else if (prune
== FALSE
)
2592 arg
+= _T(" --no-prune");
2595 arg
+= _T(" --tags");
2596 else if (fetchTags
== 0)
2597 arg
+= _T(" --no-tags");
2599 if (fetchAllRemotes
)
2600 cmd
.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR
)arg
);
2602 cmd
.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR
)arg
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranch
);
2604 CProgressDlg progress
;
2605 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2609 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ DoFetch(url
, fetchAllRemotes
, loadPuttyAgent
, prune
, bDepth
, nDepth
, fetchTags
, remoteBranch
, runRebase
, rebasePreserveMerges
); });
2613 postCmdList
.emplace_back(IDI_LOG
, IDS_MENULOG
, []
2615 CString cmd
= _T("/command:log");
2616 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2617 CAppUtils::RunTortoiseGitProc(cmd
);
2620 postCmdList
.emplace_back(IDI_REVERT
, IDS_PROC_RESET
, []
2622 CString pullRemote
, pullBranch
;
2623 g_Git
.GetRemoteTrackedBranchForHEAD(pullRemote
, pullBranch
);
2624 CString defaultUpstream
;
2625 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2626 defaultUpstream
.Format(_T("remotes/%s/%s"), (LPCTSTR
)pullRemote
, (LPCTSTR
)pullBranch
);
2627 CAppUtils::GitReset(&defaultUpstream
, 2);
2630 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, []{ CAppUtils::Fetch(); });
2632 if (!runRebase
&& !GitAdminDir::IsBareRepo(g_Git
.m_CurrentDir
))
2633 postCmdList
.emplace_back(IDI_REBASE
, IDS_MENUREBASE
, [&]{ runRebase
= false; CAppUtils::RebaseAfterFetch(); });
2636 progress
.m_GitCmd
= cmd
;
2638 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_FETCH
))
2640 CGitProgressDlg gitdlg
;
2641 FetchProgressCommand fetchProgressCommand
;
2642 if (!fetchAllRemotes
)
2643 fetchProgressCommand
.SetUrl(url
);
2644 gitdlg
.SetCommand(&fetchProgressCommand
);
2645 fetchProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
2646 fetchProgressCommand
.SetAutoTag(fetchTags
== 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL
: fetchTags
== 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO
: GIT_REMOTE_DOWNLOAD_TAGS_NONE
);
2647 if (!fetchAllRemotes
)
2648 fetchProgressCommand
.SetRefSpec(remoteBranch
);
2649 return gitdlg
.DoModal() == IDOK
;
2652 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
&)
2654 if (exitCode
|| !runRebase
)
2657 CGitHash remoteBranchHash
;
2658 g_Git
.GetHash(remoteBranchHash
, upstream
);
2659 if (runRebase
== 1 && remoteBranchHash
== oldUpstreamHash
&& !oldUpstreamHash
.IsEmpty() && CMessageBox::ShowCheck(nullptr, IDS_REBASE_BRANCH_UNCHANGED
, IDS_APPNAME
, MB_ICONQUESTION
| MB_YESNO
| MB_DEFBUTTON2
, L
"OpenRebaseRemoteBranchUnchanged", IDS_MSGBOX_DONOTSHOWAGAIN
) == IDNO
)
2662 if (runRebase
== 1 && g_Git
.IsFastForward(L
"HEAD", upstream
))
2664 UINT ret
= CMessageBox::ShowCheck(nullptr, IDS_REBASE_BRANCH_FF
, IDS_APPNAME
, 2, IDI_QUESTION
, IDS_MERGEBUTTON
, IDS_REBASEBUTTON
, IDS_ABORTBUTTON
, L
"OpenRebaseRemoteBranchFastForwards", IDS_MSGBOX_DONOTSHOWAGAIN
);
2669 CProgressDlg mergeProgress
;
2670 mergeProgress
.m_GitCmd
= L
"git.exe merge --ff-only " + upstream
;
2671 mergeProgress
.m_AutoClose
= AUTOCLOSE_IF_NO_ERRORS
;
2672 mergeProgress
.m_PostCmdCallback
= [](DWORD status
, PostCmdList
& postCmdList
)
2674 if (status
&& g_Git
.HasWorkingTreeConflicts())
2676 // there are conflict files
2677 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
2680 sCmd
.Format(L
"/command:commit /path:\"%s\"", g_Git
.m_CurrentDir
);
2681 CAppUtils::RunTortoiseGitProc(sCmd
);
2685 mergeProgress
.DoModal();
2690 CAppUtils::RebaseAfterFetch(upstream
, runRebase
, rebasePreserveMerges
);
2693 return progress
.DoModal() == IDOK
;
2696 bool CAppUtils::Fetch(const CString
& remoteName
, bool allRemotes
)
2699 dlg
.m_PreSelectRemote
= remoteName
;
2701 dlg
.m_bAllRemotes
= allRemotes
;
2703 if(dlg
.DoModal()==IDOK
)
2704 return DoFetch(dlg
.m_RemoteURL
, dlg
.m_bAllRemotes
== BST_CHECKED
, dlg
.m_bAutoLoad
== BST_CHECKED
, dlg
.m_bPrune
, dlg
.m_bDepth
== BST_CHECKED
, dlg
.m_nDepth
, dlg
.m_bFetchTags
, dlg
.m_RemoteBranchName
, dlg
.m_bRebase
== BST_CHECKED
? 1 : 0, FALSE
);
2709 bool CAppUtils::DoPush(bool autoloadKey
, bool pack
, bool tags
, bool allRemotes
, bool allBranches
, bool force
, bool forceWithLease
, const CString
& localBranch
, const CString
& remote
, const CString
& remoteBranch
, bool setUpstream
, int recurseSubmodules
)
2712 DWORD exitcode
= 0xFFFFFFFF;
2713 if (CHooks::Instance().PrePush(g_Git
.m_CurrentDir
, exitcode
, error
))
2718 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2719 CMessageBox::Show(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2724 int iRecurseSubmodules
= 0;
2725 if (GetMsysgitVersion() >= 0x02070000)
2727 CString sRecurseSubmodules
= g_Git
.GetConfigValue(_T("push.recurseSubmodules"));
2728 if (sRecurseSubmodules
== _T("check"))
2729 iRecurseSubmodules
= 1;
2730 else if (sRecurseSubmodules
== _T("on-demand"))
2731 iRecurseSubmodules
= 2;
2736 arg
+= _T("--thin ");
2737 if (tags
&& !allBranches
)
2738 arg
+= _T("--tags ");
2740 arg
+= _T("--force ");
2742 arg
+= _T("--force-with-lease ");
2744 arg
+= _T("--set-upstream ");
2745 if (recurseSubmodules
== 0 && recurseSubmodules
!= iRecurseSubmodules
)
2746 arg
+= _T("--recurse-submodules=no ");
2747 if (recurseSubmodules
== 1 && recurseSubmodules
!= iRecurseSubmodules
)
2748 arg
+= _T("--recurse-submodules=check ");
2749 if (recurseSubmodules
== 2 && recurseSubmodules
!= iRecurseSubmodules
)
2750 arg
+= _T("--recurse-submodules=on-demand ");
2752 arg
+= _T("--progress ");
2754 CProgressDlg progress
;
2756 STRING_VECTOR remotesList
;
2758 g_Git
.GetRemoteList(remotesList
);
2760 remotesList
.push_back(remote
);
2762 for (unsigned int i
= 0; i
< remotesList
.size(); ++i
)
2765 CAppUtils::LaunchPAgent(nullptr, &remotesList
[i
]);
2770 cmd
.Format(_T("git.exe push --all %s\"%s\""),
2772 (LPCTSTR
)remotesList
[i
]);
2776 progress
.m_GitCmdList
.push_back(cmd
);
2777 cmd
.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR
)arg
, (LPCTSTR
)remotesList
[i
]);
2782 cmd
.Format(_T("git.exe push %s\"%s\" %s"),
2784 (LPCTSTR
)remotesList
[i
],
2785 (LPCTSTR
)localBranch
);
2786 if (!remoteBranch
.IsEmpty())
2789 cmd
+= remoteBranch
;
2792 progress
.m_GitCmdList
.push_back(cmd
);
2794 if (!allBranches
&& !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE
))
2796 cmd
.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR
)localBranch
);
2797 progress
.m_GitCmdList
.push_back(cmd
);
2801 CString superprojectRoot
;
2802 GitAdminDir::HasAdminDir(g_Git
.m_CurrentDir
, false, &superprojectRoot
);
2803 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2805 // need to execute hooks as those might be needed by post action commands
2806 DWORD exitcode
= 0xFFFFFFFF;
2808 if (CHooks::Instance().PostPush(g_Git
.m_CurrentDir
, exitcode
, error
))
2813 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2814 MessageBox(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2820 bool rejected
= progress
.GetLogText().Find(_T("! [rejected]")) > 0;
2823 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, []{ Pull(true); });
2824 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, [&]{ Fetch(allRemotes
? _T("") : remote
, allRemotes
); });
2826 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2830 postCmdList
.emplace_back(IDS_PROC_REQUESTPULL
, [&]{ RequestPull(remoteBranch
); });
2831 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2832 postCmdList
.emplace_back(IDI_SWITCH
, IDS_MENUSWITCH
, [&]{ Switch(); });
2833 if (!superprojectRoot
.IsEmpty())
2835 postCmdList
.emplace_back(IDI_COMMIT
, IDS_PROC_COMMIT_SUPERPROJECT
, [&]
2838 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)superprojectRoot
);
2839 RunTortoiseGitProc(sCmd
);
2844 INT_PTR ret
= progress
.DoModal();
2848 bool CAppUtils::Push(const CString
& selectLocalBranch
)
2851 dlg
.m_BranchSourceName
= selectLocalBranch
;
2853 if (dlg
.DoModal() == IDOK
)
2854 return DoPush(!!dlg
.m_bAutoLoad
, !!dlg
.m_bPack
, !!dlg
.m_bTags
, !!dlg
.m_bPushAllRemotes
, !!dlg
.m_bPushAllBranches
, !!dlg
.m_bForce
, !!dlg
.m_bForceWithLease
, dlg
.m_BranchSourceName
, dlg
.m_URL
, dlg
.m_BranchRemoteName
, !!dlg
.m_bSetUpstream
, dlg
.m_RecurseSubmodules
);
2859 bool CAppUtils::RequestPull(const CString
& endrevision
, const CString
& repositoryUrl
, bool bIsMainWnd
)
2861 CRequestPullDlg dlg
;
2862 dlg
.m_RepositoryURL
= repositoryUrl
;
2863 dlg
.m_EndRevision
= endrevision
;
2864 if (dlg
.DoModal()==IDOK
)
2867 cmd
.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR
)dlg
.m_StartRevision
, (LPCTSTR
)dlg
.m_RepositoryURL
, (LPCTSTR
)dlg
.m_EndRevision
);
2869 CSysProgressDlg sysProgressDlg
;
2870 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
2871 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST
)));
2872 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
2873 sysProgressDlg
.SetShowProgressBar(false);
2874 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
2876 CString tempFileName
= GetTempFile();
2878 DeleteFile(tempFileName
);
2879 CreateDirectory(tempFileName
, nullptr);
2880 tempFileName
+= _T("\\pullrequest.txt");
2881 if (g_Git
.RunLogFile(cmd
, tempFileName
, &err
))
2884 msg
.LoadString(IDS_ERR_PULLREUQESTFAILED
);
2885 MessageBox(nullptr, msg
+ _T("\n") + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2889 if (sysProgressDlg
.HasUserCancelled())
2891 CMessageBox::Show(nullptr, IDS_USERCANCELLED
, IDS_APPNAME
, MB_OK
);
2892 ::DeleteFile(tempFileName
);
2896 sysProgressDlg
.Stop();
2898 if (dlg
.m_bSendMail
)
2900 CSendMailDlg sendmaildlg
;
2901 sendmaildlg
.m_PathList
= CTGitPathList(CTGitPath(tempFileName
));
2902 sendmaildlg
.m_bCustomSubject
= true;
2904 if (sendmaildlg
.DoModal() == IDOK
)
2906 if (sendmaildlg
.m_PathList
.IsEmpty())
2909 CGitProgressDlg progDlg
;
2911 theApp
.m_pMainWnd
= &progDlg
;
2912 SendMailProgressCommand sendMailProgressCommand
;
2913 progDlg
.SetCommand(&sendMailProgressCommand
);
2915 sendMailProgressCommand
.SetPathList(sendmaildlg
.m_PathList
);
2916 progDlg
.SetItemCount(sendmaildlg
.m_PathList
.GetCount());
2918 CSendMailCombineable
sendMailCombineable(sendmaildlg
.m_To
, sendmaildlg
.m_CC
, sendmaildlg
.m_Subject
, !!sendmaildlg
.m_bAttachment
, !!sendmaildlg
.m_bCombine
);
2919 sendMailProgressCommand
.SetSendMailOption(&sendMailCombineable
);
2928 CAppUtils::LaunchAlternativeEditor(tempFileName
);
2933 void CAppUtils::RemoveTrailSlash(CString
&path
)
2938 // For URL, do not trim the slash just after the host name component.
2939 int index
= path
.Find(_T("://"));
2943 index
= path
.Find(_T('/'), index
);
2944 if (index
== path
.GetLength() - 1)
2948 while(path
[path
.GetLength()-1] == _T('\\') || path
[path
.GetLength()-1] == _T('/' ) )
2950 path
=path
.Left(path
.GetLength()-1);
2956 bool CAppUtils::CheckUserData()
2958 while(g_Git
.GetUserName().IsEmpty() || g_Git
.GetUserEmail().IsEmpty())
2960 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA
, IDS_APPNAME
, MB_YESNO
| MB_ICONERROR
) == IDYES
)
2962 CTGitPath
path(g_Git
.m_CurrentDir
);
2963 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
,&path
);
2964 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
2965 dlg
.SetTreeWidth(220);
2966 dlg
.m_DefaultPage
= _T("gitconfig");
2969 dlg
.HandleRestart();
2979 BOOL
CAppUtils::Commit(const CString
& bugid
, BOOL bWholeProject
, CString
&sLogMsg
,
2980 CTGitPathList
&pathList
,
2981 CTGitPathList
&selectedList
,
2982 bool bSelectFilesForCommit
)
2984 bool bFailed
= true;
2986 if (!CheckUserData())
2993 dlg
.m_sBugID
= bugid
;
2995 dlg
.m_bWholeProject
= bWholeProject
;
2997 dlg
.m_sLogMessage
= sLogMsg
;
2998 dlg
.m_pathList
= pathList
;
2999 dlg
.m_checkedPathList
= selectedList
;
3000 dlg
.m_bSelectFilesForCommit
= bSelectFilesForCommit
;
3001 if (dlg
.DoModal() == IDOK
)
3003 if (dlg
.m_pathList
.IsEmpty())
3005 // if the user hasn't changed the list of selected items
3006 // we don't use that list. Because if we would use the list
3007 // of pre-checked items, the dialog would show different
3008 // checked items on the next startup: it would only try
3009 // to check the parent folder (which might not even show)
3010 // instead, we simply use an empty list and let the
3011 // default checking do its job.
3012 if (!dlg
.m_pathList
.IsEqual(pathList
))
3013 selectedList
= dlg
.m_pathList
;
3014 pathList
= dlg
.m_updatedPathList
;
3015 sLogMsg
= dlg
.m_sLogMessage
;
3016 bSelectFilesForCommit
= true;
3018 switch (dlg
.m_PostCmd
)
3020 case GIT_POSTCOMMIT_CMD_DCOMMIT
:
3021 CAppUtils::SVNDCommit();
3023 case GIT_POSTCOMMIT_CMD_PUSH
:
3026 case GIT_POSTCOMMIT_CMD_CREATETAG
:
3027 CAppUtils::CreateBranchTag(TRUE
);
3029 case GIT_POSTCOMMIT_CMD_PULL
:
3030 CAppUtils::Pull(true);
3036 // CGitProgressDlg progDlg;
3037 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3038 // if (parser.HasVal(_T("closeonend")))
3039 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3040 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3041 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3042 // progDlg.SetPathList(dlg.m_pathList);
3043 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3044 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3045 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3046 // progDlg.SetItemCount(dlg.m_itemsCount);
3047 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3048 // progDlg.DoModal();
3049 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3050 // err = (DWORD)progDlg.DidErrorsOccur();
3051 // bFailed = progDlg.DidErrorsOccur();
3052 // bRet = progDlg.DidErrorsOccur();
3053 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3054 // if (DWORD(bFailRepeat)==0)
3055 // bFailed = false; // do not repeat if the user chose not to in the settings.
3061 BOOL
CAppUtils::SVNDCommit()
3063 CSVNDCommitDlg dcommitdlg
;
3064 CString gitSetting
= g_Git
.GetConfigValue(_T("svn.rmdir"));
3065 if (gitSetting
.IsEmpty()) {
3066 if (dcommitdlg
.DoModal() != IDOK
)
3070 if (dcommitdlg
.m_remember
)
3072 if (dcommitdlg
.m_rmdir
)
3073 gitSetting
= _T("true");
3075 gitSetting
= _T("false");
3076 if(g_Git
.SetConfigValue(_T("svn.rmdir"),gitSetting
))
3079 msg
.Format(IDS_PROC_SAVECONFIGFAILED
, _T("svn.rmdir"), gitSetting
);
3080 CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3086 BOOL IsStash
= false;
3087 if(!g_Git
.CheckCleanWorkTree())
3089 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3091 CSysProgressDlg sysProgressDlg
;
3092 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3093 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3094 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3095 sysProgressDlg
.SetShowProgressBar(false);
3096 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3097 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3100 cmd
=_T("git.exe stash");
3101 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3103 sysProgressDlg
.Stop();
3104 MessageBox(nullptr, out
,_T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3107 sysProgressDlg
.Stop();
3115 CProgressDlg progress
;
3116 if (dcommitdlg
.m_rmdir
)
3117 progress
.m_GitCmd
=_T("git.exe svn dcommit --rmdir");
3119 progress
.m_GitCmd
=_T("git.exe svn dcommit");
3120 if(progress
.DoModal()==IDOK
&& progress
.m_GitStatus
== 0)
3124 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
3126 CSysProgressDlg sysProgressDlg
;
3127 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3128 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3129 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3130 sysProgressDlg
.SetShowProgressBar(false);
3131 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3132 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3135 cmd
=_T("git.exe stash pop");
3136 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3138 sysProgressDlg
.Stop();
3139 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3142 sysProgressDlg
.Stop();
3152 BOOL
CAppUtils::Merge(const CString
* commit
, bool showStashPop
)
3154 if (!CheckUserData())
3157 if (IsTGitRebaseActive())
3162 dlg
.m_initialRefName
= *commit
;
3164 if(dlg
.DoModal()==IDOK
)
3170 args
+= _T(" --no-ff");
3171 else if (dlg
.m_bFFonly
)
3172 args
+= _T(" --ff-only");
3175 args
+= _T(" --squash");
3178 args
+= _T(" --no-commit");
3181 args
.AppendFormat(L
" --log=%d", dlg
.m_nLog
);
3183 if (!dlg
.m_MergeStrategy
.IsEmpty())
3185 args
+= _T(" --strategy=") + dlg
.m_MergeStrategy
;
3186 if (!dlg
.m_StrategyOption
.IsEmpty())
3188 args
+= _T(" --strategy-option=") + dlg
.m_StrategyOption
;
3189 if (!dlg
.m_StrategyParam
.IsEmpty())
3190 args
+= _T("=") + dlg
.m_StrategyParam
;
3194 if(!dlg
.m_strLogMesage
.IsEmpty())
3196 CString logmsg
= dlg
.m_strLogMesage
;
3197 logmsg
.Replace(_T("\\\""), _T("\\\\\""));
3198 logmsg
.Replace(_T("\""), _T("\\\""));
3199 args
+= _T(" -m \"") + logmsg
+ _T("\"");
3201 cmd
.Format(_T("git.exe merge%s %s"), (LPCTSTR
)args
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
3203 CProgressDlg Prodlg
;
3204 Prodlg
.m_GitCmd
= cmd
;
3206 Prodlg
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3210 int hasConflicts
= g_Git
.HasWorkingTreeConflicts();
3211 if (hasConflicts
< 0)
3212 CMessageBox::Show(nullptr, g_Git
.GetGitLastErr(L
"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS
), _T("TortoiseGit"), MB_ICONEXCLAMATION
);
3213 else if (hasConflicts
)
3215 // there are conflict files
3217 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
3220 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3221 CAppUtils::RunTortoiseGitProc(sCmd
);
3225 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ CAppUtils::StashSave(_T(""), false, false, true, g_Git
.FixBranchName(dlg
.m_VersionName
)); });
3230 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ StashPop(); });
3232 if (dlg
.m_bNoCommit
)
3234 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []
3237 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3238 CAppUtils::RunTortoiseGitProc(sCmd
);
3243 if (dlg
.m_bIsBranch
&& dlg
.m_VersionName
.Find(L
"remotes/") == -1) // do not ask to remove remote branches
3245 postCmdList
.emplace_back(IDI_DELETE
, IDS_PROC_REMOVEBRANCH
, [&]
3248 msg
.Format(IDS_PROC_DELETEBRANCHTAG
, dlg
.m_VersionName
);
3249 if (CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), 2, IDI_QUESTION
, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON
)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON
))) == 1)
3252 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)dlg
.m_VersionName
);
3253 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3254 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
);
3258 if (dlg
.m_bIsBranch
)
3259 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ Push(); });
3261 BOOL hasGitSVN
= CTGitPath(g_Git
.m_CurrentDir
).GetAdminDirMask() & ITEMIS_GITSVN
;
3263 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSVNDCOMMIT
, []{ SVNDCommit(); });
3267 return !Prodlg
.m_GitStatus
;
3272 BOOL
CAppUtils::MergeAbort()
3275 if (dlg
.DoModal() == IDOK
)
3276 return Reset(_T("HEAD"), dlg
.m_ResetType
+ 1);
3281 void CAppUtils::EditNote(GitRevLoglist
* rev
)
3283 if (!CheckUserData())
3287 dlg
.m_sHintText
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3288 dlg
.m_sInputText
= rev
->m_Notes
;
3289 dlg
.m_sTitle
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3290 //dlg.m_pProjectProperties = &m_ProjectProperties;
3291 dlg
.m_bUseLogWidth
= true;
3292 if(dlg
.DoModal() == IDOK
)
3295 cmd
=_T("notes add -f -F \"");
3297 CString tempfile
=::GetTempFile();
3298 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_sInputText
))
3300 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3305 cmd
+= rev
->m_CommitHash
.ToString();
3309 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd
, CP_UTF8
).GetBuffer()))
3310 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3312 rev
->m_Notes
= dlg
.m_sInputText
;
3315 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3317 ::DeleteFile(tempfile
);
3322 int CAppUtils::GetMsysgitVersion()
3324 if (g_Git
.ms_LastMsysGitVersion
)
3325 return g_Git
.ms_LastMsysGitVersion
;
3328 CString versiondebug
;
3331 CRegDWORD regTime
= CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3332 CRegDWORD regVersion
= CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3334 CString gitpath
= CGit::ms_LastMsysGitDir
+_T("\\git.exe");
3337 if (!CGit::GetFileModifyTime(gitpath
, &time
))
3339 if((DWORD
)time
== regTime
)
3341 g_Git
.ms_LastMsysGitVersion
= regVersion
;
3347 int ver
= g_Git
.GetGitVersion(&versiondebug
, &err
);
3350 CMessageBox::Show(nullptr, _T("git.exe not correctly set up (") + err
+ _T(")\nCheck TortoiseGit settings and consult help file for \"Git.exe Path\"."), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3357 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug
+ _T("\""), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3362 regTime
= time
&0xFFFFFFFF;
3364 g_Git
.ms_LastMsysGitVersion
= ver
;
3369 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd
)
3371 typedef HRESULT (WINAPI
*SHGPSFW
) (HWND hwnd
,REFIID riid
,void** ppv
);
3373 CAutoLibrary hShell
= AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3375 if (hShell
.IsValid()) {
3376 SHGPSFW pfnSHGPSFW
= (SHGPSFW
)::GetProcAddress(hShell
, "SHGetPropertyStoreForWindow");
3378 IPropertyStore
*pps
;
3379 HRESULT hr
= pfnSHGPSFW(hWnd
, IID_PPV_ARGS(&pps
));
3380 if (SUCCEEDED(hr
)) {
3383 var
.boolVal
= VARIANT_TRUE
;
3384 pps
->SetValue(PKEY_AppUserModel_PreventPinning
, var
);
3391 void CAppUtils::SetWindowTitle(HWND hWnd
, const CString
& urlorpath
, const CString
& dialogname
)
3393 ASSERT(dialogname
.GetLength() < 70);
3394 ASSERT(urlorpath
.GetLength() < MAX_PATH
);
3395 WCHAR pathbuf
[MAX_PATH
] = {0};
3397 PathCompactPathEx(pathbuf
, urlorpath
, 70 - dialogname
.GetLength(), 0);
3399 wcscat_s(pathbuf
, L
" - ");
3400 wcscat_s(pathbuf
, dialogname
);
3401 wcscat_s(pathbuf
, L
" - ");
3402 wcscat_s(pathbuf
, CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3403 SetWindowText(hWnd
, pathbuf
);
3406 bool CAppUtils::BisectStart(const CString
& lastGood
, const CString
& firstBad
, bool bIsMainWnd
)
3408 if (!g_Git
.CheckCleanWorkTree())
3410 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3412 CSysProgressDlg sysProgressDlg
;
3413 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3414 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3415 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3416 sysProgressDlg
.SetShowProgressBar(false);
3417 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3418 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3421 cmd
= _T("git.exe stash");
3422 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3424 sysProgressDlg
.Stop();
3425 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3428 sysProgressDlg
.Stop();
3434 CBisectStartDlg bisectStartDlg
;
3436 if (!lastGood
.IsEmpty())
3437 bisectStartDlg
.m_sLastGood
= lastGood
;
3438 if (!firstBad
.IsEmpty())
3439 bisectStartDlg
.m_sFirstBad
= firstBad
;
3441 if (bisectStartDlg
.DoModal() == IDOK
)
3443 CProgressDlg progress
;
3445 theApp
.m_pMainWnd
= &progress
;
3446 progress
.m_GitCmdList
.push_back(_T("git.exe bisect start"));
3447 progress
.m_GitCmdList
.push_back(_T("git.exe bisect good ") + bisectStartDlg
.m_LastGoodRevision
);
3448 progress
.m_GitCmdList
.push_back(_T("git.exe bisect bad ") + bisectStartDlg
.m_FirstBadRevision
);
3450 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3455 CTGitPath
path(g_Git
.m_CurrentDir
);
3456 if (path
.HasSubmodules())
3458 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3461 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3462 CAppUtils::RunTortoiseGitProc(sCmd
);
3467 INT_PTR ret
= progress
.DoModal();
3474 bool CAppUtils::BisectOperation(const CString
& op
, const CString
& ref
, bool bIsMainWnd
)
3476 CString cmd
= _T("git.exe bisect ") + op
;
3484 CProgressDlg progress
;
3486 theApp
.m_pMainWnd
= &progress
;
3487 progress
.m_GitCmd
= cmd
;
3489 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3494 CTGitPath path
= g_Git
.m_CurrentDir
;
3495 if (path
.HasSubmodules())
3497 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3500 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3501 CAppUtils::RunTortoiseGitProc(sCmd
);
3505 if (op
!= _T("reset"))
3506 postCmdList
.emplace_back(IDS_MENUBISECTRESET
, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3509 INT_PTR ret
= progress
.DoModal();
3513 int CAppUtils::Git2GetUserPassword(git_cred
**out
, const char *url
, const char *username_from_url
, unsigned int /*allowed_types*/, void * /*payload*/)
3516 dlg
.m_URL
= CUnicodeUtils::GetUnicode(url
, CP_UTF8
);
3517 if (username_from_url
)
3518 dlg
.m_UserName
= CUnicodeUtils::GetUnicode(username_from_url
, CP_UTF8
);
3520 CStringA username
, password
;
3521 if (dlg
.DoModal() == IDOK
)
3523 username
= CUnicodeUtils::GetMulti(dlg
.m_UserName
, CP_UTF8
);
3524 password
= CUnicodeUtils::GetMulti(dlg
.m_Password
, CP_UTF8
);
3525 return git_cred_userpass_plaintext_new(out
, username
, password
);
3527 giterr_set_str(GITERR_NONE
, "User cancelled.");
3531 int CAppUtils::Git2CertificateCheck(git_cert
* base_cert
, int /*valid*/, const char* host
, void* /*payload*/)
3533 if (base_cert
->cert_type
== GIT_CERT_X509
)
3535 git_cert_x509
* cert
= (git_cert_x509
*)base_cert
;
3537 if (last_accepted_cert
.cmp(cert
))
3540 PCCERT_CONTEXT pServerCert
= CertCreateCertificateContext(X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, (BYTE
*)cert
->data
, (DWORD
)cert
->len
);
3541 SCOPE_EXIT
{ CertFreeCertificateContext(pServerCert
); };
3543 DWORD verificationError
= VerifyServerCertificate(pServerCert
, CUnicodeUtils::GetUnicode(host
).GetBuffer(), 0);
3544 if (!verificationError
)
3546 last_accepted_cert
.set(cert
);
3550 CString servernameInCert
;
3551 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, 0, nullptr, CStrBuf(servernameInCert
, 128), 128);
3554 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, CERT_NAME_ISSUER_FLAG
, nullptr, CStrBuf(issuer
, 128), 128);
3556 CCheckCertificateDlg dlg
;
3558 dlg
.m_sCertificateCN
= servernameInCert
;
3559 dlg
.m_sCertificateIssuer
= issuer
;
3560 dlg
.m_sHostname
= CUnicodeUtils::GetUnicode(host
);
3561 dlg
.m_sError
= CFormatMessageWrapper(verificationError
);
3562 if (dlg
.DoModal() == IDOK
)
3564 last_accepted_cert
.set(cert
);
3568 return GIT_ECERTIFICATE
;
3571 int CAppUtils::ExploreTo(HWND hwnd
, CString path
)
3573 if (PathFileExists(path
))
3576 ITEMIDLIST __unaligned
* pidl
= ILCreateFromPath(path
);
3579 ret
= SHOpenFolderAndSelectItems(pidl
, 0, 0, 0);
3582 return SUCCEEDED(ret
) ? 0 : -1;
3584 // if filepath does not exist any more, navigate to closest matching folder
3587 int pos
= path
.ReverseFind(_T('\\'));
3590 path
= path
.Left(pos
);
3591 } while (!PathFileExists(path
));
3592 return (INT_PTR
)ShellExecute(hwnd
, _T("explore"), path
, nullptr, nullptr, SW_SHOW
) > 32 ? 0 : -1;
3595 int CAppUtils::ResolveConflict(CTGitPath
& path
, resolve_with resolveWith
)
3597 bool b_local
= false, b_remote
= false;
3601 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3602 if (g_Git
.Run(cmd
, &vector
))
3604 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3609 if (list
.ParserFromLsFile(vector
))
3611 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3617 for (int i
= 0; i
< list
.GetCount(); ++i
)
3619 if (list
[i
].m_Stage
== 2)
3621 if (list
[i
].m_Stage
== 3)
3626 CBlockCacheForPath
block(g_Git
.m_CurrentDir
);
3627 if (path
.IsDirectory()) // is submodule conflict
3629 CString err
= _T("We're sorry, but you hit a very rare conflict condition with a submodule which cannot be resolved by TortoiseGit. You have to use the command line git for this.");
3630 if (b_local
&& b_remote
)
3632 if (!path
.HasAdminDir()) // check if submodule is initialized
3634 err
+= _T("\n\nYou have to checkout the submodule manually into \"") + path
.GetGitPathString() + _T("\" and then reset HEAD to the right commit (see resolve submodule conflict dialog for this).");
3635 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3639 subgit
.m_CurrentDir
= g_Git
.CombinePath(path
);
3640 CGitHash submoduleHead
;
3641 if (subgit
.GetHash(submoduleHead
, _T("HEAD")))
3643 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3646 CString baseHash
, localHash
, remoteHash
;
3647 ParseHashesFromLsFile(vector
, baseHash
, localHash
, remoteHash
);
3648 if (resolveWith
== RESOLVE_WITH_THEIRS
&& submoduleHead
.ToString() != remoteHash
)
3650 CString origPath
= g_Git
.m_CurrentDir
;
3651 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3652 if (!GitReset(&remoteHash
))
3654 g_Git
.m_CurrentDir
= origPath
;
3657 g_Git
.m_CurrentDir
= origPath
;
3659 else if (resolveWith
== RESOLVE_WITH_MINE
&& submoduleHead
.ToString() != localHash
)
3661 CString origPath
= g_Git
.m_CurrentDir
;
3662 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3663 if (!GitReset(&localHash
))
3665 g_Git
.m_CurrentDir
= origPath
;
3668 g_Git
.m_CurrentDir
= origPath
;
3673 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3678 if (resolveWith
== RESOLVE_WITH_THEIRS
)
3680 CString gitcmd
, output
;
3681 if (b_local
&& b_remote
)
3682 gitcmd
.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3684 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3686 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3687 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3689 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3693 else if (resolveWith
== RESOLVE_WITH_MINE
)
3695 CString gitcmd
, output
;
3696 if (b_local
&& b_remote
)
3697 gitcmd
.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3699 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3701 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3702 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3704 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3709 if (b_local
&& b_remote
&& path
.m_Action
& CTGitPath::LOGACTIONS_UNMERGED
)
3711 CString gitcmd
, output
;
3712 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3713 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3714 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3717 path
.m_Action
|= CTGitPath::LOGACTIONS_MODIFIED
;
3718 path
.m_Action
&= ~CTGitPath::LOGACTIONS_UNMERGED
;
3722 RemoveTempMergeFile(path
);
3726 bool CAppUtils::ShellOpen(const CString
& file
, HWND hwnd
/*= nullptr */)
3728 if ((INT_PTR
)ShellExecute(hwnd
, nullptr, file
, nullptr, nullptr, SW_SHOW
) > HINSTANCE_ERROR
)
3731 return ShowOpenWithDialog(file
, hwnd
);
3734 bool CAppUtils::ShowOpenWithDialog(const CString
& file
, HWND hwnd
/*= nullptr */)
3736 OPENASINFO oi
= { 0 };
3738 oi
.oaifInFlags
= OAIF_EXEC
;
3739 return SUCCEEDED(SHOpenWithDialog(hwnd
, &oi
));
3742 bool CAppUtils::IsTGitRebaseActive()
3745 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3748 if (!PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3751 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND
, IDS_APPNAME
, 2, IDI_EXCLAMATION
, IDS_REMOVESTALEBUTTON
, IDS_ABORTBUTTON
) == 2)
3754 RemoveDirectory(adminDir
+ L
"tgitrebase.active");