1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "GitForWindows.h"
24 #include "UnicodeUtils.h"
28 #include "FormatMessageWrapper.h"
29 #include "SmartHandle.h"
30 #include "MassiveGitTaskBase.h"
31 #include "git2/sys/filter.h"
32 #include "git2/sys/transport.h"
33 #include "../libgit2/filter-filter.h"
34 #include "../libgit2/ssh-wintunnel.h"
36 bool CGit::ms_bCygwinGit
= (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE
) == TRUE
);
37 bool CGit::ms_bMsys2Git
= (CRegDWORD(_T("Software\\TortoiseGit\\Msys2Hack"), FALSE
) == TRUE
);
38 int CGit::m_LogEncode
=CP_UTF8
;
39 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
41 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
43 if (!path
|| !buf
|| buflen
== 0)
46 const wchar_t* base
= path
;
47 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
49 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
52 *buf
= L
'\0'; /* reserved a byte via initial subtract */
54 while (*path
== term
|| *path
== L
';')
57 return (path
!= base
) ? path
: nullptr;
60 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
62 TCHAR buf
[MAX_PATH
] = { 0 };
64 // search in all paths defined in PATH
65 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != nullptr && *buf
)
67 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
69 // ensure trailing slash
70 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
71 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
73 const size_t len
= _tcslen(buf
);
75 if ((len
+ filename
.GetLength()) < MAX_PATH
)
76 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
80 if (PathFileExists(buf
))
91 static BOOL
FindGitPath()
94 _tgetenv_s(&size
, nullptr, 0, _T("PATH"));
98 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
101 _tgetenv_s(&size
, env
, size
, _T("PATH"));
103 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
104 if (!gitExeDirectory
.IsEmpty())
106 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
107 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
108 if (CGit::ms_LastMsysGitDir
.GetLength() > 12 && (CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw64\\bin")))
110 // prefer cmd directory as early Git for Windows 2.x releases only had this
111 CString installRoot
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd\\git.exe");
112 if (PathFileExists(installRoot
))
113 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd");
115 if (CGit::ms_LastMsysGitDir
.GetLength() > 4 && CGit::ms_LastMsysGitDir
.Right(4) == _T("\\cmd"))
117 // often the msysgit\cmd folder is on the %PATH%, but
118 // that git.exe does not work, so try to guess the bin folder
119 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
120 if (PathFileExists(binDir
))
121 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
129 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
131 CString filename
= executable
;
133 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
134 filename
+= _T(".exe");
136 if (PathFileExists(filename
))
139 filename
= FindFileOnPath(filename
, env
);
140 if (!filename
.IsEmpty())
146 static bool g_bSortLogical
;
147 static bool g_bSortLocalBranchesFirst
;
148 static bool g_bSortTagsReversed
;
149 static git_cred_acquire_cb g_Git2CredCallback
;
150 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
152 static void GetSortOptions()
154 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
156 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
157 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
158 if (g_bSortLocalBranchesFirst
)
159 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
160 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
161 if (!g_bSortTagsReversed
)
162 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
165 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
168 return StrCmpLogicalW(left
, right
) < 0;
169 return StrCmpI(left
, right
) < 0;
172 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
175 return StrCmpLogicalW(left
, right
) > 0;
176 return StrCmpI(left
, right
) > 0;
179 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
181 if (g_bSortLocalBranchesFirst
)
183 int leftIsRemote
= left
.Find(_T("remotes/"));
184 int rightIsRemote
= right
.Find(_T("remotes/"));
186 if (leftIsRemote
== 0 && rightIsRemote
< 0)
188 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
192 return StrCmpLogicalW(left
, right
) < 0;
193 return StrCmpI(left
, right
) < 0;
196 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
198 CString
CGit::ms_LastMsysGitDir
;
199 CString
CGit::ms_MsysGitRootDir
;
200 int CGit::ms_LastMsysGitVersion
= 0;
207 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
208 m_IsGitDllInited
= false;
210 m_GitSimpleListDiff
=0;
211 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
212 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
213 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
215 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
218 this->m_bInitialized
=false;
220 m_critGitDllSec
.Init();
227 git_close_diff(m_GitDiff
);
230 if(this->m_GitSimpleListDiff
)
232 git_close_diff(m_GitSimpleListDiff
);
233 m_GitSimpleListDiff
=0;
235 git_libgit2_shutdown();
238 bool CGit::IsBranchNameValid(const CString
& branchname
)
240 if (branchname
.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
242 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
244 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
245 return !!git_reference_is_valid_name(branchA
);
248 static bool IsPowerShell(CString cmd
)
251 int powerShellPos
= cmd
.Find(_T("powershell"));
252 if (powerShellPos
< 0)
255 // found the word powershell, check that it is the command and not any parameter
256 int end
= cmd
.GetLength();
257 if (cmd
.Find(_T('"')) == 0)
259 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
260 if (secondDoubleQuote
> 0)
261 end
= secondDoubleQuote
;
265 int firstSpace
= cmd
.Find(_T(' '));
270 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
273 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
275 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
276 CAutoGeneralHandle hStdioFile
;
278 SECURITY_ATTRIBUTES sa
= { 0 };
279 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
280 sa
.bInheritHandle
=TRUE
;
281 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
283 CString err
= CFormatMessageWrapper();
284 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
285 return TGIT_GIT_ERROR_OPEN_PIP
;
287 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
289 CString err
= CFormatMessageWrapper();
290 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
291 return TGIT_GIT_ERROR_OPEN_PIP
;
295 hStdioFile
= CreateFile(*StdioFile
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
297 STARTUPINFO si
= { 0 };
298 PROCESS_INFORMATION pi
= { 0 };
299 si
.cb
=sizeof(STARTUPINFO
);
302 si
.hStdError
= hWriteErr
;
304 si
.hStdError
= hWrite
;
306 si
.hStdOutput
=hStdioFile
;
308 si
.hStdOutput
=hWrite
;
310 si
.wShowWindow
=SW_HIDE
;
311 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
313 LPTSTR pEnv
= m_Environment
;
314 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
316 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
318 // CREATE_NEW_CONSOLE makes git (but not ssh.exe, see issue #2257) recognize that it has no console in order to launch askpass to ask for the password,
319 // DETACHED_PROCESS which was originally used here has the same effect (but works with git.exe AND ssh.exe), however, it prevents PowerShell from working (cf. issue #2143)
320 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
321 if (IsPowerShell(cmd
))
322 dwFlags
|= CREATE_NEW_CONSOLE
;
324 dwFlags
|= DETACHED_PROCESS
;
326 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
328 if (ms_bMsys2Git
&& cmd
.Find(_T("git")) == 0 && cmd
.Find(L
"git.exe config ") == -1)
330 cmd
.Replace(_T("\\"), _T("\\\\\\\\"));
331 cmd
.Replace(_T("\""), _T("\\\""));
332 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/usr/bin/") + cmd
+ _T('"');
334 else if (ms_bCygwinGit
&& cmd
.Find(_T("git")) == 0 && cmd
.Find(L
"git.exe config ") == -1)
336 cmd
.Replace(_T('\\'), _T('/'));
337 cmd
.Replace(_T("\""), _T("\\\""));
338 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
340 else if (cmd
.Find(_T("git")) == 0 || cmd
.Find(_T("bash")) == 0)
342 int firstSpace
= cmd
.Find(_T(" "));
344 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
346 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
349 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
350 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
352 CString err
= CFormatMessageWrapper();
353 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), (LPCTSTR
)err
.Trim());
354 return TGIT_GIT_ERROR_CREATE_PROCESS
;
362 *hReadOut
= hRead
.Detach();
364 *hErrReadOut
= hReadErr
.Detach();
367 //Must use sperate function to convert ANSI str to union code string
368 //Becuase A2W use stack as internal convert buffer.
369 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
376 len
= (int)strlen((const char*)p
);
381 int currentContentLen
= str
->GetLength();
382 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
383 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
384 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
387 // This method was originally used to check for orphaned branches
388 BOOL
CGit::CanParseRev(CString ref
)
394 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
402 // Checks if we have an orphaned HEAD
403 BOOL
CGit::IsInitRepos()
406 if (GetHash(hash
, _T("HEAD")) != 0)
408 return hash
.IsEmpty() ? TRUE
: FALSE
;
411 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
413 PASYNCREADSTDERRTHREADARGS pDataArray
;
414 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
417 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
418 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
420 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
427 int CGit::Run(CGitCall
* pcall
)
429 PROCESS_INFORMATION pi
;
430 CAutoGeneralHandle hRead
, hReadErr
;
431 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
432 return TGIT_GIT_ERROR_CREATE_PROCESS
;
434 CAutoGeneralHandle
piThread(pi
.hThread
);
435 CAutoGeneralHandle
piProcess(pi
.hProcess
);
437 ASYNCREADSTDERRTHREADARGS threadArguments
;
438 threadArguments
.fileHandle
= hReadErr
;
439 threadArguments
.pcall
= pcall
;
440 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
443 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
445 while (ReadFile(hRead
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
447 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
448 if(!bAborted
)//For now, flush output when command aborted.
449 if(pcall
->OnOutputData(data
,readnumber
))
456 WaitForSingleObject(thread
, INFINITE
);
458 WaitForSingleObject(pi
.hProcess
, INFINITE
);
461 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
463 CString err
= CFormatMessageWrapper();
464 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
465 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
468 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
472 class CGitCall_ByteVector
: public CGitCall
475 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= nullptr) : CGitCall(cmd
),m_pvector(pvector
), m_pvectorErr(pvectorErr
) {}
476 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
478 if (!m_pvector
|| size
== 0)
480 size_t oldsize
=m_pvector
->size();
481 m_pvector
->resize(m_pvector
->size()+size
);
482 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
485 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
487 if (!m_pvectorErr
|| size
== 0)
489 size_t oldsize
= m_pvectorErr
->size();
490 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
491 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
494 BYTE_VECTOR
* m_pvector
;
495 BYTE_VECTOR
* m_pvectorErr
;
497 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
499 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
502 int CGit::Run(CString cmd
, CString
* output
, int code
)
506 ret
= Run(cmd
, output
, &err
, code
);
508 if (output
&& !err
.IsEmpty())
510 if (!output
->IsEmpty())
517 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
519 BYTE_VECTOR vector
, vectorErr
;
522 ret
= Run(cmd
, &vector
, &vectorErr
);
524 ret
= Run(cmd
, &vector
);
527 StringAppend(output
, &(vector
[0]), code
);
531 vectorErr
.push_back(0);
532 StringAppend(outputErr
, &(vectorErr
[0]), code
);
538 class CGitCallCb
: public CGitCall
541 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
, BYTE_VECTOR
* pvectorErr
= nullptr)
544 , m_pvectorErr(pvectorErr
)
547 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
552 int oldEndPos
= m_buffer
.GetLength();
553 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
554 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
556 // Break into lines and feed to m_recv
558 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
560 m_recv(m_buffer
.Left(eolPos
));
561 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
566 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
568 if (!m_pvectorErr
|| size
== 0)
570 size_t oldsize
= m_pvectorErr
->size();
571 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
572 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
576 virtual void OnEnd() override
578 if (!m_buffer
.IsEmpty())
580 m_buffer
.Empty(); // Just for sure
584 GitReceiverFunc m_recv
;
586 BYTE_VECTOR
* m_pvectorErr
;
589 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
, CString
* outputErr
)
593 BYTE_VECTOR vectorErr
;
594 CGitCallCb
call(cmd
, recv
, &vectorErr
);
595 int ret
= Run(&call
);
596 vectorErr
.push_back(0);
597 StringAppend(outputErr
, &(vectorErr
[0]));
601 CGitCallCb
call(cmd
, recv
);
605 CString
CGit::GetUserName(void)
608 env
.CopyProcessEnvironment();
609 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
610 if (!envname
.IsEmpty())
612 return GetConfigValue(L
"user.name");
614 CString
CGit::GetUserEmail(void)
617 env
.CopyProcessEnvironment();
618 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
619 if (!envmail
.IsEmpty())
622 return GetConfigValue(L
"user.email");
625 CString
CGit::GetConfigValue(const CString
& name
, const CString
& def
, bool wantBool
)
628 if(this->m_IsUseGitDLL
)
630 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
639 key
= CUnicodeUtils::GetUTF8(name
);
643 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
646 catch (const char *msg
)
648 ::MessageBox(nullptr, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
652 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
658 cmd
.Format(L
"git.exe config%s %s", wantBool
? _T(" --bool") : _T(""), (LPCTSTR
)name
);
659 if (Run(cmd
, &configValue
, nullptr, CP_UTF8
))
661 if (configValue
.IsEmpty())
663 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
667 bool CGit::GetConfigValueBool(const CString
& name
, const bool def
)
669 CString configValue
= GetConfigValue(name
, def
? _T("true") : _T("false"), true);
670 configValue
.MakeLower();
672 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
678 int CGit::GetConfigValueInt32(const CString
& name
, const int def
)
680 CString configValue
= GetConfigValue(name
);
682 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
687 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
689 if(this->m_IsUseGitDLL
)
691 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
699 CStringA keya
, valuea
;
700 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
701 valuea
= CUnicodeUtils::GetUTF8(value
);
705 return [=]() { return get_set_config(keya
, valuea
, type
); }();
707 catch (const char *msg
)
709 ::MessageBox(nullptr, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
720 option
= _T("--global");
723 option
= _T("--system");
728 CString mangledValue
= value
;
729 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
730 mangledValue
.Replace(_T("\""), _T("\\\""));
731 cmd
.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
733 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
739 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
741 if(this->m_IsUseGitDLL
)
743 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
752 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
756 return [=]() { return get_set_config(keya
, nullptr, type
); }();
758 catch (const char *msg
)
760 ::MessageBox(nullptr, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
771 option
= _T("--global");
774 option
= _T("--system");
779 cmd
.Format(_T("git.exe config %s --unset %s"), (LPCTSTR
)option
, (LPCTSTR
)key
);
781 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
787 CString
CGit::GetCurrentBranch(bool fallback
)
790 //Run(_T("git.exe branch"),&branch);
792 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
793 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
794 return _T("(no branch)");
799 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
801 if (localBranch
.IsEmpty())
805 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
806 pullRemote
= GetConfigValue(configName
);
808 //Select pull-branch from current branch
809 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
810 pullBranch
= StripRefName(GetConfigValue(configName
));
813 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
816 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
818 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
821 void CGit::GetRemotePushBranch(const CString
& localBranch
, CString
& pushRemote
, CString
& pushBranch
)
823 if (localBranch
.IsEmpty())
828 configName
.Format(L
"branch.%s.pushremote", (LPCTSTR
)localBranch
);
829 pushRemote
= g_Git
.GetConfigValue(configName
);
830 if (pushRemote
.IsEmpty())
832 pushRemote
= g_Git
.GetConfigValue(L
"remote.pushdefault");
833 if (pushRemote
.IsEmpty())
835 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
836 pushRemote
= g_Git
.GetConfigValue(configName
);
840 configName
.Format(L
"branch.%s.pushbranch", (LPCTSTR
)localBranch
);
841 pushBranch
= g_Git
.GetConfigValue(configName
); // do not strip branch name (for gerrit), see issue #1609)
842 if (pushBranch
.IsEmpty())
844 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
845 pushBranch
= CGit::StripRefName(g_Git
.GetConfigValue(configName
));
849 CString
CGit::GetFullRefName(const CString
& shortRefName
)
853 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
854 if (Run(cmd
, &refName
, nullptr, CP_UTF8
) != 0)
855 return CString();//Error
856 return refName
.TrimRight();
859 CString
CGit::StripRefName(CString refName
)
861 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
862 refName
= refName
.Mid(11);
863 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
864 refName
= refName
.Mid(5);
865 return refName
.TrimRight();
868 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
870 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
872 if ( sProjectRoot
.IsEmpty() )
876 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
879 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
881 CAutoFILE pFile
= _tfsopen(sHeadFile
.GetString(), _T("r"), SH_DENYWR
);
886 fgets(s
, sizeof(s
), pFile
);
888 const char *pfx
= "ref: refs/heads/";
889 const int len
= 16;//strlen(pfx)
891 if ( !strncmp(s
, pfx
, len
) )
893 //# We're on a branch. It might not exist. But
894 //# HEAD looks good enough to be a branch.
895 CStringA
utf8Branch(s
+ len
);
896 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
897 sBranchOut
.TrimRight(_T(" \r\n\t"));
899 if ( sBranchOut
.IsEmpty() )
904 CStringA
utf8Hash(s
);
905 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
906 unicodeHash
.TrimRight(_T(" \r\n\t"));
907 if (CGitHash::IsValidSHA1(unicodeHash
))
908 sBranchOut
= unicodeHash
;
910 //# Assume this is a detached head.
911 sBranchOut
= _T("HEAD");
916 //# Assume this is a detached head.
925 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
928 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
932 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
934 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
936 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
938 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
940 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
942 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
944 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
948 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
950 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
952 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
957 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
963 CString
CGit::GetLogCmd(const CString
& range
, const CTGitPath
* path
, int mask
,
968 if(mask
& LOG_INFO_STAT
)
969 param
+= _T(" --numstat");
970 if(mask
& LOG_INFO_FILESTATE
)
971 param
+= _T(" --raw");
973 if(mask
& LOG_INFO_FULLHISTORY
)
974 param
+= _T(" --full-history");
976 if(mask
& LOG_INFO_BOUNDARY
)
977 param
+= _T(" --left-right --boundary");
979 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
980 param
+= _T(" --all");
982 if (mask
& CGit::LOG_INFO_BASIC_REFS
)
984 param
+= _T(" --branches");
985 param
+= _T(" --tags");
986 param
+= _T(" --remotes");
987 param
+= _T(" --glob=stas[h]"); // require at least one glob operator
988 param
+= _T(" --glob=bisect");
991 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
992 param
+= _T(" --branches");
994 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
997 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
1000 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
1001 param
+= _T(" --first-parent");
1003 if(mask
& CGit::LOG_INFO_NO_MERGE
)
1004 param
+= _T(" --no-merges");
1006 if(mask
& CGit::LOG_INFO_FOLLOW
)
1007 param
+= _T(" --follow");
1009 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
1012 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
1013 param
+= _T(" --full-diff");
1015 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
1016 param
+= _T(" --simplify-by-decoration");
1020 if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_N_YEARS
)
1022 CTime now
= CTime::GetCurrentTime();
1023 CTime time
= CTime(now
.GetYear(), now
.GetMonth(), now
.GetDay(), 0, 0, 0);
1024 __time64_t substract
= 86400;
1026 switch (Filter
->m_NumberOfLogsScale
)
1028 case CFilterData::SHOW_LAST_N_YEARS
:
1031 case CFilterData::SHOW_LAST_N_MONTHS
:
1034 case CFilterData::SHOW_LAST_N_WEEKS
:
1038 Filter
->m_From
= (DWORD
)time
.GetTime() - (Filter
->m_NumberOfLogs
* substract
);
1040 if (Filter
->m_NumberOfLogsScale
== CFilterData::SHOW_LAST_N_COMMITS
)
1041 param
.AppendFormat(L
" -n%ld", Filter
->m_NumberOfLogs
);
1042 else if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_SEL_DATE
&& Filter
->m_From
> 0)
1043 param
.AppendFormat(L
" --max-age=%I64u", Filter
->m_From
);
1046 if( Filter
&& (Filter
->m_To
!= -1))
1047 param
.AppendFormat(L
" --min-age=%I64u", Filter
->m_To
);
1049 bool isgrep
= false;
1050 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1052 param
.AppendFormat(L
" --author=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1056 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1058 param
.AppendFormat(L
" --committer=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1062 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1064 param
.AppendFormat(L
" --grep=\"%s\"", (LPCTSTR
)Filter
->m_MessageFilter
);
1068 if(Filter
&& isgrep
)
1070 if(!Filter
->m_IsRegex
)
1071 param
+= _T(" --fixed-strings");
1073 param
+= _T(" --regexp-ignore-case --extended-regexp");
1076 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1077 if (logOrderBy
== LOG_ORDER_TOPOORDER
|| (mask
& CGit::LOG_ORDER_TOPOORDER
))
1078 param
+= _T(" --topo-order");
1079 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1080 param
+= _T(" --date-order");
1085 file
.Format(_T(" \"%s\""), (LPCTSTR
)path
->GetGitPathString());
1086 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1087 cmd
.Format(_T("--ignore-this-parameter -z%s %s --parents --%s"), (LPCTSTR
)param
, (LPCTSTR
)range
, (LPCTSTR
)file
);
1092 void GetTempPath(CString
&path
)
1094 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1096 DWORD dwBufSize
=BUFSIZE
;
1097 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1098 lpPathBuffer
); // buffer for path
1099 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1101 path
.Format(_T("%s"),lpPathBuffer
);
1103 CString
GetTempFile()
1105 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1107 DWORD dwBufSize
=BUFSIZE
;
1108 TCHAR szTempName
[BUFSIZE
] = { 0 };
1111 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1112 lpPathBuffer
); // buffer for path
1113 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1115 // Create a temporary file.
1116 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1117 TEXT("Patch"), // temp file name prefix
1118 0, // create unique name
1119 szTempName
); // buffer for name
1124 return CString(szTempName
);
1127 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1129 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1130 if (result
== 0) return 0;
1131 if (!lpBuffer
|| (result
+ 13 > nBufferLength
))
1138 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1139 CreateDirectory(lpBuffer
, nullptr);
1144 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1147 PROCESS_INFORMATION pi
;
1148 si
.cb
=sizeof(STARTUPINFO
);
1149 GetStartupInfo(&si
);
1151 SECURITY_ATTRIBUTES psa
= {sizeof(psa
), nullptr, TRUE
};
1152 psa
.bInheritHandle
=TRUE
;
1154 CAutoGeneralHandle hReadErr
, hWriteErr
;
1155 if (!CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &psa
, 0))
1157 CString err
= CFormatMessageWrapper();
1158 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
1159 return TGIT_GIT_ERROR_OPEN_PIP
;
1162 CAutoFile houtfile
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &psa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
1165 CString err
= CFormatMessageWrapper();
1166 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
1167 return TGIT_GIT_ERROR_OPEN_PIP
;
1170 si
.wShowWindow
= SW_HIDE
;
1171 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1172 si
.hStdOutput
= houtfile
;
1173 si
.hStdError
= hWriteErr
;
1175 LPTSTR pEnv
= m_Environment
;
1176 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
1178 if(cmd
.Find(_T("git")) == 0)
1179 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1181 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
1182 if (!CreateProcess(nullptr, (LPWSTR
)cmd
.GetString(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, (LPWSTR
)m_CurrentDir
.GetString(), &si
, &pi
))
1184 CString err
= CFormatMessageWrapper();
1185 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), (LPCTSTR
)err
.Trim());
1187 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1190 CAutoGeneralHandle
piThread(pi
.hThread
);
1191 CAutoGeneralHandle
piProcess(pi
.hProcess
);
1193 BYTE_VECTOR stderrVector
;
1194 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1195 ASYNCREADSTDERRTHREADARGS threadArguments
;
1196 threadArguments
.fileHandle
= hReadErr
;
1197 threadArguments
.pcall
= &pcall
;
1198 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1200 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1202 hWriteErr
.CloseHandle();
1203 hReadErr
.CloseHandle();
1206 WaitForSingleObject(thread
, INFINITE
);
1208 stderrVector
.push_back(0);
1209 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1212 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1214 CString err
= CFormatMessageWrapper();
1215 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
1216 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1219 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1224 CAutoRepository
CGit::GetGitRepository() const
1226 return CAutoRepository(GetGitPathStringA(m_CurrentDir
));
1229 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1233 // no need to parse a ref if it's already a 40-byte hash
1234 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1236 hash
= CGitHash(friendname
);
1240 int isHeadOrphan
= git_repository_head_unborn(repo
);
1241 if (isHeadOrphan
!= 0)
1244 if (isHeadOrphan
== 1)
1250 CAutoObject gitObject
;
1251 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1254 const git_oid
* oid
= git_object_id(gitObject
);
1258 hash
= CGitHash((char *)oid
->id
);
1263 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1265 // no need to parse a ref if it's already a 40-byte hash
1266 if (CGitHash::IsValidSHA1(friendname
))
1268 hash
= CGitHash(friendname
);
1274 CAutoRepository
repo(GetGitRepository());
1278 return GetHash(repo
, hash
, friendname
, true);
1282 CString branch
= FixBranchName(friendname
);
1283 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1284 branch
= friendname
;
1286 cmd
.Format(_T("git.exe rev-parse %s"), (LPCTSTR
)branch
);
1288 int ret
= Run(cmd
, &gitLastErr
, nullptr, CP_UTF8
);
1289 hash
= CGitHash(gitLastErr
.Trim());
1292 else if (friendname
== _T("HEAD")) // special check for unborn branch
1294 CString currentbranch
;
1295 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1304 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1309 cmd
=_T("git.exe ls-files -s -t -z");
1311 if (Run(cmd
, &cmdout
))
1314 if (outputlist
.ParserFromLsFile(cmdout
))
1316 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1317 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1321 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1325 if (ignoreSpaceAtEol
)
1326 ignore
+= _T(" --ignore-space-at-eol");
1327 if (ignoreSpaceChange
)
1328 ignore
+= _T(" --ignore-space-change");
1330 ignore
+= _T(" --ignore-all-space");
1331 if (ignoreBlankLines
)
1332 ignore
+= _T(" --ignore-blank-lines");
1334 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1337 if(rev1
== GIT_REV_ZERO
)
1338 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1340 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev1
);
1343 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
, (LPCTSTR
)rev1
);
1349 return outputlist
.ParserFromLog(out
);
1352 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1354 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1355 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1359 int CGit::GetTagList(STRING_VECTOR
&list
)
1361 size_t prevCount
= list
.size();
1362 if (this->m_IsUseLibGit2
)
1364 CAutoRepository
repo(GetGitRepository());
1368 CAutoStrArray tag_names
;
1370 if (git_tag_list(tag_names
, repo
))
1373 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1375 CStringA
tagName(tag_names
->strings
[i
]);
1376 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1379 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1385 int ret
= Run(L
"git.exe tag -l", [&](const CStringA
& lineA
)
1387 if (lineA
.IsEmpty())
1389 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1392 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1393 else if (ret
== 1 && IsInitRepos())
1399 CString
CGit::GetGitLastErr(const CString
& msg
)
1401 if (this->m_IsUseLibGit2
)
1402 return GetLibGit2LastErr(msg
);
1403 else if (gitLastErr
.IsEmpty())
1404 return msg
+ _T("\nUnknown git.exe error.");
1407 CString lastError
= gitLastErr
;
1409 return msg
+ _T("\n") + lastError
;
1413 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1415 if (UsingLibGit2(cmd
))
1416 return GetLibGit2LastErr(msg
);
1417 else if (gitLastErr
.IsEmpty())
1418 return msg
+ _T("\nUnknown git.exe error.");
1421 CString lastError
= gitLastErr
;
1423 return msg
+ _T("\n") + lastError
;
1427 CString
CGit::GetLibGit2LastErr()
1429 const git_error
*libgit2err
= giterr_last();
1432 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1434 return _T("libgit2 returned: ") + lastError
;
1437 return _T("An error occoured in libgit2, but no message is available.");
1440 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1443 return msg
+ _T("\n") + GetLibGit2LastErr();
1444 return GetLibGit2LastErr();
1447 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1449 if(branchName
== "FETCH_HEAD")
1450 branchName
= DerefFetchHead();
1454 CString
CGit::FixBranchName(const CString
& branchName
)
1456 CString tempBranchName
= branchName
;
1457 FixBranchName_Mod(tempBranchName
);
1458 return tempBranchName
;
1461 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1465 CAutoRepository
repo(GetGitRepository());
1467 return true; // TODO: optimize error reporting
1469 CAutoReference tagRef
;
1470 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1473 CAutoReference branchRef
;
1474 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1481 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR
)name
, (LPCTSTR
)name
);
1484 Run(cmd
, [&](const CStringA
& lineA
)
1486 if (lineA
.IsEmpty())
1491 return (refCnt
<= 1);
1494 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1498 CAutoRepository
repo(GetGitRepository());
1500 return false; // TODO: optimize error reporting
1504 prefix
= _T("refs/heads/");
1506 prefix
= _T("refs/tags/");
1509 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1515 CString cmd
, output
;
1517 cmd
= _T("git.exe show-ref ");
1519 cmd
+= _T("--heads ");
1521 cmd
+= _T("--tags ");
1523 cmd
+= _T("refs/heads/") + name
;
1524 cmd
+= _T(" refs/tags/") + name
;
1526 int ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1529 if (!output
.IsEmpty())
1536 CString
CGit::DerefFetchHead()
1539 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1540 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1541 int forMergeLineCount
= 0;
1543 std::string hashToReturn
;
1544 while(getline(fetchHeadFile
, line
))
1546 //Tokenize this line
1547 std::string::size_type prevPos
= 0;
1548 std::string::size_type pos
= line
.find('\t');
1549 if(pos
== std::string::npos
) continue; //invalid line
1551 std::string hash
= line
.substr(0, pos
);
1552 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1554 bool forMerge
= pos
== prevPos
;
1555 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1557 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1562 hashToReturn
= hash
;
1563 ++forMergeLineCount
;
1564 if(forMergeLineCount
> 1)
1565 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1569 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1572 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1574 size_t prevCount
= list
.size();
1577 bool headIsDetached
= false;
1580 CAutoRepository
repo(GetGitRepository());
1584 if (git_repository_head_detached(repo
) == 1)
1585 headIsDetached
= true;
1587 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1589 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1590 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1591 flags
= GIT_BRANCH_ALL
;
1592 else if (type
& BRANCH_REMOTE
)
1593 flags
= GIT_BRANCH_REMOTE
;
1595 CAutoBranchIterator it
;
1596 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1599 git_reference
* ref
= nullptr;
1600 git_branch_t branchType
;
1601 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1603 CAutoReference
autoRef(ref
);
1604 const char * name
= nullptr;
1605 if (git_branch_name(&name
, ref
))
1608 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1609 if (branchType
& GIT_BRANCH_REMOTE
)
1610 list
.push_back(_T("remotes/") + branchname
);
1613 if (git_branch_is_head(ref
))
1615 list
.push_back(branchname
);
1622 CString cmd
= L
"git.exe branch --no-color";
1624 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1626 else if (type
& BRANCH_REMOTE
)
1629 ret
= Run(cmd
, [&](CStringA lineA
)
1631 lineA
.Trim(" \r\n\t");
1632 if (lineA
.IsEmpty())
1634 if (lineA
.Find(" -> ") >= 0)
1635 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1637 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1638 if (lineA
[0] == '*')
1640 branch
= branch
.Mid(2);
1643 // check whether HEAD is detached
1644 CString currentHead
;
1645 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1647 headIsDetached
= true;
1651 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1652 branch
= L
"remotes/" + branch
;
1653 list
.push_back(branch
);
1655 if (ret
== 1 && IsInitRepos())
1659 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1660 list
.push_back(L
"FETCH_HEAD");
1662 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1664 if (current
&& !headIsDetached
)
1666 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1679 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1681 size_t prevCount
= list
.size();
1682 if (this->m_IsUseLibGit2
)
1684 CAutoRepository
repo(GetGitRepository());
1688 CAutoStrArray remotes
;
1689 if (git_remote_list(remotes
, repo
))
1692 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1694 CStringA
remote(remotes
->strings
[i
]);
1695 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1698 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1703 return Run(L
"git.exe remote", [&](const CStringA
& lineA
)
1705 if (lineA
.IsEmpty())
1707 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1711 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1713 size_t prevCount
= list
.size();
1714 if (UsingLibGit2(GIT_CMD_FETCH
))
1716 CAutoRepository
repo(GetGitRepository());
1720 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1721 CAutoRemote gitremote
;
1722 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1725 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1726 callbacks
.credentials
= g_Git2CredCallback
;
1727 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1728 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
, nullptr) < 0)
1731 const git_remote_head
** heads
= nullptr;
1733 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1736 for (size_t i
= 0; i
< size
; i
++)
1738 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1740 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1742 // do not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1743 if (ref
.Find(_T("^{}")) >= 1)
1745 list
.push_back(shortname
);
1747 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1752 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), (LPCTSTR
)remote
);
1753 gitLastErr
= cmd
+ L
'\n';
1754 if (Run(cmd
, [&](CStringA lineA
)
1756 lineA
= lineA
.Mid(51); // sha1, tab + refs/tags/
1757 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1758 if (lineA
.Find("^{}") >= 1)
1760 if (!lineA
.IsEmpty())
1761 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1764 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1768 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1770 if (UsingLibGit2(GIT_CMD_PUSH
))
1772 CAutoRepository
repo(GetGitRepository());
1776 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1778 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1781 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1782 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1783 callbacks
.credentials
= g_Git2CredCallback
;
1784 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1785 std::vector
<CStringA
> refspecs
;
1786 for (const auto& ref
: list
)
1787 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1789 std::vector
<char*> vc
;
1790 vc
.reserve(refspecs
.size());
1791 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1792 git_strarray specs
= { &vc
[0], vc
.size() };
1794 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1799 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1800 for (const auto& ref
: list
)
1802 CString refspec
= _T(":") + ref
;
1803 mgtPush
.AddFile(refspec
);
1806 BOOL cancel
= FALSE
;
1807 mgtPush
.Execute(cancel
);
1813 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1815 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1816 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1820 int CGit::GetRefList(STRING_VECTOR
&list
)
1822 size_t prevCount
= list
.size();
1823 if (this->m_IsUseLibGit2
)
1825 CAutoRepository
repo(GetGitRepository());
1829 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1832 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1837 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1839 int start
= lineA
.Find(L
' ');
1840 ASSERT(start
== 40);
1844 CString name
= CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1));
1845 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1846 list
.push_back(name
);
1849 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1850 else if (ret
== 1 && IsInitRepos())
1855 typedef struct map_each_ref_payload
{
1856 git_repository
* repo
;
1857 MAP_HASH_NAME
* map
;
1858 } map_each_ref_payload
;
1860 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1862 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1864 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1866 CAutoObject gitObject
;
1867 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1870 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1872 str
+= _T("^{}"); // deref tag
1873 CAutoObject derefedTag
;
1874 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1876 gitObject
.Swap(derefedTag
);
1879 const git_oid
* oid
= git_object_id(gitObject
);
1883 CGitHash
hash((char *)oid
->id
);
1884 (*payloadContent
->map
)[hash
].push_back(str
);
1888 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1892 map_each_ref_payload payloadContent
= { repo
, &map
};
1894 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1897 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1899 std::sort(it
->second
.begin(), it
->second
.end());
1905 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1907 if (this->m_IsUseLibGit2
)
1909 CAutoRepository
repo(GetGitRepository());
1913 return GetMapHashToFriendName(repo
, map
);
1916 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1918 int start
= lineA
.Find(L
' ');
1919 ASSERT(start
== 40);
1924 hash
.ConvertFromStrA(lineA
.Left(start
));
1925 map
[hash
].push_back(CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1)));
1928 if (ret
== 1 && IsInitRepos())
1933 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1935 CAutoConfig
config(true);
1936 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1938 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1940 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1941 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1942 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1943 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1948 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1950 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1951 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1954 static void SetLibGit2TemplatePath(const CString
&value
)
1956 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1957 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1960 int CGit::FindAndSetGitExePath(BOOL bFallback
)
1962 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
1963 CString str
= msysdir
;
1964 if (!str
.IsEmpty() && PathFileExists(str
+ _T("\\git.exe")))
1966 CGit::ms_LastMsysGitDir
= str
;
1970 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
1974 // first, search PATH if git/bin directory is already present
1977 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
1978 msysdir
= CGit::ms_LastMsysGitDir
;
1983 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1984 str
= msyslocalinstalldir
;
1985 str
.TrimRight(_T("\\"));
1989 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1990 str
= msysinstalldir
;
1991 str
.TrimRight(_T("\\"));
1996 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1997 str
= msysinstalldir
;
1998 str
.TrimRight(_T("\\"));
2002 if (PathFileExists(str
+ _T("\\bin\\git.exe")))
2004 else if (PathFileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2008 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR
)str
);
2012 CGit::ms_LastMsysGitDir
= str
;
2017 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2021 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2026 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2027 this->m_Environment
.clear();
2028 m_Environment
.CopyProcessEnvironment();
2029 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2031 // set HOME if not set already
2033 _tgetenv_s(&homesize
, nullptr, 0, _T("HOME"));
2035 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2038 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2039 if (sshclient
.IsEmpty())
2040 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2042 if(!sshclient
.IsEmpty())
2044 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2045 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2049 TCHAR sPlink
[MAX_PATH
] = {0};
2050 GetModuleFileName(nullptr, sPlink
, _countof(sPlink
));
2051 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2053 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPlink.exe"));
2054 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2055 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2060 TCHAR sAskPass
[MAX_PATH
] = {0};
2061 GetModuleFileName(nullptr, sAskPass
, _countof(sAskPass
));
2062 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2065 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2066 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2067 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2068 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2072 if (!FindAndSetGitExePath(bFallback
))
2076 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2077 static const CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2078 static const int prefixes_len
[] = { 8, 8, 0 };
2079 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2085 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2086 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2090 if (ms_bMsys2Git
) // in Msys2 git.exe is in usr\bin; this also need to be after the check for etc folder, as Msys2 also has mingw64\etc, but uses etc
2091 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\.."));
2092 CGit::ms_MsysGitRootDir
= msysGitDir
;
2094 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2095 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2097 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2098 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR
)CGit::ms_MsysGitRootDir
);
2099 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), (LPCTSTR
)g_Git
.GetGitSystemConfig());
2100 if (!ms_bCygwinGit
&& !ms_bMsys2Git
)
2102 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ProgramData config = %s\n", (LPCTSTR
)g_Git
.GetGitProgramDataConfig());
2103 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitProgramDataConfig()).GetContainingDirectory().GetWinPathString());
2106 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2108 // Configure libgit2 search paths
2109 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2110 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2111 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2112 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition
= { [](git_smart_subtransport
**out
, git_transport
* owner
, void*) -> int { return git_smart_subtransport_ssh_wintunnel(out
, owner
, FindExecutableOnPath(g_Git
.m_Environment
.GetEnv(_T("GIT_SSH")), g_Git
.m_Environment
.GetEnv(_T("PATH"))), g_Git
.m_Environment
); }, 0 };
2113 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2114 git_libgit2_opts(GIT_OPT_SET_USER_AGENT
, "TortoiseGit libgit2");
2115 if (!(ms_bCygwinGit
|| ms_bMsys2Git
))
2116 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2118 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2120 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2121 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2123 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2124 // register filter only once
2125 if (!git_filter_lookup("filter"))
2128 for (const CString
& binDirPrefix
: { L
"\\..\\usr\\bin", L
"\\..\\bin", L
"" })
2130 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2131 if (PathFileExists(possibleShExe
))
2134 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2135 sh
.Format(L
"\"%s\"", (LPCTSTR
)temp
);
2136 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2137 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2142 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2143 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2144 CString gitExecPath
= CGit::ms_MsysGitRootDir
;
2145 gitExecPath
.Append(_T("libexec\\git-core"));
2146 m_Environment
.AddToPath(gitExecPath
);
2148 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2153 m_bInitialized
= TRUE
;
2157 CString
CGit::GetHomeDirectory() const
2159 const wchar_t * homeDir
= wget_windows_home_directory();
2160 return CString(homeDir
, (int)wcslen(homeDir
));
2163 CString
CGit::GetGitLocalConfig() const
2166 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2167 path
+= _T("config");
2171 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2173 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2176 CString
CGit::GetGitGlobalConfig() const
2178 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2181 CString
CGit::GetGitGlobalXDGConfigPath() const
2183 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2186 CString
CGit::GetGitGlobalXDGConfig() const
2188 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2191 CString
CGit::GetGitProgramDataConfig() const
2193 const wchar_t* programdataConfig
= wget_program_data_config();
2194 return CString(programdataConfig
);
2197 CString
CGit::GetGitSystemConfig() const
2199 const wchar_t * systemConfig
= wget_msysgit_etc();
2200 return CString(systemConfig
, (int)wcslen(systemConfig
));
2203 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2205 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2207 CAutoRepository
repo(GetGitRepository());
2211 if (git_repository_head_unborn(repo
))
2214 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2215 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2216 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2218 CAutoStatusList status
;
2219 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2222 return (0 == git_status_list_entrycount(status
));
2227 cmd
=_T("git.exe rev-parse --verify HEAD");
2229 if(Run(cmd
,&out
,CP_UTF8
))
2232 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2233 if(Run(cmd
,&out
,CP_UTF8
))
2236 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2237 if(Run(cmd
,&out
,CP_UTF8
))
2240 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2241 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2246 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2249 for (int i
= 0; i
< list
.GetCount(); ++i
)
2251 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2257 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2261 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2263 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2265 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2271 // if the filenames only differ in case, we have to pass "-f"
2272 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2274 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR
)force
, (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2275 if (Run(cmd
, &err
, CP_UTF8
))
2280 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2281 if (Run(cmd
, &err
, CP_UTF8
))
2285 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitOldPathString());
2286 if (Run(cmd
, &err
, CP_UTF8
))
2289 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2290 { //To init git repository, there are not HEAD, so we can use git reset command
2291 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2293 if (Run(cmd
, &err
, CP_UTF8
))
2298 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitPathString());
2299 if (Run(cmd
, &err
, CP_UTF8
))
2303 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2305 cmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2306 if (Run(cmd
, &err
, CP_UTF8
))
2313 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2318 if (git_repository_index(index
.GetPointer(), repo
))
2321 return git_index_has_conflicts(index
);
2324 int CGit::HasWorkingTreeConflicts()
2326 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2328 CAutoRepository
repo(GetGitRepository());
2332 return HasWorkingTreeConflicts(repo
);
2335 CString cmd
= _T("git.exe ls-files -u -t -z");
2338 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2341 return output
.IsEmpty() ? 0 : 1;
2344 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2346 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2348 CAutoRepository
repo(GetGitRepository());
2352 CGitHash fromHash
, toHash
, baseHash
;
2353 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2356 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2360 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2363 baseHash
= baseOid
.id
;
2366 *commonAncestor
= baseHash
;
2368 return fromHash
== baseHash
;
2372 CGitHash basehash
,hash
;
2374 cmd
.Format(_T("git.exe merge-base %s %s"), (LPCTSTR
)FixBranchName(to
), (LPCTSTR
)FixBranchName(from
));
2376 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2378 basehash
= base
.Trim();
2380 GetHash(hash
, from
);
2383 *commonAncestor
= basehash
;
2385 return hash
== basehash
;
2388 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2391 for (int i
= 0; i
< 4; ++i
)
2394 ret
|= hash
.m_hash
[i
];
2399 int CGit::RefreshGitIndex()
2401 if(g_Git
.m_IsUseGitDLL
)
2403 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2406 int result
= [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2420 cmd
=_T("git.exe update-index --refresh");
2421 return Run(cmd
, &output
, CP_UTF8
);
2425 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2427 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2429 CAutoRepository
repo(GetGitRepository());
2434 if (GetHash(repo
, hash
, Refname
))
2438 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2442 if (git_commit_tree(tree
.GetPointer(), commit
))
2445 CAutoTreeEntry entry
;
2446 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2450 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2453 CAutoFILE file
= _tfsopen(outputfile
, _T("wb"), SH_DENYWR
);
2454 if (file
== nullptr)
2456 giterr_set_str(GITERR_NONE
, "Could not create file.");
2460 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2462 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2464 giterr_set_str(GITERR_OS
, "Could not write to file.");
2470 else if (g_Git
.m_IsUseGitDLL
)
2472 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2475 g_Git
.CheckAndInitDll();
2476 CStringA ref
, patha
, outa
;
2477 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2478 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2479 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2480 ::DeleteFile(outputfile
);
2481 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2482 outa
.ReleaseBuffer();
2486 catch (const char * msg
)
2488 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2493 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2500 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR
)Refname
, (LPCTSTR
)path
.GetGitPathString());
2501 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2505 void CEnvironment::clear()
2511 bool CEnvironment::empty()
2513 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2516 CEnvironment::operator LPTSTR()
2520 return &__super::at(0);
2523 CEnvironment::operator LPWSTR
*()
2528 void CEnvironment::CopyProcessEnvironment()
2532 TCHAR
*porig
= GetEnvironmentStrings();
2534 while(*p
!=0 || *(p
+1) !=0)
2535 this->push_back(*p
++);
2537 push_back(_T('\0'));
2538 push_back(_T('\0'));
2539 baseptr
= &__super::at(0);
2541 FreeEnvironmentStrings(porig
);
2544 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2547 for (size_t i
= 0; i
< size(); ++i
)
2551 CString sname
= str
.Tokenize(_T("="),start
);
2552 if(sname
.CompareNoCase(name
) == 0)
2553 return &(*this)[i
+start
];
2559 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2562 for (i
= 0; i
< size(); ++i
)
2564 CString str
= &(*this)[i
];
2566 CString sname
= str
.Tokenize(_T("="),start
);
2567 if(sname
.CompareNoCase(name
) == 0)
2574 if (!value
) // as we haven't found the variable we want to remove, just return
2576 if (i
== 0) // make inserting into an empty environment work
2578 this->push_back(_T('\0'));
2581 i
-= 1; // roll back terminate \0\0
2582 this->push_back(_T('\0'));
2585 CEnvironment::iterator it
;
2589 while(*it
&& i
<size())
2596 if (value
== nullptr) // remove the variable
2602 baseptr
= &__super::at(0);
2608 this->insert(it
,*name
++);
2613 this->insert(it
, _T('='));
2619 this->insert(it
,*value
++);
2623 baseptr
= &__super::at(0);
2626 void CEnvironment::AddToPath(CString value
)
2628 value
.TrimRight(L
"\\");
2629 if (value
.IsEmpty())
2632 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2634 // do not double add paths to %PATH%
2635 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2640 SetEnv(L
"PATH", path
);
2643 int CGit::GetGitEncode(TCHAR
* configkey
)
2645 CString str
=GetConfigValue(configkey
);
2650 return CUnicodeUtils::GetCPCode(str
);
2654 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2660 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2665 diff
= GetGitDiff();
2667 git_open_diff(&diff
, arg
);
2671 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2682 isStat
= !!strstr(arg
, "stat");
2687 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2689 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2698 for (int j
= 0; j
< count
; ++j
)
2707 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2708 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2709 &mode
,&IsBin
,&inc
,&dec
);
2711 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2712 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2714 path
.SetFromGit(strnewname
,&stroldname
);
2715 path
.ParserAction((BYTE
)mode
);
2719 path
.m_StatAdd
=_T("-");
2720 path
.m_StatDel
=_T("-");
2724 path
.m_StatAdd
.Format(_T("%d"),inc
);
2725 path
.m_StatDel
.Format(_T("%d"),dec
);
2727 PathList
->AddPath(path
);
2729 git_diff_flush(diff
);
2732 git_close_diff(diff
);
2737 int CGit::GetShortHASHLength() const
2742 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2746 REF_TYPE type
= CGit::UNKNOWN
;
2748 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2749 type
= CGit::LOCAL_BRANCH
;
2750 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2751 type
= CGit::REMOTE_BRANCH
;
2752 else if (str
.Right(3) == L
"^{}" && CGit::GetShortName(str
, shortname
, L
"refs/tags/"))
2753 type
= CGit::ANNOTATED_TAG
;
2754 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2756 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2759 shortname
=_T("stash");
2761 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2765 g_Git
.GetBisectTerms(&bisectGood
, &bisectBad
);
2767 if (shortname
.Find(bisectGood
) == 0 && ((c
= shortname
.GetAt(bisectGood
.GetLength())) == '-' || c
== '\0'))
2769 type
= CGit::BISECT_GOOD
;
2770 shortname
= bisectGood
;
2773 if (shortname
.Find(bisectBad
) == 0 && ((c
= shortname
.GetAt(bisectBad
.GetLength())) == '-' || c
== '\0'))
2775 type
= CGit::BISECT_BAD
;
2776 shortname
= bisectBad
;
2779 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2781 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2782 type
= CGit::UNKNOWN
;
2785 type
= CGit::UNKNOWN
;
2795 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2797 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2800 void CGit::SetGit2CredentialCallback(void* callback
)
2802 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2805 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2807 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2810 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
2813 if (rev2
== GitRev::GetWorkingCopy())
2814 cmd
.Format(_T("git.exe diff --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
);
2815 else if (rev1
== GitRev::GetWorkingCopy())
2816 cmd
.Format(_T("git.exe diff -R --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev2
);
2827 if (diffContext
>= 0)
2828 unified
.Format(_T(" --unified=%d"), diffContext
);
2829 cmd
.Format(_T("git.exe diff-tree -r -p%s%s --stat%s %s %s --"), (LPCTSTR
)merge
, (LPCTSTR
)unified
, bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
, (LPCTSTR
)rev2
);
2832 if (!path
.IsEmpty())
2835 cmd
+= path
.GetGitPathString();
2842 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2844 ATLASSERT(payload
&& text
);
2845 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2846 fwrite("\n", 1, 1, (FILE *)payload
);
2849 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2851 ATLASSERT(payload
&& line
);
2852 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2853 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2854 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2858 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2860 ATLASSERT(repo
&& identifier
&& tree
);
2862 /* try to resolve identifier */
2864 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2868 return GIT_ENOTFOUND
;
2871 switch (git_object_type(obj
))
2874 *tree
= (git_tree
*)obj
.Detach();
2876 case GIT_OBJ_COMMIT
:
2877 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2880 err
= GIT_ENOTFOUND
;
2886 /* use libgit2 get unified diff */
2887 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const git_revnum_t
& revOld
, const git_revnum_t
& revNew
, std::function
<void(const git_buf
*, void*)> statCallback
, git_diff_line_cb callback
, void* data
, bool /* bMerge */, bool bNoPrefix
)
2889 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2890 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2892 CAutoRepository
repo(g_Git
.GetGitRepository());
2896 int isHeadOrphan
= git_repository_head_unborn(repo
);
2897 if (isHeadOrphan
== 1)
2899 else if (isHeadOrphan
!= 0)
2902 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2903 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2904 char *buf
= pathA
.GetBuffer();
2905 if (!pathA
.IsEmpty())
2907 opts
.pathspec
.strings
= &buf
;
2908 opts
.pathspec
.count
= 1;
2912 opts
.new_prefix
= "";
2913 opts
.old_prefix
= "";
2917 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2922 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2925 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2928 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2931 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2934 if (git_diff_merge(diff
, diff2
))
2939 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2942 if (tree1
.IsEmpty())
2950 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2953 if (tree2
.IsEmpty())
2955 /* don't check return value, there are not parent commit at first commit*/
2956 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2958 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2960 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2964 CAutoDiffStats stats
;
2965 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2968 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2970 statCallback(statBuf
, data
);
2972 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2975 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2978 if (git_patch_print(patch
, callback
, data
))
2982 pathA
.ReleaseBuffer();
2987 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
2989 if (UsingLibGit2(GIT_CMD_DIFF
))
2991 CAutoFILE file
= _tfsopen(patchfile
, _T("w"), SH_DENYRW
);
2994 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
, bNoPrefix
);
2999 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
, bNoPrefix
);
3000 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3004 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3006 ATLASSERT(payload
&& text
);
3007 CStringA
*str
= (CStringA
*) payload
;
3008 str
->Append(text
->ptr
, (int)text
->size
);
3009 str
->AppendChar('\n');
3012 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3014 ATLASSERT(payload
&& line
);
3015 CStringA
*str
= (CStringA
*) payload
;
3016 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3017 str
->Append(&line
->origin
, 1);
3018 str
->Append(line
->content
, (int)line
->content_len
);
3022 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3024 if (UsingLibGit2(GIT_CMD_DIFF
))
3025 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
, false);
3029 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3031 int ret
= Run(cmd
, &vector
);
3032 if (!vector
.empty())
3034 vector
.push_back(0); // vector is not NUL terminated
3035 buffer
->Append((char *)&vector
[0]);
3041 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3043 if (UsingLibGit2(GIT_CMD_REVERT
))
3045 CAutoRepository
repo(GetGitRepository());
3050 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3053 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3054 revert_opts
.mainline
= parent
;
3055 int result
= git_revert(repo
, commit
, &revert_opts
);
3057 return !result
? 0 : -1;
3063 merge
.Format(_T("-m %d "), parent
);
3064 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR
)merge
, (LPCTSTR
)hash
.ToString());
3065 gitLastErr
= cmd
+ _T("\n");
3066 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3076 int CGit::DeleteRef(const CString
& reference
)
3078 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3080 CAutoRepository
repo(GetGitRepository());
3085 if (reference
.Right(3) == _T("^{}"))
3086 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3088 refA
= CUnicodeUtils::GetUTF8(reference
);
3091 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3095 if (git_reference_is_tag(ref
))
3096 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3097 else if (git_reference_is_branch(ref
))
3098 result
= git_branch_delete(ref
);
3099 else if (git_reference_is_remote(ref
))
3100 result
= git_branch_delete(ref
);
3102 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3108 CString cmd
, shortname
;
3109 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3110 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)shortname
);
3111 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3112 cmd
.Format(_T("git.exe tag -d -- %s"), (LPCTSTR
)shortname
);
3113 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3114 cmd
.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR
)shortname
);
3117 gitLastErr
= L
"unsupported reference type: " + reference
;
3121 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3129 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3131 if (!PathFileExists(filename
))
3134 CAutoFILE pFile
= _tfsopen(filename
, _T("r"), SH_DENYWR
);
3137 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3138 return true; // load no further files
3144 char s
[8196] = { 0 };
3145 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3148 str
+= CStringA(s
, read
);
3150 msg
+= CUnicodeUtils::GetUnicode(str
);
3151 msg
.Replace(_T("\r\n"), _T("\n"));
3152 msg
.TrimRight(_T("\n"));
3155 return true; // load no further files
3158 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3161 return GetInitAddList(result
);
3167 count
= filterlist
->GetCount();
3169 CString head
= _T("HEAD");
3171 head
= _T("HEAD~1");
3173 for (int i
= 0; i
< count
; ++i
)
3177 if (ms_bCygwinGit
|| ms_bMsys2Git
)
3179 // Prevent showing all files as modified when using cygwin's git
3181 cmd
= _T("git.exe status --");
3183 cmd
.Format(_T("git.exe status -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3188 // also list staged files which will be in the commit
3189 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3192 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3194 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3197 if (Run(cmd
, &cmdout
, &cmdErr
))
3199 int last
= cmdErr
.RevertFind(0, -1);
3201 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3202 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3205 out
.append(cmdout
, 0);
3207 result
.ParserFromLog(out
);
3209 std::map
<CString
, int> duplicateMap
;
3210 for (int i
= 0; i
< result
.GetCount(); ++i
)
3211 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), i
));
3213 // handle delete conflict case, when remote : modified, local : deleted.
3214 for (int i
= 0; i
< count
; ++i
)
3220 cmd
= _T("git.exe ls-files -u -t -z");
3222 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3226 CTGitPathList conflictlist
;
3227 conflictlist
.ParserFromLog(cmdout
);
3228 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3230 auto existing
= duplicateMap
.find(conflictlist
[j
].GetGitPathString());
3231 if (existing
!= duplicateMap
.end())
3233 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3234 p
.m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3238 result
.AddPath(conflictlist
[j
]);
3239 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3244 // handle source files of file renames/moves (issue #860)
3245 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3246 for (int i
= 0; i
< count
; ++i
)
3252 cmd
= _T("git.exe ls-files -d -z");
3254 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3258 CTGitPathList deletelist
;
3259 deletelist
.ParserFromLog(cmdout
, true);
3260 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3262 auto existing
= duplicateMap
.find(deletelist
[j
].GetGitPathString());
3263 if (existing
== duplicateMap
.end())
3265 result
.AddPath(deletelist
[j
]);
3266 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3270 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3271 p
.m_Action
|= CTGitPath::LOGACTIONS_MISSING
;
3279 int CGit::IsRebaseRunning()
3282 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3285 if (PathIsDirectory(adminDir
+ L
"rebase-apply") || PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3290 void CGit::GetBisectTerms(CString
* good
, CString
* bad
)
3292 static CString lastGood
;
3293 static CString lastBad
;
3294 static ULONGLONG lastRead
= 0;
3304 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3305 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3306 // as we only read a small file the performance effects should be negligible
3307 if (lastRead
+ 5000 > GetTickCount64())
3315 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir
, adminDir
))
3318 CString termsFile
= adminDir
+ L
"BISECT_TERMS";
3320 _tfopen_s(fp
.GetPointer(), termsFile
, L
"rb");
3323 char badA
[MAX_PATH
] = { 0 };
3324 fgets(badA
, MAX_PATH
, fp
);
3325 size_t len
= strlen(badA
);
3326 if (len
> 0 && badA
[len
- 1] == '\n')
3327 badA
[len
- 1] = '\0';
3328 char goodA
[MAX_PATH
] = { 0 };
3329 fgets(goodA
, MAX_PATH
, fp
);
3330 len
= strlen(goodA
);
3331 if (len
> 0 && goodA
[len
- 1] == '\n')
3332 goodA
[len
- 1] = '\0';
3333 lastGood
= CUnicodeUtils::GetUnicode(goodA
);
3334 lastBad
= CUnicodeUtils::GetUnicode(badA
);
3335 lastRead
= GetTickCount64();
3338 int CGit::GetGitVersion(CString
* versiondebug
, CString
* errStr
)
3340 CString version
, err
;
3341 if (Run(_T("git.exe --version"), &version
, &err
, CP_UTF8
))
3351 *versiondebug
= version
;
3355 CString str
= version
.Tokenize(_T("."), start
);
3356 int space
= str
.ReverseFind(_T(' '));
3357 str
= str
.Mid(space
+ 1, start
);
3361 version
= version
.Mid(start
);
3364 str
= version
.Tokenize(_T("."), start
);
3365 ver
|= (_ttol(str
) & 0xFF) << 16;
3367 str
= version
.Tokenize(_T("."), start
);
3368 ver
|= (_ttol(str
) & 0xFF) << 8;
3370 str
= version
.Tokenize(_T("."), start
);
3371 ver
|= (_ttol(str
) & 0xFF);