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 (com
.Left(1).Compare(L
"#") == 0)
273 if (com
.IsEmpty()||(com
.Left(1).Compare(_T("#"))==0))
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
= viewer
.Left(1) == _T("#");
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
= viewer
.Left(1) == _T("#");
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 void CAppUtils::CreateFontForLogs(CFont
& fontToCreate
)
649 HDC hScreenDC
= ::GetDC(nullptr);
650 logFont
.lfHeight
= -MulDiv((DWORD
)CRegDWORD(_T("Software\\TortoiseGit\\LogFontSize"), 8), GetDeviceCaps(hScreenDC
, LOGPIXELSY
), 72);
651 ::ReleaseDC(nullptr, hScreenDC
);
653 logFont
.lfEscapement
= 0;
654 logFont
.lfOrientation
= 0;
655 logFont
.lfWeight
= FW_NORMAL
;
656 logFont
.lfItalic
= 0;
657 logFont
.lfUnderline
= 0;
658 logFont
.lfStrikeOut
= 0;
659 logFont
.lfCharSet
= DEFAULT_CHARSET
;
660 logFont
.lfOutPrecision
= OUT_DEFAULT_PRECIS
;
661 logFont
.lfClipPrecision
= CLIP_DEFAULT_PRECIS
;
662 logFont
.lfQuality
= DRAFT_QUALITY
;
663 logFont
.lfPitchAndFamily
= FF_DONTCARE
| FIXED_PITCH
;
664 _tcscpy_s(logFont
.lfFaceName
, 32, (LPCTSTR
)(CString
)CRegString(_T("Software\\TortoiseGit\\LogFontName"), _T("Courier New")));
665 VERIFY(fontToCreate
.CreateFontIndirect(&logFont
));
668 bool CAppUtils::LaunchPAgent(const CString
* keyfile
, const CString
* pRemote
)
679 cmd
.Format(_T("remote.%s.puttykeyfile"), (LPCTSTR
)remote
);
680 key
= g_Git
.GetConfigValue(cmd
);
688 CString proc
=CPathUtils::GetAppDirectory();
689 proc
+= _T("pageant.exe \"");
693 CString tempfile
= GetTempFile();
694 ::DeleteFile(tempfile
);
696 proc
+= _T(" -c \"");
697 proc
+= CPathUtils::GetAppDirectory();
698 proc
+= _T("tgittouch.exe\"");
703 CString appDir
= CPathUtils::GetAppDirectory();
704 bool b
= LaunchApplication(proc
, IDS_ERR_PAGEANT
, true, &appDir
);
709 while(!::PathFileExists(tempfile
))
714 break; //timeout 5 minutes
718 CMessageBox::Show(nullptr, IDS_ERR_PAEGENTTIMEOUT
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
719 ::DeleteFile(tempfile
);
722 bool CAppUtils::LaunchAlternativeEditor(const CString
& filename
, bool uac
)
724 CString editTool
= CRegString(_T("Software\\TortoiseGit\\AlternativeEditor"));
725 if (editTool
.IsEmpty() || (editTool
.Left(1).Compare(_T("#"))==0)) {
726 editTool
= CPathUtils::GetAppDirectory() + _T("notepad2.exe");
730 sCmd
.Format(_T("\"%s\" \"%s\""), (LPCTSTR
)editTool
, (LPCTSTR
)filename
);
732 LaunchApplication(sCmd
, 0, false, nullptr, uac
);
735 bool CAppUtils::LaunchRemoteSetting()
737 CTGitPath
path(g_Git
.m_CurrentDir
);
738 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
, &path
);
739 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
740 dlg
.SetTreeWidth(220);
741 dlg
.m_DefaultPage
= _T("gitremote");
748 * Launch the external blame viewer
750 bool CAppUtils::LaunchTortoiseBlame(const CString
& sBlameFile
, const CString
& Rev
, const CString
& sParams
)
752 CString viewer
= _T("\"") + CPathUtils::GetAppDirectory();
753 viewer
+= _T("TortoiseGitBlame.exe");
754 viewer
+= _T("\" \"") + sBlameFile
+ _T("\"");
755 //viewer += _T(" \"") + sLogFile + _T("\"");
756 //viewer += _T(" \"") + sOriginalFile + _T("\"");
757 if(!Rev
.IsEmpty() && Rev
!= GIT_REV_ZERO
)
758 viewer
+= CString(_T(" /rev:"))+Rev
;
759 if (!g_sGroupingUUID
.IsEmpty())
761 viewer
+= L
" /groupuuid:\"";
762 viewer
+= g_sGroupingUUID
;
765 viewer
+= _T(" ")+sParams
;
767 return LaunchApplication(viewer
, IDS_ERR_TGITBLAME
, false);
770 bool CAppUtils::FormatTextInRichEditControl(CWnd
* pWnd
)
775 bool bStyled
= false;
776 pWnd
->GetWindowText(sText
);
777 // the rich edit control doesn't count the CR char!
778 // to be exact: CRLF is treated as one char.
779 sText
.Remove(_T('\r'));
781 // style each line separately
786 nNewlinePos
= sText
.Find('\n', offset
);
787 CString sLine
= nNewlinePos
>= 0 ? sText
.Mid(offset
, nNewlinePos
- offset
) : sText
.Mid(offset
);
791 while (FindStyleChars(sLine
, '*', start
, end
))
793 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
794 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
795 SetCharFormat(pWnd
, CFM_BOLD
, CFE_BOLD
);
801 while (FindStyleChars(sLine
, '^', start
, end
))
803 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
804 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
805 SetCharFormat(pWnd
, CFM_ITALIC
, CFE_ITALIC
);
811 while (FindStyleChars(sLine
, '_', start
, end
))
813 CHARRANGE range
= {(LONG
)start
+offset
, (LONG
)end
+offset
};
814 pWnd
->SendMessage(EM_EXSETSEL
, NULL
, (LPARAM
)&range
);
815 SetCharFormat(pWnd
, CFM_UNDERLINE
, CFE_UNDERLINE
);
819 offset
= nNewlinePos
+1;
820 } while(nNewlinePos
>=0);
824 bool CAppUtils::FindStyleChars(const CString
& sText
, TCHAR stylechar
, int& start
, int& end
)
827 int last
= sText
.GetLength() - 1;
828 bool bFoundMarker
= false;
829 TCHAR c
= i
== 0 ? _T('\0') : sText
[i
- 1];
830 TCHAR nextChar
= i
>= last
? _T('\0') : sText
[i
+ 1];
832 // find a starting marker
837 nextChar
= sText
[i
+ 1];
839 // IsCharAlphaNumeric can be somewhat expensive.
840 // Long lines of "*****" or "----" will be pre-empted efficiently
841 // by the (c != nextChar) condition.
843 if ((c
== stylechar
) && (c
!= nextChar
))
845 if (IsCharAlphaNumeric(nextChar
) && !IsCharAlphaNumeric(prevChar
))
857 // find ending marker
860 bFoundMarker
= false;
867 if ((i
== last
) || (!IsCharAlphaNumeric(sText
[i
+ 1]) && IsCharAlphaNumeric(prevChar
)))
882 bool IsValidURLChar(wchar_t ch
)
884 return iswalnum(ch
) ||
885 ch
== L
'_' || ch
== L
'/' || ch
== L
';' || ch
== L
'?' || ch
== L
'&' || ch
== L
'=' ||
886 ch
== L
'%' || ch
== L
':' || ch
== L
'.' || ch
== L
'#' || ch
== L
'-' || ch
== L
'+' ||
887 ch
== L
'|' || ch
== L
'>' || ch
== L
'<' || ch
== L
'!' || ch
== L
'@';
890 bool IsUrlOrEmail(const CString
& sText
)
892 if (!PathIsURLW(sText
))
894 auto atpos
= sText
.Find(L
'@');
897 if (sText
.ReverseFind(L
'.') > atpos
)
901 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ftp://", L
"file://", L
"mailto:" })
903 if (CStringUtils::StartsWith(sText
, prefix
) && sText
.GetLength() != prefix
.GetLength())
910 BOOL
CAppUtils::StyleURLs(const CString
& msg
, CWnd
* pWnd
)
912 std::vector
<CHARRANGE
> positions
= FindURLMatches(msg
);
913 CAppUtils::SetCharFormat(pWnd
, CFM_LINK
, CFE_LINK
, positions
);
915 return positions
.empty() ? FALSE
: TRUE
;
919 * implements URL searching with the same logic as CSciEdit::StyleURLs
921 std::vector
<CHARRANGE
> CAppUtils::FindURLMatches(const CString
& msg
)
923 std::vector
<CHARRANGE
> result
;
925 int len
= msg
.GetLength();
928 for (int i
= 0; i
<= msg
.GetLength(); ++i
)
930 if ((i
< len
) && IsValidURLChar(msg
[i
]))
940 if (msg
[starturl
] == '<' && i
< len
) // try to detect and do not strip URLs put within <>
942 while (starturl
<= i
&& msg
[starturl
] == '<') // strip leading '<'
946 while (i
< len
&& msg
[i
] != '\r' && msg
[i
] != '\n' && msg
[i
] != '>') // find first '>' or new line after resetting i to start position
949 if (!IsUrlOrEmail(msg
.Mid(starturl
, i
- starturl
)))
955 int skipTrailing
= 0;
956 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] == '!'))
959 CHARRANGE range
= { starturl
, i
- skipTrailing
};
960 result
.push_back(range
);
969 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd
, const CTGitPath
& url1
, const git_revnum_t
& rev1
,
970 const CTGitPath
& /*url2*/, const git_revnum_t
& rev2
,
971 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
972 bool bAlternateDiff
/* = false */, bool /*bIgnoreAncestry*/ /* = false */,
973 bool /* blame = false */,
978 int diffContext
= g_Git
.GetConfigValueInt32(L
"diff.context", -1);
979 CString tempfile
=GetTempFile();
980 if (g_Git
.GetUnifiedDiff(url1
, rev1
, rev2
, tempfile
, bMerge
, bCombine
, diffContext
, bNoPrefix
))
982 CMessageBox::Show(hWnd
, g_Git
.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF
), _T("TortoiseGit"), MB_OK
);
985 CAppUtils::StartUnifiedDiffViewer(tempfile
, rev1
+ L
":" + rev2
, FALSE
, bAlternateDiff
);
989 sCmd
.Format(_T("%s /command:showcompare /unified"),
990 (LPCTSTR
)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
991 sCmd
+= _T(" /url1:\"") + url1
.GetGitPathString() + _T("\"");
993 sCmd
+= _T(" /revision1:") + rev1
.ToString();
994 sCmd
+= _T(" /url2:\"") + url2
.GetGitPathString() + _T("\"");
996 sCmd
+= _T(" /revision2:") + rev2
.ToString();
998 sCmd
+= _T(" /pegrevision:") + peg
.ToString();
999 if (headpeg
.IsValid())
1000 sCmd
+= _T(" /headpegrevision:") + headpeg
.ToString();
1003 sCmd
+= _T(" /alternatediff");
1005 if (bIgnoreAncestry
)
1006 sCmd
+= _T(" /ignoreancestry");
1010 sCmd
+= _T(" /hwnd:");
1012 _stprintf_s(buf
, 30, _T("%p"), (void*)hWnd
);
1016 return CAppUtils::LaunchApplication(sCmd
, 0, false);
1021 bool CAppUtils::SetupDiffScripts(bool force
, const CString
& type
)
1023 CString scriptsdir
= CPathUtils::GetAppParentDirectory();
1024 scriptsdir
+= _T("Diff-Scripts");
1025 CSimpleFileFind
files(scriptsdir
);
1026 while (files
.FindNextFileNoDirectories())
1028 CString file
= files
.GetFilePath();
1029 CString filename
= files
.GetFileName();
1030 CString ext
= file
.Mid(file
.ReverseFind('-') + 1);
1031 ext
= _T(".") + ext
.Left(ext
.ReverseFind('.'));
1032 std::set
<CString
> extensions
;
1033 extensions
.insert(ext
);
1035 if (file
.Right(3).CompareNoCase(_T("vbs"))==0)
1036 kind
= _T(" //E:vbscript");
1037 if (file
.Right(2).CompareNoCase(_T("js"))==0)
1038 kind
= _T(" //E:javascript");
1039 // open the file, read the first line and find possible extensions
1040 // this script can handle
1043 CStdioFile
f(file
, CFile::modeRead
| CFile::shareDenyNone
);
1045 if (f
.ReadString(extline
))
1047 if ((extline
.GetLength() > 15 ) &&
1048 ((extline
.Left(15).Compare(_T("// extensions: ")) == 0) ||
1049 (extline
.Left(14).Compare(_T("' extensions: ")) == 0)))
1051 if (extline
[0] == '/')
1052 extline
= extline
.Mid(15);
1054 extline
= extline
.Mid(14);
1057 sToken
= extline
.Tokenize(_T(";"), curPos
);
1058 while (!sToken
.IsEmpty())
1060 if (!sToken
.IsEmpty())
1062 if (sToken
[0] != '.')
1063 sToken
= _T(".") + sToken
;
1064 extensions
.insert(sToken
);
1066 sToken
= extline
.Tokenize(_T(";"), curPos
);
1072 catch (CFileException
* e
)
1077 for (const auto& extension
: extensions
)
1079 if (type
.IsEmpty() || (type
.Compare(_T("Diff")) == 0))
1081 if (filename
.Left(5).CompareNoCase(_T("diff-")) == 0)
1083 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension
);
1084 CString diffregstring
= diffreg
;
1085 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1086 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %base %mine") + kind
;
1089 if (type
.IsEmpty() || (type
.Compare(_T("Merge"))==0))
1091 if (filename
.Left(6).CompareNoCase(_T("merge-"))==0)
1093 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension
);
1094 CString diffregstring
= diffreg
;
1095 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1096 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %merged %theirs %mine %base") + kind
;
1105 bool CAppUtils::Export(const CString
* BashHash
, const CTGitPath
* orgPath
)
1107 // ask from where the export has to be done
1110 dlg
.m_initialRefName
=*BashHash
;
1113 if (PathIsRelative(orgPath
->GetWinPath()))
1114 dlg
.m_orgPath
= g_Git
.CombinePath(orgPath
);
1116 dlg
.m_orgPath
= *orgPath
;
1119 if (dlg
.DoModal() == IDOK
)
1122 cmd
.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1123 (LPCTSTR
)dlg
.m_strFile
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
1127 pro
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1131 postCmdList
.emplace_back(IDI_EXPLORER
, IDS_STATUSLIST_CONTEXT_EXPLORE
, [&]{ CAppUtils::ExploreTo(hWndExplorer
, dlg
.m_strFile
); });
1135 if (!dlg
.m_bWholeProject
&& !dlg
.m_orgPath
.IsEmpty() && PathIsDirectory(dlg
.m_orgPath
.GetWinPathString()))
1137 git
.m_CurrentDir
= dlg
.m_orgPath
.GetWinPathString();
1140 return (pro
.DoModal() == IDOK
);
1145 bool CAppUtils::UpdateBranchDescription(const CString
& branch
, CString description
)
1147 if (branch
.IsEmpty())
1151 key
.Format(L
"branch.%s.description", (LPCTSTR
)branch
);
1152 description
.Replace(L
"\r", L
"");
1154 if (description
.IsEmpty())
1155 g_Git
.UnsetConfigValue(key
);
1157 g_Git
.SetConfigValue(key
, description
);
1162 bool CAppUtils::CreateBranchTag(bool isTag
/*true*/, const CString
* commitHash
/*nullptr*/, bool switchNewBranch
/*false*/, LPCTSTR name
/*nullptr*/)
1164 CCreateBranchTagDlg dlg
;
1165 dlg
.m_bIsTag
= isTag
;
1166 dlg
.m_bSwitch
= switchNewBranch
;
1169 dlg
.m_initialRefName
= *commitHash
;
1172 dlg
.m_BranchTagName
= name
;
1174 if(dlg
.DoModal()==IDOK
)
1179 if(dlg
.m_bTrack
== TRUE
)
1180 track
=_T(" --track ");
1181 else if(dlg
.m_bTrack
== FALSE
)
1182 track
=_T(" --no-track");
1193 cmd
.Format(_T("git.exe tag %s %s %s %s"),
1196 (LPCTSTR
)dlg
.m_BranchTagName
,
1197 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1200 if(!dlg
.m_Message
.Trim().IsEmpty())
1202 CString tempfile
= ::GetTempFile();
1203 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_Message
))
1205 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1208 cmd
+= _T(" -F ")+tempfile
;
1213 cmd
.Format(_T("git.exe branch %s %s %s %s"),
1216 (LPCTSTR
)dlg
.m_BranchTagName
,
1217 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1221 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1223 CMessageBox::Show(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1226 if (!isTag
&& dlg
.m_bSwitch
)
1228 // it is a new branch and the user has requested to switch to it
1229 PerformSwitch(dlg
.m_BranchTagName
);
1231 if (!isTag
&& !dlg
.m_Message
.IsEmpty())
1232 UpdateBranchDescription(dlg
.m_BranchTagName
, dlg
.m_Message
);
1239 bool CAppUtils::Switch(const CString
& initialRefName
)
1242 if(!initialRefName
.IsEmpty())
1243 dlg
.m_initialRefName
= initialRefName
;
1245 if (dlg
.DoModal() == IDOK
)
1249 branch
= dlg
.m_NewBranch
;
1251 // if refs/heads/ is not stripped, checkout will detach HEAD
1252 // checkout prefers branches on name clashes (with tags)
1253 if (dlg
.m_VersionName
.Left(11) ==_T("refs/heads/") && dlg
.m_bBranchOverride
!= TRUE
)
1254 dlg
.m_VersionName
= dlg
.m_VersionName
.Mid(11);
1256 return PerformSwitch(dlg
.m_VersionName
, dlg
.m_bForce
== TRUE
, branch
, dlg
.m_bBranchOverride
== TRUE
, dlg
.m_bTrack
, dlg
.m_bMerge
== TRUE
);
1261 bool CAppUtils::PerformSwitch(const CString
& ref
, bool bForce
/* false */, const CString
& sNewBranch
/* CString() */, bool bBranchOverride
/* false */, BOOL bTrack
/* 2 */, bool bMerge
/* false */)
1269 if(!sNewBranch
.IsEmpty()){
1270 if (bBranchOverride
)
1271 branch
.Format(_T("-B %s "), (LPCTSTR
)sNewBranch
);
1273 branch
.Format(_T("-b %s "), (LPCTSTR
)sNewBranch
);
1275 track
= _T("--track ");
1276 else if (bTrack
== FALSE
)
1277 track
= _T("--no-track ");
1282 merge
= _T("--merge ");
1284 cmd
.Format(_T("git.exe checkout %s%s%s%s%s --"),
1289 (LPCTSTR
)g_Git
.FixBranchName(ref
));
1291 CProgressDlg progress
;
1292 progress
.m_GitCmd
= cmd
;
1294 CString currentBranch
;
1295 bool hasBranch
= CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
) == 0;
1296 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1300 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1301 if (gitPath
.HasSubmodules())
1303 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1306 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1307 RunTortoiseGitProc(sCmd
);
1311 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ Merge(¤tBranch
); });
1315 if (!CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, newBranch
))
1316 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
1318 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []{
1319 CTGitPathList pathlist
;
1320 CTGitPathList selectedlist
;
1321 pathlist
.AddPath(CTGitPath());
1322 bool bSelectFilesForCommit
= !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE
));
1324 Commit(CString(), false, str
, pathlist
, selectedlist
, bSelectFilesForCommit
);
1329 if (bMerge
&& g_Git
.HasWorkingTreeConflicts() > 0)
1331 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
1334 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1335 CAppUtils::RunTortoiseGitProc(sCmd
);
1338 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, bMerge
); });
1340 postCmdList
.emplace_back(IDI_SWITCH
, IDS_SWITCH_WITH_MERGE
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, true); });
1343 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
& extraMsg
)
1345 if (bMerge
&& !exitCode
&& g_Git
.HasWorkingTreeConflicts() > 0)
1347 exitCode
= 1; // Treat it as failure
1348 extraMsg
= _T("Has merge conflict");
1352 INT_PTR ret
= progress
.DoModal();
1357 class CIgnoreFile
: public CStdioFile
1360 STRING_VECTOR m_Items
;
1363 virtual BOOL
ReadString(CString
& rString
)
1365 if (GetPosition() == 0)
1367 unsigned char utf8bom
[] = { 0xEF, 0xBB, 0xBF };
1368 char buf
[3] = { 0, 0, 0 };
1370 if (memcpy(buf
, utf8bom
, sizeof(utf8bom
)))
1375 char lastChar
= '\0';
1376 for (char c
= '\0'; Read(&c
, 1) == 1; lastChar
= c
)
1382 m_eol
= lastChar
== '\r' ? _T("\r\n") : _T("\n");
1390 rString
= CUnicodeUtils::GetUnicode(strA
);
1401 bool CAppUtils::OpenIgnoreFile(CIgnoreFile
&file
, const CString
& filename
)
1404 if (!file
.Open(filename
, CFile::modeCreate
| CFile::modeReadWrite
| CFile::modeNoTruncate
| CFile::typeBinary
))
1406 CMessageBox::Show(nullptr, filename
+ _T(" Open Failure"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1410 if (file
.GetLength() > 0)
1413 while (file
.ReadString(fileText
))
1414 file
.m_Items
.push_back(fileText
);
1415 file
.Seek(file
.GetLength() - 1, 0);
1416 char lastchar
[1] = { 0 };
1417 file
.Read(lastchar
, 1);
1419 if (lastchar
[0] != '\n')
1421 CStringA eol
= CStringA(file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
);
1422 file
.Write(eol
, eol
.GetLength());
1431 bool CAppUtils::IgnoreFile(const CTGitPathList
& path
,bool IsMask
)
1433 CIgnoreDlg ignoreDlg
;
1434 if (ignoreDlg
.DoModal() == IDOK
)
1437 ignorefile
= g_Git
.m_CurrentDir
+ _T("\\");
1439 switch (ignoreDlg
.m_IgnoreFile
)
1442 ignorefile
+= _T(".gitignore");
1445 GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, ignorefile
);
1446 ignorefile
+= _T("info");
1447 if (!PathFileExists(ignorefile
))
1448 CreateDirectory(ignorefile
, nullptr);
1449 ignorefile
+= _T("\\exclude");
1456 if (ignoreDlg
.m_IgnoreFile
!= 1 && !OpenIgnoreFile(file
, ignorefile
))
1459 for (int i
= 0; i
< path
.GetCount(); ++i
)
1461 if (ignoreDlg
.m_IgnoreFile
== 1)
1463 ignorefile
= g_Git
.CombinePath(path
[i
].GetContainingDirectory()) + _T("\\.gitignore");
1464 if (!OpenIgnoreFile(file
, ignorefile
))
1468 CString ignorePattern
;
1469 if (ignoreDlg
.m_IgnoreType
== 0)
1471 if (ignoreDlg
.m_IgnoreFile
!= 1 && !path
[i
].GetContainingDirectory().GetGitPathString().IsEmpty())
1472 ignorePattern
+= _T("/") + path
[i
].GetContainingDirectory().GetGitPathString();
1474 ignorePattern
+= _T("/");
1477 ignorePattern
+= _T("*") + path
[i
].GetFileExtension();
1479 ignorePattern
+= path
[i
].GetFileOrDirectoryName();
1481 // escape [ and ] so that files get ignored correctly
1482 ignorePattern
.Replace(_T("["), _T("\\["));
1483 ignorePattern
.Replace(_T("]"), _T("\\]"));
1486 for (size_t j
= 0; j
< file
.m_Items
.size(); ++j
)
1488 if (file
.m_Items
[j
] == ignorePattern
)
1496 file
.m_Items
.push_back(ignorePattern
);
1497 ignorePattern
+= file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
;
1498 CStringA ignorePatternA
= CUnicodeUtils::GetUTF8(ignorePattern
);
1499 file
.Write(ignorePatternA
, ignorePatternA
.GetLength());
1502 if (ignoreDlg
.m_IgnoreFile
== 1)
1506 if (ignoreDlg
.m_IgnoreFile
!= 1)
1520 static bool Reset(const CString
& resetTo
, int resetType
)
1527 type
= _T("--soft");
1530 type
= _T("--mixed");
1533 type
= _T("--hard");
1537 type
= _T("--mixed");
1540 cmd
.Format(_T("git.exe reset %s %s --"), (LPCTSTR
)type
, (LPCTSTR
)resetTo
);
1542 CProgressDlg progress
;
1543 progress
.m_GitCmd
= cmd
;
1545 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1549 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ Reset(resetTo
, resetType
); });
1553 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1554 if (gitPath
.HasSubmodules() && resetType
== 2)
1556 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1559 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1560 CAppUtils::RunTortoiseGitProc(sCmd
);
1566 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_RESET
))
1568 CGitProgressDlg gitdlg
;
1569 ResetProgressCommand resetProgressCommand
;
1570 gitdlg
.SetCommand(&resetProgressCommand
);
1571 resetProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
1572 resetProgressCommand
.SetRevision(resetTo
);
1573 resetProgressCommand
.SetResetType(resetType
);
1574 ret
= gitdlg
.DoModal();
1577 ret
= progress
.DoModal();
1582 bool CAppUtils::GitReset(const CString
* CommitHash
, int type
)
1585 dlg
.m_ResetType
=type
;
1586 dlg
.m_ResetToVersion
=*CommitHash
;
1587 dlg
.m_initialRefName
= *CommitHash
;
1588 if (dlg
.DoModal() == IDOK
)
1589 return Reset(dlg
.m_ResetToVersion
, dlg
.m_ResetType
);
1594 void CAppUtils::DescribeConflictFile(bool mode
, bool base
,CString
&descript
)
1598 descript
.LoadString(IDS_SVNACTION_DELETE
);
1603 descript
.LoadString(IDS_SVNACTION_MODIFIED
);
1606 descript
.LoadString(IDS_PROC_CREATED
);
1609 void CAppUtils::RemoveTempMergeFile(const CTGitPath
& path
)
1611 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path
));
1612 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path
));
1613 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path
));
1615 CString
CAppUtils::GetMergeTempFile(const CString
& type
, const CTGitPath
&merge
)
1618 file
= g_Git
.CombinePath(merge
.GetWinPathString() + _T(".") + type
+ merge
.GetFileExtension());
1623 bool ParseHashesFromLsFile(const BYTE_VECTOR
& out
, CString
& hash1
, CString
& hash2
, CString
& hash3
)
1629 while (pos
< out
.size())
1633 CGit::StringAppend(&one
, &out
[pos
], CP_UTF8
);
1635 one
.Tokenize(_T("\t"), tabstart
);
1638 part
= one
.Tokenize(_T(" "), tabstart
); //Tag
1639 part
= one
.Tokenize(_T(" "), tabstart
); //Mode
1640 part
= one
.Tokenize(_T(" "), tabstart
); //Hash
1641 CString hash
= part
;
1642 part
= one
.Tokenize(_T("\t"), tabstart
); //Stage
1643 int stage
= _ttol(part
);
1646 else if (stage
== 2)
1648 else if (stage
== 3)
1654 pos
= out
.findNextString(pos
);
1660 bool CAppUtils::ConflictEdit(const CTGitPath
& path
, bool bAlternativeTool
/*= false*/, bool revertTheirMy
/*= false*/, HWND resolveMsgHwnd
/*= nullptr*/)
1664 CTGitPath merge
=path
;
1665 CTGitPath directory
= merge
.GetDirectory();
1667 // we have the conflicted file (%merged)
1668 // now look for the other required files
1670 //stat.GetStatus(merge);
1671 //if (stat.status == nullptr)
1677 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1679 if (g_Git
.Run(cmd
, &vector
))
1682 if (merge
.IsDirectory())
1684 CString baseHash
, realBaseHash(GIT_REV_ZERO
), localHash(GIT_REV_ZERO
), remoteHash(GIT_REV_ZERO
);
1685 if (merge
.HasAdminDir()) {
1687 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1689 subgit
.GetHash(hash
, _T("HEAD"));
1692 if (ParseHashesFromLsFile(vector
, realBaseHash
, localHash
, remoteHash
)) // in base no submodule, but in remote submodule
1693 baseHash
= realBaseHash
;
1695 CGitDiff::ChangeType changeTypeMine
= CGitDiff::Unknown
;
1696 CGitDiff::ChangeType changeTypeTheirs
= CGitDiff::Unknown
;
1698 bool baseOK
= false, mineOK
= false, theirsOK
= false;
1699 CString baseSubject
, mineSubject
, theirsSubject
;
1700 if (merge
.HasAdminDir())
1703 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1704 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, localHash
, baseOK
, mineOK
, changeTypeMine
, baseSubject
, mineSubject
);
1705 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, remoteHash
, baseOK
, theirsOK
, changeTypeTheirs
, baseSubject
, theirsSubject
);
1707 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)
1709 changeTypeMine
= CGitDiff::Identical
;
1710 changeTypeTheirs
= CGitDiff::NewSubmodule
;
1711 baseSubject
= _T("no submodule");
1712 mineSubject
= baseSubject
;
1713 theirsSubject
= _T("not initialized");
1715 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
1717 baseHash
= localHash
;
1718 baseSubject
= _T("not initialized");
1719 mineSubject
= baseSubject
;
1720 theirsSubject
= _T("not initialized");
1721 changeTypeMine
= CGitDiff::Identical
;
1722 changeTypeTheirs
= CGitDiff::DeleteSubmodule
;
1724 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
1726 baseSubject
= _T("not initialized");
1727 mineSubject
= baseSubject
;
1728 theirsSubject
= baseSubject
;
1729 if (baseHash
== localHash
)
1730 changeTypeMine
= CGitDiff::Identical
;
1735 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog
;
1736 resolveSubmoduleConflictDialog
.SetDiff(merge
.GetGitPathString(), revertTheirMy
, baseHash
, baseSubject
, baseOK
, localHash
, mineSubject
, mineOK
, changeTypeMine
, remoteHash
, theirsSubject
, theirsOK
, changeTypeTheirs
);
1737 resolveSubmoduleConflictDialog
.DoModal();
1738 if (resolveSubmoduleConflictDialog
.m_bResolved
&& resolveMsgHwnd
)
1740 static UINT WM_REVERTMSG
= RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1741 ::PostMessage(resolveMsgHwnd
, WM_REVERTMSG
, NULL
, NULL
);
1748 if (list
.ParserFromLsFile(vector
))
1750 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1763 mine
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1764 theirs
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1768 mine
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1769 theirs
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1771 base
.SetFromGit(GetMergeTempFile(_T("BASE"),merge
));
1775 //format=_T("git.exe cat-file blob \":%d:%s\"");
1776 format
= _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1778 //create a empty file, incase stage is not three
1779 tempfile
.Open(mine
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1781 tempfile
.Open(theirs
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1783 tempfile
.Open(base
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1786 bool b_base
=false, b_local
=false, b_remote
=false;
1788 for (int i
= 0; i
< list
.GetCount(); ++i
)
1794 if( list
[i
].m_Stage
== 1)
1796 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1798 outfile
= base
.GetWinPathString();
1801 if( list
[i
].m_Stage
== 2 )
1803 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1805 outfile
= mine
.GetWinPathString();
1808 if( list
[i
].m_Stage
== 3 )
1810 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1812 outfile
= theirs
.GetWinPathString();
1814 CString output
, err
;
1815 if(!outfile
.IsEmpty())
1816 if (!g_Git
.Run(cmd
, &output
, &err
, CP_UTF8
))
1820 file
= output
.Tokenize(_T("\t"), start
);
1821 ::MoveFileEx(file
,outfile
,MOVEFILE_REPLACE_EXISTING
|MOVEFILE_COPY_ALLOWED
);
1824 CMessageBox::Show(nullptr, output
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1827 if(b_local
&& b_remote
)
1829 merge
.SetFromWin(g_Git
.CombinePath(merge
));
1831 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, mine
, theirs
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1833 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, theirs
, mine
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1837 ::DeleteFile(mine
.GetWinPathString());
1838 ::DeleteFile(theirs
.GetWinPathString());
1839 ::DeleteFile(base
.GetWinPathString());
1841 CDeleteConflictDlg dlg
;
1842 DescribeConflictFile(b_local
, b_base
,dlg
.m_LocalStatus
);
1843 DescribeConflictFile(b_remote
,b_base
,dlg
.m_RemoteStatus
);
1844 CGitHash localHash
, remoteHash
;
1845 if (!g_Git
.GetHash(localHash
, _T("HEAD")))
1846 dlg
.m_LocalHash
= localHash
.ToString();
1847 if (!g_Git
.GetHash(remoteHash
, _T("MERGE_HEAD")))
1848 dlg
.m_RemoteHash
= remoteHash
.ToString();
1849 else if (!g_Git
.GetHash(remoteHash
, _T("rebase-apply/original-commit")))
1850 dlg
.m_RemoteHash
= remoteHash
.ToString();
1851 else if (!g_Git
.GetHash(remoteHash
, _T("CHERRY_PICK_HEAD")))
1852 dlg
.m_RemoteHash
= remoteHash
.ToString();
1853 else if (!g_Git
.GetHash(remoteHash
, _T("REVERT_HEAD")))
1854 dlg
.m_RemoteHash
= remoteHash
.ToString();
1855 dlg
.m_bShowModifiedButton
=b_base
;
1856 dlg
.m_File
=merge
.GetGitPathString();
1857 if(dlg
.DoModal() == IDOK
)
1861 cmd
.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1863 cmd
.Format(_T("git.exe add -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1865 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1867 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1877 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1878 base
, theirs
, mine
, merge
);
1881 if (stat
.status
->text_status
== svn_wc_status_conflicted
)
1883 // we have a text conflict, use our merge tool to resolve the conflict
1885 CTSVNPath
theirs(directory
);
1886 CTSVNPath
mine(directory
);
1887 CTSVNPath
base(directory
);
1888 bool bConflictData
= false;
1890 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_new
))
1892 theirs
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_new
));
1893 bConflictData
= true;
1895 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_old
))
1897 base
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_old
));
1898 bConflictData
= true;
1900 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_wrk
))
1902 mine
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_wrk
));
1903 bConflictData
= true;
1908 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1909 base
, theirs
, mine
, merge
);
1912 if (stat
.status
->prop_status
== svn_wc_status_conflicted
)
1914 // we have a property conflict
1915 CTSVNPath
prej(directory
);
1916 if ((stat
.status
->entry
)&&(stat
.status
->entry
->prejfile
))
1918 prej
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->prejfile
));
1919 // there's a problem: the prej file contains a _description_ of the conflict, and
1920 // that description string might be translated. That means we have no way of parsing
1921 // the file to find out the conflicting values.
1922 // The only thing we can do: show a dialog with the conflict description, then
1923 // let the user either accept the existing property or open the property edit dialog
1924 // to manually change the properties and values. And a button to mark the conflict as
1926 CEditPropConflictDlg dlg
;
1927 dlg
.SetPrejFile(prej
);
1928 dlg
.SetConflictedItem(merge
);
1929 bRet
= (dlg
.DoModal() != IDCANCEL
);
1933 if (stat
.status
->tree_conflict
)
1935 // we have a tree conflict
1937 const SVNInfoData
* pInfoData
= info
.GetFirstFileInfo(merge
, SVNRev(), SVNRev());
1940 if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_text
)
1942 CTSVNPath
theirs(directory
);
1943 CTSVNPath
mine(directory
);
1944 CTSVNPath
base(directory
);
1945 bool bConflictData
= false;
1947 if (pInfoData
->treeconflict_theirfile
)
1949 theirs
.AppendPathString(pInfoData
->treeconflict_theirfile
);
1950 bConflictData
= true;
1952 if (pInfoData
->treeconflict_basefile
)
1954 base
.AppendPathString(pInfoData
->treeconflict_basefile
);
1955 bConflictData
= true;
1957 if (pInfoData
->treeconflict_myfile
)
1959 mine
.AppendPathString(pInfoData
->treeconflict_myfile
);
1960 bConflictData
= true;
1965 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1966 base
, theirs
, mine
, merge
);
1968 else if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_tree
)
1970 CString sConflictAction
;
1971 CString sConflictReason
;
1972 CString sResolveTheirs
;
1973 CString sResolveMine
;
1974 CTSVNPath treeConflictPath
= CTSVNPath(pInfoData
->treeconflict_path
);
1975 CString sItemName
= treeConflictPath
.GetUIFileOrDirectoryName();
1977 if (pInfoData
->treeconflict_nodekind
== svn_node_file
)
1979 switch (pInfoData
->treeconflict_operation
)
1981 case svn_wc_operation_update
:
1982 switch (pInfoData
->treeconflict_action
)
1984 case svn_wc_conflict_action_edit
:
1985 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEEDIT
, (LPCTSTR
)sItemName
);
1986 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1988 case svn_wc_conflict_action_add
:
1989 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEADD
, (LPCTSTR
)sItemName
);
1990 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1992 case svn_wc_conflict_action_delete
:
1993 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEDELETE
, (LPCTSTR
)sItemName
);
1994 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
1998 case svn_wc_operation_switch
:
1999 switch (pInfoData
->treeconflict_action
)
2001 case svn_wc_conflict_action_edit
:
2002 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHEDIT
, (LPCTSTR
)sItemName
);
2003 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2005 case svn_wc_conflict_action_add
:
2006 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHADD
, (LPCTSTR
)sItemName
);
2007 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2009 case svn_wc_conflict_action_delete
:
2010 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHDELETE
, (LPCTSTR
)sItemName
);
2011 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2015 case svn_wc_operation_merge
:
2016 switch (pInfoData
->treeconflict_action
)
2018 case svn_wc_conflict_action_edit
:
2019 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEEDIT
, (LPCTSTR
)sItemName
);
2020 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2022 case svn_wc_conflict_action_add
:
2023 sResolveTheirs
.Format(IDS_TREECONFLICT_FILEMERGEADD
, (LPCTSTR
)sItemName
);
2024 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2026 case svn_wc_conflict_action_delete
:
2027 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEDELETE
, (LPCTSTR
)sItemName
);
2028 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2034 else if (pInfoData
->treeconflict_nodekind
== svn_node_dir
)
2036 switch (pInfoData
->treeconflict_operation
)
2038 case svn_wc_operation_update
:
2039 switch (pInfoData
->treeconflict_action
)
2041 case svn_wc_conflict_action_edit
:
2042 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEEDIT
, (LPCTSTR
)sItemName
);
2043 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2045 case svn_wc_conflict_action_add
:
2046 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEADD
, (LPCTSTR
)sItemName
);
2047 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2049 case svn_wc_conflict_action_delete
:
2050 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEDELETE
, (LPCTSTR
)sItemName
);
2051 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2055 case svn_wc_operation_switch
:
2056 switch (pInfoData
->treeconflict_action
)
2058 case svn_wc_conflict_action_edit
:
2059 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHEDIT
, (LPCTSTR
)sItemName
);
2060 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2062 case svn_wc_conflict_action_add
:
2063 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHADD
, (LPCTSTR
)sItemName
);
2064 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2066 case svn_wc_conflict_action_delete
:
2067 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHDELETE
, (LPCTSTR
)sItemName
);
2068 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2072 case svn_wc_operation_merge
:
2073 switch (pInfoData
->treeconflict_action
)
2075 case svn_wc_conflict_action_edit
:
2076 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEEDIT
, (LPCTSTR
)sItemName
);
2077 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2079 case svn_wc_conflict_action_add
:
2080 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEADD
, (LPCTSTR
)sItemName
);
2081 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2083 case svn_wc_conflict_action_delete
:
2084 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEDELETE
, (LPCTSTR
)sItemName
);
2085 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2093 switch (pInfoData
->treeconflict_reason
)
2095 case svn_wc_conflict_reason_edited
:
2096 uReasonID
= IDS_TREECONFLICT_REASON_EDITED
;
2097 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2099 case svn_wc_conflict_reason_obstructed
:
2100 uReasonID
= IDS_TREECONFLICT_REASON_OBSTRUCTED
;
2101 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2103 case svn_wc_conflict_reason_deleted
:
2104 uReasonID
= IDS_TREECONFLICT_REASON_DELETED
;
2105 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2107 case svn_wc_conflict_reason_added
:
2108 uReasonID
= IDS_TREECONFLICT_REASON_ADDED
;
2109 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2111 case svn_wc_conflict_reason_missing
:
2112 uReasonID
= IDS_TREECONFLICT_REASON_MISSING
;
2113 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2115 case svn_wc_conflict_reason_unversioned
:
2116 uReasonID
= IDS_TREECONFLICT_REASON_UNVERSIONED
;
2117 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2120 sConflictReason
.Format(uReasonID
, (LPCTSTR
)sConflictAction
);
2122 CTreeConflictEditorDlg dlg
;
2123 dlg
.SetConflictInfoText(sConflictReason
);
2124 dlg
.SetResolveTexts(sResolveTheirs
, sResolveMine
);
2125 dlg
.SetPath(treeConflictPath
);
2126 INT_PTR dlgRet
= dlg
.DoModal();
2127 bRet
= (dlgRet
!= IDCANCEL
);
2135 bool CAppUtils::IsSSHPutty()
2137 CString sshclient
=g_Git
.m_Environment
.GetEnv(_T("GIT_SSH"));
2138 sshclient
=sshclient
.MakeLower();
2139 if(sshclient
.Find(_T("plink.exe"),0)>=0)
2144 CString
CAppUtils::GetClipboardLink(const CString
&skipGitPrefix
, int paramsCount
)
2146 if (!OpenClipboard(nullptr))
2149 CString sClipboardText
;
2150 HGLOBAL hglb
= GetClipboardData(CF_TEXT
);
2153 LPCSTR lpstr
= (LPCSTR
)GlobalLock(hglb
);
2154 sClipboardText
= CString(lpstr
);
2157 hglb
= GetClipboardData(CF_UNICODETEXT
);
2160 LPCTSTR lpstr
= (LPCTSTR
)GlobalLock(hglb
);
2161 sClipboardText
= lpstr
;
2166 if(!sClipboardText
.IsEmpty())
2168 if(sClipboardText
[0] == _T('\"') && sClipboardText
[sClipboardText
.GetLength()-1] == _T('\"'))
2169 sClipboardText
=sClipboardText
.Mid(1,sClipboardText
.GetLength()-2);
2171 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ssh://", L
"git@" })
2173 if (CStringUtils::StartsWith(sClipboardText
, prefix
) && sClipboardText
.GetLength() != prefix
.GetLength())
2174 return sClipboardText
;
2177 if(sClipboardText
.GetLength()>=2)
2178 if( sClipboardText
[1] == _T(':') )
2179 if( (sClipboardText
[0] >= 'A' && sClipboardText
[0] <= 'Z')
2180 || (sClipboardText
[0] >= 'a' && sClipboardText
[0] <= 'z') )
2181 return sClipboardText
;
2183 // trim prefixes like "git clone "
2184 if (!skipGitPrefix
.IsEmpty() && CStringUtils::StartsWith(sClipboardText
, skipGitPrefix
))
2186 sClipboardText
= sClipboardText
.Mid(skipGitPrefix
.GetLength()).Trim();
2188 while (paramsCount
>= 0)
2191 spacePos
= sClipboardText
.Find(_T(' '), spacePos
+ 1);
2195 if (spacePos
> 0 && paramsCount
< 0)
2196 sClipboardText
.Truncate(spacePos
);
2197 return sClipboardText
;
2204 CString
CAppUtils::ChooseRepository(const CString
* path
)
2206 CBrowseFolder browseFolder
;
2207 CRegString regLastResopitory
= CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2209 browseFolder
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
2210 CString strCloneDirectory
;
2212 strCloneDirectory
=*path
;
2214 strCloneDirectory
= regLastResopitory
;
2217 title
.LoadString(IDS_CHOOSE_REPOSITORY
);
2219 browseFolder
.SetInfo(title
);
2221 if (browseFolder
.Show(nullptr, strCloneDirectory
) == CBrowseFolder::OK
)
2223 regLastResopitory
= strCloneDirectory
;
2224 return strCloneDirectory
;
2230 bool CAppUtils::SendPatchMail(CTGitPathList
& list
, bool bIsMainWnd
)
2234 dlg
.m_PathList
= list
;
2236 if(dlg
.DoModal()==IDOK
)
2238 if (dlg
.m_PathList
.IsEmpty())
2241 CGitProgressDlg progDlg
;
2243 theApp
.m_pMainWnd
= &progDlg
;
2244 SendMailProgressCommand sendMailProgressCommand
;
2245 progDlg
.SetCommand(&sendMailProgressCommand
);
2247 sendMailProgressCommand
.SetPathList(dlg
.m_PathList
);
2248 progDlg
.SetItemCount(dlg
.m_PathList
.GetCount());
2250 CSendMailPatch
sendMailPatch(dlg
.m_To
, dlg
.m_CC
, dlg
.m_Subject
, !!dlg
.m_bAttachment
, !!dlg
.m_bCombine
);
2251 sendMailProgressCommand
.SetSendMailOption(&sendMailPatch
);
2260 bool CAppUtils::SendPatchMail(const CString
& cmd
, const CString
& formatpatchoutput
, bool bIsMainWnd
)
2263 CString log
=formatpatchoutput
;
2264 int start
=log
.Find(cmd
);
2266 CString one
=log
.Tokenize(_T("\n"),start
);
2272 CString one
=log
.Tokenize(_T("\n"),start
);
2274 if (one
.IsEmpty() || one
.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS
))) == 0)
2276 one
.Replace(_T('/'),_T('\\'));
2278 path
.SetFromWin(one
);
2281 if (!list
.IsEmpty())
2282 return SendPatchMail(list
, bIsMainWnd
);
2285 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES
, IDS_APPNAME
, MB_ICONINFORMATION
);
2291 int CAppUtils::GetLogOutputEncode(CGit
*pGit
)
2294 output
= pGit
->GetConfigValue(_T("i18n.logOutputEncoding"));
2295 if(output
.IsEmpty())
2296 return CUnicodeUtils::GetCPCode(pGit
->GetConfigValue(_T("i18n.commitencoding")));
2298 return CUnicodeUtils::GetCPCode(output
);
2300 int CAppUtils::SaveCommitUnicodeFile(const CString
& filename
, CString
&message
)
2304 CFile
file(filename
, CFile::modeReadWrite
| CFile::modeCreate
);
2305 int cp
= CUnicodeUtils::GetCPCode(g_Git
.GetConfigValue(_T("i18n.commitencoding")));
2307 bool stripComments
= (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE
) == TRUE
);
2308 TCHAR commentChar
= L
'#';
2311 CString commentCharValue
= g_Git
.GetConfigValue(L
"core.commentchar");
2312 if (!commentCharValue
.IsEmpty())
2313 commentChar
= commentCharValue
[0];
2316 bool sanitize
= (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE
) == TRUE
);
2318 message
.Trim(L
" \r\n");
2320 int len
= message
.GetLength();
2322 int emptyLineCnt
= 0;
2323 while (start
>= 0 && start
< len
)
2325 int oldStart
= start
;
2326 start
= message
.Find(L
"\n", oldStart
);
2327 CString line
= message
.Mid(oldStart
);
2330 line
.Truncate(start
- oldStart
);
2331 ++start
; // move forward so we don't find the same char again
2333 if (stripComments
&& (!line
.IsEmpty() && line
.GetAt(0) == commentChar
) || (start
< 0 && line
.IsEmpty()))
2335 line
.TrimRight(L
" \r");
2343 if (emptyLineCnt
) // squash multiple newlines
2344 file
.Write("\n", 1);
2347 CStringA lineA
= CUnicodeUtils::GetMulti(line
+ L
"\n", cp
);
2348 file
.Write((LPCSTR
)lineA
, lineA
.GetLength());
2353 catch (CFileException
*e
)
2360 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
)
2363 CAppUtils::LaunchPAgent(nullptr, &url
);
2366 if (g_Git
.GetHash(hashOld
, L
"HEAD"))
2368 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash."), L
"TortoiseGit", MB_ICONERROR
);
2373 if (CRegDWORD(L
"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE
) == FALSE
)
2374 args
+= L
" --no-rebase";
2376 if (bFetchTags
== BST_UNCHECKED
)
2377 args
+= L
" --no-tags";
2378 else if (bFetchTags
== BST_CHECKED
)
2382 args
+= L
" --no-ff";
2385 args
+= L
" --ff-only";
2388 args
+= L
" --squash";
2391 args
+= L
" --no-commit";
2394 args
.AppendFormat(L
" --depth %d", *nDepth
);
2396 if (bPrune
== BST_CHECKED
)
2397 args
+= L
" --prune";
2398 else if (bPrune
== BST_UNCHECKED
)
2399 args
+= L
" --no-prune";
2402 args
+= L
" --allow-unrelated-histories";
2405 cmd
.Format(L
"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR
)args
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranchName
);
2406 CProgressDlg progress
;
2407 progress
.m_GitCmd
= cmd
;
2409 CGitHash hashNew
; // declare outside lambda, because it is captured by reference
2410 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2414 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2416 STRING_VECTOR remotes
;
2417 g_Git
.GetRemoteList(remotes
);
2418 if (std::find(remotes
.begin(), remotes
.end(), url
) != remotes
.end())
2420 CString currentBranch
;
2421 if (g_Git
.GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
))
2422 currentBranch
.Empty();
2423 CString remoteRef
= L
"remotes/" + url
+ L
"/" + remoteBranchName
;
2424 if (!currentBranch
.IsEmpty() && remoteBranchName
.IsEmpty())
2426 CString pullRemote
, pullBranch
;
2427 g_Git
.GetRemoteTrackedBranch(currentBranch
, pullRemote
, pullBranch
);
2428 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2429 remoteRef
= L
"remotes/" + pullRemote
+ L
"/" + pullBranch
;
2432 g_Git
.IsFastForward(L
"HEAD", remoteRef
, &common
);
2433 if (common
.IsEmpty())
2434 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoPull(url
, bAutoLoad
, bFetchTags
, bNoFF
, bFFonly
, bSquash
, bNoCommit
, nDepth
, bPrune
, remoteBranchName
, showPush
, showStashPop
, true); });
2438 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(); });
2439 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ CAppUtils::StashSave(L
"", true); });
2444 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
2446 if (g_Git
.GetHash(hashNew
, L
"HEAD"))
2447 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash after pulling."), L
"TortoiseGit", MB_ICONERROR
);
2450 postCmdList
.emplace_back(IDI_DIFF
, IDS_PROC_PULL_DIFFS
, [&]
2453 dlg
.SetDiff(nullptr, hashOld
.ToString(), hashNew
.ToString());
2456 postCmdList
.emplace_back(IDI_LOG
, IDS_PROC_PULL_LOG
, [&]
2459 dlg
.SetParams(CTGitPath(L
""), CTGitPath(L
""), L
"", hashOld
.ToString() + L
".." + hashNew
.ToString(), 0);
2465 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
2467 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
2468 if (gitPath
.HasSubmodules())
2470 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
2473 sCmd
.Format(L
"/command:subupdate /bkpath:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
2474 CAppUtils::RunTortoiseGitProc(sCmd
);
2479 INT_PTR ret
= progress
.DoModal();
2481 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
)
2483 CChangedDlg changeddlg
;
2484 changeddlg
.m_pathList
.AddPath(CTGitPath());
2485 changeddlg
.DoModal();
2493 bool CAppUtils::Pull(bool showPush
, bool showStashPop
)
2495 if (IsTGitRebaseActive())
2499 dlg
.m_IsPull
= TRUE
;
2500 if (dlg
.DoModal() == IDOK
)
2502 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2504 return DoFetch(dlg
.m_RemoteURL
,
2505 FALSE
, // Fetch all remotes
2506 dlg
.m_bAutoLoad
== BST_CHECKED
,
2508 dlg
.m_bDepth
== BST_CHECKED
,
2511 dlg
.m_RemoteBranchName
,
2512 dlg
.m_bRebaseActivatedInConfigForPull
? 2 : 1, // Rebase after fetching
2513 dlg
.m_bRebasePreserveMerges
== TRUE
); // Preserve merges on rebase
2515 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);
2521 bool CAppUtils::RebaseAfterFetch(const CString
& upstream
, int rebase
, bool preserveMerges
)
2526 if (!upstream
.IsEmpty())
2527 dlg
.m_Upstream
= upstream
;
2528 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENULOG
)));
2529 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH
)));
2530 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL
)));
2531 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE
)));
2532 dlg
.m_bRebaseAutoStart
= (rebase
== 2);
2533 dlg
.m_bPreserveMerges
= preserveMerges
;
2534 INT_PTR response
= dlg
.DoModal();
2535 if (response
== IDOK
)
2537 else if (response
== IDC_REBASE_POST_BUTTON
)
2539 CString cmd
= _T("/command:log");
2540 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2541 CAppUtils::RunTortoiseGitProc(cmd
);
2544 else if (response
== IDC_REBASE_POST_BUTTON
+ 1)
2546 else if (response
== IDC_REBASE_POST_BUTTON
+ 2)
2548 CString cmd
, out
, err
;
2549 cmd
.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2550 (LPCTSTR
)g_Git
.m_CurrentDir
,
2551 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Upstream
),
2552 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Branch
));
2553 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
2555 CMessageBox::Show(nullptr, out
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2558 CAppUtils::SendPatchMail(cmd
, out
);
2561 else if (response
== IDC_REBASE_POST_BUTTON
+ 3)
2563 else if (response
== IDCANCEL
)
2569 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
)
2573 if (fetchAllRemotes
)
2576 g_Git
.GetRemoteList(list
);
2578 for (const auto& remote
: list
)
2579 CAppUtils::LaunchPAgent(nullptr, &remote
);
2582 CAppUtils::LaunchPAgent(nullptr, &url
);
2585 CString upstream
= _T("FETCH_HEAD");
2586 CGitHash oldUpstreamHash
;
2590 g_Git
.GetRemoteList(list
);
2591 for (auto it
= list
.cbegin(); it
!= list
.cend(); ++it
)
2595 CString remote
, trackedBranch
;
2596 g_Git
.GetRemoteTrackedBranchForHEAD(remote
, trackedBranch
);
2597 if (!remote
.IsEmpty() && !trackedBranch
.IsEmpty())
2599 upstream
= L
"remotes/" + remote
+ L
"/" + trackedBranch
;
2600 g_Git
.GetHash(oldUpstreamHash
, upstream
);
2608 arg
= _T(" --progress");
2611 arg
.AppendFormat(_T(" --depth %d"), nDepth
);
2614 arg
+= _T(" --prune");
2615 else if (prune
== FALSE
)
2616 arg
+= _T(" --no-prune");
2619 arg
+= _T(" --tags");
2620 else if (fetchTags
== 0)
2621 arg
+= _T(" --no-tags");
2623 if (fetchAllRemotes
)
2624 cmd
.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR
)arg
);
2626 cmd
.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR
)arg
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranch
);
2628 CProgressDlg progress
;
2629 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2633 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ DoFetch(url
, fetchAllRemotes
, loadPuttyAgent
, prune
, bDepth
, nDepth
, fetchTags
, remoteBranch
, runRebase
, rebasePreserveMerges
); });
2637 postCmdList
.emplace_back(IDI_LOG
, IDS_MENULOG
, []
2639 CString cmd
= _T("/command:log");
2640 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2641 CAppUtils::RunTortoiseGitProc(cmd
);
2644 postCmdList
.emplace_back(IDI_REVERT
, IDS_PROC_RESET
, []
2646 CString pullRemote
, pullBranch
;
2647 g_Git
.GetRemoteTrackedBranchForHEAD(pullRemote
, pullBranch
);
2648 CString defaultUpstream
;
2649 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2650 defaultUpstream
.Format(_T("remotes/%s/%s"), (LPCTSTR
)pullRemote
, (LPCTSTR
)pullBranch
);
2651 CAppUtils::GitReset(&defaultUpstream
, 2);
2654 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, []{ CAppUtils::Fetch(); });
2656 if (!runRebase
&& !GitAdminDir::IsBareRepo(g_Git
.m_CurrentDir
))
2657 postCmdList
.emplace_back(IDI_REBASE
, IDS_MENUREBASE
, [&]{ runRebase
= false; CAppUtils::RebaseAfterFetch(); });
2660 progress
.m_GitCmd
= cmd
;
2662 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_FETCH
))
2664 CGitProgressDlg gitdlg
;
2665 FetchProgressCommand fetchProgressCommand
;
2666 if (!fetchAllRemotes
)
2667 fetchProgressCommand
.SetUrl(url
);
2668 gitdlg
.SetCommand(&fetchProgressCommand
);
2669 fetchProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
2670 fetchProgressCommand
.SetAutoTag(fetchTags
== 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL
: fetchTags
== 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO
: GIT_REMOTE_DOWNLOAD_TAGS_NONE
);
2671 if (!fetchAllRemotes
)
2672 fetchProgressCommand
.SetRefSpec(remoteBranch
);
2673 return gitdlg
.DoModal() == IDOK
;
2676 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
&)
2678 if (exitCode
|| !runRebase
)
2681 CGitHash remoteBranchHash
;
2682 g_Git
.GetHash(remoteBranchHash
, upstream
);
2683 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
)
2686 if (runRebase
== 1 && g_Git
.IsFastForward(L
"HEAD", upstream
))
2688 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
);
2693 CProgressDlg mergeProgress
;
2694 mergeProgress
.m_GitCmd
= L
"git.exe merge --ff-only " + upstream
;
2695 mergeProgress
.m_AutoClose
= AUTOCLOSE_IF_NO_ERRORS
;
2696 mergeProgress
.m_PostCmdCallback
= [](DWORD status
, PostCmdList
& postCmdList
)
2698 if (status
&& g_Git
.HasWorkingTreeConflicts())
2700 // there are conflict files
2701 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
2704 sCmd
.Format(L
"/command:commit /path:\"%s\"", g_Git
.m_CurrentDir
);
2705 CAppUtils::RunTortoiseGitProc(sCmd
);
2709 mergeProgress
.DoModal();
2714 CAppUtils::RebaseAfterFetch(upstream
, runRebase
, rebasePreserveMerges
);
2717 return progress
.DoModal() == IDOK
;
2720 bool CAppUtils::Fetch(const CString
& remoteName
, bool allRemotes
)
2723 dlg
.m_PreSelectRemote
= remoteName
;
2725 dlg
.m_bAllRemotes
= allRemotes
;
2727 if(dlg
.DoModal()==IDOK
)
2728 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
);
2733 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
)
2736 DWORD exitcode
= 0xFFFFFFFF;
2737 if (CHooks::Instance().PrePush(g_Git
.m_CurrentDir
, exitcode
, error
))
2742 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2743 CMessageBox::Show(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2748 int iRecurseSubmodules
= 0;
2749 if (GetMsysgitVersion() >= 0x02070000)
2751 CString sRecurseSubmodules
= g_Git
.GetConfigValue(_T("push.recurseSubmodules"));
2752 if (sRecurseSubmodules
== _T("check"))
2753 iRecurseSubmodules
= 1;
2754 else if (sRecurseSubmodules
== _T("on-demand"))
2755 iRecurseSubmodules
= 2;
2760 arg
+= _T("--thin ");
2761 if (tags
&& !allBranches
)
2762 arg
+= _T("--tags ");
2764 arg
+= _T("--force ");
2766 arg
+= _T("--force-with-lease ");
2768 arg
+= _T("--set-upstream ");
2769 if (recurseSubmodules
== 0 && recurseSubmodules
!= iRecurseSubmodules
)
2770 arg
+= _T("--recurse-submodules=no ");
2771 if (recurseSubmodules
== 1 && recurseSubmodules
!= iRecurseSubmodules
)
2772 arg
+= _T("--recurse-submodules=check ");
2773 if (recurseSubmodules
== 2 && recurseSubmodules
!= iRecurseSubmodules
)
2774 arg
+= _T("--recurse-submodules=on-demand ");
2776 arg
+= _T("--progress ");
2778 CProgressDlg progress
;
2780 STRING_VECTOR remotesList
;
2782 g_Git
.GetRemoteList(remotesList
);
2784 remotesList
.push_back(remote
);
2786 for (unsigned int i
= 0; i
< remotesList
.size(); ++i
)
2789 CAppUtils::LaunchPAgent(nullptr, &remotesList
[i
]);
2794 cmd
.Format(_T("git.exe push --all %s\"%s\""),
2796 (LPCTSTR
)remotesList
[i
]);
2800 progress
.m_GitCmdList
.push_back(cmd
);
2801 cmd
.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR
)arg
, (LPCTSTR
)remotesList
[i
]);
2806 cmd
.Format(_T("git.exe push %s\"%s\" %s"),
2808 (LPCTSTR
)remotesList
[i
],
2809 (LPCTSTR
)localBranch
);
2810 if (!remoteBranch
.IsEmpty())
2813 cmd
+= remoteBranch
;
2816 progress
.m_GitCmdList
.push_back(cmd
);
2818 if (!allBranches
&& !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE
))
2820 cmd
.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR
)localBranch
);
2821 progress
.m_GitCmdList
.push_back(cmd
);
2825 CString superprojectRoot
;
2826 GitAdminDir::HasAdminDir(g_Git
.m_CurrentDir
, false, &superprojectRoot
);
2827 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2829 // need to execute hooks as those might be needed by post action commands
2830 DWORD exitcode
= 0xFFFFFFFF;
2832 if (CHooks::Instance().PostPush(g_Git
.m_CurrentDir
, exitcode
, error
))
2837 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2838 MessageBox(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2844 bool rejected
= progress
.GetLogText().Find(_T("! [rejected]")) > 0;
2847 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, []{ Pull(true); });
2848 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, [&]{ Fetch(allRemotes
? _T("") : remote
, allRemotes
); });
2850 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2854 postCmdList
.emplace_back(IDS_PROC_REQUESTPULL
, [&]{ RequestPull(remoteBranch
); });
2855 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2856 postCmdList
.emplace_back(IDI_SWITCH
, IDS_MENUSWITCH
, [&]{ Switch(); });
2857 if (!superprojectRoot
.IsEmpty())
2859 postCmdList
.emplace_back(IDI_COMMIT
, IDS_PROC_COMMIT_SUPERPROJECT
, [&]
2862 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)superprojectRoot
);
2863 RunTortoiseGitProc(sCmd
);
2868 INT_PTR ret
= progress
.DoModal();
2872 bool CAppUtils::Push(const CString
& selectLocalBranch
)
2875 dlg
.m_BranchSourceName
= selectLocalBranch
;
2877 if (dlg
.DoModal() == IDOK
)
2878 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
);
2883 bool CAppUtils::RequestPull(const CString
& endrevision
, const CString
& repositoryUrl
, bool bIsMainWnd
)
2885 CRequestPullDlg dlg
;
2886 dlg
.m_RepositoryURL
= repositoryUrl
;
2887 dlg
.m_EndRevision
= endrevision
;
2888 if (dlg
.DoModal()==IDOK
)
2891 cmd
.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR
)dlg
.m_StartRevision
, (LPCTSTR
)dlg
.m_RepositoryURL
, (LPCTSTR
)dlg
.m_EndRevision
);
2893 CSysProgressDlg sysProgressDlg
;
2894 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
2895 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST
)));
2896 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
2897 sysProgressDlg
.SetShowProgressBar(false);
2898 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
2900 CString tempFileName
= GetTempFile();
2902 DeleteFile(tempFileName
);
2903 CreateDirectory(tempFileName
, nullptr);
2904 tempFileName
+= _T("\\pullrequest.txt");
2905 if (g_Git
.RunLogFile(cmd
, tempFileName
, &err
))
2908 msg
.LoadString(IDS_ERR_PULLREUQESTFAILED
);
2909 MessageBox(nullptr, msg
+ _T("\n") + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2913 if (sysProgressDlg
.HasUserCancelled())
2915 CMessageBox::Show(nullptr, IDS_USERCANCELLED
, IDS_APPNAME
, MB_OK
);
2916 ::DeleteFile(tempFileName
);
2920 sysProgressDlg
.Stop();
2922 if (dlg
.m_bSendMail
)
2924 CSendMailDlg sendmaildlg
;
2925 sendmaildlg
.m_PathList
= CTGitPathList(CTGitPath(tempFileName
));
2926 sendmaildlg
.m_bCustomSubject
= true;
2928 if (sendmaildlg
.DoModal() == IDOK
)
2930 if (sendmaildlg
.m_PathList
.IsEmpty())
2933 CGitProgressDlg progDlg
;
2935 theApp
.m_pMainWnd
= &progDlg
;
2936 SendMailProgressCommand sendMailProgressCommand
;
2937 progDlg
.SetCommand(&sendMailProgressCommand
);
2939 sendMailProgressCommand
.SetPathList(sendmaildlg
.m_PathList
);
2940 progDlg
.SetItemCount(sendmaildlg
.m_PathList
.GetCount());
2942 CSendMailCombineable
sendMailCombineable(sendmaildlg
.m_To
, sendmaildlg
.m_CC
, sendmaildlg
.m_Subject
, !!sendmaildlg
.m_bAttachment
, !!sendmaildlg
.m_bCombine
);
2943 sendMailProgressCommand
.SetSendMailOption(&sendMailCombineable
);
2952 CAppUtils::LaunchAlternativeEditor(tempFileName
);
2957 void CAppUtils::RemoveTrailSlash(CString
&path
)
2962 // For URL, do not trim the slash just after the host name component.
2963 int index
= path
.Find(_T("://"));
2967 index
= path
.Find(_T('/'), index
);
2968 if (index
== path
.GetLength() - 1)
2972 while(path
[path
.GetLength()-1] == _T('\\') || path
[path
.GetLength()-1] == _T('/' ) )
2974 path
.Truncate(path
.GetLength() - 1);
2980 bool CAppUtils::CheckUserData()
2982 while(g_Git
.GetUserName().IsEmpty() || g_Git
.GetUserEmail().IsEmpty())
2984 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA
, IDS_APPNAME
, MB_YESNO
| MB_ICONERROR
) == IDYES
)
2986 CTGitPath
path(g_Git
.m_CurrentDir
);
2987 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
,&path
);
2988 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
2989 dlg
.SetTreeWidth(220);
2990 dlg
.m_DefaultPage
= _T("gitconfig");
2993 dlg
.HandleRestart();
3003 BOOL
CAppUtils::Commit(const CString
& bugid
, BOOL bWholeProject
, CString
&sLogMsg
,
3004 CTGitPathList
&pathList
,
3005 CTGitPathList
&selectedList
,
3006 bool bSelectFilesForCommit
)
3008 bool bFailed
= true;
3010 if (!CheckUserData())
3017 dlg
.m_sBugID
= bugid
;
3019 dlg
.m_bWholeProject
= bWholeProject
;
3021 dlg
.m_sLogMessage
= sLogMsg
;
3022 dlg
.m_pathList
= pathList
;
3023 dlg
.m_checkedPathList
= selectedList
;
3024 dlg
.m_bSelectFilesForCommit
= bSelectFilesForCommit
;
3025 if (dlg
.DoModal() == IDOK
)
3027 if (dlg
.m_pathList
.IsEmpty())
3029 // if the user hasn't changed the list of selected items
3030 // we don't use that list. Because if we would use the list
3031 // of pre-checked items, the dialog would show different
3032 // checked items on the next startup: it would only try
3033 // to check the parent folder (which might not even show)
3034 // instead, we simply use an empty list and let the
3035 // default checking do its job.
3036 if (!dlg
.m_pathList
.IsEqual(pathList
))
3037 selectedList
= dlg
.m_pathList
;
3038 pathList
= dlg
.m_updatedPathList
;
3039 sLogMsg
= dlg
.m_sLogMessage
;
3040 bSelectFilesForCommit
= true;
3042 switch (dlg
.m_PostCmd
)
3044 case GIT_POSTCOMMIT_CMD_DCOMMIT
:
3045 CAppUtils::SVNDCommit();
3047 case GIT_POSTCOMMIT_CMD_PUSH
:
3050 case GIT_POSTCOMMIT_CMD_CREATETAG
:
3051 CAppUtils::CreateBranchTag(TRUE
);
3053 case GIT_POSTCOMMIT_CMD_PULL
:
3054 CAppUtils::Pull(true);
3060 // CGitProgressDlg progDlg;
3061 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3062 // if (parser.HasVal(_T("closeonend")))
3063 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3064 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3065 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3066 // progDlg.SetPathList(dlg.m_pathList);
3067 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3068 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3069 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3070 // progDlg.SetItemCount(dlg.m_itemsCount);
3071 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3072 // progDlg.DoModal();
3073 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3074 // err = (DWORD)progDlg.DidErrorsOccur();
3075 // bFailed = progDlg.DidErrorsOccur();
3076 // bRet = progDlg.DidErrorsOccur();
3077 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3078 // if (DWORD(bFailRepeat)==0)
3079 // bFailed = false; // do not repeat if the user chose not to in the settings.
3085 BOOL
CAppUtils::SVNDCommit()
3087 CSVNDCommitDlg dcommitdlg
;
3088 CString gitSetting
= g_Git
.GetConfigValue(_T("svn.rmdir"));
3089 if (gitSetting
.IsEmpty()) {
3090 if (dcommitdlg
.DoModal() != IDOK
)
3094 if (dcommitdlg
.m_remember
)
3096 if (dcommitdlg
.m_rmdir
)
3097 gitSetting
= _T("true");
3099 gitSetting
= _T("false");
3100 if(g_Git
.SetConfigValue(_T("svn.rmdir"),gitSetting
))
3103 msg
.Format(IDS_PROC_SAVECONFIGFAILED
, _T("svn.rmdir"), gitSetting
);
3104 CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3110 BOOL IsStash
= false;
3111 if(!g_Git
.CheckCleanWorkTree())
3113 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3115 CSysProgressDlg sysProgressDlg
;
3116 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3117 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3118 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3119 sysProgressDlg
.SetShowProgressBar(false);
3120 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3121 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3124 cmd
=_T("git.exe stash");
3125 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3127 sysProgressDlg
.Stop();
3128 MessageBox(nullptr, out
,_T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3131 sysProgressDlg
.Stop();
3139 CProgressDlg progress
;
3140 if (dcommitdlg
.m_rmdir
)
3141 progress
.m_GitCmd
=_T("git.exe svn dcommit --rmdir");
3143 progress
.m_GitCmd
=_T("git.exe svn dcommit");
3144 if(progress
.DoModal()==IDOK
&& progress
.m_GitStatus
== 0)
3148 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
3150 CSysProgressDlg sysProgressDlg
;
3151 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3152 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3153 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3154 sysProgressDlg
.SetShowProgressBar(false);
3155 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3156 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3159 cmd
=_T("git.exe stash pop");
3160 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3162 sysProgressDlg
.Stop();
3163 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3166 sysProgressDlg
.Stop();
3176 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
)
3180 args
+= L
" --no-ff";
3182 args
+= L
" --ff-only";
3185 args
+= L
" --squash";
3188 args
+= L
" --no-commit";
3191 args
+= L
" --allow-unrelated-histories";
3194 args
.AppendFormat(L
" --log=%d", *log
);
3196 if (!mergeStrategy
.IsEmpty())
3198 args
+= L
" --strategy=" + mergeStrategy
;
3199 if (!strategyOption
.IsEmpty())
3201 args
+= L
" --strategy-option=" + strategyOption
;
3202 if (!strategyParam
.IsEmpty())
3203 args
+= L
'=' + strategyParam
;
3207 if (!logMessage
.IsEmpty())
3209 CString logmsg
= logMessage
;
3210 logmsg
.Replace(L
"\\\"", L
"\\\\\"");
3211 logmsg
.Replace(L
"\"", L
"\\\"");
3212 args
+= L
" -m \"" + logmsg
+ L
"\"";
3215 CString mergeVersion
= g_Git
.FixBranchName(version
);
3217 cmd
.Format(L
"git.exe merge%s %s", (LPCTSTR
)args
, (LPCTSTR
)mergeVersion
);
3219 CProgressDlg Prodlg
;
3220 Prodlg
.m_GitCmd
= cmd
;
3222 Prodlg
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3226 int hasConflicts
= g_Git
.HasWorkingTreeConflicts();
3227 if (hasConflicts
< 0)
3228 CMessageBox::Show(nullptr, g_Git
.GetGitLastErr(L
"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS
), L
"TortoiseGit", MB_ICONEXCLAMATION
);
3229 else if (hasConflicts
)
3231 // there are conflict files
3233 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
3236 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3237 CAppUtils::RunTortoiseGitProc(sCmd
);
3241 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3244 g_Git
.IsFastForward(L
"HEAD", mergeVersion
, &common
);
3245 if (common
.IsEmpty())
3246 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoMerge(noFF
, ffOnly
, squash
, noCommit
, log
, true, mergeStrategy
, strategyOption
, strategyParam
, logMessage
, version
, isBranch
, showStashPop
); });
3249 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [=]{ CAppUtils::StashSave(L
"", false, false, true, mergeVersion
); });
3255 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
3259 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []
3262 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3263 CAppUtils::RunTortoiseGitProc(sCmd
);
3268 if (isBranch
&& !CStringUtils::StartsWith(version
, L
"remotes/")) // do not ask to remove remote branches
3270 postCmdList
.emplace_back(IDI_DELETE
, IDS_PROC_REMOVEBRANCH
, [&]
3273 msg
.Format(IDS_PROC_DELETEBRANCHTAG
, version
);
3274 if (CMessageBox::Show(nullptr, msg
, L
"TortoiseGit", 2, IDI_QUESTION
, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON
)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON
))) == 1)
3277 cmd
.Format(L
"git.exe branch -D -- %s", (LPCTSTR
)version
);
3278 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3279 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
);
3284 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
3286 BOOL hasGitSVN
= CTGitPath(g_Git
.m_CurrentDir
).GetAdminDirMask() & ITEMIS_GITSVN
;
3288 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSVNDCOMMIT
, []{ CAppUtils::SVNDCommit(); });
3292 return !Prodlg
.m_GitStatus
;
3295 BOOL
CAppUtils::Merge(const CString
* commit
, bool showStashPop
)
3297 if (!CheckUserData())
3300 if (IsTGitRebaseActive())
3305 dlg
.m_initialRefName
= *commit
;
3307 if (dlg
.DoModal() == IDOK
)
3308 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
);
3313 BOOL
CAppUtils::MergeAbort()
3316 if (dlg
.DoModal() == IDOK
)
3317 return Reset(_T("HEAD"), dlg
.m_ResetType
+ 1);
3322 void CAppUtils::EditNote(GitRevLoglist
* rev
)
3324 if (!CheckUserData())
3328 dlg
.m_sHintText
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3329 dlg
.m_sInputText
= rev
->m_Notes
;
3330 dlg
.m_sTitle
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3331 //dlg.m_pProjectProperties = &m_ProjectProperties;
3332 dlg
.m_bUseLogWidth
= true;
3333 if(dlg
.DoModal() == IDOK
)
3336 cmd
=_T("notes add -f -F \"");
3338 CString tempfile
=::GetTempFile();
3339 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_sInputText
))
3341 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3346 cmd
+= rev
->m_CommitHash
.ToString();
3350 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd
, CP_UTF8
).GetBuffer()))
3351 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3353 rev
->m_Notes
= dlg
.m_sInputText
;
3356 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3358 ::DeleteFile(tempfile
);
3363 int CAppUtils::GetMsysgitVersion()
3365 if (g_Git
.ms_LastMsysGitVersion
)
3366 return g_Git
.ms_LastMsysGitVersion
;
3369 CString versiondebug
;
3372 CRegDWORD regTime
= CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3373 CRegDWORD regVersion
= CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3375 CString gitpath
= CGit::ms_LastMsysGitDir
+_T("\\git.exe");
3378 if (!CGit::GetFileModifyTime(gitpath
, &time
))
3380 if((DWORD
)time
== regTime
)
3382 g_Git
.ms_LastMsysGitVersion
= regVersion
;
3388 int ver
= g_Git
.GetGitVersion(&versiondebug
, &err
);
3391 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
);
3398 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug
+ _T("\""), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3403 regTime
= time
&0xFFFFFFFF;
3405 g_Git
.ms_LastMsysGitVersion
= ver
;
3410 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd
)
3412 typedef HRESULT (WINAPI
*SHGPSFW
) (HWND hwnd
,REFIID riid
,void** ppv
);
3414 CAutoLibrary hShell
= AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3416 if (hShell
.IsValid()) {
3417 SHGPSFW pfnSHGPSFW
= (SHGPSFW
)::GetProcAddress(hShell
, "SHGetPropertyStoreForWindow");
3419 IPropertyStore
*pps
;
3420 HRESULT hr
= pfnSHGPSFW(hWnd
, IID_PPV_ARGS(&pps
));
3421 if (SUCCEEDED(hr
)) {
3424 var
.boolVal
= VARIANT_TRUE
;
3425 pps
->SetValue(PKEY_AppUserModel_PreventPinning
, var
);
3432 void CAppUtils::SetWindowTitle(HWND hWnd
, const CString
& urlorpath
, const CString
& dialogname
)
3434 ASSERT(dialogname
.GetLength() < 70);
3435 ASSERT(urlorpath
.GetLength() < MAX_PATH
);
3436 WCHAR pathbuf
[MAX_PATH
] = {0};
3438 PathCompactPathEx(pathbuf
, urlorpath
, 70 - dialogname
.GetLength(), 0);
3440 wcscat_s(pathbuf
, L
" - ");
3441 wcscat_s(pathbuf
, dialogname
);
3442 wcscat_s(pathbuf
, L
" - ");
3443 wcscat_s(pathbuf
, CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3444 SetWindowText(hWnd
, pathbuf
);
3447 bool CAppUtils::BisectStart(const CString
& lastGood
, const CString
& firstBad
, bool bIsMainWnd
)
3449 if (!g_Git
.CheckCleanWorkTree())
3451 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3453 CSysProgressDlg sysProgressDlg
;
3454 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3455 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3456 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3457 sysProgressDlg
.SetShowProgressBar(false);
3458 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3459 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3462 cmd
= _T("git.exe stash");
3463 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3465 sysProgressDlg
.Stop();
3466 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3469 sysProgressDlg
.Stop();
3475 CBisectStartDlg bisectStartDlg
;
3477 if (!lastGood
.IsEmpty())
3478 bisectStartDlg
.m_sLastGood
= lastGood
;
3479 if (!firstBad
.IsEmpty())
3480 bisectStartDlg
.m_sFirstBad
= firstBad
;
3482 if (bisectStartDlg
.DoModal() == IDOK
)
3484 CProgressDlg progress
;
3486 theApp
.m_pMainWnd
= &progress
;
3487 progress
.m_GitCmdList
.push_back(_T("git.exe bisect start"));
3488 progress
.m_GitCmdList
.push_back(_T("git.exe bisect good ") + bisectStartDlg
.m_LastGoodRevision
);
3489 progress
.m_GitCmdList
.push_back(_T("git.exe bisect bad ") + bisectStartDlg
.m_FirstBadRevision
);
3491 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3496 CTGitPath
path(g_Git
.m_CurrentDir
);
3497 if (path
.HasSubmodules())
3499 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3502 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3503 CAppUtils::RunTortoiseGitProc(sCmd
);
3508 INT_PTR ret
= progress
.DoModal();
3515 bool CAppUtils::BisectOperation(const CString
& op
, const CString
& ref
, bool bIsMainWnd
)
3517 CString cmd
= _T("git.exe bisect ") + op
;
3525 CProgressDlg progress
;
3527 theApp
.m_pMainWnd
= &progress
;
3528 progress
.m_GitCmd
= cmd
;
3530 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3535 CTGitPath path
= g_Git
.m_CurrentDir
;
3536 if (path
.HasSubmodules())
3538 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3541 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3542 CAppUtils::RunTortoiseGitProc(sCmd
);
3546 if (op
!= _T("reset"))
3547 postCmdList
.emplace_back(IDS_MENUBISECTRESET
, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3550 INT_PTR ret
= progress
.DoModal();
3554 int CAppUtils::Git2GetUserPassword(git_cred
**out
, const char *url
, const char *username_from_url
, unsigned int /*allowed_types*/, void * /*payload*/)
3557 dlg
.m_URL
= CUnicodeUtils::GetUnicode(url
, CP_UTF8
);
3558 if (username_from_url
)
3559 dlg
.m_UserName
= CUnicodeUtils::GetUnicode(username_from_url
, CP_UTF8
);
3561 CStringA username
, password
;
3562 if (dlg
.DoModal() == IDOK
)
3564 username
= CUnicodeUtils::GetMulti(dlg
.m_UserName
, CP_UTF8
);
3565 password
= CUnicodeUtils::GetMulti(dlg
.m_Password
, CP_UTF8
);
3566 return git_cred_userpass_plaintext_new(out
, username
, password
);
3568 giterr_set_str(GITERR_NONE
, "User cancelled.");
3572 int CAppUtils::Git2CertificateCheck(git_cert
* base_cert
, int /*valid*/, const char* host
, void* /*payload*/)
3574 if (base_cert
->cert_type
== GIT_CERT_X509
)
3576 git_cert_x509
* cert
= (git_cert_x509
*)base_cert
;
3578 if (last_accepted_cert
.cmp(cert
))
3581 PCCERT_CONTEXT pServerCert
= CertCreateCertificateContext(X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, (BYTE
*)cert
->data
, (DWORD
)cert
->len
);
3582 SCOPE_EXIT
{ CertFreeCertificateContext(pServerCert
); };
3584 DWORD verificationError
= VerifyServerCertificate(pServerCert
, CUnicodeUtils::GetUnicode(host
).GetBuffer(), 0);
3585 if (!verificationError
)
3587 last_accepted_cert
.set(cert
);
3591 CString servernameInCert
;
3592 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, 0, nullptr, CStrBuf(servernameInCert
, 128), 128);
3595 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, CERT_NAME_ISSUER_FLAG
, nullptr, CStrBuf(issuer
, 128), 128);
3597 CCheckCertificateDlg dlg
;
3599 dlg
.m_sCertificateCN
= servernameInCert
;
3600 dlg
.m_sCertificateIssuer
= issuer
;
3601 dlg
.m_sHostname
= CUnicodeUtils::GetUnicode(host
);
3602 dlg
.m_sError
= CFormatMessageWrapper(verificationError
);
3603 if (dlg
.DoModal() == IDOK
)
3605 last_accepted_cert
.set(cert
);
3609 return GIT_ECERTIFICATE
;
3612 int CAppUtils::ExploreTo(HWND hwnd
, CString path
)
3614 if (PathFileExists(path
))
3617 ITEMIDLIST __unaligned
* pidl
= ILCreateFromPath(path
);
3620 ret
= SHOpenFolderAndSelectItems(pidl
, 0, 0, 0);
3623 return SUCCEEDED(ret
) ? 0 : -1;
3625 // if filepath does not exist any more, navigate to closest matching folder
3628 int pos
= path
.ReverseFind(_T('\\'));
3632 } while (!PathFileExists(path
));
3633 return (INT_PTR
)ShellExecute(hwnd
, _T("explore"), path
, nullptr, nullptr, SW_SHOW
) > 32 ? 0 : -1;
3636 int CAppUtils::ResolveConflict(CTGitPath
& path
, resolve_with resolveWith
)
3638 bool b_local
= false, b_remote
= false;
3642 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3643 if (g_Git
.Run(cmd
, &vector
))
3645 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3650 if (list
.ParserFromLsFile(vector
))
3652 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3658 for (int i
= 0; i
< list
.GetCount(); ++i
)
3660 if (list
[i
].m_Stage
== 2)
3662 if (list
[i
].m_Stage
== 3)
3667 CBlockCacheForPath
block(g_Git
.m_CurrentDir
);
3668 if (path
.IsDirectory()) // is submodule conflict
3670 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.");
3671 if (b_local
&& b_remote
)
3673 if (!path
.HasAdminDir()) // check if submodule is initialized
3675 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).");
3676 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3680 subgit
.m_CurrentDir
= g_Git
.CombinePath(path
);
3681 CGitHash submoduleHead
;
3682 if (subgit
.GetHash(submoduleHead
, _T("HEAD")))
3684 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3687 CString baseHash
, localHash
, remoteHash
;
3688 ParseHashesFromLsFile(vector
, baseHash
, localHash
, remoteHash
);
3689 if (resolveWith
== RESOLVE_WITH_THEIRS
&& submoduleHead
.ToString() != remoteHash
)
3691 CString origPath
= g_Git
.m_CurrentDir
;
3692 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3693 if (!GitReset(&remoteHash
))
3695 g_Git
.m_CurrentDir
= origPath
;
3698 g_Git
.m_CurrentDir
= origPath
;
3700 else if (resolveWith
== RESOLVE_WITH_MINE
&& submoduleHead
.ToString() != localHash
)
3702 CString origPath
= g_Git
.m_CurrentDir
;
3703 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3704 if (!GitReset(&localHash
))
3706 g_Git
.m_CurrentDir
= origPath
;
3709 g_Git
.m_CurrentDir
= origPath
;
3714 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3719 if (resolveWith
== RESOLVE_WITH_THEIRS
)
3721 CString gitcmd
, output
;
3722 if (b_local
&& b_remote
)
3723 gitcmd
.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3725 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3727 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3728 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3730 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3734 else if (resolveWith
== RESOLVE_WITH_MINE
)
3736 CString gitcmd
, output
;
3737 if (b_local
&& b_remote
)
3738 gitcmd
.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3740 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3742 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3743 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3745 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3750 if (b_local
&& b_remote
&& path
.m_Action
& CTGitPath::LOGACTIONS_UNMERGED
)
3752 CString gitcmd
, output
;
3753 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3754 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3755 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3758 path
.m_Action
|= CTGitPath::LOGACTIONS_MODIFIED
;
3759 path
.m_Action
&= ~CTGitPath::LOGACTIONS_UNMERGED
;
3763 RemoveTempMergeFile(path
);
3767 bool CAppUtils::ShellOpen(const CString
& file
, HWND hwnd
/*= nullptr */)
3769 if ((INT_PTR
)ShellExecute(hwnd
, nullptr, file
, nullptr, nullptr, SW_SHOW
) > HINSTANCE_ERROR
)
3772 return ShowOpenWithDialog(file
, hwnd
);
3775 bool CAppUtils::ShowOpenWithDialog(const CString
& file
, HWND hwnd
/*= nullptr */)
3777 OPENASINFO oi
= { 0 };
3779 oi
.oaifInFlags
= OAIF_EXEC
;
3780 return SUCCEEDED(SHOpenWithDialog(hwnd
, &oi
));
3783 bool CAppUtils::IsTGitRebaseActive()
3786 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3789 if (!PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3792 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND
, IDS_APPNAME
, 2, IDI_EXCLAMATION
, IDS_REMOVESTALEBUTTON
, IDS_ABORTBUTTON
) == 2)
3795 RemoveDirectory(adminDir
+ L
"tgitrebase.active");