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
'!';
890 bool IsUrl(const CString
& sText
)
892 if (!PathIsURLW(sText
))
894 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ftp://", L
"file://", L
"mailto:" })
896 if (CStringUtils::StartsWith(sText
, prefix
) && sText
.GetLength() != prefix
.GetLength())
903 BOOL
CAppUtils::StyleURLs(const CString
& msg
, CWnd
* pWnd
)
905 std::vector
<CHARRANGE
> positions
= FindURLMatches(msg
);
906 CAppUtils::SetCharFormat(pWnd
, CFM_LINK
, CFE_LINK
, positions
);
908 return positions
.empty() ? FALSE
: TRUE
;
912 * implements URL searching with the same logic as CSciEdit::StyleURLs
914 std::vector
<CHARRANGE
> CAppUtils::FindURLMatches(const CString
& msg
)
916 std::vector
<CHARRANGE
> result
;
918 int len
= msg
.GetLength();
921 for (int i
= 0; i
<= msg
.GetLength(); ++i
)
923 if ((i
< len
) && IsValidURLChar(msg
[i
]))
933 if (msg
[starturl
] == '<' && i
< len
) // try to detect and do not strip URLs put within <>
935 while (starturl
<= i
&& msg
[starturl
] == '<') // strip leading '<'
939 while (i
< len
&& msg
[i
] != '\r' && msg
[i
] != '\n' && msg
[i
] != '>') // find first '>' or new line after resetting i to start position
942 if (!IsUrl(msg
.Mid(starturl
, i
- starturl
)))
948 int skipTrailing
= 0;
949 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] == '!'))
952 CHARRANGE range
= { starturl
, i
- skipTrailing
};
953 result
.push_back(range
);
962 bool CAppUtils::StartShowUnifiedDiff(HWND hWnd
, const CTGitPath
& url1
, const git_revnum_t
& rev1
,
963 const CTGitPath
& /*url2*/, const git_revnum_t
& rev2
,
964 //const GitRev& peg /* = GitRev */, const GitRev& headpeg /* = GitRev */,
965 bool bAlternateDiff
/* = false */, bool /*bIgnoreAncestry*/ /* = false */,
966 bool /* blame = false */,
971 int diffContext
= g_Git
.GetConfigValueInt32(L
"diff.context", -1);
972 CString tempfile
=GetTempFile();
973 if (g_Git
.GetUnifiedDiff(url1
, rev1
, rev2
, tempfile
, bMerge
, bCombine
, diffContext
, bNoPrefix
))
975 CMessageBox::Show(hWnd
, g_Git
.GetGitLastErr(_T("Could not get unified diff."), CGit::GIT_CMD_DIFF
), _T("TortoiseGit"), MB_OK
);
978 CAppUtils::StartUnifiedDiffViewer(tempfile
, rev1
+ L
":" + rev2
, FALSE
, bAlternateDiff
);
982 sCmd
.Format(_T("%s /command:showcompare /unified"),
983 (LPCTSTR
)(CPathUtils::GetAppDirectory()+_T("TortoiseGitProc.exe")));
984 sCmd
+= _T(" /url1:\"") + url1
.GetGitPathString() + _T("\"");
986 sCmd
+= _T(" /revision1:") + rev1
.ToString();
987 sCmd
+= _T(" /url2:\"") + url2
.GetGitPathString() + _T("\"");
989 sCmd
+= _T(" /revision2:") + rev2
.ToString();
991 sCmd
+= _T(" /pegrevision:") + peg
.ToString();
992 if (headpeg
.IsValid())
993 sCmd
+= _T(" /headpegrevision:") + headpeg
.ToString();
996 sCmd
+= _T(" /alternatediff");
999 sCmd
+= _T(" /ignoreancestry");
1003 sCmd
+= _T(" /hwnd:");
1005 _stprintf_s(buf
, 30, _T("%p"), (void*)hWnd
);
1009 return CAppUtils::LaunchApplication(sCmd
, 0, false);
1014 bool CAppUtils::SetupDiffScripts(bool force
, const CString
& type
)
1016 CString scriptsdir
= CPathUtils::GetAppParentDirectory();
1017 scriptsdir
+= _T("Diff-Scripts");
1018 CSimpleFileFind
files(scriptsdir
);
1019 while (files
.FindNextFileNoDirectories())
1021 CString file
= files
.GetFilePath();
1022 CString filename
= files
.GetFileName();
1023 CString ext
= file
.Mid(file
.ReverseFind('-') + 1);
1024 ext
= _T(".") + ext
.Left(ext
.ReverseFind('.'));
1025 std::set
<CString
> extensions
;
1026 extensions
.insert(ext
);
1028 if (file
.Right(3).CompareNoCase(_T("vbs"))==0)
1029 kind
= _T(" //E:vbscript");
1030 if (file
.Right(2).CompareNoCase(_T("js"))==0)
1031 kind
= _T(" //E:javascript");
1032 // open the file, read the first line and find possible extensions
1033 // this script can handle
1036 CStdioFile
f(file
, CFile::modeRead
| CFile::shareDenyNone
);
1038 if (f
.ReadString(extline
))
1040 if ((extline
.GetLength() > 15 ) &&
1041 ((extline
.Left(15).Compare(_T("// extensions: ")) == 0) ||
1042 (extline
.Left(14).Compare(_T("' extensions: ")) == 0)))
1044 if (extline
[0] == '/')
1045 extline
= extline
.Mid(15);
1047 extline
= extline
.Mid(14);
1050 sToken
= extline
.Tokenize(_T(";"), curPos
);
1051 while (!sToken
.IsEmpty())
1053 if (!sToken
.IsEmpty())
1055 if (sToken
[0] != '.')
1056 sToken
= _T(".") + sToken
;
1057 extensions
.insert(sToken
);
1059 sToken
= extline
.Tokenize(_T(";"), curPos
);
1065 catch (CFileException
* e
)
1070 for (const auto& extension
: extensions
)
1072 if (type
.IsEmpty() || (type
.Compare(_T("Diff")) == 0))
1074 if (filename
.Left(5).CompareNoCase(_T("diff-")) == 0)
1076 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\DiffTools\\") + extension
);
1077 CString diffregstring
= diffreg
;
1078 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1079 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %base %mine") + kind
;
1082 if (type
.IsEmpty() || (type
.Compare(_T("Merge"))==0))
1084 if (filename
.Left(6).CompareNoCase(_T("merge-"))==0)
1086 CRegString diffreg
= CRegString(_T("Software\\TortoiseGit\\MergeTools\\") + extension
);
1087 CString diffregstring
= diffreg
;
1088 if (force
|| (diffregstring
.IsEmpty()) || (diffregstring
.Find(filename
) >= 0))
1089 diffreg
= _T("wscript.exe \"") + file
+ _T("\" %merged %theirs %mine %base") + kind
;
1098 bool CAppUtils::Export(const CString
* BashHash
, const CTGitPath
* orgPath
)
1100 // ask from where the export has to be done
1103 dlg
.m_initialRefName
=*BashHash
;
1106 if (PathIsRelative(orgPath
->GetWinPath()))
1107 dlg
.m_orgPath
= g_Git
.CombinePath(orgPath
);
1109 dlg
.m_orgPath
= *orgPath
;
1112 if (dlg
.DoModal() == IDOK
)
1115 cmd
.Format(_T("git.exe archive --output=\"%s\" --format=zip --verbose %s --"),
1116 (LPCTSTR
)dlg
.m_strFile
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
1120 pro
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1124 postCmdList
.emplace_back(IDI_EXPLORER
, IDS_STATUSLIST_CONTEXT_EXPLORE
, [&]{ CAppUtils::ExploreTo(hWndExplorer
, dlg
.m_strFile
); });
1128 if (!dlg
.m_bWholeProject
&& !dlg
.m_orgPath
.IsEmpty() && PathIsDirectory(dlg
.m_orgPath
.GetWinPathString()))
1130 git
.m_CurrentDir
= dlg
.m_orgPath
.GetWinPathString();
1133 return (pro
.DoModal() == IDOK
);
1138 bool CAppUtils::UpdateBranchDescription(const CString
& branch
, CString description
)
1140 if (branch
.IsEmpty())
1144 key
.Format(L
"branch.%s.description", (LPCTSTR
)branch
);
1145 description
.Replace(L
"\r", L
"");
1147 if (description
.IsEmpty())
1148 g_Git
.UnsetConfigValue(key
);
1150 g_Git
.SetConfigValue(key
, description
);
1155 bool CAppUtils::CreateBranchTag(bool isTag
/*true*/, const CString
* commitHash
/*nullptr*/, bool switchNewBranch
/*false*/, LPCTSTR name
/*nullptr*/)
1157 CCreateBranchTagDlg dlg
;
1158 dlg
.m_bIsTag
= isTag
;
1159 dlg
.m_bSwitch
= switchNewBranch
;
1162 dlg
.m_initialRefName
= *commitHash
;
1165 dlg
.m_BranchTagName
= name
;
1167 if(dlg
.DoModal()==IDOK
)
1172 if(dlg
.m_bTrack
== TRUE
)
1173 track
=_T(" --track ");
1174 else if(dlg
.m_bTrack
== FALSE
)
1175 track
=_T(" --no-track");
1186 cmd
.Format(_T("git.exe tag %s %s %s %s"),
1189 (LPCTSTR
)dlg
.m_BranchTagName
,
1190 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1193 if(!dlg
.m_Message
.Trim().IsEmpty())
1195 CString tempfile
= ::GetTempFile();
1196 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_Message
))
1198 CMessageBox::Show(nullptr, _T("Could not save tag message"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1201 cmd
+= _T(" -F ")+tempfile
;
1206 cmd
.Format(_T("git.exe branch %s %s %s %s"),
1209 (LPCTSTR
)dlg
.m_BranchTagName
,
1210 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
)
1214 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1216 CMessageBox::Show(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1219 if (!isTag
&& dlg
.m_bSwitch
)
1221 // it is a new branch and the user has requested to switch to it
1222 PerformSwitch(dlg
.m_BranchTagName
);
1224 if (!isTag
&& !dlg
.m_Message
.IsEmpty())
1225 UpdateBranchDescription(dlg
.m_BranchTagName
, dlg
.m_Message
);
1232 bool CAppUtils::Switch(const CString
& initialRefName
)
1235 if(!initialRefName
.IsEmpty())
1236 dlg
.m_initialRefName
= initialRefName
;
1238 if (dlg
.DoModal() == IDOK
)
1242 branch
= dlg
.m_NewBranch
;
1244 // if refs/heads/ is not stripped, checkout will detach HEAD
1245 // checkout prefers branches on name clashes (with tags)
1246 if (dlg
.m_VersionName
.Left(11) ==_T("refs/heads/") && dlg
.m_bBranchOverride
!= TRUE
)
1247 dlg
.m_VersionName
= dlg
.m_VersionName
.Mid(11);
1249 return PerformSwitch(dlg
.m_VersionName
, dlg
.m_bForce
== TRUE
, branch
, dlg
.m_bBranchOverride
== TRUE
, dlg
.m_bTrack
, dlg
.m_bMerge
== TRUE
);
1254 bool CAppUtils::PerformSwitch(const CString
& ref
, bool bForce
/* false */, const CString
& sNewBranch
/* CString() */, bool bBranchOverride
/* false */, BOOL bTrack
/* 2 */, bool bMerge
/* false */)
1262 if(!sNewBranch
.IsEmpty()){
1263 if (bBranchOverride
)
1264 branch
.Format(_T("-B %s "), (LPCTSTR
)sNewBranch
);
1266 branch
.Format(_T("-b %s "), (LPCTSTR
)sNewBranch
);
1268 track
= _T("--track ");
1269 else if (bTrack
== FALSE
)
1270 track
= _T("--no-track ");
1275 merge
= _T("--merge ");
1277 cmd
.Format(_T("git.exe checkout %s%s%s%s%s --"),
1282 (LPCTSTR
)g_Git
.FixBranchName(ref
));
1284 CProgressDlg progress
;
1285 progress
.m_GitCmd
= cmd
;
1287 CString currentBranch
;
1288 bool hasBranch
= CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
) == 0;
1289 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1293 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1294 if (gitPath
.HasSubmodules())
1296 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1299 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1300 RunTortoiseGitProc(sCmd
);
1304 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ Merge(¤tBranch
); });
1308 if (!CGit::GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, newBranch
))
1309 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
1311 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []{
1312 CTGitPathList pathlist
;
1313 CTGitPathList selectedlist
;
1314 pathlist
.AddPath(CTGitPath());
1315 bool bSelectFilesForCommit
= !!DWORD(CRegStdDWORD(_T("Software\\TortoiseGit\\SelectFilesForCommit"), TRUE
));
1317 Commit(CString(), false, str
, pathlist
, selectedlist
, bSelectFilesForCommit
);
1322 if (bMerge
&& g_Git
.HasWorkingTreeConflicts() > 0)
1324 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
1327 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1328 CAppUtils::RunTortoiseGitProc(sCmd
);
1331 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, bMerge
); });
1333 postCmdList
.emplace_back(IDI_SWITCH
, IDS_SWITCH_WITH_MERGE
, [&]{ PerformSwitch(ref
, bForce
, sNewBranch
, bBranchOverride
, bTrack
, true); });
1336 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
& extraMsg
)
1338 if (bMerge
&& !exitCode
&& g_Git
.HasWorkingTreeConflicts() > 0)
1340 exitCode
= 1; // Treat it as failure
1341 extraMsg
= _T("Has merge conflict");
1345 INT_PTR ret
= progress
.DoModal();
1350 class CIgnoreFile
: public CStdioFile
1353 STRING_VECTOR m_Items
;
1356 virtual BOOL
ReadString(CString
& rString
)
1358 if (GetPosition() == 0)
1360 unsigned char utf8bom
[] = { 0xEF, 0xBB, 0xBF };
1361 char buf
[3] = { 0, 0, 0 };
1363 if (memcpy(buf
, utf8bom
, sizeof(utf8bom
)))
1368 char lastChar
= '\0';
1369 for (char c
= '\0'; Read(&c
, 1) == 1; lastChar
= c
)
1375 m_eol
= lastChar
== '\r' ? _T("\r\n") : _T("\n");
1383 rString
= CUnicodeUtils::GetUnicode(strA
);
1394 bool CAppUtils::OpenIgnoreFile(CIgnoreFile
&file
, const CString
& filename
)
1397 if (!file
.Open(filename
, CFile::modeCreate
| CFile::modeReadWrite
| CFile::modeNoTruncate
| CFile::typeBinary
))
1399 CMessageBox::Show(nullptr, filename
+ _T(" Open Failure"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1403 if (file
.GetLength() > 0)
1406 while (file
.ReadString(fileText
))
1407 file
.m_Items
.push_back(fileText
);
1408 file
.Seek(file
.GetLength() - 1, 0);
1409 char lastchar
[1] = { 0 };
1410 file
.Read(lastchar
, 1);
1412 if (lastchar
[0] != '\n')
1414 CStringA eol
= CStringA(file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
);
1415 file
.Write(eol
, eol
.GetLength());
1424 bool CAppUtils::IgnoreFile(const CTGitPathList
& path
,bool IsMask
)
1426 CIgnoreDlg ignoreDlg
;
1427 if (ignoreDlg
.DoModal() == IDOK
)
1430 ignorefile
= g_Git
.m_CurrentDir
+ _T("\\");
1432 switch (ignoreDlg
.m_IgnoreFile
)
1435 ignorefile
+= _T(".gitignore");
1438 GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, ignorefile
);
1439 ignorefile
+= _T("info");
1440 if (!PathFileExists(ignorefile
))
1441 CreateDirectory(ignorefile
, nullptr);
1442 ignorefile
+= _T("\\exclude");
1449 if (ignoreDlg
.m_IgnoreFile
!= 1 && !OpenIgnoreFile(file
, ignorefile
))
1452 for (int i
= 0; i
< path
.GetCount(); ++i
)
1454 if (ignoreDlg
.m_IgnoreFile
== 1)
1456 ignorefile
= g_Git
.CombinePath(path
[i
].GetContainingDirectory()) + _T("\\.gitignore");
1457 if (!OpenIgnoreFile(file
, ignorefile
))
1461 CString ignorePattern
;
1462 if (ignoreDlg
.m_IgnoreType
== 0)
1464 if (ignoreDlg
.m_IgnoreFile
!= 1 && !path
[i
].GetContainingDirectory().GetGitPathString().IsEmpty())
1465 ignorePattern
+= _T("/") + path
[i
].GetContainingDirectory().GetGitPathString();
1467 ignorePattern
+= _T("/");
1470 ignorePattern
+= _T("*") + path
[i
].GetFileExtension();
1472 ignorePattern
+= path
[i
].GetFileOrDirectoryName();
1474 // escape [ and ] so that files get ignored correctly
1475 ignorePattern
.Replace(_T("["), _T("\\["));
1476 ignorePattern
.Replace(_T("]"), _T("\\]"));
1479 for (size_t j
= 0; j
< file
.m_Items
.size(); ++j
)
1481 if (file
.m_Items
[j
] == ignorePattern
)
1489 file
.m_Items
.push_back(ignorePattern
);
1490 ignorePattern
+= file
.m_eol
.IsEmpty() ? _T("\n") : file
.m_eol
;
1491 CStringA ignorePatternA
= CUnicodeUtils::GetUTF8(ignorePattern
);
1492 file
.Write(ignorePatternA
, ignorePatternA
.GetLength());
1495 if (ignoreDlg
.m_IgnoreFile
== 1)
1499 if (ignoreDlg
.m_IgnoreFile
!= 1)
1513 static bool Reset(const CString
& resetTo
, int resetType
)
1520 type
= _T("--soft");
1523 type
= _T("--mixed");
1526 type
= _T("--hard");
1530 type
= _T("--mixed");
1533 cmd
.Format(_T("git.exe reset %s %s --"), (LPCTSTR
)type
, (LPCTSTR
)resetTo
);
1535 CProgressDlg progress
;
1536 progress
.m_GitCmd
= cmd
;
1538 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
1542 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ Reset(resetTo
, resetType
); });
1546 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
1547 if (gitPath
.HasSubmodules() && resetType
== 2)
1549 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, [&]
1552 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
1553 CAppUtils::RunTortoiseGitProc(sCmd
);
1559 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_RESET
))
1561 CGitProgressDlg gitdlg
;
1562 ResetProgressCommand resetProgressCommand
;
1563 gitdlg
.SetCommand(&resetProgressCommand
);
1564 resetProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
1565 resetProgressCommand
.SetRevision(resetTo
);
1566 resetProgressCommand
.SetResetType(resetType
);
1567 ret
= gitdlg
.DoModal();
1570 ret
= progress
.DoModal();
1575 bool CAppUtils::GitReset(const CString
* CommitHash
, int type
)
1578 dlg
.m_ResetType
=type
;
1579 dlg
.m_ResetToVersion
=*CommitHash
;
1580 dlg
.m_initialRefName
= *CommitHash
;
1581 if (dlg
.DoModal() == IDOK
)
1582 return Reset(dlg
.m_ResetToVersion
, dlg
.m_ResetType
);
1587 void CAppUtils::DescribeConflictFile(bool mode
, bool base
,CString
&descript
)
1591 descript
.LoadString(IDS_SVNACTION_DELETE
);
1596 descript
.LoadString(IDS_SVNACTION_MODIFIED
);
1599 descript
.LoadString(IDS_PROC_CREATED
);
1602 void CAppUtils::RemoveTempMergeFile(const CTGitPath
& path
)
1604 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("LOCAL"), path
));
1605 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("REMOTE"), path
));
1606 ::DeleteFile(CAppUtils::GetMergeTempFile(_T("BASE"), path
));
1608 CString
CAppUtils::GetMergeTempFile(const CString
& type
, const CTGitPath
&merge
)
1611 file
= g_Git
.CombinePath(merge
.GetWinPathString() + _T(".") + type
+ merge
.GetFileExtension());
1616 bool ParseHashesFromLsFile(const BYTE_VECTOR
& out
, CString
& hash1
, CString
& hash2
, CString
& hash3
)
1622 while (pos
< out
.size())
1626 CGit::StringAppend(&one
, &out
[pos
], CP_UTF8
);
1628 one
.Tokenize(_T("\t"), tabstart
);
1631 part
= one
.Tokenize(_T(" "), tabstart
); //Tag
1632 part
= one
.Tokenize(_T(" "), tabstart
); //Mode
1633 part
= one
.Tokenize(_T(" "), tabstart
); //Hash
1634 CString hash
= part
;
1635 part
= one
.Tokenize(_T("\t"), tabstart
); //Stage
1636 int stage
= _ttol(part
);
1639 else if (stage
== 2)
1641 else if (stage
== 3)
1647 pos
= out
.findNextString(pos
);
1653 bool CAppUtils::ConflictEdit(const CTGitPath
& path
, bool bAlternativeTool
/*= false*/, bool revertTheirMy
/*= false*/, HWND resolveMsgHwnd
/*= nullptr*/)
1657 CTGitPath merge
=path
;
1658 CTGitPath directory
= merge
.GetDirectory();
1660 // we have the conflicted file (%merged)
1661 // now look for the other required files
1663 //stat.GetStatus(merge);
1664 //if (stat.status == nullptr)
1670 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1672 if (g_Git
.Run(cmd
, &vector
))
1675 if (merge
.IsDirectory())
1677 CString baseHash
, realBaseHash(GIT_REV_ZERO
), localHash(GIT_REV_ZERO
), remoteHash(GIT_REV_ZERO
);
1678 if (merge
.HasAdminDir()) {
1680 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1682 subgit
.GetHash(hash
, _T("HEAD"));
1685 if (ParseHashesFromLsFile(vector
, realBaseHash
, localHash
, remoteHash
)) // in base no submodule, but in remote submodule
1686 baseHash
= realBaseHash
;
1688 CGitDiff::ChangeType changeTypeMine
= CGitDiff::Unknown
;
1689 CGitDiff::ChangeType changeTypeTheirs
= CGitDiff::Unknown
;
1691 bool baseOK
= false, mineOK
= false, theirsOK
= false;
1692 CString baseSubject
, mineSubject
, theirsSubject
;
1693 if (merge
.HasAdminDir())
1696 subgit
.m_CurrentDir
= g_Git
.CombinePath(merge
);
1697 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, localHash
, baseOK
, mineOK
, changeTypeMine
, baseSubject
, mineSubject
);
1698 CGitDiff::GetSubmoduleChangeType(subgit
, baseHash
, remoteHash
, baseOK
, theirsOK
, changeTypeTheirs
, baseSubject
, theirsSubject
);
1700 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)
1702 changeTypeMine
= CGitDiff::Identical
;
1703 changeTypeTheirs
= CGitDiff::NewSubmodule
;
1704 baseSubject
= _T("no submodule");
1705 mineSubject
= baseSubject
;
1706 theirsSubject
= _T("not initialized");
1708 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
1710 baseHash
= localHash
;
1711 baseSubject
= _T("not initialized");
1712 mineSubject
= baseSubject
;
1713 theirsSubject
= _T("not initialized");
1714 changeTypeMine
= CGitDiff::Identical
;
1715 changeTypeTheirs
= CGitDiff::DeleteSubmodule
;
1717 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
1719 baseSubject
= _T("not initialized");
1720 mineSubject
= baseSubject
;
1721 theirsSubject
= baseSubject
;
1722 if (baseHash
== localHash
)
1723 changeTypeMine
= CGitDiff::Identical
;
1728 CSubmoduleResolveConflictDlg resolveSubmoduleConflictDialog
;
1729 resolveSubmoduleConflictDialog
.SetDiff(merge
.GetGitPathString(), revertTheirMy
, baseHash
, baseSubject
, baseOK
, localHash
, mineSubject
, mineOK
, changeTypeMine
, remoteHash
, theirsSubject
, theirsOK
, changeTypeTheirs
);
1730 resolveSubmoduleConflictDialog
.DoModal();
1731 if (resolveSubmoduleConflictDialog
.m_bResolved
&& resolveMsgHwnd
)
1733 static UINT WM_REVERTMSG
= RegisterWindowMessage(_T("GITSLNM_NEEDSREFRESH"));
1734 ::PostMessage(resolveMsgHwnd
, WM_REVERTMSG
, NULL
, NULL
);
1741 if (list
.ParserFromLsFile(vector
))
1743 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1756 mine
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1757 theirs
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1761 mine
.SetFromGit(GetMergeTempFile(_T("LOCAL"), merge
));
1762 theirs
.SetFromGit(GetMergeTempFile(_T("REMOTE"), merge
));
1764 base
.SetFromGit(GetMergeTempFile(_T("BASE"),merge
));
1768 //format=_T("git.exe cat-file blob \":%d:%s\"");
1769 format
= _T("git.exe checkout-index --temp --stage=%d -- \"%s\"");
1771 //create a empty file, incase stage is not three
1772 tempfile
.Open(mine
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1774 tempfile
.Open(theirs
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1776 tempfile
.Open(base
.GetWinPathString(),CFile::modeCreate
|CFile::modeReadWrite
);
1779 bool b_base
=false, b_local
=false, b_remote
=false;
1781 for (int i
= 0; i
< list
.GetCount(); ++i
)
1787 if( list
[i
].m_Stage
== 1)
1789 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1791 outfile
= base
.GetWinPathString();
1794 if( list
[i
].m_Stage
== 2 )
1796 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1798 outfile
= mine
.GetWinPathString();
1801 if( list
[i
].m_Stage
== 3 )
1803 cmd
.Format(format
, list
[i
].m_Stage
, (LPCTSTR
)list
[i
].GetGitPathString());
1805 outfile
= theirs
.GetWinPathString();
1807 CString output
, err
;
1808 if(!outfile
.IsEmpty())
1809 if (!g_Git
.Run(cmd
, &output
, &err
, CP_UTF8
))
1813 file
= output
.Tokenize(_T("\t"), start
);
1814 ::MoveFileEx(file
,outfile
,MOVEFILE_REPLACE_EXISTING
|MOVEFILE_COPY_ALLOWED
);
1817 CMessageBox::Show(nullptr, output
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1820 if(b_local
&& b_remote
)
1822 merge
.SetFromWin(g_Git
.CombinePath(merge
));
1824 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, mine
, theirs
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1826 bRet
= !!CAppUtils::StartExtMerge(bAlternativeTool
, base
, theirs
, mine
, merge
, L
"BASE", L
"REMOTE", L
"LOCAL", CString(), false, resolveMsgHwnd
, true);
1830 ::DeleteFile(mine
.GetWinPathString());
1831 ::DeleteFile(theirs
.GetWinPathString());
1832 ::DeleteFile(base
.GetWinPathString());
1834 CDeleteConflictDlg dlg
;
1835 DescribeConflictFile(b_local
, b_base
,dlg
.m_LocalStatus
);
1836 DescribeConflictFile(b_remote
,b_base
,dlg
.m_RemoteStatus
);
1837 CGitHash localHash
, remoteHash
;
1838 if (!g_Git
.GetHash(localHash
, _T("HEAD")))
1839 dlg
.m_LocalHash
= localHash
.ToString();
1840 if (!g_Git
.GetHash(remoteHash
, _T("MERGE_HEAD")))
1841 dlg
.m_RemoteHash
= remoteHash
.ToString();
1842 else if (!g_Git
.GetHash(remoteHash
, _T("rebase-apply/original-commit")))
1843 dlg
.m_RemoteHash
= remoteHash
.ToString();
1844 else if (!g_Git
.GetHash(remoteHash
, _T("CHERRY_PICK_HEAD")))
1845 dlg
.m_RemoteHash
= remoteHash
.ToString();
1846 else if (!g_Git
.GetHash(remoteHash
, _T("REVERT_HEAD")))
1847 dlg
.m_RemoteHash
= remoteHash
.ToString();
1848 dlg
.m_bShowModifiedButton
=b_base
;
1849 dlg
.m_File
=merge
.GetGitPathString();
1850 if(dlg
.DoModal() == IDOK
)
1854 cmd
.Format(_T("git.exe rm -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1856 cmd
.Format(_T("git.exe add -- \"%s\""), (LPCTSTR
)merge
.GetGitPathString());
1858 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1860 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
1870 CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1871 base
, theirs
, mine
, merge
);
1874 if (stat
.status
->text_status
== svn_wc_status_conflicted
)
1876 // we have a text conflict, use our merge tool to resolve the conflict
1878 CTSVNPath
theirs(directory
);
1879 CTSVNPath
mine(directory
);
1880 CTSVNPath
base(directory
);
1881 bool bConflictData
= false;
1883 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_new
))
1885 theirs
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_new
));
1886 bConflictData
= true;
1888 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_old
))
1890 base
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_old
));
1891 bConflictData
= true;
1893 if ((stat
.status
->entry
)&&(stat
.status
->entry
->conflict_wrk
))
1895 mine
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->conflict_wrk
));
1896 bConflictData
= true;
1901 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1902 base
, theirs
, mine
, merge
);
1905 if (stat
.status
->prop_status
== svn_wc_status_conflicted
)
1907 // we have a property conflict
1908 CTSVNPath
prej(directory
);
1909 if ((stat
.status
->entry
)&&(stat
.status
->entry
->prejfile
))
1911 prej
.AppendPathString(CUnicodeUtils::GetUnicode(stat
.status
->entry
->prejfile
));
1912 // there's a problem: the prej file contains a _description_ of the conflict, and
1913 // that description string might be translated. That means we have no way of parsing
1914 // the file to find out the conflicting values.
1915 // The only thing we can do: show a dialog with the conflict description, then
1916 // let the user either accept the existing property or open the property edit dialog
1917 // to manually change the properties and values. And a button to mark the conflict as
1919 CEditPropConflictDlg dlg
;
1920 dlg
.SetPrejFile(prej
);
1921 dlg
.SetConflictedItem(merge
);
1922 bRet
= (dlg
.DoModal() != IDCANCEL
);
1926 if (stat
.status
->tree_conflict
)
1928 // we have a tree conflict
1930 const SVNInfoData
* pInfoData
= info
.GetFirstFileInfo(merge
, SVNRev(), SVNRev());
1933 if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_text
)
1935 CTSVNPath
theirs(directory
);
1936 CTSVNPath
mine(directory
);
1937 CTSVNPath
base(directory
);
1938 bool bConflictData
= false;
1940 if (pInfoData
->treeconflict_theirfile
)
1942 theirs
.AppendPathString(pInfoData
->treeconflict_theirfile
);
1943 bConflictData
= true;
1945 if (pInfoData
->treeconflict_basefile
)
1947 base
.AppendPathString(pInfoData
->treeconflict_basefile
);
1948 bConflictData
= true;
1950 if (pInfoData
->treeconflict_myfile
)
1952 mine
.AppendPathString(pInfoData
->treeconflict_myfile
);
1953 bConflictData
= true;
1958 bRet
= !!CAppUtils::StartExtMerge(CAppUtils::MergeFlags().AlternativeTool(bAlternativeTool
),
1959 base
, theirs
, mine
, merge
);
1961 else if (pInfoData
->treeconflict_kind
== svn_wc_conflict_kind_tree
)
1963 CString sConflictAction
;
1964 CString sConflictReason
;
1965 CString sResolveTheirs
;
1966 CString sResolveMine
;
1967 CTSVNPath treeConflictPath
= CTSVNPath(pInfoData
->treeconflict_path
);
1968 CString sItemName
= treeConflictPath
.GetUIFileOrDirectoryName();
1970 if (pInfoData
->treeconflict_nodekind
== svn_node_file
)
1972 switch (pInfoData
->treeconflict_operation
)
1974 case svn_wc_operation_update
:
1975 switch (pInfoData
->treeconflict_action
)
1977 case svn_wc_conflict_action_edit
:
1978 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEEDIT
, (LPCTSTR
)sItemName
);
1979 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1981 case svn_wc_conflict_action_add
:
1982 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEADD
, (LPCTSTR
)sItemName
);
1983 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1985 case svn_wc_conflict_action_delete
:
1986 sConflictAction
.Format(IDS_TREECONFLICT_FILEUPDATEDELETE
, (LPCTSTR
)sItemName
);
1987 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
1991 case svn_wc_operation_switch
:
1992 switch (pInfoData
->treeconflict_action
)
1994 case svn_wc_conflict_action_edit
:
1995 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHEDIT
, (LPCTSTR
)sItemName
);
1996 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
1998 case svn_wc_conflict_action_add
:
1999 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHADD
, (LPCTSTR
)sItemName
);
2000 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2002 case svn_wc_conflict_action_delete
:
2003 sConflictAction
.Format(IDS_TREECONFLICT_FILESWITCHDELETE
, (LPCTSTR
)sItemName
);
2004 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2008 case svn_wc_operation_merge
:
2009 switch (pInfoData
->treeconflict_action
)
2011 case svn_wc_conflict_action_edit
:
2012 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEEDIT
, (LPCTSTR
)sItemName
);
2013 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2015 case svn_wc_conflict_action_add
:
2016 sResolveTheirs
.Format(IDS_TREECONFLICT_FILEMERGEADD
, (LPCTSTR
)sItemName
);
2017 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYFILE
);
2019 case svn_wc_conflict_action_delete
:
2020 sConflictAction
.Format(IDS_TREECONFLICT_FILEMERGEDELETE
, (LPCTSTR
)sItemName
);
2021 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2027 else if (pInfoData
->treeconflict_nodekind
== svn_node_dir
)
2029 switch (pInfoData
->treeconflict_operation
)
2031 case svn_wc_operation_update
:
2032 switch (pInfoData
->treeconflict_action
)
2034 case svn_wc_conflict_action_edit
:
2035 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEEDIT
, (LPCTSTR
)sItemName
);
2036 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2038 case svn_wc_conflict_action_add
:
2039 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEADD
, (LPCTSTR
)sItemName
);
2040 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2042 case svn_wc_conflict_action_delete
:
2043 sConflictAction
.Format(IDS_TREECONFLICT_DIRUPDATEDELETE
, (LPCTSTR
)sItemName
);
2044 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2048 case svn_wc_operation_switch
:
2049 switch (pInfoData
->treeconflict_action
)
2051 case svn_wc_conflict_action_edit
:
2052 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHEDIT
, (LPCTSTR
)sItemName
);
2053 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2055 case svn_wc_conflict_action_add
:
2056 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHADD
, (LPCTSTR
)sItemName
);
2057 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2059 case svn_wc_conflict_action_delete
:
2060 sConflictAction
.Format(IDS_TREECONFLICT_DIRSWITCHDELETE
, (LPCTSTR
)sItemName
);
2061 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2065 case svn_wc_operation_merge
:
2066 switch (pInfoData
->treeconflict_action
)
2068 case svn_wc_conflict_action_edit
:
2069 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEEDIT
, (LPCTSTR
)sItemName
);
2070 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2072 case svn_wc_conflict_action_add
:
2073 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEADD
, (LPCTSTR
)sItemName
);
2074 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_KEEPREPOSITORYDIR
);
2076 case svn_wc_conflict_action_delete
:
2077 sConflictAction
.Format(IDS_TREECONFLICT_DIRMERGEDELETE
, (LPCTSTR
)sItemName
);
2078 sResolveTheirs
.LoadString(IDS_TREECONFLICT_RESOLVE_REMOVEDIR
);
2086 switch (pInfoData
->treeconflict_reason
)
2088 case svn_wc_conflict_reason_edited
:
2089 uReasonID
= IDS_TREECONFLICT_REASON_EDITED
;
2090 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2092 case svn_wc_conflict_reason_obstructed
:
2093 uReasonID
= IDS_TREECONFLICT_REASON_OBSTRUCTED
;
2094 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2096 case svn_wc_conflict_reason_deleted
:
2097 uReasonID
= IDS_TREECONFLICT_REASON_DELETED
;
2098 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2100 case svn_wc_conflict_reason_added
:
2101 uReasonID
= IDS_TREECONFLICT_REASON_ADDED
;
2102 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2104 case svn_wc_conflict_reason_missing
:
2105 uReasonID
= IDS_TREECONFLICT_REASON_MISSING
;
2106 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_REMOVEDIR
: IDS_TREECONFLICT_RESOLVE_REMOVEFILE
);
2108 case svn_wc_conflict_reason_unversioned
:
2109 uReasonID
= IDS_TREECONFLICT_REASON_UNVERSIONED
;
2110 sResolveMine
.LoadString(pInfoData
->treeconflict_nodekind
== svn_node_dir
? IDS_TREECONFLICT_RESOLVE_KEEPLOCALDIR
: IDS_TREECONFLICT_RESOLVE_KEEPLOCALFILE
);
2113 sConflictReason
.Format(uReasonID
, (LPCTSTR
)sConflictAction
);
2115 CTreeConflictEditorDlg dlg
;
2116 dlg
.SetConflictInfoText(sConflictReason
);
2117 dlg
.SetResolveTexts(sResolveTheirs
, sResolveMine
);
2118 dlg
.SetPath(treeConflictPath
);
2119 INT_PTR dlgRet
= dlg
.DoModal();
2120 bRet
= (dlgRet
!= IDCANCEL
);
2128 bool CAppUtils::IsSSHPutty()
2130 CString sshclient
=g_Git
.m_Environment
.GetEnv(_T("GIT_SSH"));
2131 sshclient
=sshclient
.MakeLower();
2132 if(sshclient
.Find(_T("plink.exe"),0)>=0)
2137 CString
CAppUtils::GetClipboardLink(const CString
&skipGitPrefix
, int paramsCount
)
2139 if (!OpenClipboard(nullptr))
2142 CString sClipboardText
;
2143 HGLOBAL hglb
= GetClipboardData(CF_TEXT
);
2146 LPCSTR lpstr
= (LPCSTR
)GlobalLock(hglb
);
2147 sClipboardText
= CString(lpstr
);
2150 hglb
= GetClipboardData(CF_UNICODETEXT
);
2153 LPCTSTR lpstr
= (LPCTSTR
)GlobalLock(hglb
);
2154 sClipboardText
= lpstr
;
2159 if(!sClipboardText
.IsEmpty())
2161 if(sClipboardText
[0] == _T('\"') && sClipboardText
[sClipboardText
.GetLength()-1] == _T('\"'))
2162 sClipboardText
=sClipboardText
.Mid(1,sClipboardText
.GetLength()-2);
2164 for (const CString
& prefix
: { L
"http://", L
"https://", L
"git://", L
"ssh://", L
"git@" })
2166 if (CStringUtils::StartsWith(sClipboardText
, prefix
) && sClipboardText
.GetLength() != prefix
.GetLength())
2167 return sClipboardText
;
2170 if(sClipboardText
.GetLength()>=2)
2171 if( sClipboardText
[1] == _T(':') )
2172 if( (sClipboardText
[0] >= 'A' && sClipboardText
[0] <= 'Z')
2173 || (sClipboardText
[0] >= 'a' && sClipboardText
[0] <= 'z') )
2174 return sClipboardText
;
2176 // trim prefixes like "git clone "
2177 if (!skipGitPrefix
.IsEmpty() && CStringUtils::StartsWith(sClipboardText
, skipGitPrefix
))
2179 sClipboardText
= sClipboardText
.Mid(skipGitPrefix
.GetLength()).Trim();
2181 while (paramsCount
>= 0)
2184 spacePos
= sClipboardText
.Find(_T(' '), spacePos
+ 1);
2188 if (spacePos
> 0 && paramsCount
< 0)
2189 sClipboardText
.Truncate(spacePos
);
2190 return sClipboardText
;
2197 CString
CAppUtils::ChooseRepository(const CString
* path
)
2199 CBrowseFolder browseFolder
;
2200 CRegString regLastResopitory
= CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2202 browseFolder
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
2203 CString strCloneDirectory
;
2205 strCloneDirectory
=*path
;
2207 strCloneDirectory
= regLastResopitory
;
2210 title
.LoadString(IDS_CHOOSE_REPOSITORY
);
2212 browseFolder
.SetInfo(title
);
2214 if (browseFolder
.Show(nullptr, strCloneDirectory
) == CBrowseFolder::OK
)
2216 regLastResopitory
= strCloneDirectory
;
2217 return strCloneDirectory
;
2223 bool CAppUtils::SendPatchMail(CTGitPathList
& list
, bool bIsMainWnd
)
2227 dlg
.m_PathList
= list
;
2229 if(dlg
.DoModal()==IDOK
)
2231 if (dlg
.m_PathList
.IsEmpty())
2234 CGitProgressDlg progDlg
;
2236 theApp
.m_pMainWnd
= &progDlg
;
2237 SendMailProgressCommand sendMailProgressCommand
;
2238 progDlg
.SetCommand(&sendMailProgressCommand
);
2240 sendMailProgressCommand
.SetPathList(dlg
.m_PathList
);
2241 progDlg
.SetItemCount(dlg
.m_PathList
.GetCount());
2243 CSendMailPatch
sendMailPatch(dlg
.m_To
, dlg
.m_CC
, dlg
.m_Subject
, !!dlg
.m_bAttachment
, !!dlg
.m_bCombine
);
2244 sendMailProgressCommand
.SetSendMailOption(&sendMailPatch
);
2253 bool CAppUtils::SendPatchMail(const CString
& cmd
, const CString
& formatpatchoutput
, bool bIsMainWnd
)
2256 CString log
=formatpatchoutput
;
2257 int start
=log
.Find(cmd
);
2259 CString one
=log
.Tokenize(_T("\n"),start
);
2265 CString one
=log
.Tokenize(_T("\n"),start
);
2267 if (one
.IsEmpty() || one
.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS
))) == 0)
2269 one
.Replace(_T('/'),_T('\\'));
2271 path
.SetFromWin(one
);
2274 if (!list
.IsEmpty())
2275 return SendPatchMail(list
, bIsMainWnd
);
2278 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES
, IDS_APPNAME
, MB_ICONINFORMATION
);
2284 int CAppUtils::GetLogOutputEncode(CGit
*pGit
)
2287 output
= pGit
->GetConfigValue(_T("i18n.logOutputEncoding"));
2288 if(output
.IsEmpty())
2289 return CUnicodeUtils::GetCPCode(pGit
->GetConfigValue(_T("i18n.commitencoding")));
2291 return CUnicodeUtils::GetCPCode(output
);
2293 int CAppUtils::SaveCommitUnicodeFile(const CString
& filename
, CString
&message
)
2297 CFile
file(filename
, CFile::modeReadWrite
| CFile::modeCreate
);
2298 int cp
= CUnicodeUtils::GetCPCode(g_Git
.GetConfigValue(_T("i18n.commitencoding")));
2300 bool stripComments
= (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE
) == TRUE
);
2301 TCHAR commentChar
= L
'#';
2304 CString commentCharValue
= g_Git
.GetConfigValue(L
"core.commentchar");
2305 if (!commentCharValue
.IsEmpty())
2306 commentChar
= commentCharValue
[0];
2309 bool sanitize
= (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE
) == TRUE
);
2311 message
.Trim(L
" \r\n");
2313 int len
= message
.GetLength();
2315 int emptyLineCnt
= 0;
2316 while (start
>= 0 && start
< len
)
2318 int oldStart
= start
;
2319 start
= message
.Find(L
"\n", oldStart
);
2320 CString line
= message
.Mid(oldStart
);
2323 line
.Truncate(start
- oldStart
);
2324 ++start
; // move forward so we don't find the same char again
2326 if (stripComments
&& (!line
.IsEmpty() && line
.GetAt(0) == commentChar
) || (start
< 0 && line
.IsEmpty()))
2328 line
.TrimRight(L
" \r");
2336 if (emptyLineCnt
) // squash multiple newlines
2337 file
.Write("\n", 1);
2340 CStringA lineA
= CUnicodeUtils::GetMulti(line
+ L
"\n", cp
);
2341 file
.Write((LPCSTR
)lineA
, lineA
.GetLength());
2346 catch (CFileException
*e
)
2353 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
)
2356 CAppUtils::LaunchPAgent(nullptr, &url
);
2359 if (g_Git
.GetHash(hashOld
, L
"HEAD"))
2361 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash."), L
"TortoiseGit", MB_ICONERROR
);
2366 if (CRegDWORD(L
"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE
) == FALSE
)
2367 args
+= L
" --no-rebase";
2369 if (bFetchTags
== BST_UNCHECKED
)
2370 args
+= L
" --no-tags";
2371 else if (bFetchTags
== BST_CHECKED
)
2375 args
+= L
" --no-ff";
2378 args
+= L
" --ff-only";
2381 args
+= L
" --squash";
2384 args
+= L
" --no-commit";
2387 args
.AppendFormat(L
" --depth %d", *nDepth
);
2389 if (bPrune
== BST_CHECKED
)
2390 args
+= L
" --prune";
2391 else if (bPrune
== BST_UNCHECKED
)
2392 args
+= L
" --no-prune";
2395 args
+= L
" --allow-unrelated-histories";
2398 cmd
.Format(L
"git.exe pull --progress -v%s \"%s\" %s", (LPCTSTR
)args
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranchName
);
2399 CProgressDlg progress
;
2400 progress
.m_GitCmd
= cmd
;
2402 CGitHash hashNew
; // declare outside lambda, because it is captured by reference
2403 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2407 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
2409 STRING_VECTOR remotes
;
2410 g_Git
.GetRemoteList(remotes
);
2411 if (std::find(remotes
.begin(), remotes
.end(), url
) != remotes
.end())
2413 CString currentBranch
;
2414 if (g_Git
.GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentBranch
))
2415 currentBranch
.Empty();
2416 CString remoteRef
= L
"remotes/" + url
+ L
"/" + remoteBranchName
;
2417 if (!currentBranch
.IsEmpty() && remoteBranchName
.IsEmpty())
2419 CString pullRemote
, pullBranch
;
2420 g_Git
.GetRemoteTrackedBranch(currentBranch
, pullRemote
, pullBranch
);
2421 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2422 remoteRef
= L
"remotes/" + pullRemote
+ L
"/" + pullBranch
;
2425 g_Git
.IsFastForward(L
"HEAD", remoteRef
, &common
);
2426 if (common
.IsEmpty())
2427 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoPull(url
, bAutoLoad
, bFetchTags
, bNoFF
, bFFonly
, bSquash
, bNoCommit
, nDepth
, bPrune
, remoteBranchName
, showPush
, showStashPop
, true); });
2431 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(); });
2432 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ CAppUtils::StashSave(L
"", true); });
2437 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
2439 if (g_Git
.GetHash(hashNew
, L
"HEAD"))
2440 MessageBox(nullptr, g_Git
.GetGitLastErr(L
"Could not get HEAD hash after pulling."), L
"TortoiseGit", MB_ICONERROR
);
2443 postCmdList
.emplace_back(IDI_DIFF
, IDS_PROC_PULL_DIFFS
, [&]
2446 dlg
.SetDiff(nullptr, hashOld
.ToString(), hashNew
.ToString());
2449 postCmdList
.emplace_back(IDI_LOG
, IDS_PROC_PULL_LOG
, [&]
2452 dlg
.SetParams(CTGitPath(L
""), CTGitPath(L
""), L
"", hashOld
.ToString() + L
".." + hashNew
.ToString(), 0);
2458 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
2460 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
2461 if (gitPath
.HasSubmodules())
2463 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
2466 sCmd
.Format(L
"/command:subupdate /bkpath:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
2467 CAppUtils::RunTortoiseGitProc(sCmd
);
2472 INT_PTR ret
= progress
.DoModal();
2474 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
)
2476 CChangedDlg changeddlg
;
2477 changeddlg
.m_pathList
.AddPath(CTGitPath());
2478 changeddlg
.DoModal();
2486 bool CAppUtils::Pull(bool showPush
, bool showStashPop
)
2488 if (IsTGitRebaseActive())
2492 dlg
.m_IsPull
= TRUE
;
2493 if (dlg
.DoModal() == IDOK
)
2495 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2497 return DoFetch(dlg
.m_RemoteURL
,
2498 FALSE
, // Fetch all remotes
2499 dlg
.m_bAutoLoad
== BST_CHECKED
,
2501 dlg
.m_bDepth
== BST_CHECKED
,
2504 dlg
.m_RemoteBranchName
,
2505 dlg
.m_bRebaseActivatedInConfigForPull
? 2 : 1, // Rebase after fetching
2506 dlg
.m_bRebasePreserveMerges
== TRUE
); // Preserve merges on rebase
2508 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);
2514 bool CAppUtils::RebaseAfterFetch(const CString
& upstream
, int rebase
, bool preserveMerges
)
2519 if (!upstream
.IsEmpty())
2520 dlg
.m_Upstream
= upstream
;
2521 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENULOG
)));
2522 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH
)));
2523 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL
)));
2524 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE
)));
2525 dlg
.m_bRebaseAutoStart
= (rebase
== 2);
2526 dlg
.m_bPreserveMerges
= preserveMerges
;
2527 INT_PTR response
= dlg
.DoModal();
2528 if (response
== IDOK
)
2530 else if (response
== IDC_REBASE_POST_BUTTON
)
2532 CString cmd
= _T("/command:log");
2533 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2534 CAppUtils::RunTortoiseGitProc(cmd
);
2537 else if (response
== IDC_REBASE_POST_BUTTON
+ 1)
2539 else if (response
== IDC_REBASE_POST_BUTTON
+ 2)
2541 CString cmd
, out
, err
;
2542 cmd
.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2543 (LPCTSTR
)g_Git
.m_CurrentDir
,
2544 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Upstream
),
2545 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Branch
));
2546 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
2548 CMessageBox::Show(nullptr, out
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2551 CAppUtils::SendPatchMail(cmd
, out
);
2554 else if (response
== IDC_REBASE_POST_BUTTON
+ 3)
2556 else if (response
== IDCANCEL
)
2562 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
)
2566 if (fetchAllRemotes
)
2569 g_Git
.GetRemoteList(list
);
2571 for (const auto& remote
: list
)
2572 CAppUtils::LaunchPAgent(nullptr, &remote
);
2575 CAppUtils::LaunchPAgent(nullptr, &url
);
2578 CString upstream
= _T("FETCH_HEAD");
2579 CGitHash oldUpstreamHash
;
2583 g_Git
.GetRemoteList(list
);
2584 for (auto it
= list
.cbegin(); it
!= list
.cend(); ++it
)
2588 CString remote
, trackedBranch
;
2589 g_Git
.GetRemoteTrackedBranchForHEAD(remote
, trackedBranch
);
2590 if (!remote
.IsEmpty() && !trackedBranch
.IsEmpty())
2592 upstream
= L
"remotes/" + remote
+ L
"/" + trackedBranch
;
2593 g_Git
.GetHash(oldUpstreamHash
, upstream
);
2601 arg
= _T(" --progress");
2604 arg
.AppendFormat(_T(" --depth %d"), nDepth
);
2607 arg
+= _T(" --prune");
2608 else if (prune
== FALSE
)
2609 arg
+= _T(" --no-prune");
2612 arg
+= _T(" --tags");
2613 else if (fetchTags
== 0)
2614 arg
+= _T(" --no-tags");
2616 if (fetchAllRemotes
)
2617 cmd
.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR
)arg
);
2619 cmd
.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR
)arg
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranch
);
2621 CProgressDlg progress
;
2622 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2626 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ DoFetch(url
, fetchAllRemotes
, loadPuttyAgent
, prune
, bDepth
, nDepth
, fetchTags
, remoteBranch
, runRebase
, rebasePreserveMerges
); });
2630 postCmdList
.emplace_back(IDI_LOG
, IDS_MENULOG
, []
2632 CString cmd
= _T("/command:log");
2633 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2634 CAppUtils::RunTortoiseGitProc(cmd
);
2637 postCmdList
.emplace_back(IDI_REVERT
, IDS_PROC_RESET
, []
2639 CString pullRemote
, pullBranch
;
2640 g_Git
.GetRemoteTrackedBranchForHEAD(pullRemote
, pullBranch
);
2641 CString defaultUpstream
;
2642 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2643 defaultUpstream
.Format(_T("remotes/%s/%s"), (LPCTSTR
)pullRemote
, (LPCTSTR
)pullBranch
);
2644 CAppUtils::GitReset(&defaultUpstream
, 2);
2647 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, []{ CAppUtils::Fetch(); });
2649 if (!runRebase
&& !GitAdminDir::IsBareRepo(g_Git
.m_CurrentDir
))
2650 postCmdList
.emplace_back(IDI_REBASE
, IDS_MENUREBASE
, [&]{ runRebase
= false; CAppUtils::RebaseAfterFetch(); });
2653 progress
.m_GitCmd
= cmd
;
2655 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_FETCH
))
2657 CGitProgressDlg gitdlg
;
2658 FetchProgressCommand fetchProgressCommand
;
2659 if (!fetchAllRemotes
)
2660 fetchProgressCommand
.SetUrl(url
);
2661 gitdlg
.SetCommand(&fetchProgressCommand
);
2662 fetchProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
2663 fetchProgressCommand
.SetAutoTag(fetchTags
== 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL
: fetchTags
== 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO
: GIT_REMOTE_DOWNLOAD_TAGS_NONE
);
2664 if (!fetchAllRemotes
)
2665 fetchProgressCommand
.SetRefSpec(remoteBranch
);
2666 return gitdlg
.DoModal() == IDOK
;
2669 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
&)
2671 if (exitCode
|| !runRebase
)
2674 CGitHash remoteBranchHash
;
2675 g_Git
.GetHash(remoteBranchHash
, upstream
);
2676 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
)
2679 if (runRebase
== 1 && g_Git
.IsFastForward(L
"HEAD", upstream
))
2681 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
);
2686 CProgressDlg mergeProgress
;
2687 mergeProgress
.m_GitCmd
= L
"git.exe merge --ff-only " + upstream
;
2688 mergeProgress
.m_AutoClose
= AUTOCLOSE_IF_NO_ERRORS
;
2689 mergeProgress
.m_PostCmdCallback
= [](DWORD status
, PostCmdList
& postCmdList
)
2691 if (status
&& g_Git
.HasWorkingTreeConflicts())
2693 // there are conflict files
2694 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
2697 sCmd
.Format(L
"/command:commit /path:\"%s\"", g_Git
.m_CurrentDir
);
2698 CAppUtils::RunTortoiseGitProc(sCmd
);
2702 mergeProgress
.DoModal();
2707 CAppUtils::RebaseAfterFetch(upstream
, runRebase
, rebasePreserveMerges
);
2710 return progress
.DoModal() == IDOK
;
2713 bool CAppUtils::Fetch(const CString
& remoteName
, bool allRemotes
)
2716 dlg
.m_PreSelectRemote
= remoteName
;
2718 dlg
.m_bAllRemotes
= allRemotes
;
2720 if(dlg
.DoModal()==IDOK
)
2721 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
);
2726 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
)
2729 DWORD exitcode
= 0xFFFFFFFF;
2730 if (CHooks::Instance().PrePush(g_Git
.m_CurrentDir
, exitcode
, error
))
2735 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2736 CMessageBox::Show(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2741 int iRecurseSubmodules
= 0;
2742 if (GetMsysgitVersion() >= 0x02070000)
2744 CString sRecurseSubmodules
= g_Git
.GetConfigValue(_T("push.recurseSubmodules"));
2745 if (sRecurseSubmodules
== _T("check"))
2746 iRecurseSubmodules
= 1;
2747 else if (sRecurseSubmodules
== _T("on-demand"))
2748 iRecurseSubmodules
= 2;
2753 arg
+= _T("--thin ");
2754 if (tags
&& !allBranches
)
2755 arg
+= _T("--tags ");
2757 arg
+= _T("--force ");
2759 arg
+= _T("--force-with-lease ");
2761 arg
+= _T("--set-upstream ");
2762 if (recurseSubmodules
== 0 && recurseSubmodules
!= iRecurseSubmodules
)
2763 arg
+= _T("--recurse-submodules=no ");
2764 if (recurseSubmodules
== 1 && recurseSubmodules
!= iRecurseSubmodules
)
2765 arg
+= _T("--recurse-submodules=check ");
2766 if (recurseSubmodules
== 2 && recurseSubmodules
!= iRecurseSubmodules
)
2767 arg
+= _T("--recurse-submodules=on-demand ");
2769 arg
+= _T("--progress ");
2771 CProgressDlg progress
;
2773 STRING_VECTOR remotesList
;
2775 g_Git
.GetRemoteList(remotesList
);
2777 remotesList
.push_back(remote
);
2779 for (unsigned int i
= 0; i
< remotesList
.size(); ++i
)
2782 CAppUtils::LaunchPAgent(nullptr, &remotesList
[i
]);
2787 cmd
.Format(_T("git.exe push --all %s\"%s\""),
2789 (LPCTSTR
)remotesList
[i
]);
2793 progress
.m_GitCmdList
.push_back(cmd
);
2794 cmd
.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR
)arg
, (LPCTSTR
)remotesList
[i
]);
2799 cmd
.Format(_T("git.exe push %s\"%s\" %s"),
2801 (LPCTSTR
)remotesList
[i
],
2802 (LPCTSTR
)localBranch
);
2803 if (!remoteBranch
.IsEmpty())
2806 cmd
+= remoteBranch
;
2809 progress
.m_GitCmdList
.push_back(cmd
);
2811 if (!allBranches
&& !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE
))
2813 cmd
.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR
)localBranch
);
2814 progress
.m_GitCmdList
.push_back(cmd
);
2818 CString superprojectRoot
;
2819 GitAdminDir::HasAdminDir(g_Git
.m_CurrentDir
, false, &superprojectRoot
);
2820 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2822 // need to execute hooks as those might be needed by post action commands
2823 DWORD exitcode
= 0xFFFFFFFF;
2825 if (CHooks::Instance().PostPush(g_Git
.m_CurrentDir
, exitcode
, error
))
2830 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2831 MessageBox(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2837 bool rejected
= progress
.GetLogText().Find(_T("! [rejected]")) > 0;
2840 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, []{ Pull(true); });
2841 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, [&]{ Fetch(allRemotes
? _T("") : remote
, allRemotes
); });
2843 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2847 postCmdList
.emplace_back(IDS_PROC_REQUESTPULL
, [&]{ RequestPull(remoteBranch
); });
2848 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2849 postCmdList
.emplace_back(IDI_SWITCH
, IDS_MENUSWITCH
, [&]{ Switch(); });
2850 if (!superprojectRoot
.IsEmpty())
2852 postCmdList
.emplace_back(IDI_COMMIT
, IDS_PROC_COMMIT_SUPERPROJECT
, [&]
2855 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)superprojectRoot
);
2856 RunTortoiseGitProc(sCmd
);
2861 INT_PTR ret
= progress
.DoModal();
2865 bool CAppUtils::Push(const CString
& selectLocalBranch
)
2868 dlg
.m_BranchSourceName
= selectLocalBranch
;
2870 if (dlg
.DoModal() == IDOK
)
2871 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
);
2876 bool CAppUtils::RequestPull(const CString
& endrevision
, const CString
& repositoryUrl
, bool bIsMainWnd
)
2878 CRequestPullDlg dlg
;
2879 dlg
.m_RepositoryURL
= repositoryUrl
;
2880 dlg
.m_EndRevision
= endrevision
;
2881 if (dlg
.DoModal()==IDOK
)
2884 cmd
.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR
)dlg
.m_StartRevision
, (LPCTSTR
)dlg
.m_RepositoryURL
, (LPCTSTR
)dlg
.m_EndRevision
);
2886 CSysProgressDlg sysProgressDlg
;
2887 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
2888 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST
)));
2889 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
2890 sysProgressDlg
.SetShowProgressBar(false);
2891 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
2893 CString tempFileName
= GetTempFile();
2895 DeleteFile(tempFileName
);
2896 CreateDirectory(tempFileName
, nullptr);
2897 tempFileName
+= _T("\\pullrequest.txt");
2898 if (g_Git
.RunLogFile(cmd
, tempFileName
, &err
))
2901 msg
.LoadString(IDS_ERR_PULLREUQESTFAILED
);
2902 MessageBox(nullptr, msg
+ _T("\n") + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2906 if (sysProgressDlg
.HasUserCancelled())
2908 CMessageBox::Show(nullptr, IDS_USERCANCELLED
, IDS_APPNAME
, MB_OK
);
2909 ::DeleteFile(tempFileName
);
2913 sysProgressDlg
.Stop();
2915 if (dlg
.m_bSendMail
)
2917 CSendMailDlg sendmaildlg
;
2918 sendmaildlg
.m_PathList
= CTGitPathList(CTGitPath(tempFileName
));
2919 sendmaildlg
.m_bCustomSubject
= true;
2921 if (sendmaildlg
.DoModal() == IDOK
)
2923 if (sendmaildlg
.m_PathList
.IsEmpty())
2926 CGitProgressDlg progDlg
;
2928 theApp
.m_pMainWnd
= &progDlg
;
2929 SendMailProgressCommand sendMailProgressCommand
;
2930 progDlg
.SetCommand(&sendMailProgressCommand
);
2932 sendMailProgressCommand
.SetPathList(sendmaildlg
.m_PathList
);
2933 progDlg
.SetItemCount(sendmaildlg
.m_PathList
.GetCount());
2935 CSendMailCombineable
sendMailCombineable(sendmaildlg
.m_To
, sendmaildlg
.m_CC
, sendmaildlg
.m_Subject
, !!sendmaildlg
.m_bAttachment
, !!sendmaildlg
.m_bCombine
);
2936 sendMailProgressCommand
.SetSendMailOption(&sendMailCombineable
);
2945 CAppUtils::LaunchAlternativeEditor(tempFileName
);
2950 void CAppUtils::RemoveTrailSlash(CString
&path
)
2955 // For URL, do not trim the slash just after the host name component.
2956 int index
= path
.Find(_T("://"));
2960 index
= path
.Find(_T('/'), index
);
2961 if (index
== path
.GetLength() - 1)
2965 while(path
[path
.GetLength()-1] == _T('\\') || path
[path
.GetLength()-1] == _T('/' ) )
2967 path
.Truncate(path
.GetLength() - 1);
2973 bool CAppUtils::CheckUserData()
2975 while(g_Git
.GetUserName().IsEmpty() || g_Git
.GetUserEmail().IsEmpty())
2977 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA
, IDS_APPNAME
, MB_YESNO
| MB_ICONERROR
) == IDYES
)
2979 CTGitPath
path(g_Git
.m_CurrentDir
);
2980 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
,&path
);
2981 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
2982 dlg
.SetTreeWidth(220);
2983 dlg
.m_DefaultPage
= _T("gitconfig");
2986 dlg
.HandleRestart();
2996 BOOL
CAppUtils::Commit(const CString
& bugid
, BOOL bWholeProject
, CString
&sLogMsg
,
2997 CTGitPathList
&pathList
,
2998 CTGitPathList
&selectedList
,
2999 bool bSelectFilesForCommit
)
3001 bool bFailed
= true;
3003 if (!CheckUserData())
3010 dlg
.m_sBugID
= bugid
;
3012 dlg
.m_bWholeProject
= bWholeProject
;
3014 dlg
.m_sLogMessage
= sLogMsg
;
3015 dlg
.m_pathList
= pathList
;
3016 dlg
.m_checkedPathList
= selectedList
;
3017 dlg
.m_bSelectFilesForCommit
= bSelectFilesForCommit
;
3018 if (dlg
.DoModal() == IDOK
)
3020 if (dlg
.m_pathList
.IsEmpty())
3022 // if the user hasn't changed the list of selected items
3023 // we don't use that list. Because if we would use the list
3024 // of pre-checked items, the dialog would show different
3025 // checked items on the next startup: it would only try
3026 // to check the parent folder (which might not even show)
3027 // instead, we simply use an empty list and let the
3028 // default checking do its job.
3029 if (!dlg
.m_pathList
.IsEqual(pathList
))
3030 selectedList
= dlg
.m_pathList
;
3031 pathList
= dlg
.m_updatedPathList
;
3032 sLogMsg
= dlg
.m_sLogMessage
;
3033 bSelectFilesForCommit
= true;
3035 switch (dlg
.m_PostCmd
)
3037 case GIT_POSTCOMMIT_CMD_DCOMMIT
:
3038 CAppUtils::SVNDCommit();
3040 case GIT_POSTCOMMIT_CMD_PUSH
:
3043 case GIT_POSTCOMMIT_CMD_CREATETAG
:
3044 CAppUtils::CreateBranchTag(TRUE
);
3046 case GIT_POSTCOMMIT_CMD_PULL
:
3047 CAppUtils::Pull(true);
3053 // CGitProgressDlg progDlg;
3054 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3055 // if (parser.HasVal(_T("closeonend")))
3056 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3057 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3058 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3059 // progDlg.SetPathList(dlg.m_pathList);
3060 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3061 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3062 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3063 // progDlg.SetItemCount(dlg.m_itemsCount);
3064 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3065 // progDlg.DoModal();
3066 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3067 // err = (DWORD)progDlg.DidErrorsOccur();
3068 // bFailed = progDlg.DidErrorsOccur();
3069 // bRet = progDlg.DidErrorsOccur();
3070 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3071 // if (DWORD(bFailRepeat)==0)
3072 // bFailed = false; // do not repeat if the user chose not to in the settings.
3078 BOOL
CAppUtils::SVNDCommit()
3080 CSVNDCommitDlg dcommitdlg
;
3081 CString gitSetting
= g_Git
.GetConfigValue(_T("svn.rmdir"));
3082 if (gitSetting
.IsEmpty()) {
3083 if (dcommitdlg
.DoModal() != IDOK
)
3087 if (dcommitdlg
.m_remember
)
3089 if (dcommitdlg
.m_rmdir
)
3090 gitSetting
= _T("true");
3092 gitSetting
= _T("false");
3093 if(g_Git
.SetConfigValue(_T("svn.rmdir"),gitSetting
))
3096 msg
.Format(IDS_PROC_SAVECONFIGFAILED
, _T("svn.rmdir"), gitSetting
);
3097 CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3103 BOOL IsStash
= false;
3104 if(!g_Git
.CheckCleanWorkTree())
3106 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3108 CSysProgressDlg sysProgressDlg
;
3109 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3110 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3111 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3112 sysProgressDlg
.SetShowProgressBar(false);
3113 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3114 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3117 cmd
=_T("git.exe stash");
3118 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3120 sysProgressDlg
.Stop();
3121 MessageBox(nullptr, out
,_T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3124 sysProgressDlg
.Stop();
3132 CProgressDlg progress
;
3133 if (dcommitdlg
.m_rmdir
)
3134 progress
.m_GitCmd
=_T("git.exe svn dcommit --rmdir");
3136 progress
.m_GitCmd
=_T("git.exe svn dcommit");
3137 if(progress
.DoModal()==IDOK
&& progress
.m_GitStatus
== 0)
3141 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
3143 CSysProgressDlg sysProgressDlg
;
3144 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3145 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3146 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3147 sysProgressDlg
.SetShowProgressBar(false);
3148 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3149 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3152 cmd
=_T("git.exe stash pop");
3153 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3155 sysProgressDlg
.Stop();
3156 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3159 sysProgressDlg
.Stop();
3169 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
)
3173 args
+= L
" --no-ff";
3175 args
+= L
" --ff-only";
3178 args
+= L
" --squash";
3181 args
+= L
" --no-commit";
3184 args
+= L
" --allow-unrelated-histories";
3187 args
.AppendFormat(L
" --log=%d", *log
);
3189 if (!mergeStrategy
.IsEmpty())
3191 args
+= L
" --strategy=" + mergeStrategy
;
3192 if (!strategyOption
.IsEmpty())
3194 args
+= L
" --strategy-option=" + strategyOption
;
3195 if (!strategyParam
.IsEmpty())
3196 args
+= L
'=' + strategyParam
;
3200 if (!logMessage
.IsEmpty())
3202 CString logmsg
= logMessage
;
3203 logmsg
.Replace(L
"\\\"", L
"\\\\\"");
3204 logmsg
.Replace(L
"\"", L
"\\\"");
3205 args
+= L
" -m \"" + logmsg
+ L
"\"";
3208 CString mergeVersion
= g_Git
.FixBranchName(version
);
3210 cmd
.Format(L
"git.exe merge%s %s", (LPCTSTR
)args
, (LPCTSTR
)mergeVersion
);
3212 CProgressDlg Prodlg
;
3213 Prodlg
.m_GitCmd
= cmd
;
3215 Prodlg
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3219 int hasConflicts
= g_Git
.HasWorkingTreeConflicts();
3220 if (hasConflicts
< 0)
3221 CMessageBox::Show(nullptr, g_Git
.GetGitLastErr(L
"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS
), L
"TortoiseGit", MB_ICONEXCLAMATION
);
3222 else if (hasConflicts
)
3224 // there are conflict files
3226 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
3229 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3230 CAppUtils::RunTortoiseGitProc(sCmd
);
3234 if (CAppUtils::GetMsysgitVersion() >= 0x02090000)
3237 g_Git
.IsFastForward(L
"HEAD", mergeVersion
, &common
);
3238 if (common
.IsEmpty())
3239 postCmdList
.emplace_back(IDI_MERGE
, IDS_MERGE_UNRELATED
, [=] { DoMerge(noFF
, ffOnly
, squash
, noCommit
, log
, true, mergeStrategy
, strategyOption
, strategyParam
, logMessage
, version
, isBranch
, showStashPop
); });
3242 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [=]{ CAppUtils::StashSave(L
"", false, false, true, mergeVersion
); });
3248 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ CAppUtils::StashPop(); });
3252 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []
3255 sCmd
.Format(L
"/command:commit /path:\"%s\"", (LPCTSTR
)g_Git
.m_CurrentDir
);
3256 CAppUtils::RunTortoiseGitProc(sCmd
);
3261 if (isBranch
&& !CStringUtils::StartsWith(version
, L
"remotes/")) // do not ask to remove remote branches
3263 postCmdList
.emplace_back(IDI_DELETE
, IDS_PROC_REMOVEBRANCH
, [&]
3266 msg
.Format(IDS_PROC_DELETEBRANCHTAG
, version
);
3267 if (CMessageBox::Show(nullptr, msg
, L
"TortoiseGit", 2, IDI_QUESTION
, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON
)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON
))) == 1)
3270 cmd
.Format(L
"git.exe branch -D -- %s", (LPCTSTR
)version
);
3271 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3272 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
);
3277 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ CAppUtils::Push(); });
3279 BOOL hasGitSVN
= CTGitPath(g_Git
.m_CurrentDir
).GetAdminDirMask() & ITEMIS_GITSVN
;
3281 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSVNDCOMMIT
, []{ CAppUtils::SVNDCommit(); });
3285 return !Prodlg
.m_GitStatus
;
3288 BOOL
CAppUtils::Merge(const CString
* commit
, bool showStashPop
)
3290 if (!CheckUserData())
3293 if (IsTGitRebaseActive())
3298 dlg
.m_initialRefName
= *commit
;
3300 if (dlg
.DoModal() == IDOK
)
3301 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
);
3306 BOOL
CAppUtils::MergeAbort()
3309 if (dlg
.DoModal() == IDOK
)
3310 return Reset(_T("HEAD"), dlg
.m_ResetType
+ 1);
3315 void CAppUtils::EditNote(GitRevLoglist
* rev
)
3317 if (!CheckUserData())
3321 dlg
.m_sHintText
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3322 dlg
.m_sInputText
= rev
->m_Notes
;
3323 dlg
.m_sTitle
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3324 //dlg.m_pProjectProperties = &m_ProjectProperties;
3325 dlg
.m_bUseLogWidth
= true;
3326 if(dlg
.DoModal() == IDOK
)
3329 cmd
=_T("notes add -f -F \"");
3331 CString tempfile
=::GetTempFile();
3332 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_sInputText
))
3334 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3339 cmd
+= rev
->m_CommitHash
.ToString();
3343 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd
, CP_UTF8
).GetBuffer()))
3344 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3346 rev
->m_Notes
= dlg
.m_sInputText
;
3349 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3351 ::DeleteFile(tempfile
);
3356 int CAppUtils::GetMsysgitVersion()
3358 if (g_Git
.ms_LastMsysGitVersion
)
3359 return g_Git
.ms_LastMsysGitVersion
;
3362 CString versiondebug
;
3365 CRegDWORD regTime
= CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3366 CRegDWORD regVersion
= CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3368 CString gitpath
= CGit::ms_LastMsysGitDir
+_T("\\git.exe");
3371 if (!CGit::GetFileModifyTime(gitpath
, &time
))
3373 if((DWORD
)time
== regTime
)
3375 g_Git
.ms_LastMsysGitVersion
= regVersion
;
3381 int ver
= g_Git
.GetGitVersion(&versiondebug
, &err
);
3384 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
);
3391 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug
+ _T("\""), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3396 regTime
= time
&0xFFFFFFFF;
3398 g_Git
.ms_LastMsysGitVersion
= ver
;
3403 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd
)
3405 typedef HRESULT (WINAPI
*SHGPSFW
) (HWND hwnd
,REFIID riid
,void** ppv
);
3407 CAutoLibrary hShell
= AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3409 if (hShell
.IsValid()) {
3410 SHGPSFW pfnSHGPSFW
= (SHGPSFW
)::GetProcAddress(hShell
, "SHGetPropertyStoreForWindow");
3412 IPropertyStore
*pps
;
3413 HRESULT hr
= pfnSHGPSFW(hWnd
, IID_PPV_ARGS(&pps
));
3414 if (SUCCEEDED(hr
)) {
3417 var
.boolVal
= VARIANT_TRUE
;
3418 pps
->SetValue(PKEY_AppUserModel_PreventPinning
, var
);
3425 void CAppUtils::SetWindowTitle(HWND hWnd
, const CString
& urlorpath
, const CString
& dialogname
)
3427 ASSERT(dialogname
.GetLength() < 70);
3428 ASSERT(urlorpath
.GetLength() < MAX_PATH
);
3429 WCHAR pathbuf
[MAX_PATH
] = {0};
3431 PathCompactPathEx(pathbuf
, urlorpath
, 70 - dialogname
.GetLength(), 0);
3433 wcscat_s(pathbuf
, L
" - ");
3434 wcscat_s(pathbuf
, dialogname
);
3435 wcscat_s(pathbuf
, L
" - ");
3436 wcscat_s(pathbuf
, CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3437 SetWindowText(hWnd
, pathbuf
);
3440 bool CAppUtils::BisectStart(const CString
& lastGood
, const CString
& firstBad
, bool bIsMainWnd
)
3442 if (!g_Git
.CheckCleanWorkTree())
3444 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3446 CSysProgressDlg sysProgressDlg
;
3447 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3448 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3449 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3450 sysProgressDlg
.SetShowProgressBar(false);
3451 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3452 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3455 cmd
= _T("git.exe stash");
3456 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3458 sysProgressDlg
.Stop();
3459 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3462 sysProgressDlg
.Stop();
3468 CBisectStartDlg bisectStartDlg
;
3470 if (!lastGood
.IsEmpty())
3471 bisectStartDlg
.m_sLastGood
= lastGood
;
3472 if (!firstBad
.IsEmpty())
3473 bisectStartDlg
.m_sFirstBad
= firstBad
;
3475 if (bisectStartDlg
.DoModal() == IDOK
)
3477 CProgressDlg progress
;
3479 theApp
.m_pMainWnd
= &progress
;
3480 progress
.m_GitCmdList
.push_back(_T("git.exe bisect start"));
3481 progress
.m_GitCmdList
.push_back(_T("git.exe bisect good ") + bisectStartDlg
.m_LastGoodRevision
);
3482 progress
.m_GitCmdList
.push_back(_T("git.exe bisect bad ") + bisectStartDlg
.m_FirstBadRevision
);
3484 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3489 CTGitPath
path(g_Git
.m_CurrentDir
);
3490 if (path
.HasSubmodules())
3492 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3495 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3496 CAppUtils::RunTortoiseGitProc(sCmd
);
3501 INT_PTR ret
= progress
.DoModal();
3508 bool CAppUtils::BisectOperation(const CString
& op
, const CString
& ref
, bool bIsMainWnd
)
3510 CString cmd
= _T("git.exe bisect ") + op
;
3518 CProgressDlg progress
;
3520 theApp
.m_pMainWnd
= &progress
;
3521 progress
.m_GitCmd
= cmd
;
3523 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3528 CTGitPath path
= g_Git
.m_CurrentDir
;
3529 if (path
.HasSubmodules())
3531 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3534 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3535 CAppUtils::RunTortoiseGitProc(sCmd
);
3539 if (op
!= _T("reset"))
3540 postCmdList
.emplace_back(IDS_MENUBISECTRESET
, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3543 INT_PTR ret
= progress
.DoModal();
3547 int CAppUtils::Git2GetUserPassword(git_cred
**out
, const char *url
, const char *username_from_url
, unsigned int /*allowed_types*/, void * /*payload*/)
3550 dlg
.m_URL
= CUnicodeUtils::GetUnicode(url
, CP_UTF8
);
3551 if (username_from_url
)
3552 dlg
.m_UserName
= CUnicodeUtils::GetUnicode(username_from_url
, CP_UTF8
);
3554 CStringA username
, password
;
3555 if (dlg
.DoModal() == IDOK
)
3557 username
= CUnicodeUtils::GetMulti(dlg
.m_UserName
, CP_UTF8
);
3558 password
= CUnicodeUtils::GetMulti(dlg
.m_Password
, CP_UTF8
);
3559 return git_cred_userpass_plaintext_new(out
, username
, password
);
3561 giterr_set_str(GITERR_NONE
, "User cancelled.");
3565 int CAppUtils::Git2CertificateCheck(git_cert
* base_cert
, int /*valid*/, const char* host
, void* /*payload*/)
3567 if (base_cert
->cert_type
== GIT_CERT_X509
)
3569 git_cert_x509
* cert
= (git_cert_x509
*)base_cert
;
3571 if (last_accepted_cert
.cmp(cert
))
3574 PCCERT_CONTEXT pServerCert
= CertCreateCertificateContext(X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, (BYTE
*)cert
->data
, (DWORD
)cert
->len
);
3575 SCOPE_EXIT
{ CertFreeCertificateContext(pServerCert
); };
3577 DWORD verificationError
= VerifyServerCertificate(pServerCert
, CUnicodeUtils::GetUnicode(host
).GetBuffer(), 0);
3578 if (!verificationError
)
3580 last_accepted_cert
.set(cert
);
3584 CString servernameInCert
;
3585 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, 0, nullptr, CStrBuf(servernameInCert
, 128), 128);
3588 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, CERT_NAME_ISSUER_FLAG
, nullptr, CStrBuf(issuer
, 128), 128);
3590 CCheckCertificateDlg dlg
;
3592 dlg
.m_sCertificateCN
= servernameInCert
;
3593 dlg
.m_sCertificateIssuer
= issuer
;
3594 dlg
.m_sHostname
= CUnicodeUtils::GetUnicode(host
);
3595 dlg
.m_sError
= CFormatMessageWrapper(verificationError
);
3596 if (dlg
.DoModal() == IDOK
)
3598 last_accepted_cert
.set(cert
);
3602 return GIT_ECERTIFICATE
;
3605 int CAppUtils::ExploreTo(HWND hwnd
, CString path
)
3607 if (PathFileExists(path
))
3610 ITEMIDLIST __unaligned
* pidl
= ILCreateFromPath(path
);
3613 ret
= SHOpenFolderAndSelectItems(pidl
, 0, 0, 0);
3616 return SUCCEEDED(ret
) ? 0 : -1;
3618 // if filepath does not exist any more, navigate to closest matching folder
3621 int pos
= path
.ReverseFind(_T('\\'));
3625 } while (!PathFileExists(path
));
3626 return (INT_PTR
)ShellExecute(hwnd
, _T("explore"), path
, nullptr, nullptr, SW_SHOW
) > 32 ? 0 : -1;
3629 int CAppUtils::ResolveConflict(CTGitPath
& path
, resolve_with resolveWith
)
3631 bool b_local
= false, b_remote
= false;
3635 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3636 if (g_Git
.Run(cmd
, &vector
))
3638 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3643 if (list
.ParserFromLsFile(vector
))
3645 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3651 for (int i
= 0; i
< list
.GetCount(); ++i
)
3653 if (list
[i
].m_Stage
== 2)
3655 if (list
[i
].m_Stage
== 3)
3660 CBlockCacheForPath
block(g_Git
.m_CurrentDir
);
3661 if (path
.IsDirectory()) // is submodule conflict
3663 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.");
3664 if (b_local
&& b_remote
)
3666 if (!path
.HasAdminDir()) // check if submodule is initialized
3668 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).");
3669 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3673 subgit
.m_CurrentDir
= g_Git
.CombinePath(path
);
3674 CGitHash submoduleHead
;
3675 if (subgit
.GetHash(submoduleHead
, _T("HEAD")))
3677 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3680 CString baseHash
, localHash
, remoteHash
;
3681 ParseHashesFromLsFile(vector
, baseHash
, localHash
, remoteHash
);
3682 if (resolveWith
== RESOLVE_WITH_THEIRS
&& submoduleHead
.ToString() != remoteHash
)
3684 CString origPath
= g_Git
.m_CurrentDir
;
3685 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3686 if (!GitReset(&remoteHash
))
3688 g_Git
.m_CurrentDir
= origPath
;
3691 g_Git
.m_CurrentDir
= origPath
;
3693 else if (resolveWith
== RESOLVE_WITH_MINE
&& submoduleHead
.ToString() != localHash
)
3695 CString origPath
= g_Git
.m_CurrentDir
;
3696 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3697 if (!GitReset(&localHash
))
3699 g_Git
.m_CurrentDir
= origPath
;
3702 g_Git
.m_CurrentDir
= origPath
;
3707 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3712 if (resolveWith
== RESOLVE_WITH_THEIRS
)
3714 CString gitcmd
, output
;
3715 if (b_local
&& b_remote
)
3716 gitcmd
.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3718 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3720 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3721 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3723 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3727 else if (resolveWith
== RESOLVE_WITH_MINE
)
3729 CString gitcmd
, output
;
3730 if (b_local
&& b_remote
)
3731 gitcmd
.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3733 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3735 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3736 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3738 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3743 if (b_local
&& b_remote
&& path
.m_Action
& CTGitPath::LOGACTIONS_UNMERGED
)
3745 CString gitcmd
, output
;
3746 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3747 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3748 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3751 path
.m_Action
|= CTGitPath::LOGACTIONS_MODIFIED
;
3752 path
.m_Action
&= ~CTGitPath::LOGACTIONS_UNMERGED
;
3756 RemoveTempMergeFile(path
);
3760 bool CAppUtils::ShellOpen(const CString
& file
, HWND hwnd
/*= nullptr */)
3762 if ((INT_PTR
)ShellExecute(hwnd
, nullptr, file
, nullptr, nullptr, SW_SHOW
) > HINSTANCE_ERROR
)
3765 return ShowOpenWithDialog(file
, hwnd
);
3768 bool CAppUtils::ShowOpenWithDialog(const CString
& file
, HWND hwnd
/*= nullptr */)
3770 OPENASINFO oi
= { 0 };
3772 oi
.oaifInFlags
= OAIF_EXEC
;
3773 return SUCCEEDED(SHOpenWithDialog(hwnd
, &oi
));
3776 bool CAppUtils::IsTGitRebaseActive()
3779 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3782 if (!PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3785 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND
, IDS_APPNAME
, 2, IDI_EXCLAMATION
, IDS_REMOVESTALEBUTTON
, IDS_ABORTBUTTON
) == 2)
3788 RemoveDirectory(adminDir
+ L
"tgitrebase.active");