1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - TortoiseGit
4 // Copyright (C) 2003-2011, 2013-2014 - TortoiseSVN
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software Foundation,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 #include "TortoiseProc.h"
22 #include "PathUtils.h"
24 #include "MessageBox.h"
28 #include "UnicodeUtils.h"
29 #include "ExportDlg.h"
30 #include "ProgressDlg.h"
31 #include "GitAdminDir.h"
32 #include "ProgressDlg.h"
33 #include "BrowseFolder.h"
34 #include "DirFileEnum.h"
35 #include "MessageBox.h"
36 #include "GitStatus.h"
37 #include "CreateBranchTagDlg.h"
38 #include "GitSwitchDlg.h"
40 #include "DeleteConflictDlg.h"
41 #include "ChangedDlg.h"
42 #include "SendMailDlg.h"
43 #include "GitProgressDlg.h"
45 #include "CommitDlg.h"
47 #include "MergeAbortDlg.h"
49 #include "..\Settings\Settings.h"
51 #include "SVNDCommitDlg.h"
52 #include "requestpulldlg.h"
53 #include "PullFetchDlg.h"
54 #include "FileDiffDlg.h"
55 #include "RebaseDlg.h"
57 #include "StashSave.h"
58 #include "IgnoreDlg.h"
59 #include "FormatMessageWrapper.h"
60 #include "SmartHandle.h"
61 #include "BisectStartDlg.h"
62 #include "SysProgressDlg.h"
63 #include "UserPassword.h"
64 #include "SendmailPatch.h"
66 #include "ProgressCommands/ResetProgressCommand.h"
67 #include "ProgressCommands/FetchProgressCommand.h"
68 #include "ProgressCommands/SendMailProgressCommand.h"
69 #include "CertificateValidationHelper.h"
70 #include "CheckCertificateDlg.h"
71 #include "SubmoduleResolveConflictDlg.h"
73 #include "../TGitCache/CacheInterface.h"
75 static struct last_accepted_cert
{
88 boolean
cmp(git_cert_x509
* cert
)
90 return len
> 0 && len
== cert
->len
&& memcmp(data
, cert
->data
, len
) == 0;
92 void set(git_cert_x509
* cert
)
101 data
= new BYTE
[len
];
102 memcpy(data
, cert
->data
, len
);
104 } last_accepted_cert
;
106 static bool DoFetch(const CString
& url
, const bool fetchAllRemotes
, const bool loadPuttyAgent
, const int prune
, const bool bDepth
, const int nDepth
, const int fetchTags
, const CString
& remoteBranch
, int runRebase
, const bool rebasePreserveMerges
);
108 CAppUtils::CAppUtils(void)
112 CAppUtils::~CAppUtils(void)
116 bool CAppUtils::StashSave(const CString
& msg
, bool showPull
, bool pullShowPush
, bool showMerge
, const CString
& mergeRev
)
119 dlg
.m_sMessage
= msg
;
120 if (dlg
.DoModal() == IDOK
)
123 cmd
= _T("git.exe stash save");
125 if (dlg
.m_bIncludeUntracked
)
126 cmd
+= L
" --include-untracked";
130 if (!dlg
.m_sMessage
.IsEmpty())
132 CString message
= dlg
.m_sMessage
;
133 message
.Replace(_T("\""), _T("\"\""));
134 cmd
+= _T(" -- \"") + message
+ _T("\"");
137 CProgressDlg progress
;
138 progress
.m_GitCmd
= cmd
;
139 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
145 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ CAppUtils::Pull(pullShowPush
, true); });
147 postCmdList
.emplace_back(IDI_MERGE
, IDS_MENUMERGE
, [&]{ CAppUtils::Merge(&mergeRev
, true); });
149 return (progress
.DoModal() == IDOK
);
154 bool CAppUtils::StashApply(CString ref
, bool showChanges
/* true */)
157 cmd
= _T("git.exe stash apply ");
158 if (ref
.Find(_T("refs/")) == 0)
160 if (ref
.Find(_T("stash{")) == 0)
161 ref
= _T("stash@") + ref
.Mid(5);
164 CSysProgressDlg sysProgressDlg
;
165 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
166 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
167 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
168 sysProgressDlg
.SetShowProgressBar(false);
169 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
170 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
172 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
174 sysProgressDlg
.Stop();
176 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
177 if (ret
&& !(ret
== 1 && hasConflicts
))
178 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHAPPLYFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
182 message
.LoadString(IDS_PROC_STASHAPPLYSUCCESS
);
184 message
.LoadString(IDS_PROC_STASHAPPLYFAILEDCONFLICTS
);
187 if (CMessageBox::Show(nullptr, message
+ _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES
)), _T("TortoiseGit"), MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
190 dlg
.m_pathList
.AddPath(CTGitPath());
197 CMessageBox::Show(nullptr, message
,_T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
204 bool CAppUtils::StashPop(int showChanges
/* = 1 */)
207 cmd
=_T("git.exe stash pop ");
209 CSysProgressDlg sysProgressDlg
;
210 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
211 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
212 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
213 sysProgressDlg
.SetShowProgressBar(false);
214 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
215 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
217 int ret
= g_Git
.Run(cmd
, &out
, CP_UTF8
);
219 sysProgressDlg
.Stop();
221 bool hasConflicts
= (out
.Find(_T("CONFLICT")) >= 0);
222 if (ret
&& !(ret
== 1 && hasConflicts
))
223 CMessageBox::Show(nullptr, CString(MAKEINTRESOURCE(IDS_PROC_STASHPOPFAILED
)) + _T("\n") + out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
227 message
.LoadString(IDS_PROC_STASHPOPSUCCESS
);
229 message
.LoadString(IDS_PROC_STASHPOPFAILEDCONFLICTS
);
230 if (showChanges
== 1 || (showChanges
== 0 && hasConflicts
))
232 if (CMessageBox::Show(nullptr, CString(message
+ _T("\n") + CString(MAKEINTRESOURCE(IDS_SEECHANGES
))), _T("TortoiseGit"), MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
235 dlg
.m_pathList
.AddPath(CTGitPath());
240 else if (showChanges
> 1)
242 CMessageBox::Show(nullptr, message
, _T("TortoiseGit"), MB_OK
| MB_ICONINFORMATION
);
245 else if (showChanges
== 0)
251 BOOL
CAppUtils::StartExtMerge(
252 const CTGitPath
& basefile
, const CTGitPath
& theirfile
, const CTGitPath
& yourfile
, const CTGitPath
& mergedfile
,
253 const CString
& basename
, const CString
& theirname
, const CString
& yourname
, const CString
& mergedname
, bool bReadOnly
,
254 HWND resolveMsgHwnd
, bool bDeleteBaseTheirsMineOnClose
)
256 CRegString regCom
= CRegString(_T("Software\\TortoiseGit\\Merge"));
257 CString ext
= mergedfile
.GetFileExtension();
258 CString com
= regCom
;
259 bool bInternal
= false;
263 // is there an extension specific merge tool?
264 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\") + ext
.MakeLower());
265 if (!CString(mergetool
).IsEmpty())
268 // is there a filename specific merge tool?
269 CRegString
mergetool(_T("Software\\TortoiseGit\\MergeTools\\.") + mergedfile
.GetFilename().MakeLower());
270 if (!CString(mergetool
).IsEmpty())
273 if (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
'<';
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 (sText
.Find(prefix
) == 0 && 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] == '<'))
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
>= 0 && pos
< (int)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(base
, mine
, theirs
, merge
, _T("BASE"), _T("REMOTE"), _T("LOCAL"), CString(), false, resolveMsgHwnd
, true);
1826 bRet
= !!CAppUtils::StartExtMerge(base
, theirs
, mine
, merge
, _T("BASE"), _T("REMOTE"), _T("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 if(sClipboardText
.Find( _T("http://")) == 0)
2165 return sClipboardText
;
2167 if(sClipboardText
.Find( _T("https://")) == 0)
2168 return sClipboardText
;
2170 if(sClipboardText
.Find( _T("git://")) == 0)
2171 return sClipboardText
;
2173 if(sClipboardText
.Find( _T("ssh://")) == 0)
2174 return sClipboardText
;
2176 if (sClipboardText
.Find(_T("git@")) == 0)
2177 return sClipboardText
;
2179 if(sClipboardText
.GetLength()>=2)
2180 if( sClipboardText
[1] == _T(':') )
2181 if( (sClipboardText
[0] >= 'A' && sClipboardText
[0] <= 'Z')
2182 || (sClipboardText
[0] >= 'a' && sClipboardText
[0] <= 'z') )
2183 return sClipboardText
;
2185 // trim prefixes like "git clone "
2186 if (!skipGitPrefix
.IsEmpty() && sClipboardText
.Find(skipGitPrefix
) == 0)
2188 sClipboardText
= sClipboardText
.Mid(skipGitPrefix
.GetLength()).Trim();
2190 while (paramsCount
>= 0)
2193 spacePos
= sClipboardText
.Find(_T(' '), spacePos
+ 1);
2197 if (spacePos
> 0 && paramsCount
< 0)
2198 sClipboardText
= sClipboardText
.Left(spacePos
);
2199 return sClipboardText
;
2206 CString
CAppUtils::ChooseRepository(const CString
* path
)
2208 CBrowseFolder browseFolder
;
2209 CRegString regLastResopitory
= CRegString(_T("Software\\TortoiseGit\\TortoiseProc\\LastRepo"),_T(""));
2211 browseFolder
.m_style
= BIF_EDITBOX
| BIF_NEWDIALOGSTYLE
| BIF_RETURNFSANCESTORS
| BIF_RETURNONLYFSDIRS
;
2212 CString strCloneDirectory
;
2214 strCloneDirectory
=*path
;
2216 strCloneDirectory
= regLastResopitory
;
2219 title
.LoadString(IDS_CHOOSE_REPOSITORY
);
2221 browseFolder
.SetInfo(title
);
2223 if (browseFolder
.Show(nullptr, strCloneDirectory
) == CBrowseFolder::OK
)
2225 regLastResopitory
= strCloneDirectory
;
2226 return strCloneDirectory
;
2232 bool CAppUtils::SendPatchMail(CTGitPathList
& list
, bool bIsMainWnd
)
2236 dlg
.m_PathList
= list
;
2238 if(dlg
.DoModal()==IDOK
)
2240 if (dlg
.m_PathList
.IsEmpty())
2243 CGitProgressDlg progDlg
;
2245 theApp
.m_pMainWnd
= &progDlg
;
2246 SendMailProgressCommand sendMailProgressCommand
;
2247 progDlg
.SetCommand(&sendMailProgressCommand
);
2249 sendMailProgressCommand
.SetPathList(dlg
.m_PathList
);
2250 progDlg
.SetItemCount(dlg
.m_PathList
.GetCount());
2252 CSendMailPatch
sendMailPatch(dlg
.m_To
, dlg
.m_CC
, dlg
.m_Subject
, !!dlg
.m_bAttachment
, !!dlg
.m_bCombine
);
2253 sendMailProgressCommand
.SetSendMailOption(&sendMailPatch
);
2262 bool CAppUtils::SendPatchMail(const CString
& cmd
, const CString
& formatpatchoutput
, bool bIsMainWnd
)
2265 CString log
=formatpatchoutput
;
2266 int start
=log
.Find(cmd
);
2268 CString one
=log
.Tokenize(_T("\n"),start
);
2274 CString one
=log
.Tokenize(_T("\n"),start
);
2276 if (one
.IsEmpty() || one
.Find(CString(MAKEINTRESOURCE(IDS_SUCCESS
))) == 0)
2278 one
.Replace(_T('/'),_T('\\'));
2280 path
.SetFromWin(one
);
2283 if (!list
.IsEmpty())
2284 return SendPatchMail(list
, bIsMainWnd
);
2287 CMessageBox::Show(nullptr, IDS_ERR_NOPATCHES
, IDS_APPNAME
, MB_ICONINFORMATION
);
2293 int CAppUtils::GetLogOutputEncode(CGit
*pGit
)
2296 output
= pGit
->GetConfigValue(_T("i18n.logOutputEncoding"));
2297 if(output
.IsEmpty())
2298 return CUnicodeUtils::GetCPCode(pGit
->GetConfigValue(_T("i18n.commitencoding")));
2300 return CUnicodeUtils::GetCPCode(output
);
2302 int CAppUtils::SaveCommitUnicodeFile(const CString
& filename
, CString
&message
)
2306 CFile
file(filename
, CFile::modeReadWrite
| CFile::modeCreate
);
2307 int cp
= CUnicodeUtils::GetCPCode(g_Git
.GetConfigValue(_T("i18n.commitencoding")));
2309 bool stripComments
= (CRegDWORD(_T("Software\\TortoiseGit\\StripCommentedLines"), FALSE
) == TRUE
);
2310 TCHAR commentChar
= L
'#';
2313 CString commentCharValue
= g_Git
.GetConfigValue(L
"core.commentchar");
2314 if (!commentCharValue
.IsEmpty())
2315 commentChar
= commentCharValue
[0];
2318 bool sanitize
= (CRegDWORD(_T("Software\\TortoiseGit\\SanitizeCommitMsg"), TRUE
) == TRUE
);
2320 message
.Trim(L
" \r\n");
2322 int len
= message
.GetLength();
2324 int emptyLineCnt
= 0;
2325 while (start
>= 0 && start
< len
)
2327 int oldStart
= start
;
2328 start
= message
.Find(L
"\n", oldStart
);
2329 CString line
= message
.Mid(oldStart
);
2332 line
= line
.Left(start
- oldStart
);
2333 ++start
; // move forward so we don't find the same char again
2335 if (stripComments
&& (!line
.IsEmpty() && line
.GetAt(0) == commentChar
) || (start
< 0 && line
.IsEmpty()))
2337 line
.TrimRight(L
" \r");
2345 if (emptyLineCnt
) // squash multiple newlines
2346 file
.Write("\n", 1);
2349 CStringA lineA
= CUnicodeUtils::GetMulti(line
+ L
"\n", cp
);
2350 file
.Write((LPCSTR
)lineA
, lineA
.GetLength());
2355 catch (CFileException
*e
)
2362 bool CAppUtils::Pull(bool showPush
, bool showStashPop
)
2364 if (IsTGitRebaseActive())
2368 dlg
.m_IsPull
= TRUE
;
2369 if (dlg
.DoModal() == IDOK
)
2371 // "git.exe pull --rebase" is not supported, never and ever. So, adapting it to Fetch & Rebase.
2373 return DoFetch(dlg
.m_RemoteURL
,
2374 FALSE
, // Fetch all remotes
2375 dlg
.m_bAutoLoad
== BST_CHECKED
,
2377 dlg
.m_bDepth
== BST_CHECKED
,
2380 dlg
.m_RemoteBranchName
,
2381 dlg
.m_bRebaseActivatedInConfigForPull
? 2 : 1, // Rebase after fetching
2382 dlg
.m_bRebasePreserveMerges
== TRUE
); // Preserve merges on rebase
2384 CString url
= dlg
.m_RemoteURL
;
2386 if (dlg
.m_bAutoLoad
)
2387 CAppUtils::LaunchPAgent(nullptr, &dlg
.m_RemoteURL
);
2391 if (g_Git
.GetHash(hashOld
, _T("HEAD")))
2393 MessageBox(nullptr, g_Git
.GetGitLastErr(_T("Could not get HEAD hash.")), _T("TortoiseGit"), MB_ICONERROR
);
2405 if (!dlg
.m_bFetchTags
)
2406 notags
= _T("--no-tags ");
2408 if (dlg
.m_bFetchTags
== TRUE
)
2409 notags
= _T("--tags ");
2412 noff
=_T("--no-ff ");
2415 ffonly
= _T("--ff-only ");
2418 squash
= _T("--squash ");
2420 if (dlg
.m_bNoCommit
)
2421 nocommit
= _T("--no-commit ");
2424 depth
.Format(_T("--depth %d "), dlg
.m_nDepth
);
2426 if (dlg
.m_bPrune
== TRUE
)
2427 prune
= _T("--prune ");
2428 else if (dlg
.m_bPrune
== FALSE
)
2429 prune
= _T("--no-prune ");
2431 cmd
.Format(_T("git.exe pull --progress%s -v %s%s%s%s%s%s%s\"%s\" %s"), CRegDWORD(L
"Software\\TortoiseGit\\PullRebaseBehaviorLike1816", FALSE
) == FALSE
? L
" --no-rebase" : L
"", (LPCTSTR
)noff
, (LPCTSTR
)ffonly
, (LPCTSTR
)squash
, (LPCTSTR
)nocommit
, (LPCTSTR
)depth
, (LPCTSTR
)notags
, (LPCTSTR
)prune
, (LPCTSTR
)url
, (LPCTSTR
)dlg
.m_RemoteBranchName
);
2432 CProgressDlg progress
;
2433 progress
.m_GitCmd
= cmd
;
2435 CGitHash hashNew
; // declare outside lambda, because it is captured by reference
2436 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2440 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, [&]{ Pull(); });
2441 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ StashSave(_T(""), true); });
2446 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ StashPop(); });
2448 if (g_Git
.GetHash(hashNew
, _T("HEAD")))
2449 MessageBox(nullptr, g_Git
.GetGitLastErr(_T("Could not get HEAD hash after pulling.")), _T("TortoiseGit"), MB_ICONERROR
);
2452 postCmdList
.emplace_back(IDI_DIFF
, IDS_PROC_PULL_DIFFS
, [&]
2455 dlg
.SetDiff(nullptr, hashOld
.ToString(), hashNew
.ToString());
2458 postCmdList
.emplace_back(IDI_LOG
, IDS_PROC_PULL_LOG
, [&]
2461 dlg
.SetParams(CTGitPath(_T("")), CTGitPath(_T("")), _T(""), hashOld
.ToString() + _T("..") + hashNew
.ToString(), 0);
2467 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ Push(); });
2469 CTGitPath gitPath
= g_Git
.m_CurrentDir
;
2470 if (gitPath
.HasSubmodules())
2472 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
2475 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
2476 CAppUtils::RunTortoiseGitProc(sCmd
);
2481 INT_PTR ret
= progress
.DoModal();
2483 if (ret
== IDOK
&& progress
.m_GitStatus
== 1 && progress
.m_LogText
.Find(_T("CONFLICT")) >= 0 && CMessageBox::Show(nullptr, IDS_SEECHANGES
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
2485 CChangedDlg changeddlg
;
2486 changeddlg
.m_pathList
.AddPath(CTGitPath());
2487 changeddlg
.DoModal();
2498 bool CAppUtils::RebaseAfterFetch(const CString
& upstream
, int rebase
, bool preserveMerges
)
2503 if (!upstream
.IsEmpty())
2504 dlg
.m_Upstream
= upstream
;
2505 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENULOG
)));
2506 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUPUSH
)));
2507 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUDESSENDMAIL
)));
2508 dlg
.m_PostButtonTexts
.Add(CString(MAKEINTRESOURCE(IDS_MENUREBASE
)));
2509 dlg
.m_bRebaseAutoStart
= (rebase
== 2);
2510 dlg
.m_bPreserveMerges
= preserveMerges
;
2511 INT_PTR response
= dlg
.DoModal();
2512 if (response
== IDOK
)
2514 else if (response
== IDC_REBASE_POST_BUTTON
)
2516 CString cmd
= _T("/command:log");
2517 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2518 CAppUtils::RunTortoiseGitProc(cmd
);
2521 else if (response
== IDC_REBASE_POST_BUTTON
+ 1)
2523 else if (response
== IDC_REBASE_POST_BUTTON
+ 2)
2525 CString cmd
, out
, err
;
2526 cmd
.Format(_T("git.exe format-patch -o \"%s\" %s..%s"),
2527 (LPCTSTR
)g_Git
.m_CurrentDir
,
2528 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Upstream
),
2529 (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_Branch
));
2530 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
2532 CMessageBox::Show(nullptr, out
+ L
"\n" + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2535 CAppUtils::SendPatchMail(cmd
, out
);
2538 else if (response
== IDC_REBASE_POST_BUTTON
+ 3)
2540 else if (response
== IDCANCEL
)
2546 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
)
2550 if (fetchAllRemotes
)
2553 g_Git
.GetRemoteList(list
);
2555 for (const auto& remote
: list
)
2556 CAppUtils::LaunchPAgent(nullptr, &remote
);
2559 CAppUtils::LaunchPAgent(nullptr, &url
);
2562 CString upstream
= _T("FETCH_HEAD");
2563 CGitHash oldUpstreamHash
;
2567 g_Git
.GetRemoteList(list
);
2568 for (auto it
= list
.cbegin(); it
!= list
.cend(); ++it
)
2572 CString remote
, trackedBranch
;
2573 g_Git
.GetRemoteTrackedBranchForHEAD(remote
, trackedBranch
);
2574 if (!remote
.IsEmpty() && !trackedBranch
.IsEmpty())
2576 upstream
= L
"remotes/" + remote
+ L
"/" + trackedBranch
;
2577 g_Git
.GetHash(oldUpstreamHash
, upstream
);
2585 arg
= _T(" --progress");
2588 arg
.AppendFormat(_T(" --depth %d"), nDepth
);
2591 arg
+= _T(" --prune");
2592 else if (prune
== FALSE
)
2593 arg
+= _T(" --no-prune");
2596 arg
+= _T(" --tags");
2597 else if (fetchTags
== 0)
2598 arg
+= _T(" --no-tags");
2600 if (fetchAllRemotes
)
2601 cmd
.Format(_T("git.exe fetch --all -v%s"), (LPCTSTR
)arg
);
2603 cmd
.Format(_T("git.exe fetch -v%s \"%s\" %s"), (LPCTSTR
)arg
, (LPCTSTR
)url
, (LPCTSTR
)remoteBranch
);
2605 CProgressDlg progress
;
2606 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2610 postCmdList
.emplace_back(IDI_REFRESH
, IDS_MSGBOX_RETRY
, [&]{ DoFetch(url
, fetchAllRemotes
, loadPuttyAgent
, prune
, bDepth
, nDepth
, fetchTags
, remoteBranch
, runRebase
, rebasePreserveMerges
); });
2614 postCmdList
.emplace_back(IDI_LOG
, IDS_MENULOG
, []
2616 CString cmd
= _T("/command:log");
2617 cmd
+= _T(" /path:\"") + g_Git
.m_CurrentDir
+ _T("\"");
2618 CAppUtils::RunTortoiseGitProc(cmd
);
2621 postCmdList
.emplace_back(IDI_REVERT
, IDS_PROC_RESET
, []
2623 CString pullRemote
, pullBranch
;
2624 g_Git
.GetRemoteTrackedBranchForHEAD(pullRemote
, pullBranch
);
2625 CString defaultUpstream
;
2626 if (!pullRemote
.IsEmpty() && !pullBranch
.IsEmpty())
2627 defaultUpstream
.Format(_T("remotes/%s/%s"), (LPCTSTR
)pullRemote
, (LPCTSTR
)pullBranch
);
2628 CAppUtils::GitReset(&defaultUpstream
, 2);
2631 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, []{ CAppUtils::Fetch(); });
2633 if (!runRebase
&& !GitAdminDir::IsBareRepo(g_Git
.m_CurrentDir
))
2634 postCmdList
.emplace_back(IDI_REBASE
, IDS_MENUREBASE
, [&]{ runRebase
= false; CAppUtils::RebaseAfterFetch(); });
2637 progress
.m_GitCmd
= cmd
;
2639 if (g_Git
.UsingLibGit2(CGit::GIT_CMD_FETCH
))
2641 CGitProgressDlg gitdlg
;
2642 FetchProgressCommand fetchProgressCommand
;
2643 if (!fetchAllRemotes
)
2644 fetchProgressCommand
.SetUrl(url
);
2645 gitdlg
.SetCommand(&fetchProgressCommand
);
2646 fetchProgressCommand
.m_PostCmdCallback
= progress
.m_PostCmdCallback
;
2647 fetchProgressCommand
.SetAutoTag(fetchTags
== 1 ? GIT_REMOTE_DOWNLOAD_TAGS_ALL
: fetchTags
== 2 ? GIT_REMOTE_DOWNLOAD_TAGS_AUTO
: GIT_REMOTE_DOWNLOAD_TAGS_NONE
);
2648 if (!fetchAllRemotes
)
2649 fetchProgressCommand
.SetRefSpec(remoteBranch
);
2650 return gitdlg
.DoModal() == IDOK
;
2653 progress
.m_PostExecCallback
= [&](DWORD
& exitCode
, CString
&)
2655 if (exitCode
|| !runRebase
)
2658 CGitHash remoteBranchHash
;
2659 g_Git
.GetHash(remoteBranchHash
, upstream
);
2660 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
)
2663 if (runRebase
== 1 && g_Git
.IsFastForward(L
"HEAD", upstream
))
2665 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
);
2670 CProgressDlg mergeProgress
;
2671 mergeProgress
.m_GitCmd
= L
"git.exe merge --ff-only " + upstream
;
2672 mergeProgress
.m_AutoClose
= AUTOCLOSE_IF_NO_ERRORS
;
2673 mergeProgress
.m_PostCmdCallback
= [](DWORD status
, PostCmdList
& postCmdList
)
2675 if (status
&& g_Git
.HasWorkingTreeConflicts())
2677 // there are conflict files
2678 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
2681 sCmd
.Format(L
"/command:commit /path:\"%s\"", g_Git
.m_CurrentDir
);
2682 CAppUtils::RunTortoiseGitProc(sCmd
);
2686 mergeProgress
.DoModal();
2691 CAppUtils::RebaseAfterFetch(upstream
, runRebase
, rebasePreserveMerges
);
2694 return progress
.DoModal() == IDOK
;
2697 bool CAppUtils::Fetch(const CString
& remoteName
, bool allRemotes
)
2700 dlg
.m_PreSelectRemote
= remoteName
;
2702 dlg
.m_bAllRemotes
= allRemotes
;
2704 if(dlg
.DoModal()==IDOK
)
2705 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
);
2710 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
)
2713 DWORD exitcode
= 0xFFFFFFFF;
2714 if (CHooks::Instance().PrePush(g_Git
.m_CurrentDir
, exitcode
, error
))
2719 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2720 CMessageBox::Show(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2725 int iRecurseSubmodules
= 0;
2726 if (GetMsysgitVersion() >= 0x02070000)
2728 CString sRecurseSubmodules
= g_Git
.GetConfigValue(_T("push.recurseSubmodules"));
2729 if (sRecurseSubmodules
== _T("check"))
2730 iRecurseSubmodules
= 1;
2731 else if (sRecurseSubmodules
== _T("on-demand"))
2732 iRecurseSubmodules
= 2;
2737 arg
+= _T("--thin ");
2738 if (tags
&& !allBranches
)
2739 arg
+= _T("--tags ");
2741 arg
+= _T("--force ");
2743 arg
+= _T("--force-with-lease ");
2745 arg
+= _T("--set-upstream ");
2746 if (recurseSubmodules
== 0 && recurseSubmodules
!= iRecurseSubmodules
)
2747 arg
+= _T("--recurse-submodules=no ");
2748 if (recurseSubmodules
== 1 && recurseSubmodules
!= iRecurseSubmodules
)
2749 arg
+= _T("--recurse-submodules=check ");
2750 if (recurseSubmodules
== 2 && recurseSubmodules
!= iRecurseSubmodules
)
2751 arg
+= _T("--recurse-submodules=on-demand ");
2753 arg
+= _T("--progress ");
2755 CProgressDlg progress
;
2757 STRING_VECTOR remotesList
;
2759 g_Git
.GetRemoteList(remotesList
);
2761 remotesList
.push_back(remote
);
2763 for (unsigned int i
= 0; i
< remotesList
.size(); ++i
)
2766 CAppUtils::LaunchPAgent(nullptr, &remotesList
[i
]);
2771 cmd
.Format(_T("git.exe push --all %s\"%s\""),
2773 (LPCTSTR
)remotesList
[i
]);
2777 progress
.m_GitCmdList
.push_back(cmd
);
2778 cmd
.Format(_T("git.exe push --tags %s\"%s\""), (LPCTSTR
)arg
, (LPCTSTR
)remotesList
[i
]);
2783 cmd
.Format(_T("git.exe push %s\"%s\" %s"),
2785 (LPCTSTR
)remotesList
[i
],
2786 (LPCTSTR
)localBranch
);
2787 if (!remoteBranch
.IsEmpty())
2790 cmd
+= remoteBranch
;
2793 progress
.m_GitCmdList
.push_back(cmd
);
2795 if (!allBranches
&& !!CRegDWORD(_T("Software\\TortoiseGit\\ShowBranchRevisionNumber"), FALSE
))
2797 cmd
.Format(_T("git.exe rev-list --count --first-parent %s"), (LPCTSTR
)localBranch
);
2798 progress
.m_GitCmdList
.push_back(cmd
);
2802 CString superprojectRoot
;
2803 GitAdminDir::HasAdminDir(g_Git
.m_CurrentDir
, false, &superprojectRoot
);
2804 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
2806 // need to execute hooks as those might be needed by post action commands
2807 DWORD exitcode
= 0xFFFFFFFF;
2809 if (CHooks::Instance().PostPush(g_Git
.m_CurrentDir
, exitcode
, error
))
2814 temp
.Format(IDS_ERR_HOOKFAILED
, (LPCTSTR
)error
);
2815 MessageBox(nullptr, temp
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2821 bool rejected
= progress
.GetLogText().Find(_T("! [rejected]")) > 0;
2824 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUPULL
, []{ Pull(true); });
2825 postCmdList
.emplace_back(IDI_PULL
, IDS_MENUFETCH
, [&]{ Fetch(allRemotes
? _T("") : remote
, allRemotes
); });
2827 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2831 postCmdList
.emplace_back(IDS_PROC_REQUESTPULL
, [&]{ RequestPull(remoteBranch
); });
2832 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, [&]{ Push(localBranch
); });
2833 postCmdList
.emplace_back(IDI_SWITCH
, IDS_MENUSWITCH
, [&]{ Switch(); });
2834 if (!superprojectRoot
.IsEmpty())
2836 postCmdList
.emplace_back(IDI_COMMIT
, IDS_PROC_COMMIT_SUPERPROJECT
, [&]
2839 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)superprojectRoot
);
2840 RunTortoiseGitProc(sCmd
);
2845 INT_PTR ret
= progress
.DoModal();
2849 bool CAppUtils::Push(const CString
& selectLocalBranch
)
2852 dlg
.m_BranchSourceName
= selectLocalBranch
;
2854 if (dlg
.DoModal() == IDOK
)
2855 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
);
2860 bool CAppUtils::RequestPull(const CString
& endrevision
, const CString
& repositoryUrl
, bool bIsMainWnd
)
2862 CRequestPullDlg dlg
;
2863 dlg
.m_RepositoryURL
= repositoryUrl
;
2864 dlg
.m_EndRevision
= endrevision
;
2865 if (dlg
.DoModal()==IDOK
)
2868 cmd
.Format(_T("git.exe request-pull %s \"%s\" %s"), (LPCTSTR
)dlg
.m_StartRevision
, (LPCTSTR
)dlg
.m_RepositoryURL
, (LPCTSTR
)dlg
.m_EndRevision
);
2870 CSysProgressDlg sysProgressDlg
;
2871 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
2872 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_CREATINGPULLREUQEST
)));
2873 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
2874 sysProgressDlg
.SetShowProgressBar(false);
2875 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
2877 CString tempFileName
= GetTempFile();
2879 DeleteFile(tempFileName
);
2880 CreateDirectory(tempFileName
, nullptr);
2881 tempFileName
+= _T("\\pullrequest.txt");
2882 if (g_Git
.RunLogFile(cmd
, tempFileName
, &err
))
2885 msg
.LoadString(IDS_ERR_PULLREUQESTFAILED
);
2886 MessageBox(nullptr, msg
+ _T("\n") + err
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
2890 if (sysProgressDlg
.HasUserCancelled())
2892 CMessageBox::Show(nullptr, IDS_USERCANCELLED
, IDS_APPNAME
, MB_OK
);
2893 ::DeleteFile(tempFileName
);
2897 sysProgressDlg
.Stop();
2899 if (dlg
.m_bSendMail
)
2901 CSendMailDlg sendmaildlg
;
2902 sendmaildlg
.m_PathList
= CTGitPathList(CTGitPath(tempFileName
));
2903 sendmaildlg
.m_bCustomSubject
= true;
2905 if (sendmaildlg
.DoModal() == IDOK
)
2907 if (sendmaildlg
.m_PathList
.IsEmpty())
2910 CGitProgressDlg progDlg
;
2912 theApp
.m_pMainWnd
= &progDlg
;
2913 SendMailProgressCommand sendMailProgressCommand
;
2914 progDlg
.SetCommand(&sendMailProgressCommand
);
2916 sendMailProgressCommand
.SetPathList(sendmaildlg
.m_PathList
);
2917 progDlg
.SetItemCount(sendmaildlg
.m_PathList
.GetCount());
2919 CSendMailCombineable
sendMailCombineable(sendmaildlg
.m_To
, sendmaildlg
.m_CC
, sendmaildlg
.m_Subject
, !!sendmaildlg
.m_bAttachment
, !!sendmaildlg
.m_bCombine
);
2920 sendMailProgressCommand
.SetSendMailOption(&sendMailCombineable
);
2929 CAppUtils::LaunchAlternativeEditor(tempFileName
);
2934 void CAppUtils::RemoveTrailSlash(CString
&path
)
2939 // For URL, do not trim the slash just after the host name component.
2940 int index
= path
.Find(_T("://"));
2944 index
= path
.Find(_T('/'), index
);
2945 if (index
== path
.GetLength() - 1)
2949 while(path
[path
.GetLength()-1] == _T('\\') || path
[path
.GetLength()-1] == _T('/' ) )
2951 path
=path
.Left(path
.GetLength()-1);
2957 bool CAppUtils::CheckUserData()
2959 while(g_Git
.GetUserName().IsEmpty() || g_Git
.GetUserEmail().IsEmpty())
2961 if (CMessageBox::Show(nullptr, IDS_PROC_NOUSERDATA
, IDS_APPNAME
, MB_YESNO
| MB_ICONERROR
) == IDYES
)
2963 CTGitPath
path(g_Git
.m_CurrentDir
);
2964 CSettings
dlg(IDS_PROC_SETTINGS_TITLE
,&path
);
2965 dlg
.SetTreeViewMode(TRUE
, TRUE
, TRUE
);
2966 dlg
.SetTreeWidth(220);
2967 dlg
.m_DefaultPage
= _T("gitconfig");
2970 dlg
.HandleRestart();
2980 BOOL
CAppUtils::Commit(const CString
& bugid
, BOOL bWholeProject
, CString
&sLogMsg
,
2981 CTGitPathList
&pathList
,
2982 CTGitPathList
&selectedList
,
2983 bool bSelectFilesForCommit
)
2985 bool bFailed
= true;
2987 if (!CheckUserData())
2994 dlg
.m_sBugID
= bugid
;
2996 dlg
.m_bWholeProject
= bWholeProject
;
2998 dlg
.m_sLogMessage
= sLogMsg
;
2999 dlg
.m_pathList
= pathList
;
3000 dlg
.m_checkedPathList
= selectedList
;
3001 dlg
.m_bSelectFilesForCommit
= bSelectFilesForCommit
;
3002 if (dlg
.DoModal() == IDOK
)
3004 if (dlg
.m_pathList
.IsEmpty())
3006 // if the user hasn't changed the list of selected items
3007 // we don't use that list. Because if we would use the list
3008 // of pre-checked items, the dialog would show different
3009 // checked items on the next startup: it would only try
3010 // to check the parent folder (which might not even show)
3011 // instead, we simply use an empty list and let the
3012 // default checking do its job.
3013 if (!dlg
.m_pathList
.IsEqual(pathList
))
3014 selectedList
= dlg
.m_pathList
;
3015 pathList
= dlg
.m_updatedPathList
;
3016 sLogMsg
= dlg
.m_sLogMessage
;
3017 bSelectFilesForCommit
= true;
3019 switch (dlg
.m_PostCmd
)
3021 case GIT_POSTCOMMIT_CMD_DCOMMIT
:
3022 CAppUtils::SVNDCommit();
3024 case GIT_POSTCOMMIT_CMD_PUSH
:
3027 case GIT_POSTCOMMIT_CMD_CREATETAG
:
3028 CAppUtils::CreateBranchTag(TRUE
);
3030 case GIT_POSTCOMMIT_CMD_PULL
:
3031 CAppUtils::Pull(true);
3037 // CGitProgressDlg progDlg;
3038 // progDlg.SetChangeList(dlg.m_sChangeList, !!dlg.m_bKeepChangeList);
3039 // if (parser.HasVal(_T("closeonend")))
3040 // progDlg.SetAutoClose(parser.GetLongVal(_T("closeonend")));
3041 // progDlg.SetCommand(CGitProgressDlg::GitProgress_Commit);
3042 // progDlg.SetOptions(dlg.m_bKeepLocks ? ProgOptKeeplocks : ProgOptNone);
3043 // progDlg.SetPathList(dlg.m_pathList);
3044 // progDlg.SetCommitMessage(dlg.m_sLogMessage);
3045 // progDlg.SetDepth(dlg.m_bRecursive ? Git_depth_infinity : svn_depth_empty);
3046 // progDlg.SetSelectedList(dlg.m_selectedPathList);
3047 // progDlg.SetItemCount(dlg.m_itemsCount);
3048 // progDlg.SetBugTraqProvider(dlg.m_BugTraqProvider);
3049 // progDlg.DoModal();
3050 // CRegDWORD err = CRegDWORD(_T("Software\\TortoiseGit\\ErrorOccurred"), FALSE);
3051 // err = (DWORD)progDlg.DidErrorsOccur();
3052 // bFailed = progDlg.DidErrorsOccur();
3053 // bRet = progDlg.DidErrorsOccur();
3054 // CRegDWORD bFailRepeat = CRegDWORD(_T("Software\\TortoiseGit\\CommitReopen"), FALSE);
3055 // if (DWORD(bFailRepeat)==0)
3056 // bFailed = false; // do not repeat if the user chose not to in the settings.
3062 BOOL
CAppUtils::SVNDCommit()
3064 CSVNDCommitDlg dcommitdlg
;
3065 CString gitSetting
= g_Git
.GetConfigValue(_T("svn.rmdir"));
3066 if (gitSetting
.IsEmpty()) {
3067 if (dcommitdlg
.DoModal() != IDOK
)
3071 if (dcommitdlg
.m_remember
)
3073 if (dcommitdlg
.m_rmdir
)
3074 gitSetting
= _T("true");
3076 gitSetting
= _T("false");
3077 if(g_Git
.SetConfigValue(_T("svn.rmdir"),gitSetting
))
3080 msg
.Format(IDS_PROC_SAVECONFIGFAILED
, _T("svn.rmdir"), gitSetting
);
3081 CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3087 BOOL IsStash
= false;
3088 if(!g_Git
.CheckCleanWorkTree())
3090 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3092 CSysProgressDlg sysProgressDlg
;
3093 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3094 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3095 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3096 sysProgressDlg
.SetShowProgressBar(false);
3097 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3098 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3101 cmd
=_T("git.exe stash");
3102 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3104 sysProgressDlg
.Stop();
3105 MessageBox(nullptr, out
,_T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3108 sysProgressDlg
.Stop();
3116 CProgressDlg progress
;
3117 if (dcommitdlg
.m_rmdir
)
3118 progress
.m_GitCmd
=_T("git.exe svn dcommit --rmdir");
3120 progress
.m_GitCmd
=_T("git.exe svn dcommit");
3121 if(progress
.DoModal()==IDOK
&& progress
.m_GitStatus
== 0)
3125 if (CMessageBox::Show(nullptr, IDS_DCOMMIT_STASH_POP
, IDS_APPNAME
, MB_YESNO
| MB_ICONINFORMATION
) == IDYES
)
3127 CSysProgressDlg sysProgressDlg
;
3128 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3129 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3130 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3131 sysProgressDlg
.SetShowProgressBar(false);
3132 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3133 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3136 cmd
=_T("git.exe stash pop");
3137 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3139 sysProgressDlg
.Stop();
3140 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3143 sysProgressDlg
.Stop();
3153 BOOL
CAppUtils::Merge(const CString
* commit
, bool showStashPop
)
3155 if (!CheckUserData())
3158 if (IsTGitRebaseActive())
3163 dlg
.m_initialRefName
= *commit
;
3165 if(dlg
.DoModal()==IDOK
)
3171 args
+= _T(" --no-ff");
3172 else if (dlg
.m_bFFonly
)
3173 args
+= _T(" --ff-only");
3176 args
+= _T(" --squash");
3179 args
+= _T(" --no-commit");
3182 args
.AppendFormat(L
" --log=%d", dlg
.m_nLog
);
3184 if (!dlg
.m_MergeStrategy
.IsEmpty())
3186 args
+= _T(" --strategy=") + dlg
.m_MergeStrategy
;
3187 if (!dlg
.m_StrategyOption
.IsEmpty())
3189 args
+= _T(" --strategy-option=") + dlg
.m_StrategyOption
;
3190 if (!dlg
.m_StrategyParam
.IsEmpty())
3191 args
+= _T("=") + dlg
.m_StrategyParam
;
3195 if(!dlg
.m_strLogMesage
.IsEmpty())
3197 CString logmsg
= dlg
.m_strLogMesage
;
3198 logmsg
.Replace(_T("\\\""), _T("\\\\\""));
3199 logmsg
.Replace(_T("\""), _T("\\\""));
3200 args
+= _T(" -m \"") + logmsg
+ _T("\"");
3202 cmd
.Format(_T("git.exe merge%s %s"), (LPCTSTR
)args
, (LPCTSTR
)g_Git
.FixBranchName(dlg
.m_VersionName
));
3204 CProgressDlg Prodlg
;
3205 Prodlg
.m_GitCmd
= cmd
;
3207 Prodlg
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3211 int hasConflicts
= g_Git
.HasWorkingTreeConflicts();
3212 if (hasConflicts
< 0)
3213 CMessageBox::Show(nullptr, g_Git
.GetGitLastErr(L
"Checking for conflicts failed.", CGit::GIT_CMD_CHECKCONFLICTS
), _T("TortoiseGit"), MB_ICONEXCLAMATION
);
3214 else if (hasConflicts
)
3216 // there are conflict files
3218 postCmdList
.emplace_back(IDI_RESOLVE
, IDS_PROGRS_CMD_RESOLVE
, []
3221 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3222 CAppUtils::RunTortoiseGitProc(sCmd
);
3226 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSTASHSAVE
, [&]{ CAppUtils::StashSave(_T(""), false, false, true, g_Git
.FixBranchName(dlg
.m_VersionName
)); });
3231 postCmdList
.emplace_back(IDI_RELOCATE
, IDS_MENUSTASHPOP
, []{ StashPop(); });
3233 if (dlg
.m_bNoCommit
)
3235 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUCOMMIT
, []
3238 sCmd
.Format(_T("/command:commit /path:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3239 CAppUtils::RunTortoiseGitProc(sCmd
);
3244 if (dlg
.m_bIsBranch
&& dlg
.m_VersionName
.Find(L
"remotes/") == -1) // do not ask to remove remote branches
3246 postCmdList
.emplace_back(IDI_DELETE
, IDS_PROC_REMOVEBRANCH
, [&]
3249 msg
.Format(IDS_PROC_DELETEBRANCHTAG
, dlg
.m_VersionName
);
3250 if (CMessageBox::Show(nullptr, msg
, _T("TortoiseGit"), 2, IDI_QUESTION
, CString(MAKEINTRESOURCE(IDS_DELETEBUTTON
)), CString(MAKEINTRESOURCE(IDS_ABORTBUTTON
))) == 1)
3253 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)dlg
.m_VersionName
);
3254 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3255 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
);
3259 if (dlg
.m_bIsBranch
)
3260 postCmdList
.emplace_back(IDI_PUSH
, IDS_MENUPUSH
, []{ Push(); });
3262 BOOL hasGitSVN
= CTGitPath(g_Git
.m_CurrentDir
).GetAdminDirMask() & ITEMIS_GITSVN
;
3264 postCmdList
.emplace_back(IDI_COMMIT
, IDS_MENUSVNDCOMMIT
, []{ SVNDCommit(); });
3268 return !Prodlg
.m_GitStatus
;
3273 BOOL
CAppUtils::MergeAbort()
3276 if (dlg
.DoModal() == IDOK
)
3277 return Reset(_T("HEAD"), dlg
.m_ResetType
+ 1);
3282 void CAppUtils::EditNote(GitRevLoglist
* rev
)
3284 if (!CheckUserData())
3288 dlg
.m_sHintText
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3289 dlg
.m_sInputText
= rev
->m_Notes
;
3290 dlg
.m_sTitle
= CString(MAKEINTRESOURCE(IDS_PROGS_TITLE_EDITNOTES
));
3291 //dlg.m_pProjectProperties = &m_ProjectProperties;
3292 dlg
.m_bUseLogWidth
= true;
3293 if(dlg
.DoModal() == IDOK
)
3296 cmd
=_T("notes add -f -F \"");
3298 CString tempfile
=::GetTempFile();
3299 if (CAppUtils::SaveCommitUnicodeFile(tempfile
, dlg
.m_sInputText
))
3301 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3306 cmd
+= rev
->m_CommitHash
.ToString();
3310 if (git_run_cmd("notes", CUnicodeUtils::GetMulti(cmd
, CP_UTF8
).GetBuffer()))
3311 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3313 rev
->m_Notes
= dlg
.m_sInputText
;
3316 CMessageBox::Show(nullptr, IDS_PROC_FAILEDSAVINGNOTES
, IDS_APPNAME
, MB_OK
| MB_ICONERROR
);
3318 ::DeleteFile(tempfile
);
3323 int CAppUtils::GetMsysgitVersion()
3325 if (g_Git
.ms_LastMsysGitVersion
)
3326 return g_Git
.ms_LastMsysGitVersion
;
3329 CString versiondebug
;
3332 CRegDWORD regTime
= CRegDWORD(_T("Software\\TortoiseGit\\git_file_time"));
3333 CRegDWORD regVersion
= CRegDWORD(_T("Software\\TortoiseGit\\git_cached_version"));
3335 CString gitpath
= CGit::ms_LastMsysGitDir
+_T("\\git.exe");
3338 if (!CGit::GetFileModifyTime(gitpath
, &time
))
3340 if((DWORD
)time
== regTime
)
3342 g_Git
.ms_LastMsysGitVersion
= regVersion
;
3348 int ver
= g_Git
.GetGitVersion(&versiondebug
, &err
);
3351 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
);
3358 CMessageBox::Show(nullptr, _T("Could not parse git.exe version number: \"") + versiondebug
+ _T("\""), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3363 regTime
= time
&0xFFFFFFFF;
3365 g_Git
.ms_LastMsysGitVersion
= ver
;
3370 void CAppUtils::MarkWindowAsUnpinnable(HWND hWnd
)
3372 typedef HRESULT (WINAPI
*SHGPSFW
) (HWND hwnd
,REFIID riid
,void** ppv
);
3374 CAutoLibrary hShell
= AtlLoadSystemLibraryUsingFullPath(_T("Shell32.dll"));
3376 if (hShell
.IsValid()) {
3377 SHGPSFW pfnSHGPSFW
= (SHGPSFW
)::GetProcAddress(hShell
, "SHGetPropertyStoreForWindow");
3379 IPropertyStore
*pps
;
3380 HRESULT hr
= pfnSHGPSFW(hWnd
, IID_PPV_ARGS(&pps
));
3381 if (SUCCEEDED(hr
)) {
3384 var
.boolVal
= VARIANT_TRUE
;
3385 pps
->SetValue(PKEY_AppUserModel_PreventPinning
, var
);
3392 void CAppUtils::SetWindowTitle(HWND hWnd
, const CString
& urlorpath
, const CString
& dialogname
)
3394 ASSERT(dialogname
.GetLength() < 70);
3395 ASSERT(urlorpath
.GetLength() < MAX_PATH
);
3396 WCHAR pathbuf
[MAX_PATH
] = {0};
3398 PathCompactPathEx(pathbuf
, urlorpath
, 70 - dialogname
.GetLength(), 0);
3400 wcscat_s(pathbuf
, L
" - ");
3401 wcscat_s(pathbuf
, dialogname
);
3402 wcscat_s(pathbuf
, L
" - ");
3403 wcscat_s(pathbuf
, CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3404 SetWindowText(hWnd
, pathbuf
);
3407 bool CAppUtils::BisectStart(const CString
& lastGood
, const CString
& firstBad
, bool bIsMainWnd
)
3409 if (!g_Git
.CheckCleanWorkTree())
3411 if (CMessageBox::Show(nullptr, IDS_ERROR_NOCLEAN_STASH
, IDS_APPNAME
, 1, IDI_QUESTION
, IDS_STASHBUTTON
, IDS_ABORTBUTTON
) == 1)
3413 CSysProgressDlg sysProgressDlg
;
3414 sysProgressDlg
.SetTitle(CString(MAKEINTRESOURCE(IDS_APPNAME
)));
3415 sysProgressDlg
.SetLine(1, CString(MAKEINTRESOURCE(IDS_PROC_STASHRUNNING
)));
3416 sysProgressDlg
.SetLine(2, CString(MAKEINTRESOURCE(IDS_PROGRESSWAIT
)));
3417 sysProgressDlg
.SetShowProgressBar(false);
3418 sysProgressDlg
.SetCancelMsg(IDS_PROGRS_INFOFAILED
);
3419 sysProgressDlg
.ShowModeless((HWND
)nullptr, true);
3422 cmd
= _T("git.exe stash");
3423 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
3425 sysProgressDlg
.Stop();
3426 MessageBox(nullptr, out
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3429 sysProgressDlg
.Stop();
3435 CBisectStartDlg bisectStartDlg
;
3437 if (!lastGood
.IsEmpty())
3438 bisectStartDlg
.m_sLastGood
= lastGood
;
3439 if (!firstBad
.IsEmpty())
3440 bisectStartDlg
.m_sFirstBad
= firstBad
;
3442 if (bisectStartDlg
.DoModal() == IDOK
)
3444 CProgressDlg progress
;
3446 theApp
.m_pMainWnd
= &progress
;
3447 progress
.m_GitCmdList
.push_back(_T("git.exe bisect start"));
3448 progress
.m_GitCmdList
.push_back(_T("git.exe bisect good ") + bisectStartDlg
.m_LastGoodRevision
);
3449 progress
.m_GitCmdList
.push_back(_T("git.exe bisect bad ") + bisectStartDlg
.m_FirstBadRevision
);
3451 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3456 CTGitPath
path(g_Git
.m_CurrentDir
);
3457 if (path
.HasSubmodules())
3459 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3462 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3463 CAppUtils::RunTortoiseGitProc(sCmd
);
3468 INT_PTR ret
= progress
.DoModal();
3475 bool CAppUtils::BisectOperation(const CString
& op
, const CString
& ref
, bool bIsMainWnd
)
3477 CString cmd
= _T("git.exe bisect ") + op
;
3485 CProgressDlg progress
;
3487 theApp
.m_pMainWnd
= &progress
;
3488 progress
.m_GitCmd
= cmd
;
3490 progress
.m_PostCmdCallback
= [&](DWORD status
, PostCmdList
& postCmdList
)
3495 CTGitPath path
= g_Git
.m_CurrentDir
;
3496 if (path
.HasSubmodules())
3498 postCmdList
.emplace_back(IDI_UPDATE
, IDS_PROC_SUBMODULESUPDATE
, []
3501 sCmd
.Format(_T("/command:subupdate /bkpath:\"%s\""), (LPCTSTR
)g_Git
.m_CurrentDir
);
3502 CAppUtils::RunTortoiseGitProc(sCmd
);
3506 if (op
!= _T("reset"))
3507 postCmdList
.emplace_back(IDS_MENUBISECTRESET
, []{ CAppUtils::RunTortoiseGitProc(_T("/command:bisect /reset")); });
3510 INT_PTR ret
= progress
.DoModal();
3514 int CAppUtils::Git2GetUserPassword(git_cred
**out
, const char *url
, const char *username_from_url
, unsigned int /*allowed_types*/, void * /*payload*/)
3517 dlg
.m_URL
= CUnicodeUtils::GetUnicode(url
, CP_UTF8
);
3518 if (username_from_url
)
3519 dlg
.m_UserName
= CUnicodeUtils::GetUnicode(username_from_url
, CP_UTF8
);
3521 CStringA username
, password
;
3522 if (dlg
.DoModal() == IDOK
)
3524 username
= CUnicodeUtils::GetMulti(dlg
.m_UserName
, CP_UTF8
);
3525 password
= CUnicodeUtils::GetMulti(dlg
.m_Password
, CP_UTF8
);
3526 return git_cred_userpass_plaintext_new(out
, username
, password
);
3528 giterr_set_str(GITERR_NONE
, "User cancelled.");
3532 int CAppUtils::Git2CertificateCheck(git_cert
* base_cert
, int /*valid*/, const char* host
, void* /*payload*/)
3534 if (base_cert
->cert_type
== GIT_CERT_X509
)
3536 git_cert_x509
* cert
= (git_cert_x509
*)base_cert
;
3538 if (last_accepted_cert
.cmp(cert
))
3541 PCCERT_CONTEXT pServerCert
= CertCreateCertificateContext(X509_ASN_ENCODING
| PKCS_7_ASN_ENCODING
, (BYTE
*)cert
->data
, (DWORD
)cert
->len
);
3542 SCOPE_EXIT
{ CertFreeCertificateContext(pServerCert
); };
3544 DWORD verificationError
= VerifyServerCertificate(pServerCert
, CUnicodeUtils::GetUnicode(host
).GetBuffer(), 0);
3545 if (!verificationError
)
3547 last_accepted_cert
.set(cert
);
3551 CString servernameInCert
;
3552 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, 0, nullptr, CStrBuf(servernameInCert
, 128), 128);
3555 CertGetNameString(pServerCert
, CERT_NAME_SIMPLE_DISPLAY_TYPE
, CERT_NAME_ISSUER_FLAG
, nullptr, CStrBuf(issuer
, 128), 128);
3557 CCheckCertificateDlg dlg
;
3559 dlg
.m_sCertificateCN
= servernameInCert
;
3560 dlg
.m_sCertificateIssuer
= issuer
;
3561 dlg
.m_sHostname
= CUnicodeUtils::GetUnicode(host
);
3562 dlg
.m_sError
= CFormatMessageWrapper(verificationError
);
3563 if (dlg
.DoModal() == IDOK
)
3565 last_accepted_cert
.set(cert
);
3569 return GIT_ECERTIFICATE
;
3572 int CAppUtils::ExploreTo(HWND hwnd
, CString path
)
3574 if (PathFileExists(path
))
3577 ITEMIDLIST __unaligned
* pidl
= ILCreateFromPath(path
);
3580 ret
= SHOpenFolderAndSelectItems(pidl
, 0, 0, 0);
3583 return SUCCEEDED(ret
) ? 0 : -1;
3585 // if filepath does not exist any more, navigate to closest matching folder
3588 int pos
= path
.ReverseFind(_T('\\'));
3591 path
= path
.Left(pos
);
3592 } while (!PathFileExists(path
));
3593 return (INT_PTR
)ShellExecute(hwnd
, _T("explore"), path
, nullptr, nullptr, SW_SHOW
) > 32 ? 0 : -1;
3596 int CAppUtils::ResolveConflict(CTGitPath
& path
, resolve_with resolveWith
)
3598 bool b_local
= false, b_remote
= false;
3602 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3603 if (g_Git
.Run(cmd
, &vector
))
3605 CMessageBox::Show(nullptr, _T("git ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3610 if (list
.ParserFromLsFile(vector
))
3612 CMessageBox::Show(nullptr, _T("Parse ls-files failed!"), _T("TortoiseGit"), MB_OK
);
3618 for (int i
= 0; i
< list
.GetCount(); ++i
)
3620 if (list
[i
].m_Stage
== 2)
3622 if (list
[i
].m_Stage
== 3)
3627 CBlockCacheForPath
block(g_Git
.m_CurrentDir
);
3628 if (path
.IsDirectory()) // is submodule conflict
3630 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.");
3631 if (b_local
&& b_remote
)
3633 if (!path
.HasAdminDir()) // check if submodule is initialized
3635 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).");
3636 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3640 subgit
.m_CurrentDir
= g_Git
.CombinePath(path
);
3641 CGitHash submoduleHead
;
3642 if (subgit
.GetHash(submoduleHead
, _T("HEAD")))
3644 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3647 CString baseHash
, localHash
, remoteHash
;
3648 ParseHashesFromLsFile(vector
, baseHash
, localHash
, remoteHash
);
3649 if (resolveWith
== RESOLVE_WITH_THEIRS
&& submoduleHead
.ToString() != remoteHash
)
3651 CString origPath
= g_Git
.m_CurrentDir
;
3652 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3653 if (!GitReset(&remoteHash
))
3655 g_Git
.m_CurrentDir
= origPath
;
3658 g_Git
.m_CurrentDir
= origPath
;
3660 else if (resolveWith
== RESOLVE_WITH_MINE
&& submoduleHead
.ToString() != localHash
)
3662 CString origPath
= g_Git
.m_CurrentDir
;
3663 g_Git
.m_CurrentDir
= g_Git
.CombinePath(path
);
3664 if (!GitReset(&localHash
))
3666 g_Git
.m_CurrentDir
= origPath
;
3669 g_Git
.m_CurrentDir
= origPath
;
3674 MessageBox(nullptr, err
, _T("TortoiseGit"), MB_ICONERROR
);
3679 if (resolveWith
== RESOLVE_WITH_THEIRS
)
3681 CString gitcmd
, output
;
3682 if (b_local
&& b_remote
)
3683 gitcmd
.Format(_T("git.exe checkout-index -f --stage=3 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3685 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3687 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3688 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3690 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3694 else if (resolveWith
== RESOLVE_WITH_MINE
)
3696 CString gitcmd
, output
;
3697 if (b_local
&& b_remote
)
3698 gitcmd
.Format(_T("git.exe checkout-index -f --stage=2 -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3700 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3702 gitcmd
.Format(_T("git.exe rm -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3703 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3705 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3710 if (b_local
&& b_remote
&& path
.m_Action
& CTGitPath::LOGACTIONS_UNMERGED
)
3712 CString gitcmd
, output
;
3713 gitcmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
3714 if (g_Git
.Run(gitcmd
, &output
, CP_UTF8
))
3715 CMessageBox::Show(nullptr, output
, _T("TortoiseGit"), MB_ICONERROR
);
3718 path
.m_Action
|= CTGitPath::LOGACTIONS_MODIFIED
;
3719 path
.m_Action
&= ~CTGitPath::LOGACTIONS_UNMERGED
;
3723 RemoveTempMergeFile(path
);
3727 bool CAppUtils::ShellOpen(const CString
& file
, HWND hwnd
/*= nullptr */)
3729 if ((INT_PTR
)ShellExecute(hwnd
, nullptr, file
, nullptr, nullptr, SW_SHOW
) > HINSTANCE_ERROR
)
3732 return ShowOpenWithDialog(file
, hwnd
);
3735 bool CAppUtils::ShowOpenWithDialog(const CString
& file
, HWND hwnd
/*= nullptr */)
3737 OPENASINFO oi
= { 0 };
3739 oi
.oaifInFlags
= OAIF_EXEC
;
3740 return SUCCEEDED(SHOpenWithDialog(hwnd
, &oi
));
3743 bool CAppUtils::IsTGitRebaseActive()
3746 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3749 if (!PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3752 if (CMessageBox::Show(nullptr, IDS_REBASELOCKFILEFOUND
, IDS_APPNAME
, 2, IDI_EXCLAMATION
, IDS_REMOVESTALEBUTTON
, IDS_ABORTBUTTON
) == 2)
3755 RemoveDirectory(adminDir
+ L
"tgitrebase.active");