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 bool CAppUtils::StashSave(const CString
& msg
, bool showPull
, bool pullShowPush
, bool showMerge
, const CString
& mergeRev
)
111 dlg
.m_sMessage
= msg
;
112 if (dlg
.DoModal() == IDOK
)
115 cmd
= _T("git.exe stash save");
117 if (dlg
.m_bIncludeUntracked
)
118 cmd
+= L
" --include-untracked";
122 if (!dlg
.m_sMessage
.IsEmpty())
124 CString message
= dlg
.m_sMessage
;
125 message
.Replace(_T("\""), _T("\"\""));
126 cmd
+= _T(" -- \"") + message
+ _T("\"");
129 CProgressDlg progress
;
130 progress
.m_GitCmd
= cmd
;
131 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
137 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(pullShowPush
, true); });
139 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ CAppUtils::Merge(&mergeRev
, true); });
141 return (progress
.DoModal() == IDOK
);
146 bool CAppUtils::StashApply(CString ref
, bool showChanges
/* true */)
149 cmd
= _T("git.exe stash apply ");
150 if (CStringUtils::StartsWith(ref
, L
"refs/"))
152 if (CStringUtils::StartsWith(ref
, L
"stash{"))
153 ref
= _T("stash@") + ref
.Mid(5);
156 CSysProgressDlg sysProgressDlg
;
157 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
158 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
159 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
160 sysProgressDlg
.SetShowProgressBar(false);
161 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
162 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
164 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
166 sysProgressDlg
.Stop();
168 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
169 if (ret
&& !(ret
== 1 && hasConflicts
))
170 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
174 message
.LoadString(IDS_PROC_STASHAPPLYSUCCESS
);
176 message
.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS
);
179 if (CMessageBox::Show(nullptr, message
+ _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES
)), _T("TortoiseGit"), MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
182 dlg
.m_pathList
.AddPath(CTGitPath());
189 CMessageBox::Show(nullptr, message
,_T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
196 bool CAppUtils::StashPop(int showChanges
/* = 1 */)
199 cmd
=_T("git.exe stash pop ");
201 CSysProgressDlg sysProgressDlg
;
202 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
203 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
204 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
205 sysProgressDlg
.SetShowProgressBar(false);
206 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
207 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
209 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
211 sysProgressDlg
.Stop();
213 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
214 if (ret
&& !(ret
== 1 && hasConflicts
))
215 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
219 message
.LoadString(IDS_PROC_STASHPOPSUCCESS
);
221 message
.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS
);
222 if (showChanges
== 1 || (showChanges
== 0 && hasConflicts
))
224 if (CMessageBox::ShowCheck(nullptr, message
+ L
'\n' + CString(MAKEINTRESOURCE(IDS_SEECHANGES
)), L
"TortoiseGit", MB_YESNO
| (hasConflicts
? MB_ICONEXCLAMATION
: MB_ICONINFORMATION
), hasConflicts
? L
"StashPopShowConflictChanges" : L
"StashPopShowChanges") == IDYES
)
227 dlg
.m_pathList
.AddPath(CTGitPath());
232 else if (showChanges
> 1)
234 CMessageBox::Show(nullptr, message
, _T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
237 else if (showChanges
== 0)
243 BOOL
CAppUtils::StartExtMerge(bool bAlternative
,
244 const CTGitPath
& basefile
, const CTGitPath
& theirfile
, const CTGitPath
& yourfile
, const CTGitPath
& mergedfile
,
245 const CString
& basename
, const CString
& theirname
, const CString
& yourname
, const CString
& mergedname
, bool bReadOnly
,
246 HWND resolveMsgHwnd
, bool bDeleteBaseTheirsMineOnClose
)
248 CRegString regCom
= CRegString(_T("Software\\TortoiseGit\\Merge"));
249 CString ext
= mergedfile
.GetFileExtension();
250 CString com
= regCom
;
251 bool bInternal
= false;
255 // is there an extension specific merge tool?
256 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext
.MakeLower());
257 if (!CString(mergetool
).IsEmpty())
260 // is there a filename specific merge tool?
261 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile
.GetFilename().MakeLower());
262 if (!CString(mergetool
).IsEmpty())
265 if (bAlternative
&& !com
.IsEmpty())
267 if (CStringUtils::StartsWith(com
, L
"#"))
273 if (com
.IsEmpty() || CStringUtils::StartsWith(com
, L
"#"))
275 // Maybe we should use TortoiseIDiff?
276 if ((ext
== _T(".jpg")) || (ext
== _T(".jpeg")) ||
277 (ext
== _T(".bmp")) || (ext
== _T(".gif")) ||
278 (ext
== _T(".png")) || (ext
== _T(".ico")) ||
279 (ext
== _T(".tif")) || (ext
== _T(".tiff")) ||
280 (ext
== _T(".dib")) || (ext
== _T(".emf")) ||
283 com
= CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe");
284 com
= _T("\"") + com
+ _T("\"");
285 com
= com
+ _T(" /base:%base /theirs:%theirs /mine:%mine /result:%merged");
286 com
= com
+ _T(" /basetitle:%bname /theirstitle:%tname /minetitle:%yname");
288 com
.AppendFormat(L
" /resolvemsghwnd:%I64d", (__int64
)resolveMsgHwnd
);
292 // use TortoiseGitMerge
294 com
= CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe");
295 com
= _T("\"") + com
+ _T("\"");
296 com
= com
+ _T(" /base:%base /theirs:%theirs /mine:%mine /merged:%merged");
297 com
= com
+ _T(" /basename:%bname /theirsname:%tname /minename:%yname /mergedname:%mname");
298 com
+= _T(" /saverequired");
300 com
.AppendFormat(L
" /resolvemsghwnd:%I64d", (__int64
)resolveMsgHwnd
);
301 if (bDeleteBaseTheirsMineOnClose
)
302 com
+= _T(" /deletebasetheirsmineonclose");
304 if (!g_sGroupingUUID
.IsEmpty())
306 com
+= L
" /groupuuid:\"";
307 com
+= g_sGroupingUUID
;
311 // check if the params are set. If not, just add the files to the command line
312 if ((com
.Find(_T("%merged"))<0)&&(com
.Find(_T("%base"))<0)&&(com
.Find(_T("%theirs"))<0)&&(com
.Find(_T("%mine"))<0))
314 com
+= _T(" \"")+basefile
.GetWinPathString()+_T("\"");
315 com
+= _T(" \"")+theirfile
.GetWinPathString()+_T("\"");
316 com
+= _T(" \"")+yourfile
.GetWinPathString()+_T("\"");
317 com
+= _T(" \"")+mergedfile
.GetWinPathString()+_T("\"");
319 if (basefile
.IsEmpty())
321 com
.Replace(_T("/base:%base"), _T(""));
322 com
.Replace(_T("%base"), _T(""));
325 com
.Replace(_T("%base"), _T("\"") + basefile
.GetWinPathString() + _T("\""));
326 if (theirfile
.IsEmpty())
328 com
.Replace(_T("/theirs:%theirs"), _T(""));
329 com
.Replace(_T("%theirs"), _T(""));
332 com
.Replace(_T("%theirs"), _T("\"") + theirfile
.GetWinPathString() + _T("\""));
333 if (yourfile
.IsEmpty())
335 com
.Replace(_T("/mine:%mine"), _T(""));
336 com
.Replace(_T("%mine"), _T(""));
339 com
.Replace(_T("%mine"), _T("\"") + yourfile
.GetWinPathString() + _T("\""));
340 if (mergedfile
.IsEmpty())
342 com
.Replace(_T("/merged:%merged"), _T(""));
343 com
.Replace(_T("%merged"), _T(""));
346 com
.Replace(_T("%merged"), _T("\"") + mergedfile
.GetWinPathString() + _T("\""));
347 if (basename
.IsEmpty())
349 if (basefile
.IsEmpty())
351 com
.Replace(_T("/basename:%bname"), _T(""));
352 com
.Replace(_T("%bname"), _T(""));
355 com
.Replace(_T("%bname"), _T("\"") + basefile
.GetUIFileOrDirectoryName() + _T("\""));
358 com
.Replace(_T("%bname"), _T("\"") + basename
+ _T("\""));
359 if (theirname
.IsEmpty())
361 if (theirfile
.IsEmpty())
363 com
.Replace(_T("/theirsname:%tname"), _T(""));
364 com
.Replace(_T("%tname"), _T(""));
367 com
.Replace(_T("%tname"), _T("\"") + theirfile
.GetUIFileOrDirectoryName() + _T("\""));
370 com
.Replace(_T("%tname"), _T("\"") + theirname
+ _T("\""));
371 if (yourname
.IsEmpty())
373 if (yourfile
.IsEmpty())
375 com
.Replace(_T("/minename:%yname"), _T(""));
376 com
.Replace(_T("%yname"), _T(""));
379 com
.Replace(_T("%yname"), _T("\"") + yourfile
.GetUIFileOrDirectoryName() + _T("\""));
382 com
.Replace(_T("%yname"), _T("\"") + yourname
+ _T("\""));
383 if (mergedname
.IsEmpty())
385 if (mergedfile
.IsEmpty())
387 com
.Replace(_T("/mergedname:%mname"), _T(""));
388 com
.Replace(_T("%mname"), _T(""));
391 com
.Replace(_T("%mname"), _T("\"") + mergedfile
.GetUIFileOrDirectoryName() + _T("\""));
394 com
.Replace(_T("%mname"), _T("\"") + mergedname
+ _T("\""));
396 if ((bReadOnly
)&&(bInternal
))
397 com
+= _T(" /readonly");
399 if(!LaunchApplication(com
, IDS_ERR_EXTMERGESTART
, false))
407 BOOL
CAppUtils::StartExtPatch(const CTGitPath
& patchfile
, const CTGitPath
& dir
, const CString
& sOriginalDescription
, const CString
& sPatchedDescription
, BOOL bReversed
, BOOL bWait
)
410 // use TortoiseGitMerge
411 viewer
= CPathUtils::GetAppDirectory();
412 viewer
+= _T("TortoiseGitMerge.exe");
414 viewer
= _T("\"") + viewer
+ _T("\"");
415 viewer
= viewer
+ _T(" /diff:\"") + patchfile
.GetWinPathString() + _T("\"");
416 viewer
= viewer
+ _T(" /patchpath:\"") + dir
.GetWinPathString() + _T("\"");
418 viewer
+= _T(" /reversedpatch");
419 if (!sOriginalDescription
.IsEmpty())
420 viewer
= viewer
+ _T(" /patchoriginal:\"") + sOriginalDescription
+ _T("\"");
421 if (!sPatchedDescription
.IsEmpty())
422 viewer
= viewer
+ _T(" /patchpatched:\"") + sPatchedDescription
+ _T("\"");
423 if (!g_sGroupingUUID
.IsEmpty())
425 viewer
+= L
" /groupuuid:\"";
426 viewer
+= g_sGroupingUUID
;
429 if(!LaunchApplication(viewer
, IDS_ERR_DIFFVIEWSTART
, !!bWait
))
434 CString
CAppUtils::PickDiffTool(const CTGitPath
& file1
, const CTGitPath
& file2
)
436 CString difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file2
.GetFilename().MakeLower());
437 if (!difftool
.IsEmpty())
439 difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + file1
.GetFilename().MakeLower());
440 if (!difftool
.IsEmpty())
443 // Is there an extension specific diff tool?
444 CString ext
= file2
.GetFileExtension().MakeLower();
447 difftool
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + ext
);
448 if (!difftool
.IsEmpty())
450 // Maybe we should use TortoiseIDiff?
451 if ((ext
== _T(".jpg")) || (ext
== _T(".jpeg")) ||
452 (ext
== _T(".bmp")) || (ext
== _T(".gif")) ||
453 (ext
== _T(".png")) || (ext
== _T(".ico")) ||
454 (ext
== _T(".tif")) || (ext
== _T(".tiff")) ||
455 (ext
== _T(".dib")) || (ext
== _T(".emf")) ||
459 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitIDiff.exe") + _T("\"") +
460 _T(" /left:%base /right:%mine /lefttitle:%bname /righttitle:%yname") +
461 L
" /groupuuid:\"" + g_sGroupingUUID
+ L
"\"";
465 // Finally, pick a generic external diff tool
466 difftool
= CRegString(_T("Software\\TortoiseGit\\Diff"));
470 bool CAppUtils::StartExtDiff(
471 const CString
& file1
, const CString
& file2
,
472 const CString
& sName1
, const CString
& sName2
,
473 const CString
& originalFile1
, const CString
& originalFile2
,
474 const git_revnum_t
& hash1
, const git_revnum_t
& hash2
,
475 const DiffFlags
& flags
, int jumpToLine
)
479 CRegDWORD
blamediff(_T("Software\\TortoiseGit\\DiffBlamesWithTortoiseMerge"), FALSE
);
480 if (!flags
.bBlame
|| !(DWORD
)blamediff
)
482 viewer
= PickDiffTool(file1
, file2
);
483 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
484 bool bCommentedOut
= CStringUtils::StartsWith(viewer
, L
"#");
485 if (flags
.bAlternativeTool
)
487 // Invert external vs. internal diff tool selection.
489 viewer
.Delete(0); // uncomment
493 else if (bCommentedOut
)
497 bool bInternal
= viewer
.IsEmpty();
501 _T("\"") + CPathUtils::GetAppDirectory() + _T("TortoiseGitMerge.exe") + _T("\"") +
502 _T(" /base:%base /mine:%mine /basename:%bname /minename:%yname") +
503 _T(" /basereflectedname:%bpath /minereflectedname:%ypath");
504 if (!g_sGroupingUUID
.IsEmpty())
506 viewer
+= L
" /groupuuid:\"";
507 viewer
+= g_sGroupingUUID
;
511 viewer
+= _T(" /blame");
513 // check if the params are set. If not, just add the files to the command line
514 if ((viewer
.Find(_T("%base"))<0)&&(viewer
.Find(_T("%mine"))<0))
516 viewer
+= _T(" \"")+file1
+_T("\"");
517 viewer
+= _T(" \"")+file2
+_T("\"");
519 if (viewer
.Find(_T("%base")) >= 0)
520 viewer
.Replace(_T("%base"), _T("\"")+file1
+_T("\""));
521 if (viewer
.Find(_T("%mine")) >= 0)
522 viewer
.Replace(_T("%mine"), _T("\"")+file2
+_T("\""));
524 if (sName1
.IsEmpty())
525 viewer
.Replace(_T("%bname"), _T("\"") + file1
+ _T("\""));
527 viewer
.Replace(_T("%bname"), _T("\"") + sName1
+ _T("\""));
529 if (sName2
.IsEmpty())
530 viewer
.Replace(_T("%yname"), _T("\"") + file2
+ _T("\""));
532 viewer
.Replace(_T("%yname"), _T("\"") + sName2
+ _T("\""));
534 viewer
.Replace(_T("%bpath"), _T("\"") + originalFile1
+ _T("\""));
535 viewer
.Replace(_T("%ypath"), _T("\"") + originalFile2
+ _T("\""));
537 viewer
.Replace(_T("%brev"), _T("\"") + hash1
+ _T("\""));
538 viewer
.Replace(_T("%yrev"), _T("\"") + hash2
+ _T("\""));
540 if (flags
.bReadOnly
&& bInternal
)
541 viewer
+= _T(" /readonly");
544 viewer
.AppendFormat(L
" /line:%d", jumpToLine
);
546 return LaunchApplication(viewer
, IDS_ERR_EXTDIFFSTART
, flags
.bWait
);
549 BOOL
CAppUtils::StartUnifiedDiffViewer(const CString
& patchfile
, const CString
& title
, BOOL bWait
, bool bAlternativeTool
)
552 CRegString v
= CRegString(_T("Software\\TortoiseGit\\DiffViewer"));
555 // If registry entry for a diff program is commented out, use TortoiseGitMerge.
556 bool bCommentedOut
= CStringUtils::StartsWith(viewer
, L
"#");
557 if (bAlternativeTool
)
559 // Invert external vs. internal diff tool selection.
561 viewer
.Delete(0); // uncomment
565 else if (bCommentedOut
)
568 if (viewer
.IsEmpty())
570 // use TortoiseGitUDiff
571 viewer
= CPathUtils::GetAppDirectory();
572 viewer
+= _T("TortoiseGitUDiff.exe");
573 // enquote the path to TortoiseGitUDiff
574 viewer
= _T("\"") + viewer
+ _T("\"");
576 viewer
= viewer
+ _T(" /patchfile:%1 /title:\"%title\"");
577 if (!g_sGroupingUUID
.IsEmpty())
579 viewer
+= L
" /groupuuid:\"";
580 viewer
+= g_sGroupingUUID
;
584 if (viewer
.Find(_T("%1"))>=0)
586 if (viewer
.Find(_T("\"%1\"")) >= 0)
587 viewer
.Replace(_T("%1"), patchfile
);
589 viewer
.Replace(_T("%1"), _T("\"") + patchfile
+ _T("\""));
592 viewer
+= _T(" \"") + patchfile
+ _T("\"");
593 if (viewer
.Find(_T("%title")) >= 0)
594 viewer
.Replace(_T("%title"), title
);
596 if(!LaunchApplication(viewer
, IDS_ERR_DIFFVIEWSTART
, !!bWait
))
601 BOOL
CAppUtils::StartTextViewer(CString file
)
604 CRegString txt
= CRegString(_T(".txt\\"), _T(""), FALSE
, HKEY_CLASSES_ROOT
);
606 viewer
= viewer
+ _T("\\Shell\\Open\\Command\\");
607 CRegString txtexe
= CRegString(viewer
, _T(""), FALSE
, HKEY_CLASSES_ROOT
);
610 DWORD len
= ExpandEnvironmentStrings(viewer
, nullptr, 0);
611 auto buf
= std::make_unique
<TCHAR
[]>(len
+ 1);
612 ExpandEnvironmentStrings(viewer
, buf
.get(), len
);
614 len
= ExpandEnvironmentStrings(file
, nullptr, 0);
615 auto buf2
= std::make_unique
<TCHAR
[]>(len
+ 1);
616 ExpandEnvironmentStrings(file
, buf2
.get(), len
);
618 file
= _T("\"")+file
+_T("\"");
619 if (viewer
.IsEmpty())
620 return CAppUtils::ShowOpenWithDialog(file
) ? TRUE
: FALSE
;
621 if (viewer
.Find(_T("\"%1\"")) >= 0)
622 viewer
.Replace(_T("\"%1\""), file
);
623 else if (viewer
.Find(_T("%1")) >= 0)
624 viewer
.Replace(_T("%1"), file
);
629 if(!LaunchApplication(viewer
, IDS_ERR_TEXTVIEWSTART
, false))
634 BOOL
CAppUtils::CheckForEmptyDiff(const CTGitPath
& sDiffPath
)
637 CAutoFile hFile
= ::CreateFile(sDiffPath
.GetWinPath(), GENERIC_READ
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, nullptr, OPEN_EXISTING
, 0, nullptr);
640 length
= ::GetFileSize(hFile
, nullptr);
646 CString
CAppUtils::GetLogFontName()
648 return (CString
)CRegString(L
"Software\\TortoiseGit\\LogFontName", L
"Consolas");
651 DWORD
CAppUtils::GetLogFontSize()
653 return (DWORD
)CRegDWORD(L
"Software\\TortoiseGit\\LogFontSize", 9);
656 void CAppUtils::CreateFontForLogs(CFont
& fontToCreate
)
659 HDC hScreenDC
= ::GetDC(nullptr);
660 logFont
.lfHeight
= -MulDiv(GetLogFontSize(), GetDeviceCaps(hScreenDC
, LOGPIXELSY
), 72);
661 ::ReleaseDC(nullptr, hScreenDC
);
663 logFont
.lfEscapement
= 0;
664 logFont
.lfOrientation
= 0;
665 logFont
.lfWeight
= FW_NORMAL
;
666 logFont
.lfItalic
= 0;
667 logFont
.lfUnderline
= 0;
668 logFont
.lfStrikeOut
= 0;
669 logFont
.lfCharSet
= DEFAULT_CHARSET
;
670 logFont
.lfOutPrecision
= OUT_DEFAULT_PRECIS
;
671 logFont
.lfClipPrecision
= CLIP_DEFAULT_PRECIS
;
672 logFont
.lfQuality
= DRAFT_QUALITY
;
673 logFont
.lfPitchAndFamily
= FF_DONTCARE
| FIXED_PITCH
;
674 _tcscpy_s(logFont
.lfFaceName
, 32, (LPCTSTR
)GetLogFontName());
675 VERIFY(fontToCreate
.CreateFontIndirect(&logFont
));
678 bool CAppUtils::LaunchPAgent(const CString
* keyfile
, const CString
* pRemote
)
689 cmd
.Format(_T("remote.%s.puttykeyfile"), (LPCTSTR
)remote
);
690 key
= g_Git
.GetConfigValue(cmd
);
698 CString proc
=CPathUtils::GetAppDirectory();
699 proc
+= _T("pageant.exe \"");
703 CString tempfile
= GetTempFile();
704 ::DeleteFile(tempfile
);
706 proc
+= _T(" -c \"");
707 proc
+= CPathUtils::GetAppDirectory();
708 proc
+= _T("tgittouch.exe\"");
713 CString appDir
= CPathUtils::GetAppDirectory();
714 bool b
= LaunchApplication(proc
, IDS_ERR_PAGEANT
, true, &appDir
);
719 while(!::PathFileExists(tempfile
))
724 break; //timeout 5 minutes
728 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
729 ::DeleteFile(tempfile
);
732 bool CAppUtils::LaunchAlternativeEditor(const CString
& filename
, bool uac
)
734 CString editTool
= CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
735 if (editTool
.IsEmpty() || CStringUtils::StartsWith(editTool
, L
"#"))
736 editTool
= CPathUtils::GetAppDirectory() + _T("notepad2.exe");
739 sCmd
.Format(_T("\"%s\" \"%s\""), (LPCTSTR
)editTool
, (LPCTSTR
)filename
);
741 LaunchApplication(sCmd
, 0, false, nullptr, uac
);
744 bool CAppUtils::LaunchRemoteSetting()
746 CTGitPath
path(g_Git
.m_CurrentDir
);
747 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
, &path
);
748 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
749 dlg
.SetTreeWidth(220);
750 dlg
.m_DefaultPage
= _T("gitremote");
757 * Launch the external blame viewer
759 bool CAppUtils::LaunchTortoiseBlame(const CString
& sBlameFile
, const CString
& Rev
, const CString
& sParams
)
761 CString viewer
= _T("\"") + CPathUtils::GetAppDirectory();
762 viewer
+= _T("TortoiseGitBlame.exe");
763 viewer
+= _T("\" \"") + sBlameFile
+ _T("\"");
764 //viewer += _T(" \"") + sLogFile + _T("\"");
765 //viewer += _T(" \"") + sOriginalFile + _T("\"");
766 if(!Rev
.IsEmpty() && Rev
!= GIT_REV_ZERO
)
767 viewer
+= L
" /rev:" + Rev
;
768 if (!g_sGroupingUUID
.IsEmpty())
770 viewer
+= L
" /groupuuid:\"";
771 viewer
+= g_sGroupingUUID
;
774 viewer
+= _T(" ")+sParams
;
776 return LaunchApplication(viewer
, IDS_ERR_TGITBLAME
, false);
779 bool CAppUtils::FormatTextInRichEditControl(CWnd
* pWnd
)
784 bool bStyled
= false;
785 pWnd
->GetWindowText(sText
);
786 // the rich edit control doesn't count the CR char!
787 // to be exact: CRLF is treated as one char.
788 sText
.Remove(_T('\r'));
790 // style each line separately
795 nNewlinePos
= sText
.Find('\n', offset
);
796 CString sLine
= nNewlinePos
>= 0 ? sText
.Mid(offset
, nNewlinePos
- offset
) : sText
.Mid(offset
);
800 while (FindStyleChars(sLine
, '*', start
, end
))
802 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
803 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
804 SetCharFormat(pWnd
, CFM_BOLD
, CFE_BOLD
);
810 while (FindStyleChars(sLine
, '^', start
, end
))
812 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
813 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
814 SetCharFormat(pWnd
, CFM_ITALIC
, CFE_ITALIC
);
820 while (FindStyleChars(sLine
, '_', start
, end
))
822 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
823 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
824 SetCharFormat(pWnd
, CFM_UNDERLINE
, CFE_UNDERLINE
);
828 offset
= nNewlinePos
+1;
829 } while(nNewlinePos
>=0);
833 bool CAppUtils::FindStyleChars(const CString
& sText
, TCHAR stylechar
, int& start
, int& end
)
836 int last
= sText
.GetLength() - 1;
837 bool bFoundMarker
= false;
838 TCHAR c
= i
== 0 ? _T('\0') : sText
[i
- 1];
839 TCHAR nextChar
= i
>= last
? _T('\0') : sText
[i
+ 1];
841 // find a starting marker
846 nextChar
= sText
[i
+ 1];
848 // IsCharAlphaNumeric can be somewhat expensive.
849 // Long lines of "*****" or "----" will be pre-empted efficiently
850 // by the (c != nextChar) condition.
852 if ((c
== stylechar
) && (c
!= nextChar
))
854 if (IsCharAlphaNumeric(nextChar
) && !IsCharAlphaNumeric(prevChar
))
866 // find ending marker
869 bFoundMarker
= false;
876 if ((i
== last
) || (!IsCharAlphaNumeric(sText
[i
+ 1]) && IsCharAlphaNumeric(prevChar
)))
891 bool IsValidURLChar(wchar_t ch
)
893 return iswalnum(ch
) ||
894 ch
== L
'_' || ch
== L
'/' || ch
== L
';' || ch
== L
'?' || ch
== L
'&' || ch
== L
'=' ||
895 ch
== L
'%' || ch
== L
':' || ch
== L
'.' || ch
== L
'#' || ch
== L
'-' || ch
== L
'+' ||
896 ch
== L
'|' || ch
== L
'>' || ch
== L
'<' || ch
== L
'!' || ch
== L
'@';
899 bool IsUrlOrEmail(const CString
& sText
)
901 if (!PathIsURLW(sText
))
903 auto atpos
= sText
.Find(L
'@');
906 if (sText
.ReverseFind(L
'.') > atpos
)
910 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ftp://", L
"file://", L
"mailto:" })
912 if (CStringUtils::StartsWith(sText
, prefix
) && sText
.GetLength() != prefix
.GetLength())
919 BOOL
CAppUtils::StyleURLs(const CString
& msg
, CWnd
* pWnd
)
921 std::vector
<CHARRANGE
> positions
= FindURLMatches(msg
);
922 CAppUtils::SetCharFormat(pWnd
, CFM_LINK
, CFE_LINK
, positions
);
924 return positions
.empty() ? FALSE
: TRUE
;
928 * implements URL searching with the same logic as CSciEdit::StyleURLs
930 std::vector
<CHARRANGE
> CAppUtils::FindURLMatches(const CString
& msg
)
932 std::vector
<CHARRANGE
> result
;
934 int len
= msg
.GetLength();
937 for (int i
= 0; i
<= msg
.GetLength(); ++i
)
939 if ((i
< len
) && IsValidURLChar(msg
[i
]))
949 if (msg
[starturl
] == '<' && i
< len
) // try to detect and do not strip URLs put within <>
951 while (starturl
<= i
&& msg
[starturl
] == '<') // strip leading '<'
955 while (i
< len
&& msg
[i
] != '\r' && msg
[i
] != '\n' && msg
[i
] != '>') // find first '>' or new line after resetting i to start position
959 int skipTrailing
= 0;
960 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] == '<' || msg
[i
- skipTrailing
- 1] == '!'))
963 if (!IsUrlOrEmail(msg
.Mid(starturl
, i
- starturl
- skipTrailing
)))
969 CHARRANGE range
= { starturl
, i
- skipTrailing
};
970 result
.push_back(range
);
979 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd
, const CTGitPath
& url1
, const git_revnum_t
& rev1
,
980 const CTGitPath
& /*url2*/, const git_revnum_t
& rev2
,
981 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
982 bool bAlternateDiff
/* = false */, bool /*bIgnoreAncestry*/ /* = false */,
983 bool /* blame = false */,
988 int diffContext
= g_Git
.GetConfigValueInt32(L
"diff.context", -1);
989 CString tempfile
=GetTempFile();
990 if (g_Git
.GetUnifiedDiff(url1
, rev1
, rev2
, tempfile
, bMerge
, bCombine
, diffContext
, bNoPrefix
))
992 CMessageBox::Show(hWnd
, g_Git
.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF
), _T("TortoiseGit"), MB_OK
);
995 CAppUtils::StartUnifiedDiffViewer(tempfile
, rev1
+ L
":" + rev2
, FALSE
, bAlternateDiff
);
999 sCmd
.Format(_T("%s /command:showcompare /unified"),
1000 (LPCTSTR
)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
1001 sCmd
+= _T(" /url1:\"") + url1
.GetGitPathString() + _T("\"");
1003 sCmd
+= _T(" /revision1:") + rev1
.ToString();
1004 sCmd
+= _T(" /url2:\"") + url2
.GetGitPathString() + _T("\"");
1006 sCmd
+= _T(" /revision2:") + rev2
.ToString();
1008 sCmd
+= _T(" /pegrevision:") + peg
.ToString();
1009 if (headpeg
.IsValid())
1010 sCmd
+= _T(" /headpegrevision:") + headpeg
.ToString();
1013 sCmd
+= _T(" /alternatediff");
1015 if (bIgnoreAncestry
)
1016 sCmd
+= _T(" /ignoreancestry");
1020 sCmd
+= _T(" /hwnd:");
1022 _stprintf_s(buf
, 30, _T("%p"), (void*)hWnd
);
1026 return CAppUtils::LaunchApplication(sCmd
, 0, false);
1031 bool CAppUtils::SetupDiffScripts(bool force
, const CString
& type
)
1033 CString scriptsdir
= CPathUtils::GetAppParentDirectory();
1034 scriptsdir
+= _T("Diff-Scripts");
1035 CSimpleFileFind
files(scriptsdir
);
1036 while (files
.FindNextFileNoDirectories())
1038 CString file
= files
.GetFilePath();
1039 CString filename
= files
.GetFileName();
1040 CString ext
= file
.Mid(file
.ReverseFind('-') + 1);
1041 ext
= _T(".") + ext
.Left(ext
.ReverseFind('.'));
1042 std::set
<CString
> extensions
;
1043 extensions
.insert(ext
);
1045 if (file
.Right(3).CompareNoCase(_T("vbs"))==0)
1046 kind
= _T(" //E:vbscript");
1047 if (file
.Right(2).CompareNoCase(_T("js"))==0)
1048 kind
= _T(" //E:javascript");
1049 // open the file, read the first line and find possible extensions
1050 // this script can handle
1053 CStdioFile
f(file
, CFile::modeRead
| CFile::shareDenyNone
);
1055 if (f
.ReadString(extline
))
1057 if ((extline
.GetLength() > 15 ) &&
1058 (CStringUtils::StartsWith(extline
, L
"// extensions: ") ||
1059 CStringUtils::StartsWith(extline
, L
"' extensions: ")))
1061 if (extline
[0] == '/')
1062 extline
= extline
.Mid(15);
1064 extline
= extline
.Mid(14);
1067 sToken
= extline
.Tokenize(_T(";"), curPos
);
1068 while (!sToken
.IsEmpty())
1070 if (!sToken
.IsEmpty())
1072 if (sToken
[0] != '.')
1073 sToken
= _T(".") + sToken
;
1074 extensions
.insert(sToken
);
1076 sToken
= extline
.Tokenize(_T(";"), curPos
);
1082 catch (CFileException
* e
)
1087 for (const auto& extension
: extensions
)
1089 if (type
.IsEmpty() || (type
.Compare(_T("Diff")) == 0))
1091 if (CStringUtils::StartsWithI(filename
, L
"diff-"))
1093 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension
);
1094 CString diffregstring
= diffreg
;
1095 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1096 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %base %mine") + kind
;
1099 if (type
.IsEmpty() || (type
.Compare(_T("Merge"))==0))
1101 if (CStringUtils::StartsWithI(filename
, L
"merge-"))
1103 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension
);
1104 CString diffregstring
= diffreg
;
1105 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1106 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %merged %theirs %mine %base") + kind
;
1115 bool CAppUtils::Export(const CString
* BashHash
, const CTGitPath
* orgPath
)
1117 // ask from where the export has to be done
1120 dlg
.m_initialRefName
=*BashHash
;
1123 if (PathIsRelative(orgPath
->GetWinPath()))
1124 dlg
.m_orgPath
= g_Git
.CombinePath(orgPath
);
1126 dlg
.m_orgPath
= *orgPath
;
1129 if (dlg
.DoModal() == IDOK
)
1132 cmd
.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1133 (LPCTSTR
)dlg
.m_strFile
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
1137 pro
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1141 postCmdList
.emplace_back(IDI_EXPLORER
, IDS_STATUSLIST_CONTEXT_EXPLORE
, [&]{ CAppUtils::ExploreTo(hWndExplorer
, dlg
.m_strFile
); });
1145 if (!dlg
.m_bWholeProject
&& !dlg
.m_orgPath
.IsEmpty() && PathIsDirectory(dlg
.m_orgPath
.GetWinPathString()))
1147 git
.m_CurrentDir
= dlg
.m_orgPath
.GetWinPathString();
1150 return (pro
.DoModal() == IDOK
);
1155 bool CAppUtils::UpdateBranchDescription(const CString
& branch
, CString description
)
1157 if (branch
.IsEmpty())
1161 key
.Format(L
"branch.%s.description", (LPCTSTR
)branch
);
1162 description
.Replace(L
"\r", L
"");
1164 if (description
.IsEmpty())
1165 g_Git
.UnsetConfigValue(key
);
1167 g_Git
.SetConfigValue(key
, description
);
1172 bool CAppUtils::CreateBranchTag(bool isTag
/*true*/, const CString
* commitHash
/*nullptr*/, bool switchNewBranch
/*false*/, LPCTSTR name
/*nullptr*/)
1174 CCreateBranchTagDlg dlg
;
1175 dlg
.m_bIsTag
= isTag
;
1176 dlg
.m_bSwitch
= switchNewBranch
;
1179 dlg
.m_initialRefName
= *commitHash
;
1182 dlg
.m_BranchTagName
= name
;
1184 if(dlg
.DoModal()==IDOK
)
1189 if(dlg
.m_bTrack
== TRUE
)
1190 track
=_T(" --track ");
1191 else if(dlg
.m_bTrack
== FALSE
)
1192 track
=_T(" --no-track");
1203 cmd
.Format(_T("git.exe tag %s %s %s %s"),
1206 (LPCTSTR
)dlg
.m_BranchTagName
,
1207 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1210 if(!dlg
.m_Message
.Trim().IsEmpty())
1212 CString tempfile
= ::GetTempFile();
1213 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_Message
))
1215 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1218 cmd
+= _T(" -F ")+tempfile
;
1223 cmd
.Format(_T("git.exe branch %s %s %s %s"),
1226 (LPCTSTR
)dlg
.m_BranchTagName
,
1227 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1231 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1233 CMessageBox::Show(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1236 if (!isTag
&& dlg
.m_bSwitch
)
1238 // it is a new branch and the user has requested to switch to it
1239 PerformSwitch(dlg
.m_BranchTagName
);
1241 if (!isTag
&& !dlg
.m_Message
.IsEmpty())
1242 UpdateBranchDescription(dlg
.m_BranchTagName
, dlg
.m_Message
);
1249 bool CAppUtils::Switch(const CString
& initialRefName
)
1252 if(!initialRefName
.IsEmpty())
1253 dlg
.m_initialRefName
= initialRefName
;
1255 if (dlg
.DoModal() == IDOK
)
1259 branch
= dlg
.m_NewBranch
;
1261 // if refs/heads/ is not stripped, checkout will detach HEAD
1262 // checkout prefers branches on name clashes (with tags)
1263 if (CStringUtils::StartsWith(dlg
.m_VersionName
, L
"refs/heads/") && dlg
.m_bBranchOverride
!= TRUE
)
1264 dlg
.m_VersionName
= dlg
.m_VersionName
.Mid(11);
1266 return PerformSwitch(dlg
.m_VersionName
, dlg
.m_bForce
== TRUE
, branch
, dlg
.m_bBranchOverride
== TRUE
, dlg
.m_bTrack
, dlg
.m_bMerge
== TRUE
);
1271 bool CAppUtils::PerformSwitch(const CString
& ref
, bool bForce
/* false */, const CString
& sNewBranch
/* CString() */, bool bBranchOverride
/* false */, BOOL bTrack
/* 2 */, bool bMerge
/* false */)
1279 if(!sNewBranch
.IsEmpty()){
1280 if (bBranchOverride
)
1281 branch
.Format(_T("-B %s "), (LPCTSTR
)sNewBranch
);
1283 branch
.Format(_T("-b %s "), (LPCTSTR
)sNewBranch
);
1285 track
= _T("--track ");
1286 else if (bTrack
== FALSE
)
1287 track
= _T("--no-track ");
1292 merge
= _T("--merge ");
1294 cmd
.Format(_T("git.exe checkout %s%s%s%s%s --"),
1299 (LPCTSTR
)g_Git
.FixBranchName(ref
));
1301 CProgressDlg progress
;
1302 progress
.m_GitCmd
= cmd
;
1304 CString currentBranch
;
1305 bool hasBranch
= CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
) == 0;
1306 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1310 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1311 if (gitPath
.HasSubmodules())
1313 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1316 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1317 RunTortoiseGitProc(sCmd
);
1321 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ Merge(¤tBranch
); });
1325 if (!CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, newBranch
))
1326 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
1328 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []{
1329 CTGitPathList pathlist
;
1330 CTGitPathList selectedlist
;
1331 pathlist
.AddPath(CTGitPath());
1332 bool bSelectFilesForCommit
= !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE
));
1334 Commit(CString(), false, str
, pathlist
, selectedlist
, bSelectFilesForCommit
);
1339 if (bMerge
&& g_Git
.HasWorkingTreeConflicts() > 0)
1341 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
1344 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1345 CAppUtils::RunTortoiseGitProc(sCmd
);
1348 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, bMerge
); });
1350 postCmdList
.emplace_back(IDI_SWITCH
, IDS_SWITCH_WITH_MERGE
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, true); });
1353 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
& extraMsg
)
1355 if (bMerge
&& !exitCode
&& g_Git
.HasWorkingTreeConflicts() > 0)
1357 exitCode
= 1; // Treat it as failure
1358 extraMsg
= _T("Has merge conflict");
1362 INT_PTR ret
= progress
.DoModal();
1367 class CIgnoreFile
: public CStdioFile
1370 STRING_VECTOR m_Items
;
1373 virtual BOOL
ReadString(CString
& rString
)
1375 if (GetPosition() == 0)
1377 unsigned char utf8bom
[] = { 0xEF, 0xBB, 0xBF };
1378 char buf
[3] = { 0, 0, 0 };
1380 if (memcpy(buf
, utf8bom
, sizeof(utf8bom
)))
1385 char lastChar
= '\0';
1386 for (char c
= '\0'; Read(&c
, 1) == 1; lastChar
= c
)
1392 m_eol
= lastChar
== '\r' ? _T("\r\n") : _T("\n");
1400 rString
= CUnicodeUtils::GetUnicode(strA
);
1411 bool CAppUtils::OpenIgnoreFile(CIgnoreFile
&file
, const CString
& filename
)
1414 if (!file
.Open(filename
, CFile::modeCreate
| CFile::modeReadWrite
| CFile::modeNoTruncate
| CFile::typeBinary
))
1416 CMessageBox::Show(nullptr, filename
+ _T(" Open Failure"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1420 if (file
.GetLength() > 0)
1423 while (file
.ReadString(fileText
))
1424 file
.m_Items
.push_back(fileText
);
1425 file
.Seek(file
.GetLength() - 1, 0);
1426 char lastchar
[1] = { 0 };
1427 file
.Read(lastchar
, 1);
1429 if (lastchar
[0] != '\n')
1431 CStringA eol
= CStringA(file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
);
1432 file
.Write(eol
, eol
.GetLength());
1441 bool CAppUtils::IgnoreFile(const CTGitPathList
& path
,bool IsMask
)
1443 CIgnoreDlg ignoreDlg
;
1444 if (ignoreDlg
.DoModal() == IDOK
)
1447 ignorefile
= g_Git
.m_CurrentDir
+ _T("\\");
1449 switch (ignoreDlg
.m_IgnoreFile
)
1452 ignorefile
+= _T(".gitignore");
1455 GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, ignorefile
);
1456 ignorefile
+= _T("info");
1457 if (!PathFileExists(ignorefile
))
1458 CreateDirectory(ignorefile
, nullptr);
1459 ignorefile
+= _T("\\exclude");
1466 if (ignoreDlg
.m_IgnoreFile
!= 1 && !OpenIgnoreFile(file
, ignorefile
))
1469 for (int i
= 0; i
< path
.GetCount(); ++i
)
1471 if (ignoreDlg
.m_IgnoreFile
== 1)
1473 ignorefile
= g_Git
.CombinePath(path
[i
].GetContainingDirectory()) + _T("\\.gitignore");
1474 if (!OpenIgnoreFile(file
, ignorefile
))
1478 CString ignorePattern
;
1479 if (ignoreDlg
.m_IgnoreType
== 0)
1481 if (ignoreDlg
.m_IgnoreFile
!= 1 && !path
[i
].GetContainingDirectory().GetGitPathString().IsEmpty())
1482 ignorePattern
+= _T("/") + path
[i
].GetContainingDirectory().GetGitPathString();
1484 ignorePattern
+= _T("/");
1487 ignorePattern
+= _T("*") + path
[i
].GetFileExtension();
1489 ignorePattern
+= path
[i
].GetFileOrDirectoryName();
1491 // escape [ and ] so that files get ignored correctly
1492 ignorePattern
.Replace(_T("["), _T("\\["));
1493 ignorePattern
.Replace(_T("]"), _T("\\]"));
1496 for (size_t j
= 0; j
< file
.m_Items
.size(); ++j
)
1498 if (file
.m_Items
[j
] == ignorePattern
)
1506 file
.m_Items
.push_back(ignorePattern
);
1507 ignorePattern
+= file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
;
1508 CStringA ignorePatternA
= CUnicodeUtils::GetUTF8(ignorePattern
);
1509 file
.Write(ignorePatternA
, ignorePatternA
.GetLength());
1512 if (ignoreDlg
.m_IgnoreFile
== 1)
1516 if (ignoreDlg
.m_IgnoreFile
!= 1)
1530 static bool Reset(const CString
& resetTo
, int resetType
)
1537 type
= _T("--soft");
1540 type
= _T("--mixed");
1543 type
= _T("--hard");
1547 type
= _T("--mixed");
1550 cmd
.Format(_T("git.exe reset %s %s --"), (LPCTSTR
)type
, (LPCTSTR
)resetTo
);
1552 CProgressDlg progress
;
1553 progress
.m_GitCmd
= cmd
;
1555 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1559 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ Reset(resetTo
, resetType
); });
1563 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1564 if (gitPath
.HasSubmodules() && resetType
== 2)
1566 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1569 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1570 CAppUtils::RunTortoiseGitProc(sCmd
);
1576 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_RESET
))
1578 CGitProgressDlg gitdlg
;
1579 ResetProgressCommand resetProgressCommand
;
1580 gitdlg
.SetCommand(&resetProgressCommand
);
1581 resetProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
1582 resetProgressCommand
.SetRevision(resetTo
);
1583 resetProgressCommand
.SetResetType(resetType
);
1584 ret
= gitdlg
.DoModal();
1587 ret
= progress
.DoModal();
1592 bool CAppUtils::GitReset(const CString
* CommitHash
, int type
)
1595 dlg
.m_ResetType
=type
;
1596 dlg
.m_ResetToVersion
=*CommitHash
;
1597 dlg
.m_initialRefName
= *CommitHash
;
1598 if (dlg
.DoModal() == IDOK
)
1599 return Reset(dlg
.m_ResetToVersion
, dlg
.m_ResetType
);
1604 void CAppUtils::DescribeConflictFile(bool mode
, bool base
,CString
&descript
)
1608 descript
.LoadString(IDS_SVNACTION_DELETE
);
1613 descript
.LoadString(IDS_SVNACTION_MODIFIED
);
1616 descript
.LoadString(IDS_PROC_CREATED
);
1619 void CAppUtils::RemoveTempMergeFile(const CTGitPath
& path
)
1621 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path
));
1622 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path
));
1623 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path
));
1625 CString
CAppUtils::GetMergeTempFile(const CString
& type
, const CTGitPath
&merge
)
1628 file
= g_Git
.CombinePath(merge
.GetWinPathString() + _T(".") + type
+ merge
.GetFileExtension());
1633 bool ParseHashesFromLsFile(const BYTE_VECTOR
& out
, CString
& hash1
, CString
& hash2
, CString
& hash3
)
1639 while (pos
< out
.size())
1643 CGit::StringAppend(&one
, &out
[pos
], CP_UTF8
);
1645 one
.Tokenize(_T("\t"), tabstart
);
1648 part
= one
.Tokenize(_T(" "), tabstart
); //Tag
1649 part
= one
.Tokenize(_T(" "), tabstart
); //Mode
1650 part
= one
.Tokenize(_T(" "), tabstart
); //Hash
1651 CString hash
= part
;
1652 part
= one
.Tokenize(_T("\t"), tabstart
); //Stage
1653 int stage
= _ttol(part
);
1656 else if (stage
== 2)
1658 else if (stage
== 3)
1664 pos
= out
.findNextString(pos
);
1670 bool CAppUtils::ConflictEdit(const CTGitPath
& path
, bool bAlternativeTool
/*= false*/, bool revertTheirMy
/*= false*/, HWND resolveMsgHwnd
/*= nullptr*/)
1674 CTGitPath merge
=path
;
1675 CTGitPath directory
= merge
.GetDirectory();
1677 // we have the conflicted file (%merged)
1678 // now look for the other required files
1680 //stat.GetStatus(merge);
1681 //if (stat.status == nullptr)
1687 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1689 if (g_Git
.Run(cmd
, &vector
))
1692 if (merge
.IsDirectory())
1694 CString baseHash
, realBaseHash(GIT_REV_ZERO
), localHash(GIT_REV_ZERO
), remoteHash(GIT_REV_ZERO
);
1695 if (merge
.HasAdminDir()) {
1697 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1699 subgit
.GetHash(hash
, _T("HEAD"));
1702 if (ParseHashesFromLsFile(vector
, realBaseHash
, localHash
, remoteHash
)) // in base no submodule, but in remote submodule
1703 baseHash
= realBaseHash
;
1705 CGitDiff::ChangeType changeTypeMine
= CGitDiff::Unknown
;
1706 CGitDiff::ChangeType changeTypeTheirs
= CGitDiff::Unknown
;
1708 bool baseOK
= false, mineOK
= false, theirsOK
= false;
1709 CString baseSubject
, mineSubject
, theirsSubject
;
1710 if (merge
.HasAdminDir())
1713 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1714 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, localHash
, baseOK
, mineOK
, changeTypeMine
, baseSubject
, mineSubject
);
1715 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, remoteHash
, baseOK
, theirsOK
, changeTypeTheirs
, baseSubject
, theirsSubject
);
1717 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)
1719 changeTypeMine
= CGitDiff::Identical
;
1720 changeTypeTheirs
= CGitDiff::NewSubmodule
;
1721 baseSubject
= _T("no submodule");
1722 mineSubject
= baseSubject
;
1723 theirsSubject
= _T("not initialized");
1725 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
1727 baseHash
= localHash
;
1728 baseSubject
= _T("not initialized");
1729 mineSubject
= baseSubject
;
1730 theirsSubject
= _T("not initialized");
1731 changeTypeMine
= CGitDiff::Identical
;
1732 changeTypeTheirs
= CGitDiff::DeleteSubmodule
;
1734 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
1736 baseSubject
= _T("not initialized");
1737 mineSubject
= baseSubject
;
1738 theirsSubject
= baseSubject
;
1739 if (baseHash
== localHash
)
1740 changeTypeMine
= CGitDiff::Identical
;
1745 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog
;
1746 resolveSubmoduleConflictDialog
.SetDiff(merge
.GetGitPathString(), revertTheirMy
, baseHash
, baseSubject
, baseOK
, localHash
, mineSubject
, mineOK
, changeTypeMine
, remoteHash
, theirsSubject
, theirsOK
, changeTypeTheirs
);
1747 resolveSubmoduleConflictDialog
.DoModal();
1748 if (resolveSubmoduleConflictDialog
.m_bResolved
&& resolveMsgHwnd
)
1750 static UINT WM_REVERTMSG
= RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1751 ::PostMessage(resolveMsgHwnd
, WM_REVERTMSG
, NULL
, NULL
);
1758 if (list
.ParserFromLsFile(vector
))
1760 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1773 mine
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1774 theirs
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1778 mine
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1779 theirs
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1781 base
.SetFromGit(GetMergeTempFile(_T("BASE"),merge
));
1785 //format=_T("git.exe cat-file blob \":%d:%s\"");
1786 format
= _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1788 //create a empty file, incase stage is not three
1789 tempfile
.Open(mine
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1791 tempfile
.Open(theirs
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1793 tempfile
.Open(base
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1796 bool b_base
=false, b_local
=false, b_remote
=false;
1798 for (int i
= 0; i
< list
.GetCount(); ++i
)
1804 if( list
[i
].m_Stage
== 1)
1806 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1808 outfile
= base
.GetWinPathString();
1811 if( list
[i
].m_Stage
== 2 )
1813 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1815 outfile
= mine
.GetWinPathString();
1818 if( list
[i
].m_Stage
== 3 )
1820 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1822 outfile
= theirs
.GetWinPathString();
1824 CString output
, err
;
1825 if(!outfile
.IsEmpty())
1826 if (!g_Git
.Run(cmd
, &output
, &err
, CP_UTF8
))
1830 file
= output
.Tokenize(_T("\t"), start
);
1831 ::MoveFileEx(file
,outfile
,MOVEFILE_REPLACE_EXISTING
|MOVEFILE_COPY_ALLOWED
);
1834 CMessageBox::Show(nullptr, output
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1837 if(b_local
&& b_remote
)
1839 merge
.SetFromWin(g_Git
.CombinePath(merge
));
1841 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, mine
, theirs
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1843 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, theirs
, mine
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1847 ::DeleteFile(mine
.GetWinPathString());
1848 ::DeleteFile(theirs
.GetWinPathString());
1849 ::DeleteFile(base
.GetWinPathString());
1851 CDeleteConflictDlg dlg
;
1852 DescribeConflictFile(b_local
, b_base
,dlg
.m_LocalStatus
);
1853 DescribeConflictFile(b_remote
,b_base
,dlg
.m_RemoteStatus
);
1854 CGitHash localHash
, remoteHash
;
1855 if (!g_Git
.GetHash(localHash
, _T("HEAD")))
1856 dlg
.m_LocalHash
= localHash
.ToString();
1857 if (!g_Git
.GetHash(remoteHash
, _T("MERGE_HEAD")))
1858 dlg
.m_RemoteHash
= remoteHash
.ToString();
1859 else if (!g_Git
.GetHash(remoteHash
, _T("rebase-apply/original-commit")))
1860 dlg
.m_RemoteHash
= remoteHash
.ToString();
1861 else if (!g_Git
.GetHash(remoteHash
, _T("CHERRY_PICK_HEAD")))
1862 dlg
.m_RemoteHash
= remoteHash
.ToString();
1863 else if (!g_Git
.GetHash(remoteHash
, _T("REVERT_HEAD")))
1864 dlg
.m_RemoteHash
= remoteHash
.ToString();
1865 dlg
.m_bShowModifiedButton
=b_base
;
1866 dlg
.m_File
=merge
.GetGitPathString();
1867 if(dlg
.DoModal() == IDOK
)
1871 cmd
.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1873 cmd
.Format(_T("git.exe add -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1875 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1877 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1887 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1888 base
, theirs
, mine
, merge
);
1891 if (stat
.status
->text_status
== svn_wc_status_conflicted
)
1893 // we have a text conflict, use our merge tool to resolve the conflict
1895 CTSVNPath
theirs(directory
);
1896 CTSVNPath
mine(directory
);
1897 CTSVNPath
base(directory
);
1898 bool bConflictData
= false;
1900 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_new
))
1902 theirs
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_new
));
1903 bConflictData
= true;
1905 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_old
))
1907 base
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_old
));
1908 bConflictData
= true;
1910 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_wrk
))
1912 mine
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_wrk
));
1913 bConflictData
= true;
1918 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1919 base
, theirs
, mine
, merge
);
1922 if (stat
.status
->prop_status
== svn_wc_status_conflicted
)
1924 // we have a property conflict
1925 CTSVNPath
prej(directory
);
1926 if ((stat
.status
->entry
)&&(stat
.status
->entry
->prejfile
))
1928 prej
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->prejfile
));
1929 // there's a problem: the prej file contains a _description_ of the conflict, and
1930 // that description string might be translated. That means we have no way of parsing
1931 // the file to find out the conflicting values.
1932 // The only thing we can do: show a dialog with the conflict description, then
1933 // let the user either accept the existing property or open the property edit dialog
1934 // to manually change the properties and values. And a button to mark the conflict as
1936 CEditPropConflictDlg dlg
;
1937 dlg
.SetPrejFile(prej
);
1938 dlg
.SetConflictedItem(merge
);
1939 bRet
= (dlg
.DoModal() != IDCANCEL
);
1943 if (stat
.status
->tree_conflict
)
1945 // we have a tree conflict
1947 const SVNInfoData
* pInfoData
= info
.GetFirstFileInfo(merge
, SVNRev(), SVNRev());
1950 if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_text
)
1952 CTSVNPath
theirs(directory
);
1953 CTSVNPath
mine(directory
);
1954 CTSVNPath
base(directory
);
1955 bool bConflictData
= false;
1957 if (pInfoData
->treeconflict_theirfile
)
1959 theirs
.AppendPathString(pInfoData
->treeconflict_theirfile
);
1960 bConflictData
= true;
1962 if (pInfoData
->treeconflict_basefile
)
1964 base
.AppendPathString(pInfoData
->treeconflict_basefile
);
1965 bConflictData
= true;
1967 if (pInfoData
->treeconflict_myfile
)
1969 mine
.AppendPathString(pInfoData
->treeconflict_myfile
);
1970 bConflictData
= true;
1975 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1976 base
, theirs
, mine
, merge
);
1978 else if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_tree
)
1980 CString sConflictAction
;
1981 CString sConflictReason
;
1982 CString sResolveTheirs
;
1983 CString sResolveMine
;
1984 CTSVNPath treeConflictPath
= CTSVNPath(pInfoData
->treeconflict_path
);
1985 CString sItemName
= treeConflictPath
.GetUIFileOrDirectoryName();
1987 if (pInfoData
->treeconflict_nodekind
== svn_node_file
)
1989 switch (pInfoData
->treeconflict_operation
)
1991 case svn_wc_operation_update
:
1992 switch (pInfoData
->treeconflict_action
)
1994 case svn_wc_conflict_action_edit
:
1995 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEEDIT
, (LPCTSTR
)sItemName
);
1996 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1998 case svn_wc_conflict_action_add
:
1999 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEADD
, (LPCTSTR
)sItemName
);
2000 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2002 case svn_wc_conflict_action_delete
:
2003 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEDELETE
, (LPCTSTR
)sItemName
);
2004 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2008 case svn_wc_operation_switch
:
2009 switch (pInfoData
->treeconflict_action
)
2011 case svn_wc_conflict_action_edit
:
2012 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHEDIT
, (LPCTSTR
)sItemName
);
2013 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2015 case svn_wc_conflict_action_add
:
2016 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHADD
, (LPCTSTR
)sItemName
);
2017 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2019 case svn_wc_conflict_action_delete
:
2020 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHDELETE
, (LPCTSTR
)sItemName
);
2021 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2025 case svn_wc_operation_merge
:
2026 switch (pInfoData
->treeconflict_action
)
2028 case svn_wc_conflict_action_edit
:
2029 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEEDIT
, (LPCTSTR
)sItemName
);
2030 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2032 case svn_wc_conflict_action_add
:
2033 sResolveTheirs
.Format(IDS_TREECONFLICT_FILEMERGEADD
, (LPCTSTR
)sItemName
);
2034 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2036 case svn_wc_conflict_action_delete
:
2037 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEDELETE
, (LPCTSTR
)sItemName
);
2038 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2044 else if (pInfoData
->treeconflict_nodekind
== svn_node_dir
)
2046 switch (pInfoData
->treeconflict_operation
)
2048 case svn_wc_operation_update
:
2049 switch (pInfoData
->treeconflict_action
)
2051 case svn_wc_conflict_action_edit
:
2052 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEEDIT
, (LPCTSTR
)sItemName
);
2053 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2055 case svn_wc_conflict_action_add
:
2056 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEADD
, (LPCTSTR
)sItemName
);
2057 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2059 case svn_wc_conflict_action_delete
:
2060 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEDELETE
, (LPCTSTR
)sItemName
);
2061 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2065 case svn_wc_operation_switch
:
2066 switch (pInfoData
->treeconflict_action
)
2068 case svn_wc_conflict_action_edit
:
2069 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHEDIT
, (LPCTSTR
)sItemName
);
2070 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2072 case svn_wc_conflict_action_add
:
2073 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHADD
, (LPCTSTR
)sItemName
);
2074 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2076 case svn_wc_conflict_action_delete
:
2077 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHDELETE
, (LPCTSTR
)sItemName
);
2078 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2082 case svn_wc_operation_merge
:
2083 switch (pInfoData
->treeconflict_action
)
2085 case svn_wc_conflict_action_edit
:
2086 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEEDIT
, (LPCTSTR
)sItemName
);
2087 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2089 case svn_wc_conflict_action_add
:
2090 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEADD
, (LPCTSTR
)sItemName
);
2091 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2093 case svn_wc_conflict_action_delete
:
2094 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEDELETE
, (LPCTSTR
)sItemName
);
2095 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2103 switch (pInfoData
->treeconflict_reason
)
2105 case svn_wc_conflict_reason_edited
:
2106 uReasonID
= IDS_TREECONFLICT_REASON_EDITED
;
2107 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2109 case svn_wc_conflict_reason_obstructed
:
2110 uReasonID
= IDS_TREECONFLICT_REASON_OBSTRUCTED
;
2111 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2113 case svn_wc_conflict_reason_deleted
:
2114 uReasonID
= IDS_TREECONFLICT_REASON_DELETED
;
2115 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2117 case svn_wc_conflict_reason_added
:
2118 uReasonID
= IDS_TREECONFLICT_REASON_ADDED
;
2119 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2121 case svn_wc_conflict_reason_missing
:
2122 uReasonID
= IDS_TREECONFLICT_REASON_MISSING
;
2123 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2125 case svn_wc_conflict_reason_unversioned
:
2126 uReasonID
= IDS_TREECONFLICT_REASON_UNVERSIONED
;
2127 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2130 sConflictReason
.Format(uReasonID
, (LPCTSTR
)sConflictAction
);
2132 CTreeConflictEditorDlg dlg
;
2133 dlg
.SetConflictInfoText(sConflictReason
);
2134 dlg
.SetResolveTexts(sResolveTheirs
, sResolveMine
);
2135 dlg
.SetPath(treeConflictPath
);
2136 INT_PTR dlgRet
= dlg
.DoModal();
2137 bRet
= (dlgRet
!= IDCANCEL
);
2145 bool CAppUtils::IsSSHPutty()
2147 CString sshclient
=g_Git
.m_Environment
.GetEnv(_T("GIT_SSH"));
2148 sshclient
=sshclient
.MakeLower();
2149 return sshclient
.Find(L
"plink", 0) >= 0;
2152 CString
CAppUtils::GetClipboardLink(const CString
&skipGitPrefix
, int paramsCount
)
2154 if (!OpenClipboard(nullptr))
2157 CString sClipboardText
;
2158 HGLOBAL hglb
= GetClipboardData(CF_TEXT
);
2161 LPCSTR lpstr
= (LPCSTR
)GlobalLock(hglb
);
2162 sClipboardText
= CString(lpstr
);
2165 hglb
= GetClipboardData(CF_UNICODETEXT
);
2168 LPCTSTR lpstr
= (LPCTSTR
)GlobalLock(hglb
);
2169 sClipboardText
= lpstr
;
2174 if(!sClipboardText
.IsEmpty())
2176 if(sClipboardText
[0] == _T('\"') && sClipboardText
[sClipboardText
.GetLength()-1] == _T('\"'))
2177 sClipboardText
=sClipboardText
.Mid(1,sClipboardText
.GetLength()-2);
2179 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ssh://", L
"git@" })
2181 if (CStringUtils::StartsWith(sClipboardText
, prefix
) && sClipboardText
.GetLength() != prefix
.GetLength())
2182 return sClipboardText
;
2185 if(sClipboardText
.GetLength()>=2)
2186 if( sClipboardText
[1] == _T(':') )
2187 if( (sClipboardText
[0] >= 'A' && sClipboardText
[0] <= 'Z')
2188 || (sClipboardText
[0] >= 'a' && sClipboardText
[0] <= 'z') )
2189 return sClipboardText
;
2191 // trim prefixes like "git clone "
2192 if (!skipGitPrefix
.IsEmpty() && CStringUtils::StartsWith(sClipboardText
, skipGitPrefix
))
2194 sClipboardText
= sClipboardText
.Mid(skipGitPrefix
.GetLength()).Trim();
2196 while (paramsCount
>= 0)
2199 spacePos
= sClipboardText
.Find(_T(' '), spacePos
+ 1);
2203 if (spacePos
> 0 && paramsCount
< 0)
2204 sClipboardText
.Truncate(spacePos
);
2205 return sClipboardText
;
2212 CString
CAppUtils::ChooseRepository(const CString
* path
)
2214 CBrowseFolder browseFolder
;
2215 CRegString regLastResopitory
= CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2217 browseFolder
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
2218 CString strCloneDirectory
;
2220 strCloneDirectory
=*path
;
2222 strCloneDirectory
= regLastResopitory
;
2225 title
.LoadString(IDS_CHOOSE_REPOSITORY
);
2227 browseFolder
.SetInfo(title
);
2229 if (browseFolder
.Show(nullptr, strCloneDirectory
) == CBrowseFolder::OK
)
2231 regLastResopitory
= strCloneDirectory
;
2232 return strCloneDirectory
;
2238 bool CAppUtils::SendPatchMail(CTGitPathList
& list
, bool bIsMainWnd
)
2242 dlg
.m_PathList
= list
;
2244 if(dlg
.DoModal()==IDOK
)
2246 if (dlg
.m_PathList
.IsEmpty())
2249 CGitProgressDlg progDlg
;
2251 theApp
.m_pMainWnd
= &progDlg
;
2252 SendMailProgressCommand sendMailProgressCommand
;
2253 progDlg
.SetCommand(&sendMailProgressCommand
);
2255 sendMailProgressCommand
.SetPathList(dlg
.m_PathList
);
2256 progDlg
.SetItemCount(dlg
.m_PathList
.GetCount());
2258 CSendMailPatch
sendMailPatch(dlg
.m_To
, dlg
.m_CC
, dlg
.m_Subject
, !!dlg
.m_bAttachment
, !!dlg
.m_bCombine
);
2259 sendMailProgressCommand
.SetSendMailOption(&sendMailPatch
);
2268 bool CAppUtils::SendPatchMail(const CString
& cmd
, const CString
& formatpatchoutput
, bool bIsMainWnd
)
2271 CString log
=formatpatchoutput
;
2272 int start
=log
.Find(cmd
);
2274 CString one
=log
.Tokenize(_T("\n"),start
);
2280 CString one
=log
.Tokenize(_T("\n"),start
);
2282 if (one
.IsEmpty() || one
.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS
))) == 0)
2284 one
.Replace(_T('/'),_T('\\'));
2286 path
.SetFromWin(one
);
2289 if (!list
.IsEmpty())
2290 return SendPatchMail(list
, bIsMainWnd
);
2293 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES
, IDS_APPNAME
, MB_ICONINFORMATION
);
2299 int CAppUtils::GetLogOutputEncode(CGit
*pGit
)
2302 output
= pGit
->GetConfigValue(_T("i18n.logOutputEncoding"));
2303 if(output
.IsEmpty())
2304 return CUnicodeUtils::GetCPCode(pGit
->GetConfigValue(_T("i18n.commitencoding")));
2306 return CUnicodeUtils::GetCPCode(output
);
2308 int CAppUtils::SaveCommitUnicodeFile(const CString
& filename
, CString
&message
)
2312 CFile
file(filename
, CFile::modeReadWrite
| CFile::modeCreate
);
2313 int cp
= CUnicodeUtils::GetCPCode(g_Git
.GetConfigValue(_T("i18n.commitencoding")));
2315 bool stripComments
= (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE
) == TRUE
);
2316 TCHAR commentChar
= L
'#';
2319 CString commentCharValue
= g_Git
.GetConfigValue(L
"core.commentchar");
2320 if (!commentCharValue
.IsEmpty())
2321 commentChar
= commentCharValue
[0];
2324 bool sanitize
= (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE
) == TRUE
);
2326 message
.Trim(L
" \r\n");
2328 int len
= message
.GetLength();
2330 int emptyLineCnt
= 0;
2331 while (start
>= 0 && start
< len
)
2333 int oldStart
= start
;
2334 start
= message
.Find(L
"\n", oldStart
);
2335 CString line
= message
.Mid(oldStart
);
2338 line
.Truncate(start
- oldStart
);
2339 ++start
; // move forward so we don't find the same char again
2341 if (stripComments
&& (!line
.IsEmpty() && line
.GetAt(0) == commentChar
) || (start
< 0 && line
.IsEmpty()))
2343 line
.TrimRight(L
" \r");
2351 if (emptyLineCnt
) // squash multiple newlines
2352 file
.Write("\n", 1);
2355 CStringA lineA
= CUnicodeUtils::GetMulti(line
+ L
"\n", cp
);
2356 file
.Write((LPCSTR
)lineA
, lineA
.GetLength());
2361 catch (CFileException
*e
)
2368 bool DoPull(const CString
& url
, bool bAutoLoad
, BOOL bFetchTags
, bool bNoFF
, bool bFFonly
, bool bSquash
, bool bNoCommit
, int* nDepth
, BOOL bPrune
, const CString
& remoteBranchName
, bool showPush
, bool showStashPop
, bool bUnrelated
)
2371 CAppUtils::LaunchPAgent(nullptr, &url
);
2374 if (g_Git
.GetHash(hashOld
, L
"HEAD"))
2376 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash."), L
"TortoiseGit", MB_ICONERROR
);
2381 if (CRegDWORD(L
"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE
) == FALSE
)
2382 args
+= L
" --no-rebase";
2384 if (bFetchTags
== BST_UNCHECKED
)
2385 args
+= L
" --no-tags";
2386 else if (bFetchTags
== BST_CHECKED
)
2390 args
+= L
" --no-ff";
2393 args
+= L
" --ff-only";
2396 args
+= L
" --squash";
2399 args
+= L
" --no-commit";
2402 args
.AppendFormat(L
" --depth %d", *nDepth
);
2404 if (bPrune
== BST_CHECKED
)
2405 args
+= L
" --prune";
2406 else if (bPrune
== BST_UNCHECKED
)
2407 args
+= L
" --no-prune";
2410 args
+= L
" --allow-unrelated-histories";
2413 cmd
.Format(L
"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR
)args
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranchName
);
2414 CProgressDlg progress
;
2415 progress
.m_GitCmd
= cmd
;
2417 CGitHash hashNew
; // declare outside lambda, because it is captured by reference
2418 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2422 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2424 STRING_VECTOR remotes
;
2425 g_Git
.GetRemoteList(remotes
);
2426 if (std::find(remotes
.begin(), remotes
.end(), url
) != remotes
.end())
2428 CString currentBranch
;
2429 if (g_Git
.GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
))
2430 currentBranch
.Empty();
2431 CString remoteRef
= L
"remotes/" + url
+ L
"/" + remoteBranchName
;
2432 if (!currentBranch
.IsEmpty() && remoteBranchName
.IsEmpty())
2434 CString pullRemote
, pullBranch
;
2435 g_Git
.GetRemoteTrackedBranch(currentBranch
, pullRemote
, pullBranch
);
2436 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2437 remoteRef
= L
"remotes/" + pullRemote
+ L
"/" + pullBranch
;
2440 g_Git
.IsFastForward(L
"HEAD", remoteRef
, &common
);
2441 if (common
.IsEmpty())
2442 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoPull(url
, bAutoLoad
, bFetchTags
, bNoFF
, bFFonly
, bSquash
, bNoCommit
, nDepth
, bPrune
, remoteBranchName
, showPush
, showStashPop
, true); });
2446 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(); });
2447 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ CAppUtils::StashSave(L
"", true); });
2452 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
2454 if (g_Git
.GetHash(hashNew
, L
"HEAD"))
2455 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash after pulling."), L
"TortoiseGit", MB_ICONERROR
);
2458 postCmdList
.emplace_back(IDI_DIFF
, IDS_PROC_PULL_DIFFS
, [&]
2461 dlg
.SetDiff(nullptr, hashOld
.ToString(), hashNew
.ToString());
2464 postCmdList
.emplace_back(IDI_LOG
, IDS_PROC_PULL_LOG
, [&]
2467 dlg
.SetParams(CTGitPath(L
""), CTGitPath(L
""), L
"", hashOld
.ToString() + L
".." + hashNew
.ToString(), 0);
2473 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
2475 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
2476 if (gitPath
.HasSubmodules())
2478 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
2481 sCmd
.Format(L
"/command:subupdate /bkpath:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
2482 CAppUtils::RunTortoiseGitProc(sCmd
);
2487 INT_PTR ret
= progress
.DoModal();
2489 if (ret
== IDOK
&& progress
.m_GitStatus
== 1 && progress
.m_LogText
.Find(L
"CONFLICT") >= 0 && CMessageBox::Show(nullptr, IDS_SEECHANGES
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
2491 CChangedDlg changeddlg
;
2492 changeddlg
.m_pathList
.AddPath(CTGitPath());
2493 changeddlg
.DoModal();
2501 bool CAppUtils::Pull(bool showPush
, bool showStashPop
)
2503 if (IsTGitRebaseActive())
2507 dlg
.m_IsPull
= TRUE
;
2508 if (dlg
.DoModal() == IDOK
)
2510 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2512 return DoFetch(dlg
.m_RemoteURL
,
2513 FALSE
, // Fetch all remotes
2514 dlg
.m_bAutoLoad
== BST_CHECKED
,
2516 dlg
.m_bDepth
== BST_CHECKED
,
2519 dlg
.m_RemoteBranchName
,
2520 dlg
.m_bRebaseActivatedInConfigForPull
? 2 : 1, // Rebase after fetching
2521 dlg
.m_bRebasePreserveMerges
== TRUE
); // Preserve merges on rebase
2523 return DoPull(dlg
.m_RemoteURL
, dlg
.m_bAutoLoad
== BST_CHECKED
, dlg
.m_bFetchTags
, dlg
.m_bNoFF
== BST_CHECKED
, dlg
.m_bFFonly
== BST_CHECKED
, dlg
.m_bSquash
== BST_CHECKED
, dlg
.m_bNoCommit
== BST_CHECKED
, dlg
.m_bDepth
? &dlg
.m_nDepth
: nullptr, dlg
.m_bPrune
, dlg
.m_RemoteBranchName
, showPush
, showStashPop
, false);
2529 bool CAppUtils::RebaseAfterFetch(const CString
& upstream
, int rebase
, bool preserveMerges
)
2534 if (!upstream
.IsEmpty())
2535 dlg
.m_Upstream
= upstream
;
2536 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENULOG
)));
2537 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH
)));
2538 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL
)));
2539 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE
)));
2540 dlg
.m_bRebaseAutoStart
= (rebase
== 2);
2541 dlg
.m_bPreserveMerges
= preserveMerges
;
2542 INT_PTR response
= dlg
.DoModal();
2543 if (response
== IDOK
)
2545 else if (response
== IDC_REBASE_POST_BUTTON
)
2547 CString cmd
= _T("/command:log");
2548 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2549 CAppUtils::RunTortoiseGitProc(cmd
);
2552 else if (response
== IDC_REBASE_POST_BUTTON
+ 1)
2554 else if (response
== IDC_REBASE_POST_BUTTON
+ 2)
2556 CString cmd
, out
, err
;
2557 cmd
.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2558 (LPCTSTR
)g_Git
.m_CurrentDir
,
2559 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Upstream
),
2560 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Branch
));
2561 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
2563 CMessageBox::Show(nullptr, out
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2566 CAppUtils::SendPatchMail(cmd
, out
);
2569 else if (response
== IDC_REBASE_POST_BUTTON
+ 3)
2571 else if (response
== IDCANCEL
)
2577 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
)
2581 if (fetchAllRemotes
)
2584 g_Git
.GetRemoteList(list
);
2586 for (const auto& remote
: list
)
2587 CAppUtils::LaunchPAgent(nullptr, &remote
);
2590 CAppUtils::LaunchPAgent(nullptr, &url
);
2593 CString upstream
= _T("FETCH_HEAD");
2594 CGitHash oldUpstreamHash
;
2598 g_Git
.GetRemoteList(list
);
2599 for (auto it
= list
.cbegin(); it
!= list
.cend(); ++it
)
2603 CString remote
, trackedBranch
;
2604 g_Git
.GetRemoteTrackedBranchForHEAD(remote
, trackedBranch
);
2605 if (!remote
.IsEmpty() && !trackedBranch
.IsEmpty())
2607 upstream
= L
"remotes/" + remote
+ L
"/" + trackedBranch
;
2608 g_Git
.GetHash(oldUpstreamHash
, upstream
);
2616 arg
= _T(" --progress");
2619 arg
.AppendFormat(_T(" --depth %d"), nDepth
);
2622 arg
+= _T(" --prune");
2623 else if (prune
== FALSE
)
2624 arg
+= _T(" --no-prune");
2627 arg
+= _T(" --tags");
2628 else if (fetchTags
== 0)
2629 arg
+= _T(" --no-tags");
2631 if (fetchAllRemotes
)
2632 cmd
.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR
)arg
);
2634 cmd
.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR
)arg
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranch
);
2636 CProgressDlg progress
;
2637 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2641 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ DoFetch(url
, fetchAllRemotes
, loadPuttyAgent
, prune
, bDepth
, nDepth
, fetchTags
, remoteBranch
, runRebase
, rebasePreserveMerges
); });
2645 postCmdList
.emplace_back(IDI_LOG
, IDS_MENULOG
, []
2647 CString cmd
= _T("/command:log");
2648 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2649 CAppUtils::RunTortoiseGitProc(cmd
);
2652 postCmdList
.emplace_back(IDI_REVERT
, IDS_PROC_RESET
, []
2654 CString pullRemote
, pullBranch
;
2655 g_Git
.GetRemoteTrackedBranchForHEAD(pullRemote
, pullBranch
);
2656 CString defaultUpstream
;
2657 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2658 defaultUpstream
.Format(_T("remotes/%s/%s"), (LPCTSTR
)pullRemote
, (LPCTSTR
)pullBranch
);
2659 CAppUtils::GitReset(&defaultUpstream
, 2);
2662 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, []{ CAppUtils::Fetch(); });
2664 if (!runRebase
&& !GitAdminDir::IsBareRepo(g_Git
.m_CurrentDir
))
2665 postCmdList
.emplace_back(IDI_REBASE
, IDS_MENUREBASE
, [&]{ runRebase
= false; CAppUtils::RebaseAfterFetch(); });
2668 progress
.m_GitCmd
= cmd
;
2670 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_FETCH
))
2672 CGitProgressDlg gitdlg
;
2673 FetchProgressCommand fetchProgressCommand
;
2674 if (!fetchAllRemotes
)
2675 fetchProgressCommand
.SetUrl(url
);
2676 gitdlg
.SetCommand(&fetchProgressCommand
);
2677 fetchProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
2678 fetchProgressCommand
.SetAutoTag(fetchTags
== 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL
: fetchTags
== 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO
: GIT_REMOTE_DOWNLOAD_TAGS_NONE
);
2679 if (!fetchAllRemotes
)
2680 fetchProgressCommand
.SetRefSpec(remoteBranch
);
2681 return gitdlg
.DoModal() == IDOK
;
2684 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
&)
2686 if (exitCode
|| !runRebase
)
2689 CGitHash remoteBranchHash
;
2690 g_Git
.GetHash(remoteBranchHash
, upstream
);
2691 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
)
2694 if (runRebase
== 1 && g_Git
.IsFastForward(L
"HEAD", upstream
))
2696 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
);
2701 CProgressDlg mergeProgress
;
2702 mergeProgress
.m_GitCmd
= L
"git.exe merge --ff-only " + upstream
;
2703 mergeProgress
.m_AutoClose
= AUTOCLOSE_IF_NO_ERRORS
;
2704 mergeProgress
.m_PostCmdCallback
= [](DWORD status
, PostCmdList
& postCmdList
)
2706 if (status
&& g_Git
.HasWorkingTreeConflicts())
2708 // there are conflict files
2709 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
2712 sCmd
.Format(L
"/command:commit /path:\"%s\"", g_Git
.m_CurrentDir
);
2713 CAppUtils::RunTortoiseGitProc(sCmd
);
2717 mergeProgress
.DoModal();
2722 CAppUtils::RebaseAfterFetch(upstream
, runRebase
, rebasePreserveMerges
);
2725 return progress
.DoModal() == IDOK
;
2728 bool CAppUtils::Fetch(const CString
& remoteName
, bool allRemotes
)
2731 dlg
.m_PreSelectRemote
= remoteName
;
2733 dlg
.m_bAllRemotes
= allRemotes
;
2735 if(dlg
.DoModal()==IDOK
)
2736 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
);
2741 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
)
2744 DWORD exitcode
= 0xFFFFFFFF;
2745 if (CHooks::Instance().PrePush(g_Git
.m_CurrentDir
, exitcode
, error
))
2750 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2751 CMessageBox::Show(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2756 int iRecurseSubmodules
= 0;
2757 if (GetMsysgitVersion() >= 0x02070000)
2759 CString sRecurseSubmodules
= g_Git
.GetConfigValue(_T("push.recurseSubmodules"));
2760 if (sRecurseSubmodules
== _T("check"))
2761 iRecurseSubmodules
= 1;
2762 else if (sRecurseSubmodules
== _T("on-demand"))
2763 iRecurseSubmodules
= 2;
2768 arg
+= _T("--thin ");
2769 if (tags
&& !allBranches
)
2770 arg
+= _T("--tags ");
2772 arg
+= _T("--force ");
2774 arg
+= _T("--force-with-lease ");
2776 arg
+= _T("--set-upstream ");
2777 if (recurseSubmodules
== 0 && recurseSubmodules
!= iRecurseSubmodules
)
2778 arg
+= _T("--recurse-submodules=no ");
2779 if (recurseSubmodules
== 1 && recurseSubmodules
!= iRecurseSubmodules
)
2780 arg
+= _T("--recurse-submodules=check ");
2781 if (recurseSubmodules
== 2 && recurseSubmodules
!= iRecurseSubmodules
)
2782 arg
+= _T("--recurse-submodules=on-demand ");
2784 arg
+= _T("--progress ");
2786 CProgressDlg progress
;
2788 STRING_VECTOR remotesList
;
2790 g_Git
.GetRemoteList(remotesList
);
2792 remotesList
.push_back(remote
);
2794 for (unsigned int i
= 0; i
< remotesList
.size(); ++i
)
2797 CAppUtils::LaunchPAgent(nullptr, &remotesList
[i
]);
2802 cmd
.Format(_T("git.exe push --all %s\"%s\""),
2804 (LPCTSTR
)remotesList
[i
]);
2808 progress
.m_GitCmdList
.push_back(cmd
);
2809 cmd
.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR
)arg
, (LPCTSTR
)remotesList
[i
]);
2814 cmd
.Format(_T("git.exe push %s\"%s\" %s"),
2816 (LPCTSTR
)remotesList
[i
],
2817 (LPCTSTR
)localBranch
);
2818 if (!remoteBranch
.IsEmpty())
2821 cmd
+= remoteBranch
;
2824 progress
.m_GitCmdList
.push_back(cmd
);
2826 if (!allBranches
&& !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE
))
2828 cmd
.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR
)localBranch
);
2829 progress
.m_GitCmdList
.push_back(cmd
);
2833 CString superprojectRoot
;
2834 GitAdminDir::HasAdminDir(g_Git
.m_CurrentDir
, false, &superprojectRoot
);
2835 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2837 // need to execute hooks as those might be needed by post action commands
2838 DWORD exitcode
= 0xFFFFFFFF;
2840 if (CHooks::Instance().PostPush(g_Git
.m_CurrentDir
, exitcode
, error
))
2845 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2846 MessageBox(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2852 bool rejected
= progress
.GetLogText().Find(_T("! [rejected]")) > 0;
2855 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, []{ Pull(true); });
2856 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, [&]{ Fetch(allRemotes
? _T("") : remote
, allRemotes
); });
2858 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2862 postCmdList
.emplace_back(IDS_PROC_REQUESTPULL
, [&]{ RequestPull(remoteBranch
); });
2863 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2864 postCmdList
.emplace_back(IDI_SWITCH
, IDS_MENUSWITCH
, [&]{ Switch(); });
2865 if (!superprojectRoot
.IsEmpty())
2867 postCmdList
.emplace_back(IDI_COMMIT
, IDS_PROC_COMMIT_SUPERPROJECT
, [&]
2870 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)superprojectRoot
);
2871 RunTortoiseGitProc(sCmd
);
2876 INT_PTR ret
= progress
.DoModal();
2880 bool CAppUtils::Push(const CString
& selectLocalBranch
)
2883 dlg
.m_BranchSourceName
= selectLocalBranch
;
2885 if (dlg
.DoModal() == IDOK
)
2886 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
);
2891 bool CAppUtils::RequestPull(const CString
& endrevision
, const CString
& repositoryUrl
, bool bIsMainWnd
)
2893 CRequestPullDlg dlg
;
2894 dlg
.m_RepositoryURL
= repositoryUrl
;
2895 dlg
.m_EndRevision
= endrevision
;
2896 if (dlg
.DoModal()==IDOK
)
2899 cmd
.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR
)dlg
.m_StartRevision
, (LPCTSTR
)dlg
.m_RepositoryURL
, (LPCTSTR
)dlg
.m_EndRevision
);
2901 CSysProgressDlg sysProgressDlg
;
2902 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
2903 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST
)));
2904 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
2905 sysProgressDlg
.SetShowProgressBar(false);
2906 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
2908 CString tempFileName
= GetTempFile();
2910 DeleteFile(tempFileName
);
2911 CreateDirectory(tempFileName
, nullptr);
2912 tempFileName
+= _T("\\pullrequest.txt");
2913 if (g_Git
.RunLogFile(cmd
, tempFileName
, &err
))
2916 msg
.LoadString(IDS_ERR_PULLREUQESTFAILED
);
2917 MessageBox(nullptr, msg
+ _T("\n") + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2921 if (sysProgressDlg
.HasUserCancelled())
2923 CMessageBox::Show(nullptr, IDS_USERCANCELLED
, IDS_APPNAME
, MB_OK
);
2924 ::DeleteFile(tempFileName
);
2928 sysProgressDlg
.Stop();
2930 if (dlg
.m_bSendMail
)
2932 CSendMailDlg sendmaildlg
;
2933 sendmaildlg
.m_PathList
= CTGitPathList(CTGitPath(tempFileName
));
2934 sendmaildlg
.m_bCustomSubject
= true;
2936 if (sendmaildlg
.DoModal() == IDOK
)
2938 if (sendmaildlg
.m_PathList
.IsEmpty())
2941 CGitProgressDlg progDlg
;
2943 theApp
.m_pMainWnd
= &progDlg
;
2944 SendMailProgressCommand sendMailProgressCommand
;
2945 progDlg
.SetCommand(&sendMailProgressCommand
);
2947 sendMailProgressCommand
.SetPathList(sendmaildlg
.m_PathList
);
2948 progDlg
.SetItemCount(sendmaildlg
.m_PathList
.GetCount());
2950 CSendMailCombineable
sendMailCombineable(sendmaildlg
.m_To
, sendmaildlg
.m_CC
, sendmaildlg
.m_Subject
, !!sendmaildlg
.m_bAttachment
, !!sendmaildlg
.m_bCombine
);
2951 sendMailProgressCommand
.SetSendMailOption(&sendMailCombineable
);
2960 CAppUtils::LaunchAlternativeEditor(tempFileName
);
2965 void CAppUtils::RemoveTrailSlash(CString
&path
)
2970 // For URL, do not trim the slash just after the host name component.
2971 int index
= path
.Find(_T("://"));
2975 index
= path
.Find(_T('/'), index
);
2976 if (index
== path
.GetLength() - 1)
2980 while(path
[path
.GetLength()-1] == _T('\\') || path
[path
.GetLength()-1] == _T('/' ) )
2982 path
.Truncate(path
.GetLength() - 1);
2988 bool CAppUtils::CheckUserData()
2990 while(g_Git
.GetUserName().IsEmpty() || g_Git
.GetUserEmail().IsEmpty())
2992 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA
, IDS_APPNAME
, MB_YESNO
| MB_ICONERROR
) == IDYES
)
2994 CTGitPath
path(g_Git
.m_CurrentDir
);
2995 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
,&path
);
2996 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
2997 dlg
.SetTreeWidth(220);
2998 dlg
.m_DefaultPage
= _T("gitconfig");
3001 dlg
.HandleRestart();
3011 BOOL
CAppUtils::Commit(const CString
& bugid
, BOOL bWholeProject
, CString
&sLogMsg
,
3012 CTGitPathList
&pathList
,
3013 CTGitPathList
&selectedList
,
3014 bool bSelectFilesForCommit
)
3016 bool bFailed
= true;
3018 if (!CheckUserData())
3025 dlg
.m_sBugID
= bugid
;
3027 dlg
.m_bWholeProject
= bWholeProject
;
3029 dlg
.m_sLogMessage
= sLogMsg
;
3030 dlg
.m_pathList
= pathList
;
3031 dlg
.m_checkedPathList
= selectedList
;
3032 dlg
.m_bSelectFilesForCommit
= bSelectFilesForCommit
;
3033 if (dlg
.DoModal() == IDOK
)
3035 if (dlg
.m_pathList
.IsEmpty())
3037 // if the user hasn't changed the list of selected items
3038 // we don't use that list. Because if we would use the list
3039 // of pre-checked items, the dialog would show different
3040 // checked items on the next startup: it would only try
3041 // to check the parent folder (which might not even show)
3042 // instead, we simply use an empty list and let the
3043 // default checking do its job.
3044 if (!dlg
.m_pathList
.IsEqual(pathList
))
3045 selectedList
= dlg
.m_pathList
;
3046 pathList
= dlg
.m_updatedPathList
;
3047 sLogMsg
= dlg
.m_sLogMessage
;
3048 bSelectFilesForCommit
= true;
3050 switch (dlg
.m_PostCmd
)
3052 case GIT_POSTCOMMIT_CMD_DCOMMIT
:
3053 CAppUtils::SVNDCommit();
3055 case GIT_POSTCOMMIT_CMD_PUSH
:
3058 case GIT_POSTCOMMIT_CMD_CREATETAG
:
3059 CAppUtils::CreateBranchTag(TRUE
);
3061 case GIT_POSTCOMMIT_CMD_PULL
:
3062 CAppUtils::Pull(true);
3068 // CGitProgressDlg progDlg;
3069 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3070 // if (parser.HasVal(_T("closeonend")))
3071 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3072 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3073 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3074 // progDlg.SetPathList(dlg.m_pathList);
3075 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3076 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3077 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3078 // progDlg.SetItemCount(dlg.m_itemsCount);
3079 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3080 // progDlg.DoModal();
3081 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3082 // err = (DWORD)progDlg.DidErrorsOccur();
3083 // bFailed = progDlg.DidErrorsOccur();
3084 // bRet = progDlg.DidErrorsOccur();
3085 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3086 // if (DWORD(bFailRepeat)==0)
3087 // bFailed = false; // do not repeat if the user chose not to in the settings.
3093 BOOL
CAppUtils::SVNDCommit()
3095 CSVNDCommitDlg dcommitdlg
;
3096 CString gitSetting
= g_Git
.GetConfigValue(_T("svn.rmdir"));
3097 if (gitSetting
.IsEmpty()) {
3098 if (dcommitdlg
.DoModal() != IDOK
)
3102 if (dcommitdlg
.m_remember
)
3104 if (dcommitdlg
.m_rmdir
)
3105 gitSetting
= _T("true");
3107 gitSetting
= _T("false");
3108 if(g_Git
.SetConfigValue(_T("svn.rmdir"),gitSetting
))
3111 msg
.Format(IDS_PROC_SAVECONFIGFAILED
, _T("svn.rmdir"), gitSetting
);
3112 CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3118 BOOL IsStash
= false;
3119 if(!g_Git
.CheckCleanWorkTree())
3121 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3123 CSysProgressDlg sysProgressDlg
;
3124 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3125 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3126 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3127 sysProgressDlg
.SetShowProgressBar(false);
3128 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3129 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3132 cmd
=_T("git.exe stash");
3133 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3135 sysProgressDlg
.Stop();
3136 MessageBox(nullptr, out
,_T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3139 sysProgressDlg
.Stop();
3147 CProgressDlg progress
;
3148 if (dcommitdlg
.m_rmdir
)
3149 progress
.m_GitCmd
=_T("git.exe svn dcommit --rmdir");
3151 progress
.m_GitCmd
=_T("git.exe svn dcommit");
3152 if(progress
.DoModal()==IDOK
&& progress
.m_GitStatus
== 0)
3156 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
3158 CSysProgressDlg sysProgressDlg
;
3159 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3160 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3161 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3162 sysProgressDlg
.SetShowProgressBar(false);
3163 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3164 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3167 cmd
=_T("git.exe stash pop");
3168 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3170 sysProgressDlg
.Stop();
3171 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3174 sysProgressDlg
.Stop();
3184 static bool DoMerge(bool noFF
, bool ffOnly
, bool squash
, bool noCommit
, const int* log
, bool unrelated
, const CString
& mergeStrategy
, const CString
& strategyOption
, const CString
& strategyParam
, const CString
& logMessage
, const CString
& version
, bool isBranch
, bool showStashPop
)
3188 args
+= L
" --no-ff";
3190 args
+= L
" --ff-only";
3193 args
+= L
" --squash";
3196 args
+= L
" --no-commit";
3199 args
+= L
" --allow-unrelated-histories";
3202 args
.AppendFormat(L
" --log=%d", *log
);
3204 if (!mergeStrategy
.IsEmpty())
3206 args
+= L
" --strategy=" + mergeStrategy
;
3207 if (!strategyOption
.IsEmpty())
3209 args
+= L
" --strategy-option=" + strategyOption
;
3210 if (!strategyParam
.IsEmpty())
3211 args
+= L
'=' + strategyParam
;
3215 if (!logMessage
.IsEmpty())
3217 CString logmsg
= logMessage
;
3218 logmsg
.Replace(L
"\\\"", L
"\\\\\"");
3219 logmsg
.Replace(L
"\"", L
"\\\"");
3220 args
+= L
" -m \"" + logmsg
+ L
"\"";
3223 CString mergeVersion
= g_Git
.FixBranchName(version
);
3225 cmd
.Format(L
"git.exe merge%s %s", (LPCTSTR
)args
, (LPCTSTR
)mergeVersion
);
3227 CProgressDlg Prodlg
;
3228 Prodlg
.m_GitCmd
= cmd
;
3230 Prodlg
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3234 int hasConflicts
= g_Git
.HasWorkingTreeConflicts();
3235 if (hasConflicts
< 0)
3236 CMessageBox::Show(nullptr, g_Git
.GetGitLastErr(L
"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS
), L
"TortoiseGit", MB_ICONEXCLAMATION
);
3237 else if (hasConflicts
)
3239 // there are conflict files
3241 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
3244 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3245 CAppUtils::RunTortoiseGitProc(sCmd
);
3249 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3252 g_Git
.IsFastForward(L
"HEAD", mergeVersion
, &common
);
3253 if (common
.IsEmpty())
3254 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoMerge(noFF
, ffOnly
, squash
, noCommit
, log
, true, mergeStrategy
, strategyOption
, strategyParam
, logMessage
, version
, isBranch
, showStashPop
); });
3257 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [=]{ CAppUtils::StashSave(L
"", false, false, true, mergeVersion
); });
3263 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
3267 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []
3270 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3271 CAppUtils::RunTortoiseGitProc(sCmd
);
3276 if (isBranch
&& !CStringUtils::StartsWith(version
, L
"remotes/")) // do not ask to remove remote branches
3278 postCmdList
.emplace_back(IDI_DELETE
, IDS_PROC_REMOVEBRANCH
, [&]
3281 msg
.Format(IDS_PROC_DELETEBRANCHTAG
, version
);
3282 if (CMessageBox::Show(nullptr, msg
, L
"TortoiseGit", 2, IDI_QUESTION
, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON
)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON
))) == 1)
3285 cmd
.Format(L
"git.exe branch -D -- %s", (LPCTSTR
)version
);
3286 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3287 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
);
3292 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
3294 BOOL hasGitSVN
= CTGitPath(g_Git
.m_CurrentDir
).GetAdminDirMask() & ITEMIS_GITSVN
;
3296 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSVNDCOMMIT
, []{ CAppUtils::SVNDCommit(); });
3300 return !Prodlg
.m_GitStatus
;
3303 BOOL
CAppUtils::Merge(const CString
* commit
, bool showStashPop
)
3305 if (!CheckUserData())
3308 if (IsTGitRebaseActive())
3313 dlg
.m_initialRefName
= *commit
;
3315 if (dlg
.DoModal() == IDOK
)
3316 return DoMerge(dlg
.m_bNoFF
== BST_CHECKED
, dlg
.m_bFFonly
== BST_CHECKED
, dlg
.m_bSquash
== BST_CHECKED
, dlg
.m_bNoCommit
== BST_CHECKED
, dlg
.m_bLog
? &dlg
.m_nLog
: nullptr, false, dlg
.m_MergeStrategy
, dlg
.m_StrategyOption
, dlg
.m_StrategyParam
, dlg
.m_strLogMesage
, dlg
.m_VersionName
, dlg
.m_bIsBranch
, showStashPop
);
3321 BOOL
CAppUtils::MergeAbort()
3324 if (dlg
.DoModal() == IDOK
)
3325 return Reset(_T("HEAD"), dlg
.m_ResetType
+ 1);
3330 void CAppUtils::EditNote(GitRevLoglist
* rev
)
3332 if (!CheckUserData())
3336 dlg
.m_sHintText
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3337 dlg
.m_sInputText
= rev
->m_Notes
;
3338 dlg
.m_sTitle
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3339 //dlg.m_pProjectProperties = &m_ProjectProperties;
3340 dlg
.m_bUseLogWidth
= true;
3341 if(dlg
.DoModal() == IDOK
)
3344 cmd
=_T("notes add -f -F \"");
3346 CString tempfile
=::GetTempFile();
3347 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_sInputText
))
3349 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3354 cmd
+= rev
->m_CommitHash
.ToString();
3358 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd
, CP_UTF8
).GetBuffer()))
3359 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3361 rev
->m_Notes
= dlg
.m_sInputText
;
3364 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3366 ::DeleteFile(tempfile
);
3371 int CAppUtils::GetMsysgitVersion()
3373 if (g_Git
.ms_LastMsysGitVersion
)
3374 return g_Git
.ms_LastMsysGitVersion
;
3377 CString versiondebug
;
3380 CRegDWORD regTime
= CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3381 CRegDWORD regVersion
= CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3383 CString gitpath
= CGit::ms_LastMsysGitDir
+_T("\\git.exe");
3386 if (!CGit::GetFileModifyTime(gitpath
, &time
))
3388 if((DWORD
)time
== regTime
)
3390 g_Git
.ms_LastMsysGitVersion
= regVersion
;
3396 int ver
= g_Git
.GetGitVersion(&versiondebug
, &err
);
3399 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
);
3406 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug
+ _T("\""), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3411 regTime
= time
&0xFFFFFFFF;
3413 g_Git
.ms_LastMsysGitVersion
= ver
;
3418 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd
)
3420 typedef HRESULT (WINAPI
*SHGPSFW
) (HWND hwnd
,REFIID riid
,void** ppv
);
3422 CAutoLibrary hShell
= AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3424 if (hShell
.IsValid()) {
3425 SHGPSFW pfnSHGPSFW
= (SHGPSFW
)::GetProcAddress(hShell
, "SHGetPropertyStoreForWindow");
3427 IPropertyStore
*pps
;
3428 HRESULT hr
= pfnSHGPSFW(hWnd
, IID_PPV_ARGS(&pps
));
3429 if (SUCCEEDED(hr
)) {
3432 var
.boolVal
= VARIANT_TRUE
;
3433 pps
->SetValue(PKEY_AppUserModel_PreventPinning
, var
);
3440 void CAppUtils::SetWindowTitle(HWND hWnd
, const CString
& urlorpath
, const CString
& dialogname
)
3442 ASSERT(dialogname
.GetLength() < 70);
3443 ASSERT(urlorpath
.GetLength() < MAX_PATH
);
3444 WCHAR pathbuf
[MAX_PATH
] = {0};
3446 PathCompactPathEx(pathbuf
, urlorpath
, 70 - dialogname
.GetLength(), 0);
3448 wcscat_s(pathbuf
, L
" - ");
3449 wcscat_s(pathbuf
, dialogname
);
3450 wcscat_s(pathbuf
, L
" - ");
3451 wcscat_s(pathbuf
, CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3452 SetWindowText(hWnd
, pathbuf
);
3455 bool CAppUtils::BisectStart(const CString
& lastGood
, const CString
& firstBad
, bool bIsMainWnd
)
3457 if (!g_Git
.CheckCleanWorkTree())
3459 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3461 CSysProgressDlg sysProgressDlg
;
3462 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3463 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3464 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3465 sysProgressDlg
.SetShowProgressBar(false);
3466 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3467 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3470 cmd
= _T("git.exe stash");
3471 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3473 sysProgressDlg
.Stop();
3474 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3477 sysProgressDlg
.Stop();
3483 CBisectStartDlg bisectStartDlg
;
3485 if (!lastGood
.IsEmpty())
3486 bisectStartDlg
.m_sLastGood
= lastGood
;
3487 if (!firstBad
.IsEmpty())
3488 bisectStartDlg
.m_sFirstBad
= firstBad
;
3490 if (bisectStartDlg
.DoModal() == IDOK
)
3492 CProgressDlg progress
;
3494 theApp
.m_pMainWnd
= &progress
;
3495 progress
.m_GitCmdList
.push_back(_T("git.exe bisect start"));
3496 progress
.m_GitCmdList
.push_back(_T("git.exe bisect good ") + bisectStartDlg
.m_LastGoodRevision
);
3497 progress
.m_GitCmdList
.push_back(_T("git.exe bisect bad ") + bisectStartDlg
.m_FirstBadRevision
);
3499 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3504 CTGitPath
path(g_Git
.m_CurrentDir
);
3505 if (path
.HasSubmodules())
3507 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3510 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3511 CAppUtils::RunTortoiseGitProc(sCmd
);
3516 INT_PTR ret
= progress
.DoModal();
3523 bool CAppUtils::BisectOperation(const CString
& op
, const CString
& ref
, bool bIsMainWnd
)
3525 CString cmd
= _T("git.exe bisect ") + op
;
3533 CProgressDlg progress
;
3535 theApp
.m_pMainWnd
= &progress
;
3536 progress
.m_GitCmd
= cmd
;
3538 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3543 CTGitPath path
= g_Git
.m_CurrentDir
;
3544 if (path
.HasSubmodules())
3546 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3549 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3550 CAppUtils::RunTortoiseGitProc(sCmd
);
3554 if (op
!= _T("reset"))
3555 postCmdList
.emplace_back(IDS_MENUBISECTRESET
, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3558 INT_PTR ret
= progress
.DoModal();
3562 int CAppUtils::Git2GetUserPassword(git_cred
**out
, const char *url
, const char *username_from_url
, unsigned int /*allowed_types*/, void * /*payload*/)
3565 dlg
.m_URL
= CUnicodeUtils::GetUnicode(url
, CP_UTF8
);
3566 if (username_from_url
)
3567 dlg
.m_UserName
= CUnicodeUtils::GetUnicode(username_from_url
, CP_UTF8
);
3569 CStringA username
, password
;
3570 if (dlg
.DoModal() == IDOK
)
3572 username
= CUnicodeUtils::GetMulti(dlg
.m_UserName
, CP_UTF8
);
3573 password
= CUnicodeUtils::GetMulti(dlg
.m_Password
, CP_UTF8
);
3574 return git_cred_userpass_plaintext_new(out
, username
, password
);
3576 giterr_set_str(GITERR_NONE
, "User cancelled.");
3580 int CAppUtils::Git2CertificateCheck(git_cert
* base_cert
, int /*valid*/, const char* host
, void* /*payload*/)
3582 if (base_cert
->cert_type
== GIT_CERT_X509
)
3584 git_cert_x509
* cert
= (git_cert_x509
*)base_cert
;
3586 if (last_accepted_cert
.cmp(cert
))
3589 PCCERT_CONTEXT pServerCert
= CertCreateCertificateContext(X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, (BYTE
*)cert
->data
, (DWORD
)cert
->len
);
3590 SCOPE_EXIT
{ CertFreeCertificateContext(pServerCert
); };
3592 DWORD verificationError
= VerifyServerCertificate(pServerCert
, CUnicodeUtils::GetUnicode(host
).GetBuffer(), 0);
3593 if (!verificationError
)
3595 last_accepted_cert
.set(cert
);
3599 CString servernameInCert
;
3600 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, 0, nullptr, CStrBuf(servernameInCert
, 128), 128);
3603 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, CERT_NAME_ISSUER_FLAG
, nullptr, CStrBuf(issuer
, 128), 128);
3605 CCheckCertificateDlg dlg
;
3607 dlg
.m_sCertificateCN
= servernameInCert
;
3608 dlg
.m_sCertificateIssuer
= issuer
;
3609 dlg
.m_sHostname
= CUnicodeUtils::GetUnicode(host
);
3610 dlg
.m_sError
= CFormatMessageWrapper(verificationError
);
3611 if (dlg
.DoModal() == IDOK
)
3613 last_accepted_cert
.set(cert
);
3617 return GIT_ECERTIFICATE
;
3620 int CAppUtils::ExploreTo(HWND hwnd
, CString path
)
3622 if (PathFileExists(path
))
3625 ITEMIDLIST __unaligned
* pidl
= ILCreateFromPath(path
);
3628 ret
= SHOpenFolderAndSelectItems(pidl
, 0, 0, 0);
3631 return SUCCEEDED(ret
) ? 0 : -1;
3633 // if filepath does not exist any more, navigate to closest matching folder
3636 int pos
= path
.ReverseFind(_T('\\'));
3640 } while (!PathFileExists(path
));
3641 return (INT_PTR
)ShellExecute(hwnd
, _T("explore"), path
, nullptr, nullptr, SW_SHOW
) > 32 ? 0 : -1;
3644 int CAppUtils::ResolveConflict(CTGitPath
& path
, resolve_with resolveWith
)
3646 bool b_local
= false, b_remote
= false;
3650 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3651 if (g_Git
.Run(cmd
, &vector
))
3653 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3658 if (list
.ParserFromLsFile(vector
))
3660 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3666 for (int i
= 0; i
< list
.GetCount(); ++i
)
3668 if (list
[i
].m_Stage
== 2)
3670 if (list
[i
].m_Stage
== 3)
3675 CBlockCacheForPath
block(g_Git
.m_CurrentDir
);
3676 if (path
.IsDirectory()) // is submodule conflict
3678 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.");
3679 if (b_local
&& b_remote
)
3681 if (!path
.HasAdminDir()) // check if submodule is initialized
3683 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).");
3684 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3688 subgit
.m_CurrentDir
= g_Git
.CombinePath(path
);
3689 CGitHash submoduleHead
;
3690 if (subgit
.GetHash(submoduleHead
, _T("HEAD")))
3692 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3695 CString baseHash
, localHash
, remoteHash
;
3696 ParseHashesFromLsFile(vector
, baseHash
, localHash
, remoteHash
);
3697 if (resolveWith
== RESOLVE_WITH_THEIRS
&& submoduleHead
.ToString() != remoteHash
)
3699 CString origPath
= g_Git
.m_CurrentDir
;
3700 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3701 if (!GitReset(&remoteHash
))
3703 g_Git
.m_CurrentDir
= origPath
;
3706 g_Git
.m_CurrentDir
= origPath
;
3708 else if (resolveWith
== RESOLVE_WITH_MINE
&& submoduleHead
.ToString() != localHash
)
3710 CString origPath
= g_Git
.m_CurrentDir
;
3711 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3712 if (!GitReset(&localHash
))
3714 g_Git
.m_CurrentDir
= origPath
;
3717 g_Git
.m_CurrentDir
= origPath
;
3722 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3727 if (resolveWith
== RESOLVE_WITH_THEIRS
)
3729 CString gitcmd
, output
;
3730 if (b_local
&& b_remote
)
3731 gitcmd
.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3733 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3735 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3736 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3738 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3742 else if (resolveWith
== RESOLVE_WITH_MINE
)
3744 CString gitcmd
, output
;
3745 if (b_local
&& b_remote
)
3746 gitcmd
.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3748 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3750 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3751 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3753 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3758 if (b_local
&& b_remote
&& path
.m_Action
& CTGitPath::LOGACTIONS_UNMERGED
)
3760 CString gitcmd
, output
;
3761 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3762 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3763 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3766 path
.m_Action
|= CTGitPath::LOGACTIONS_MODIFIED
;
3767 path
.m_Action
&= ~CTGitPath::LOGACTIONS_UNMERGED
;
3771 RemoveTempMergeFile(path
);
3775 bool CAppUtils::ShellOpen(const CString
& file
, HWND hwnd
/*= nullptr */)
3777 if ((INT_PTR
)ShellExecute(hwnd
, nullptr, file
, nullptr, nullptr, SW_SHOW
) > HINSTANCE_ERROR
)
3780 return ShowOpenWithDialog(file
, hwnd
);
3783 bool CAppUtils::ShowOpenWithDialog(const CString
& file
, HWND hwnd
/*= nullptr */)
3785 OPENASINFO oi
= { 0 };
3787 oi
.oaifInFlags
= OAIF_EXEC
;
3788 return SUCCEEDED(SHOpenWithDialog(hwnd
, &oi
));
3791 bool CAppUtils::IsTGitRebaseActive()
3794 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3797 if (!PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3800 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND
, IDS_APPNAME
, 2, IDI_EXCLAMATION
, IDS_REMOVESTALEBUTTON
, IDS_ABORTBUTTON
) == 2)
3803 RemoveDirectory(adminDir
+ L
"tgitrebase.active");