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();
221 m_critSecThreadMap
.Init();
228 git_close_diff(m_GitDiff
);
231 if(this->m_GitSimpleListDiff
)
233 git_close_diff(m_GitSimpleListDiff
);
234 m_GitSimpleListDiff
=0;
236 git_libgit2_shutdown();
237 m_critSecThreadMap
.Term();
238 m_critGitDllSec
.Term();
241 bool CGit::IsBranchNameValid(const CString
& branchname
)
243 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
245 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
247 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
248 return !!git_reference_is_valid_name(branchA
);
251 static bool IsPowerShell(CString cmd
)
254 int powerShellPos
= cmd
.Find(_T("powershell"));
255 if (powerShellPos
< 0)
258 // found the word powershell, check that it is the command and not any parameter
259 int end
= cmd
.GetLength();
260 if (end
> 0 && cmd
[0] == L
'"')
262 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
263 if (secondDoubleQuote
> 0)
264 end
= secondDoubleQuote
;
268 int firstSpace
= cmd
.Find(_T(' '));
273 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
276 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
278 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
279 CAutoGeneralHandle hStdioFile
;
281 SECURITY_ATTRIBUTES sa
= { 0 };
282 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
283 sa
.bInheritHandle
=TRUE
;
284 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
286 CString err
= CFormatMessageWrapper();
287 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
288 return TGIT_GIT_ERROR_OPEN_PIP
;
290 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
292 CString err
= CFormatMessageWrapper();
293 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
294 return TGIT_GIT_ERROR_OPEN_PIP
;
298 hStdioFile
= CreateFile(*StdioFile
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
300 STARTUPINFO si
= { 0 };
301 PROCESS_INFORMATION pi
= { 0 };
302 si
.cb
=sizeof(STARTUPINFO
);
305 si
.hStdError
= hWriteErr
;
307 si
.hStdError
= hWrite
;
309 si
.hStdOutput
=hStdioFile
;
311 si
.hStdOutput
=hWrite
;
313 si
.wShowWindow
=SW_HIDE
;
314 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
316 LPTSTR pEnv
= m_Environment
;
317 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
319 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
321 // 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,
322 // 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)
323 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
324 if (IsPowerShell(cmd
))
325 dwFlags
|= CREATE_NEW_CONSOLE
;
327 dwFlags
|= DETACHED_PROCESS
;
329 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
331 bool startsWithGit
= wcsncmp(cmd
, L
"git", 3) == 0;
332 if (ms_bMsys2Git
&& startsWithGit
&& wcsncmp(cmd
, L
"git.exe config ", 15) != 0)
334 cmd
.Replace(_T("\\"), _T("\\\\\\\\"));
335 cmd
.Replace(_T("\""), _T("\\\""));
336 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/usr/bin/") + cmd
+ _T('"');
338 else if (ms_bCygwinGit
&& startsWithGit
&& wcsncmp(cmd
, L
"git.exe config ", 15) != 0)
340 cmd
.Replace(_T('\\'), _T('/'));
341 cmd
.Replace(_T("\""), _T("\\\""));
342 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
344 else if (startsWithGit
|| wcsncmp(cmd
, L
"bash", 4) == 0)
346 int firstSpace
= cmd
.Find(_T(" "));
348 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
350 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
353 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
354 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
356 CString err
= CFormatMessageWrapper();
357 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), (LPCTSTR
)err
.Trim());
358 return TGIT_GIT_ERROR_CREATE_PROCESS
;
366 *hReadOut
= hRead
.Detach();
368 *hErrReadOut
= hReadErr
.Detach();
371 //Must use sperate function to convert ANSI str to union code string
372 //Becuase A2W use stack as internal convert buffer.
373 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
380 len
= (int)strlen((const char*)p
);
385 int currentContentLen
= str
->GetLength();
386 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
387 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
388 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
391 // This method was originally used to check for orphaned branches
392 BOOL
CGit::CanParseRev(CString ref
)
398 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
406 // Checks if we have an orphaned HEAD
407 BOOL
CGit::IsInitRepos()
410 if (GetHash(hash
, _T("HEAD")) != 0)
412 return hash
.IsEmpty() ? TRUE
: FALSE
;
415 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
417 PASYNCREADSTDERRTHREADARGS pDataArray
;
418 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
421 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
422 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
424 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
432 void CGit::KillRelatedThreads(CWinThread
* thread
)
434 CAutoLocker
lock(m_critSecThreadMap
);
435 auto it
= m_AsyncReadStdErrThreadMap
.find(thread
->m_nThreadID
);
436 if (it
!= m_AsyncReadStdErrThreadMap
.cend())
438 TerminateThread(it
->second
, (DWORD
)-1);
439 m_AsyncReadStdErrThreadMap
.erase(it
);
441 TerminateThread(thread
->m_hThread
, (DWORD
)-1);
445 int CGit::Run(CGitCall
* pcall
)
447 PROCESS_INFORMATION pi
;
448 CAutoGeneralHandle hRead
, hReadErr
;
449 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
450 return TGIT_GIT_ERROR_CREATE_PROCESS
;
452 CAutoGeneralHandle
piThread(pi
.hThread
);
453 CAutoGeneralHandle
piProcess(pi
.hProcess
);
455 ASYNCREADSTDERRTHREADARGS threadArguments
;
456 threadArguments
.fileHandle
= hReadErr
;
457 threadArguments
.pcall
= pcall
;
458 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
462 CAutoLocker
lock(m_critSecThreadMap
);
463 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
467 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
469 while (ReadFile(hRead
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
471 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
472 if(!bAborted
)//For now, flush output when command aborted.
473 if(pcall
->OnOutputData(data
,readnumber
))
481 WaitForSingleObject(thread
, INFINITE
);
483 CAutoLocker
lock(m_critSecThreadMap
);
484 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
487 WaitForSingleObject(pi
.hProcess
, INFINITE
);
490 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
492 CString err
= CFormatMessageWrapper();
493 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
494 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
497 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
501 class CGitCall_ByteVector
: public CGitCall
504 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= nullptr) : CGitCall(cmd
),m_pvector(pvector
), m_pvectorErr(pvectorErr
) {}
505 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
507 if (!m_pvector
|| size
== 0)
509 size_t oldsize
=m_pvector
->size();
510 m_pvector
->resize(m_pvector
->size()+size
);
511 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
514 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
516 if (!m_pvectorErr
|| size
== 0)
518 size_t oldsize
= m_pvectorErr
->size();
519 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
520 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
523 BYTE_VECTOR
* m_pvector
;
524 BYTE_VECTOR
* m_pvectorErr
;
526 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
528 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
531 int CGit::Run(CString cmd
, CString
* output
, int code
)
535 ret
= Run(cmd
, output
, &err
, code
);
537 if (output
&& !err
.IsEmpty())
539 if (!output
->IsEmpty())
546 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
548 BYTE_VECTOR vector
, vectorErr
;
551 ret
= Run(cmd
, &vector
, &vectorErr
);
553 ret
= Run(cmd
, &vector
);
556 StringAppend(output
, &(vector
[0]), code
);
560 vectorErr
.push_back(0);
561 StringAppend(outputErr
, &(vectorErr
[0]), code
);
567 class CGitCallCb
: public CGitCall
570 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
, BYTE_VECTOR
* pvectorErr
= nullptr)
573 , m_pvectorErr(pvectorErr
)
576 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
581 int oldEndPos
= m_buffer
.GetLength();
582 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
583 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
585 // Break into lines and feed to m_recv
587 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
589 m_recv(m_buffer
.Left(eolPos
));
590 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
595 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
597 if (!m_pvectorErr
|| size
== 0)
599 size_t oldsize
= m_pvectorErr
->size();
600 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
601 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
605 virtual void OnEnd() override
607 if (!m_buffer
.IsEmpty())
609 m_buffer
.Empty(); // Just for sure
613 GitReceiverFunc m_recv
;
615 BYTE_VECTOR
* m_pvectorErr
;
618 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
, CString
* outputErr
)
622 BYTE_VECTOR vectorErr
;
623 CGitCallCb
call(cmd
, recv
, &vectorErr
);
624 int ret
= Run(&call
);
625 vectorErr
.push_back(0);
626 StringAppend(outputErr
, &(vectorErr
[0]));
630 CGitCallCb
call(cmd
, recv
);
634 CString
CGit::GetUserName(void)
637 env
.CopyProcessEnvironment();
638 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
639 if (!envname
.IsEmpty())
641 return GetConfigValue(L
"user.name");
643 CString
CGit::GetUserEmail(void)
646 env
.CopyProcessEnvironment();
647 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
648 if (!envmail
.IsEmpty())
651 return GetConfigValue(L
"user.email");
654 CString
CGit::GetConfigValue(const CString
& name
, const CString
& def
, bool wantBool
)
657 if(this->m_IsUseGitDLL
)
659 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
668 key
= CUnicodeUtils::GetUTF8(name
);
672 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
675 catch (const char *msg
)
677 ::MessageBox(nullptr, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
681 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
687 cmd
.Format(L
"git.exe config%s %s", wantBool
? _T(" --bool") : _T(""), (LPCTSTR
)name
);
688 if (Run(cmd
, &configValue
, nullptr, CP_UTF8
))
690 if (configValue
.IsEmpty())
692 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
696 bool CGit::GetConfigValueBool(const CString
& name
, const bool def
)
698 CString configValue
= GetConfigValue(name
, def
? _T("true") : _T("false"), true);
699 configValue
.MakeLower();
701 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
707 int CGit::GetConfigValueInt32(const CString
& name
, const int def
)
709 CString configValue
= GetConfigValue(name
);
711 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
716 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
718 if(this->m_IsUseGitDLL
)
720 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
728 CStringA keya
, valuea
;
729 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
730 valuea
= CUnicodeUtils::GetUTF8(value
);
734 return [=]() { return get_set_config(keya
, valuea
, type
); }();
736 catch (const char *msg
)
738 ::MessageBox(nullptr, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
749 option
= _T("--global");
752 option
= _T("--system");
757 CString mangledValue
= value
;
758 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
759 mangledValue
.Replace(_T("\""), _T("\\\""));
760 cmd
.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
762 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
768 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
770 if(this->m_IsUseGitDLL
)
772 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
781 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
785 return [=]() { return get_set_config(keya
, nullptr, type
); }();
787 catch (const char *msg
)
789 ::MessageBox(nullptr, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
800 option
= _T("--global");
803 option
= _T("--system");
808 cmd
.Format(_T("git.exe config %s --unset %s"), (LPCTSTR
)option
, (LPCTSTR
)key
);
810 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
816 CString
CGit::GetCurrentBranch(bool fallback
)
819 //Run(_T("git.exe branch"),&branch);
821 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
822 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
823 return _T("(no branch)");
828 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
830 if (localBranch
.IsEmpty())
834 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
835 pullRemote
= GetConfigValue(configName
);
837 //Select pull-branch from current branch
838 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
839 pullBranch
= StripRefName(GetConfigValue(configName
));
842 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
845 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
847 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
850 void CGit::GetRemotePushBranch(const CString
& localBranch
, CString
& pushRemote
, CString
& pushBranch
)
852 if (localBranch
.IsEmpty())
857 configName
.Format(L
"branch.%s.pushremote", (LPCTSTR
)localBranch
);
858 pushRemote
= g_Git
.GetConfigValue(configName
);
859 if (pushRemote
.IsEmpty())
861 pushRemote
= g_Git
.GetConfigValue(L
"remote.pushdefault");
862 if (pushRemote
.IsEmpty())
864 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
865 pushRemote
= g_Git
.GetConfigValue(configName
);
869 configName
.Format(L
"branch.%s.pushbranch", (LPCTSTR
)localBranch
);
870 pushBranch
= g_Git
.GetConfigValue(configName
); // do not strip branch name (for gerrit), see issue #1609)
871 if (pushBranch
.IsEmpty())
873 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
874 pushBranch
= CGit::StripRefName(g_Git
.GetConfigValue(configName
));
878 CString
CGit::GetFullRefName(const CString
& shortRefName
)
882 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
883 if (Run(cmd
, &refName
, nullptr, CP_UTF8
) != 0)
884 return CString();//Error
885 return refName
.TrimRight();
888 CString
CGit::StripRefName(CString refName
)
890 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
891 refName
= refName
.Mid(11);
892 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
893 refName
= refName
.Mid(5);
894 return refName
.TrimRight();
897 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
899 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
901 if ( sProjectRoot
.IsEmpty() )
905 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
908 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
910 CAutoFILE pFile
= _tfsopen(sHeadFile
.GetString(), _T("r"), SH_DENYWR
);
915 fgets(s
, sizeof(s
), pFile
);
917 const char *pfx
= "ref: refs/heads/";
918 const int len
= 16;//strlen(pfx)
920 if ( !strncmp(s
, pfx
, len
) )
922 //# We're on a branch. It might not exist. But
923 //# HEAD looks good enough to be a branch.
924 CStringA
utf8Branch(s
+ len
);
925 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
926 sBranchOut
.TrimRight(_T(" \r\n\t"));
928 if ( sBranchOut
.IsEmpty() )
933 CStringA
utf8Hash(s
);
934 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
935 unicodeHash
.TrimRight(_T(" \r\n\t"));
936 if (CGitHash::IsValidSHA1(unicodeHash
))
937 sBranchOut
= unicodeHash
;
939 //# Assume this is a detached head.
940 sBranchOut
= _T("HEAD");
945 //# Assume this is a detached head.
954 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
957 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
961 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
963 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
965 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
967 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
969 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
971 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
973 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
977 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
979 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
981 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
986 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
992 CString
CGit::GetLogCmd(const CString
& range
, const CTGitPath
* path
, int mask
, CFilterData
* Filter
, int logOrderBy
)
996 if(mask
& LOG_INFO_STAT
)
997 param
+= _T(" --numstat");
998 if(mask
& LOG_INFO_FILESTATE
)
999 param
+= _T(" --raw");
1001 if(mask
& LOG_INFO_FULLHISTORY
)
1002 param
+= _T(" --full-history");
1004 if(mask
& LOG_INFO_BOUNDARY
)
1005 param
+= _T(" --left-right --boundary");
1007 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
1008 param
+= _T(" --all");
1010 if (mask
& CGit::LOG_INFO_BASIC_REFS
)
1012 param
+= _T(" --branches");
1013 param
+= _T(" --tags");
1014 param
+= _T(" --remotes");
1015 param
+= _T(" --glob=stas[h]"); // require at least one glob operator
1016 param
+= _T(" --glob=bisect");
1019 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
1020 param
+= _T(" --branches");
1022 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
1025 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
1028 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
1029 param
+= _T(" --first-parent");
1031 if(mask
& CGit::LOG_INFO_NO_MERGE
)
1032 param
+= _T(" --no-merges");
1034 if(mask
& CGit::LOG_INFO_FOLLOW
)
1035 param
+= _T(" --follow");
1037 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
1040 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
1041 param
+= _T(" --full-diff");
1043 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
1044 param
+= _T(" --simplify-by-decoration");
1048 if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_N_YEARS
)
1050 CTime now
= CTime::GetCurrentTime();
1051 CTime time
= CTime(now
.GetYear(), now
.GetMonth(), now
.GetDay(), 0, 0, 0);
1052 __time64_t substract
= 86400;
1054 switch (Filter
->m_NumberOfLogsScale
)
1056 case CFilterData::SHOW_LAST_N_YEARS
:
1059 case CFilterData::SHOW_LAST_N_MONTHS
:
1062 case CFilterData::SHOW_LAST_N_WEEKS
:
1066 Filter
->m_From
= (DWORD
)time
.GetTime() - (Filter
->m_NumberOfLogs
* substract
);
1068 if (Filter
->m_NumberOfLogsScale
== CFilterData::SHOW_LAST_N_COMMITS
)
1069 param
.AppendFormat(L
" -n%ld", Filter
->m_NumberOfLogs
);
1070 else if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_SEL_DATE
&& Filter
->m_From
> 0)
1071 param
.AppendFormat(L
" --max-age=%I64u", Filter
->m_From
);
1074 if( Filter
&& (Filter
->m_To
!= -1))
1075 param
.AppendFormat(L
" --min-age=%I64u", Filter
->m_To
);
1077 bool isgrep
= false;
1078 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1080 param
.AppendFormat(L
" --author=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1084 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1086 param
.AppendFormat(L
" --committer=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1090 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1092 param
.AppendFormat(L
" --grep=\"%s\"", (LPCTSTR
)Filter
->m_MessageFilter
);
1096 if(Filter
&& isgrep
)
1098 if(!Filter
->m_IsRegex
)
1099 param
+= _T(" --fixed-strings");
1101 param
+= _T(" --regexp-ignore-case --extended-regexp");
1104 if (logOrderBy
== LOG_ORDER_TOPOORDER
|| (mask
& CGit::LOG_ORDER_TOPOORDER
))
1105 param
+= _T(" --topo-order");
1106 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1107 param
+= _T(" --date-order");
1112 file
.Format(_T(" \"%s\""), (LPCTSTR
)path
->GetGitPathString());
1113 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1114 cmd
.Format(_T("--ignore-this-parameter -z%s %s --parents --%s"), (LPCTSTR
)param
, (LPCTSTR
)range
, (LPCTSTR
)file
);
1119 void GetTempPath(CString
&path
)
1121 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1123 DWORD dwBufSize
=BUFSIZE
;
1124 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1125 lpPathBuffer
); // buffer for path
1126 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1128 path
.Format(_T("%s"),lpPathBuffer
);
1130 CString
GetTempFile()
1132 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1134 DWORD dwBufSize
=BUFSIZE
;
1135 TCHAR szTempName
[BUFSIZE
] = { 0 };
1138 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1139 lpPathBuffer
); // buffer for path
1140 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1142 // Create a temporary file.
1143 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1144 TEXT("Patch"), // temp file name prefix
1145 0, // create unique name
1146 szTempName
); // buffer for name
1151 return CString(szTempName
);
1154 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1156 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1157 if (result
== 0) return 0;
1158 if (!lpBuffer
|| (result
+ 13 > nBufferLength
))
1165 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1166 CreateDirectory(lpBuffer
, nullptr);
1171 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1174 PROCESS_INFORMATION pi
;
1175 si
.cb
=sizeof(STARTUPINFO
);
1176 GetStartupInfo(&si
);
1178 SECURITY_ATTRIBUTES psa
= {sizeof(psa
), nullptr, TRUE
};
1179 psa
.bInheritHandle
=TRUE
;
1181 CAutoGeneralHandle hReadErr
, hWriteErr
;
1182 if (!CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &psa
, 0))
1184 CString err
= CFormatMessageWrapper();
1185 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
1186 return TGIT_GIT_ERROR_OPEN_PIP
;
1189 CAutoFile houtfile
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &psa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
1192 CString err
= CFormatMessageWrapper();
1193 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
1194 return TGIT_GIT_ERROR_OPEN_PIP
;
1197 si
.wShowWindow
= SW_HIDE
;
1198 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1199 si
.hStdOutput
= houtfile
;
1200 si
.hStdError
= hWriteErr
;
1202 LPTSTR pEnv
= m_Environment
;
1203 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
1205 if (wcsncmp(cmd
, L
"git", 3) == 0)
1206 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1208 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
1209 if (!CreateProcess(nullptr, (LPWSTR
)cmd
.GetString(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, (LPWSTR
)m_CurrentDir
.GetString(), &si
, &pi
))
1211 CString err
= CFormatMessageWrapper();
1212 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), (LPCTSTR
)err
.Trim());
1214 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1217 CAutoGeneralHandle
piThread(pi
.hThread
);
1218 CAutoGeneralHandle
piProcess(pi
.hProcess
);
1220 BYTE_VECTOR stderrVector
;
1221 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1222 ASYNCREADSTDERRTHREADARGS threadArguments
;
1223 threadArguments
.fileHandle
= hReadErr
;
1224 threadArguments
.pcall
= &pcall
;
1225 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1229 CAutoLocker
lock(m_critSecThreadMap
);
1230 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
1233 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1235 hWriteErr
.CloseHandle();
1236 hReadErr
.CloseHandle();
1240 WaitForSingleObject(thread
, INFINITE
);
1242 CAutoLocker
lock(m_critSecThreadMap
);
1243 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
1246 stderrVector
.push_back(0);
1247 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1250 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1252 CString err
= CFormatMessageWrapper();
1253 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
1254 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1257 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1262 CAutoRepository
CGit::GetGitRepository() const
1264 return CAutoRepository(GetGitPathStringA(m_CurrentDir
));
1267 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1271 // no need to parse a ref if it's already a 40-byte hash
1272 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1274 hash
= CGitHash(friendname
);
1278 int isHeadOrphan
= git_repository_head_unborn(repo
);
1279 if (isHeadOrphan
!= 0)
1282 if (isHeadOrphan
== 1)
1288 CAutoObject gitObject
;
1289 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1292 const git_oid
* oid
= git_object_id(gitObject
);
1296 hash
= CGitHash((char *)oid
->id
);
1301 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1303 // no need to parse a ref if it's already a 40-byte hash
1304 if (CGitHash::IsValidSHA1(friendname
))
1306 hash
= CGitHash(friendname
);
1312 CAutoRepository
repo(GetGitRepository());
1316 return GetHash(repo
, hash
, friendname
, true);
1320 CString branch
= FixBranchName(friendname
);
1321 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1322 branch
= friendname
;
1324 cmd
.Format(_T("git.exe rev-parse %s"), (LPCTSTR
)branch
);
1326 int ret
= Run(cmd
, &gitLastErr
, nullptr, CP_UTF8
);
1327 hash
= CGitHash(gitLastErr
.Trim());
1330 else if (friendname
== _T("HEAD")) // special check for unborn branch
1332 CString currentbranch
;
1333 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1342 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1347 cmd
=_T("git.exe ls-files -s -t -z");
1349 if (Run(cmd
, &cmdout
))
1352 if (outputlist
.ParserFromLsFile(cmdout
))
1354 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1355 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1359 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1363 if (ignoreSpaceAtEol
)
1364 ignore
+= _T(" --ignore-space-at-eol");
1365 if (ignoreSpaceChange
)
1366 ignore
+= _T(" --ignore-space-change");
1368 ignore
+= _T(" --ignore-all-space");
1369 if (ignoreBlankLines
)
1370 ignore
+= _T(" --ignore-blank-lines");
1372 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1375 if(rev1
== GIT_REV_ZERO
)
1376 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1378 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev1
);
1381 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
, (LPCTSTR
)rev1
);
1387 return outputlist
.ParserFromLog(out
);
1390 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1392 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1393 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1397 int CGit::GetTagList(STRING_VECTOR
&list
)
1399 size_t prevCount
= list
.size();
1400 if (this->m_IsUseLibGit2
)
1402 CAutoRepository
repo(GetGitRepository());
1406 CAutoStrArray tag_names
;
1408 if (git_tag_list(tag_names
, repo
))
1411 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1413 CStringA
tagName(tag_names
->strings
[i
]);
1414 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1417 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1423 int ret
= Run(L
"git.exe tag -l", [&](const CStringA
& lineA
)
1425 if (lineA
.IsEmpty())
1427 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1430 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1431 else if (ret
== 1 && IsInitRepos())
1437 CString
CGit::GetGitLastErr(const CString
& msg
)
1439 if (this->m_IsUseLibGit2
)
1440 return GetLibGit2LastErr(msg
);
1441 else if (gitLastErr
.IsEmpty())
1442 return msg
+ _T("\nUnknown git.exe error.");
1445 CString lastError
= gitLastErr
;
1447 return msg
+ _T("\n") + lastError
;
1451 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1453 if (UsingLibGit2(cmd
))
1454 return GetLibGit2LastErr(msg
);
1455 else if (gitLastErr
.IsEmpty())
1456 return msg
+ _T("\nUnknown git.exe error.");
1459 CString lastError
= gitLastErr
;
1461 return msg
+ _T("\n") + lastError
;
1465 CString
CGit::GetLibGit2LastErr()
1467 const git_error
*libgit2err
= giterr_last();
1470 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1472 return _T("libgit2 returned: ") + lastError
;
1475 return _T("An error occoured in libgit2, but no message is available.");
1478 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1481 return msg
+ _T("\n") + GetLibGit2LastErr();
1482 return GetLibGit2LastErr();
1485 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1487 if(branchName
== "FETCH_HEAD")
1488 branchName
= DerefFetchHead();
1492 CString
CGit::FixBranchName(const CString
& branchName
)
1494 CString tempBranchName
= branchName
;
1495 FixBranchName_Mod(tempBranchName
);
1496 return tempBranchName
;
1499 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1503 CAutoRepository
repo(GetGitRepository());
1505 return true; // TODO: optimize error reporting
1507 CAutoReference tagRef
;
1508 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1511 CAutoReference branchRef
;
1512 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1519 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR
)name
, (LPCTSTR
)name
);
1522 Run(cmd
, [&](const CStringA
& lineA
)
1524 if (lineA
.IsEmpty())
1529 return (refCnt
<= 1);
1532 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1536 CAutoRepository
repo(GetGitRepository());
1538 return false; // TODO: optimize error reporting
1542 prefix
= _T("refs/heads/");
1544 prefix
= _T("refs/tags/");
1547 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1553 CString cmd
, output
;
1555 cmd
= _T("git.exe show-ref ");
1557 cmd
+= _T("--heads ");
1559 cmd
+= _T("--tags ");
1561 cmd
+= _T("refs/heads/") + name
;
1562 cmd
+= _T(" refs/tags/") + name
;
1564 int ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1567 if (!output
.IsEmpty())
1574 CString
CGit::DerefFetchHead()
1577 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1578 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1579 int forMergeLineCount
= 0;
1581 std::string hashToReturn
;
1582 while(getline(fetchHeadFile
, line
))
1584 //Tokenize this line
1585 std::string::size_type prevPos
= 0;
1586 std::string::size_type pos
= line
.find('\t');
1587 if(pos
== std::string::npos
) continue; //invalid line
1589 std::string hash
= line
.substr(0, pos
);
1590 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1592 bool forMerge
= pos
== prevPos
;
1593 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1595 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1600 hashToReturn
= hash
;
1601 ++forMergeLineCount
;
1602 if(forMergeLineCount
> 1)
1603 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1607 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1610 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1612 size_t prevCount
= list
.size();
1615 bool headIsDetached
= false;
1618 CAutoRepository
repo(GetGitRepository());
1622 if (git_repository_head_detached(repo
) == 1)
1623 headIsDetached
= true;
1625 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1627 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1628 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1629 flags
= GIT_BRANCH_ALL
;
1630 else if (type
& BRANCH_REMOTE
)
1631 flags
= GIT_BRANCH_REMOTE
;
1633 CAutoBranchIterator it
;
1634 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1637 git_reference
* ref
= nullptr;
1638 git_branch_t branchType
;
1639 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1641 CAutoReference
autoRef(ref
);
1642 const char * name
= nullptr;
1643 if (git_branch_name(&name
, ref
))
1646 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1647 if (branchType
& GIT_BRANCH_REMOTE
)
1648 list
.push_back(_T("remotes/") + branchname
);
1651 if (git_branch_is_head(ref
))
1653 list
.push_back(branchname
);
1660 CString cmd
= L
"git.exe branch --no-color";
1662 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1664 else if (type
& BRANCH_REMOTE
)
1667 ret
= Run(cmd
, [&](CStringA lineA
)
1669 lineA
.Trim(" \r\n\t");
1670 if (lineA
.IsEmpty())
1672 if (lineA
.Find(" -> ") >= 0)
1673 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1675 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1676 if (lineA
[0] == '*')
1678 branch
= branch
.Mid(2);
1681 // check whether HEAD is detached
1682 CString currentHead
;
1683 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1685 headIsDetached
= true;
1689 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1690 branch
= L
"remotes/" + branch
;
1691 list
.push_back(branch
);
1693 if (ret
== 1 && IsInitRepos())
1697 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1698 list
.push_back(L
"FETCH_HEAD");
1700 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1702 if (current
&& !headIsDetached
)
1704 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1717 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1719 size_t prevCount
= list
.size();
1720 if (this->m_IsUseLibGit2
)
1722 CAutoRepository
repo(GetGitRepository());
1726 CAutoStrArray remotes
;
1727 if (git_remote_list(remotes
, repo
))
1730 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1732 CStringA
remote(remotes
->strings
[i
]);
1733 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1736 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1741 return Run(L
"git.exe remote", [&](const CStringA
& lineA
)
1743 if (lineA
.IsEmpty())
1745 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1749 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1751 size_t prevCount
= list
.size();
1752 if (UsingLibGit2(GIT_CMD_FETCH
))
1754 CAutoRepository
repo(GetGitRepository());
1758 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1759 CAutoRemote gitremote
;
1760 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1763 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1764 callbacks
.credentials
= g_Git2CredCallback
;
1765 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1766 git_proxy_options proxy
= GIT_PROXY_OPTIONS_INIT
;
1767 proxy
.type
= GIT_PROXY_AUTO
;
1768 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
, &proxy
, nullptr) < 0)
1771 const git_remote_head
** heads
= nullptr;
1773 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1776 for (size_t i
= 0; i
< size
; i
++)
1778 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1780 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1782 // do not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1783 if (ref
.Find(_T("^{}")) >= 1)
1785 list
.push_back(shortname
);
1787 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1792 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), (LPCTSTR
)remote
);
1793 gitLastErr
= cmd
+ L
'\n';
1794 if (Run(cmd
, [&](CStringA lineA
)
1796 lineA
= lineA
.Mid(51); // sha1, tab + refs/tags/
1797 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1798 if (lineA
.Find("^{}") >= 1)
1800 if (!lineA
.IsEmpty())
1801 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1804 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1808 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1810 if (UsingLibGit2(GIT_CMD_PUSH
))
1812 CAutoRepository
repo(GetGitRepository());
1816 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1818 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1821 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1822 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1823 callbacks
.credentials
= g_Git2CredCallback
;
1824 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1825 std::vector
<CStringA
> refspecs
;
1826 for (const auto& ref
: list
)
1827 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1829 std::vector
<char*> vc
;
1830 vc
.reserve(refspecs
.size());
1831 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1832 git_strarray specs
= { &vc
[0], vc
.size() };
1834 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1839 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1840 for (const auto& ref
: list
)
1842 CString refspec
= _T(":") + ref
;
1843 mgtPush
.AddFile(refspec
);
1846 BOOL cancel
= FALSE
;
1847 mgtPush
.Execute(cancel
);
1853 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1855 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1856 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1860 int CGit::GetRefList(STRING_VECTOR
&list
)
1862 size_t prevCount
= list
.size();
1863 if (this->m_IsUseLibGit2
)
1865 CAutoRepository
repo(GetGitRepository());
1869 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1872 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1877 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1879 int start
= lineA
.Find(L
' ');
1880 ASSERT(start
== 40);
1884 CString name
= CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1));
1885 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1886 list
.push_back(name
);
1889 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1890 else if (ret
== 1 && IsInitRepos())
1895 typedef struct map_each_ref_payload
{
1896 git_repository
* repo
;
1897 MAP_HASH_NAME
* map
;
1898 } map_each_ref_payload
;
1900 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1902 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1904 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1906 CAutoObject gitObject
;
1907 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1910 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1912 str
+= _T("^{}"); // deref tag
1913 CAutoObject derefedTag
;
1914 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1916 gitObject
.Swap(derefedTag
);
1919 const git_oid
* oid
= git_object_id(gitObject
);
1923 CGitHash
hash((char *)oid
->id
);
1924 (*payloadContent
->map
)[hash
].push_back(str
);
1928 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1932 map_each_ref_payload payloadContent
= { repo
, &map
};
1934 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1937 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1939 std::sort(it
->second
.begin(), it
->second
.end());
1945 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1947 if (this->m_IsUseLibGit2
)
1949 CAutoRepository
repo(GetGitRepository());
1953 return GetMapHashToFriendName(repo
, map
);
1956 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1958 int start
= lineA
.Find(L
' ');
1959 ASSERT(start
== 40);
1964 hash
.ConvertFromStrA(lineA
.Left(start
));
1965 map
[hash
].push_back(CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1)));
1968 if (ret
== 1 && IsInitRepos())
1973 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1975 CAutoConfig
config(true);
1976 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1978 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1980 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1981 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1982 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1983 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1988 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1990 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1991 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1994 static void SetLibGit2TemplatePath(const CString
&value
)
1996 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1997 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
2000 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2002 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
2003 CString str
= msysdir
;
2004 if (!str
.IsEmpty() && PathFileExists(str
+ _T("\\git.exe")))
2006 CGit::ms_LastMsysGitDir
= str
;
2010 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2014 // first, search PATH if git/bin directory is already present
2017 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2018 msysdir
= CGit::ms_LastMsysGitDir
;
2023 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2024 str
= msyslocalinstalldir
;
2025 str
.TrimRight(_T("\\"));
2029 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2030 str
= msysinstalldir
;
2031 str
.TrimRight(_T("\\"));
2036 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2037 str
= msysinstalldir
;
2038 str
.TrimRight(_T("\\"));
2042 if (PathFileExists(str
+ _T("\\bin\\git.exe")))
2044 else if (PathFileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2048 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR
)str
);
2052 CGit::ms_LastMsysGitDir
= str
;
2057 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2061 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2067 this->m_Environment
.clear();
2068 m_Environment
.CopyProcessEnvironment();
2070 // set HOME if not set already
2072 _tgetenv_s(&homesize
, nullptr, 0, _T("HOME"));
2074 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2077 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2078 if (sshclient
.IsEmpty())
2079 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2081 if(!sshclient
.IsEmpty())
2083 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2084 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2088 TCHAR sPlink
[MAX_PATH
] = {0};
2089 GetModuleFileName(nullptr, sPlink
, _countof(sPlink
));
2090 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2092 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPlink.exe"));
2093 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2094 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2099 TCHAR sAskPass
[MAX_PATH
] = {0};
2100 GetModuleFileName(nullptr, sAskPass
, _countof(sAskPass
));
2101 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2104 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2105 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2106 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2107 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2111 if (!FindAndSetGitExePath(bFallback
))
2115 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2116 static const CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2117 static const int prefixes_len
[] = { 8, 8, 0 };
2118 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2124 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2125 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2129 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
2130 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\.."));
2131 CGit::ms_MsysGitRootDir
= msysGitDir
;
2133 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2134 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2136 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR
)CGit::ms_MsysGitRootDir
);
2138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), (LPCTSTR
)g_Git
.GetGitSystemConfig());
2139 if (!ms_bCygwinGit
&& !ms_bMsys2Git
)
2141 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ProgramData config = %s\n", (LPCTSTR
)g_Git
.GetGitProgramDataConfig());
2142 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitProgramDataConfig()).GetContainingDirectory().GetWinPathString());
2145 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2147 // Configure libgit2 search paths
2148 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2149 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2150 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2151 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 };
2152 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2153 git_transport_register("ssh+git", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2154 git_transport_register("git+ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2155 git_libgit2_opts(GIT_OPT_SET_USER_AGENT
, "TortoiseGit libgit2");
2156 if (!(ms_bCygwinGit
|| ms_bMsys2Git
))
2157 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2159 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2161 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2162 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2164 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2165 // register filter only once
2166 if (!git_filter_lookup("filter"))
2169 for (const CString
& binDirPrefix
: { L
"\\..\\usr\\bin", L
"\\..\\bin", L
"" })
2171 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2172 if (PathFileExists(possibleShExe
))
2175 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2176 sh
.Format(L
"\"%s\"", (LPCTSTR
)temp
);
2177 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2178 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2183 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2184 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2185 CString gitExecPath
= CGit::ms_MsysGitRootDir
;
2186 gitExecPath
.Append(_T("libexec\\git-core"));
2187 m_Environment
.AddToPath(gitExecPath
);
2189 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2194 m_bInitialized
= TRUE
;
2198 CString
CGit::GetHomeDirectory() const
2200 const wchar_t * homeDir
= wget_windows_home_directory();
2201 return CString(homeDir
, (int)wcslen(homeDir
));
2204 CString
CGit::GetGitLocalConfig() const
2207 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2208 path
+= _T("config");
2212 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2214 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2217 CString
CGit::GetGitGlobalConfig() const
2219 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2222 CString
CGit::GetGitGlobalXDGConfigPath() const
2224 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2227 CString
CGit::GetGitGlobalXDGConfig() const
2229 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2232 CString
CGit::GetGitProgramDataConfig() const
2234 const wchar_t* programdataConfig
= wget_program_data_config();
2235 return CString(programdataConfig
);
2238 CString
CGit::GetGitSystemConfig() const
2240 const wchar_t * systemConfig
= wget_msysgit_etc();
2241 return CString(systemConfig
, (int)wcslen(systemConfig
));
2244 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2246 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2248 CAutoRepository
repo(GetGitRepository());
2252 if (git_repository_head_unborn(repo
))
2255 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2256 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2257 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2259 CAutoStatusList status
;
2260 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2263 return (0 == git_status_list_entrycount(status
));
2268 cmd
=_T("git.exe rev-parse --verify HEAD");
2270 if(Run(cmd
,&out
,CP_UTF8
))
2273 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2274 if(Run(cmd
,&out
,CP_UTF8
))
2277 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2278 if(Run(cmd
,&out
,CP_UTF8
))
2281 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2282 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2287 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2290 for (int i
= 0; i
< list
.GetCount(); ++i
)
2292 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2298 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2302 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2304 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2306 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2312 // if the filenames only differ in case, we have to pass "-f"
2313 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2315 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR
)force
, (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2316 if (Run(cmd
, &err
, CP_UTF8
))
2321 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2322 if (Run(cmd
, &err
, CP_UTF8
))
2326 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitOldPathString());
2327 if (Run(cmd
, &err
, CP_UTF8
))
2330 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2331 { //To init git repository, there are not HEAD, so we can use git reset command
2332 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2334 if (Run(cmd
, &err
, CP_UTF8
))
2339 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitPathString());
2340 if (Run(cmd
, &err
, CP_UTF8
))
2344 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2346 cmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2347 if (Run(cmd
, &err
, CP_UTF8
))
2354 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2359 if (git_repository_index(index
.GetPointer(), repo
))
2362 return git_index_has_conflicts(index
);
2365 int CGit::HasWorkingTreeConflicts()
2367 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2369 CAutoRepository
repo(GetGitRepository());
2373 return HasWorkingTreeConflicts(repo
);
2376 CString cmd
= _T("git.exe ls-files -u -t -z");
2379 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2382 return output
.IsEmpty() ? 0 : 1;
2385 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2387 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2389 CAutoRepository
repo(GetGitRepository());
2393 CGitHash fromHash
, toHash
, baseHash
;
2394 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2397 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2401 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2404 baseHash
= baseOid
.id
;
2407 *commonAncestor
= baseHash
;
2409 return fromHash
== baseHash
;
2413 CGitHash basehash
,hash
;
2415 cmd
.Format(_T("git.exe merge-base %s %s"), (LPCTSTR
)FixBranchName(to
), (LPCTSTR
)FixBranchName(from
));
2417 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2419 basehash
= base
.Trim();
2421 GetHash(hash
, from
);
2424 *commonAncestor
= basehash
;
2426 return hash
== basehash
;
2429 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2432 for (int i
= 0; i
< 4; ++i
)
2435 ret
|= hash
.m_hash
[i
];
2440 int CGit::RefreshGitIndex()
2442 if(g_Git
.m_IsUseGitDLL
)
2444 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2447 int result
= [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2461 cmd
=_T("git.exe update-index --refresh");
2462 return Run(cmd
, &output
, CP_UTF8
);
2466 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2468 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2470 CAutoRepository
repo(GetGitRepository());
2475 if (GetHash(repo
, hash
, Refname
))
2479 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2483 if (git_commit_tree(tree
.GetPointer(), commit
))
2486 CAutoTreeEntry entry
;
2487 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2491 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2494 CAutoFILE file
= _tfsopen(outputfile
, _T("wb"), SH_DENYWR
);
2495 if (file
== nullptr)
2497 giterr_set_str(GITERR_NONE
, "Could not create file.");
2501 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2503 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2505 giterr_set_str(GITERR_OS
, "Could not write to file.");
2511 else if (g_Git
.m_IsUseGitDLL
)
2513 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2516 g_Git
.CheckAndInitDll();
2517 CStringA ref
, patha
, outa
;
2518 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2519 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2520 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2521 ::DeleteFile(outputfile
);
2522 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2523 outa
.ReleaseBuffer();
2527 catch (const char * msg
)
2529 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2534 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2541 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR
)Refname
, (LPCTSTR
)path
.GetGitPathString());
2542 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2546 void CEnvironment::clear()
2552 bool CEnvironment::empty()
2554 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2557 CEnvironment::operator LPTSTR()
2561 return &__super::at(0);
2564 CEnvironment::operator LPWSTR
*()
2569 void CEnvironment::CopyProcessEnvironment()
2573 TCHAR
*porig
= GetEnvironmentStrings();
2575 while(*p
!=0 || *(p
+1) !=0)
2576 this->push_back(*p
++);
2578 push_back(_T('\0'));
2579 push_back(_T('\0'));
2580 baseptr
= &__super::at(0);
2582 FreeEnvironmentStrings(porig
);
2585 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2588 for (size_t i
= 0; i
< size(); ++i
)
2592 CString sname
= str
.Tokenize(_T("="),start
);
2593 if(sname
.CompareNoCase(name
) == 0)
2594 return &(*this)[i
+start
];
2600 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2603 for (i
= 0; i
< size(); ++i
)
2605 CString str
= &(*this)[i
];
2607 CString sname
= str
.Tokenize(_T("="),start
);
2608 if(sname
.CompareNoCase(name
) == 0)
2615 if (!value
) // as we haven't found the variable we want to remove, just return
2617 if (i
== 0) // make inserting into an empty environment work
2619 this->push_back(_T('\0'));
2622 i
-= 1; // roll back terminate \0\0
2623 this->push_back(_T('\0'));
2626 CEnvironment::iterator it
;
2630 while(*it
&& i
<size())
2637 if (value
== nullptr) // remove the variable
2643 baseptr
= &__super::at(0);
2649 this->insert(it
,*name
++);
2654 this->insert(it
, _T('='));
2660 this->insert(it
,*value
++);
2664 baseptr
= &__super::at(0);
2667 void CEnvironment::AddToPath(CString value
)
2669 value
.TrimRight(L
"\\");
2670 if (value
.IsEmpty())
2673 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2675 // do not double add paths to %PATH%
2676 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2681 SetEnv(L
"PATH", path
);
2684 int CGit::GetGitEncode(TCHAR
* configkey
)
2686 CString str
=GetConfigValue(configkey
);
2691 return CUnicodeUtils::GetCPCode(str
);
2695 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2701 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2706 diff
= GetGitDiff();
2708 git_open_diff(&diff
, arg
);
2712 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2723 isStat
= !!strstr(arg
, "stat");
2728 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2730 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2739 for (int j
= 0; j
< count
; ++j
)
2748 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2749 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2750 &mode
,&IsBin
,&inc
,&dec
);
2752 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2753 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2755 path
.SetFromGit(strnewname
,&stroldname
);
2756 path
.ParserAction((BYTE
)mode
);
2760 path
.m_StatAdd
=_T("-");
2761 path
.m_StatDel
=_T("-");
2765 path
.m_StatAdd
.Format(_T("%d"),inc
);
2766 path
.m_StatDel
.Format(_T("%d"),dec
);
2768 PathList
->AddPath(path
);
2770 git_diff_flush(diff
);
2773 git_close_diff(diff
);
2778 int CGit::GetShortHASHLength() const
2783 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2787 REF_TYPE type
= CGit::UNKNOWN
;
2789 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2790 type
= CGit::LOCAL_BRANCH
;
2791 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2792 type
= CGit::REMOTE_BRANCH
;
2793 else if (str
.Right(3) == L
"^{}" && CGit::GetShortName(str
, shortname
, L
"refs/tags/"))
2794 type
= CGit::ANNOTATED_TAG
;
2795 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2797 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2800 shortname
=_T("stash");
2802 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2806 g_Git
.GetBisectTerms(&bisectGood
, &bisectBad
);
2808 if (wcsncmp(shortname
, bisectGood
, bisectGood
.GetLength()) == 0 && ((c
= shortname
.GetAt(bisectGood
.GetLength())) == '-' || c
== '\0'))
2810 type
= CGit::BISECT_GOOD
;
2811 shortname
= bisectGood
;
2814 if (wcsncmp(shortname
, bisectBad
, bisectBad
.GetLength()) == 0 && ((c
= shortname
.GetAt(bisectBad
.GetLength())) == '-' || c
== '\0'))
2816 type
= CGit::BISECT_BAD
;
2817 shortname
= bisectBad
;
2820 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2822 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2823 type
= CGit::UNKNOWN
;
2826 type
= CGit::UNKNOWN
;
2836 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2838 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2841 void CGit::SetGit2CredentialCallback(void* callback
)
2843 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2846 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2848 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2851 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
2854 if (rev2
== GitRev::GetWorkingCopy())
2855 cmd
.Format(_T("git.exe diff --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
);
2856 else if (rev1
== GitRev::GetWorkingCopy())
2857 cmd
.Format(_T("git.exe diff -R --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev2
);
2868 if (diffContext
>= 0)
2869 unified
.Format(_T(" --unified=%d"), diffContext
);
2870 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
);
2873 if (!path
.IsEmpty())
2876 cmd
+= path
.GetGitPathString();
2883 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2885 ATLASSERT(payload
&& text
);
2886 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2887 fwrite("\n", 1, 1, (FILE *)payload
);
2890 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2892 ATLASSERT(payload
&& line
);
2893 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2894 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2895 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2899 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2901 ATLASSERT(repo
&& identifier
&& tree
);
2903 /* try to resolve identifier */
2905 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2909 return GIT_ENOTFOUND
;
2912 switch (git_object_type(obj
))
2915 *tree
= (git_tree
*)obj
.Detach();
2917 case GIT_OBJ_COMMIT
:
2918 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2921 err
= GIT_ENOTFOUND
;
2927 /* use libgit2 get unified diff */
2928 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
)
2930 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2931 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2933 CAutoRepository
repo(g_Git
.GetGitRepository());
2937 int isHeadOrphan
= git_repository_head_unborn(repo
);
2938 if (isHeadOrphan
== 1)
2940 else if (isHeadOrphan
!= 0)
2943 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2944 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2945 char *buf
= pathA
.GetBuffer();
2946 if (!pathA
.IsEmpty())
2948 opts
.pathspec
.strings
= &buf
;
2949 opts
.pathspec
.count
= 1;
2953 opts
.new_prefix
= "";
2954 opts
.old_prefix
= "";
2958 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2963 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2966 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2969 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2972 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2975 if (git_diff_merge(diff
, diff2
))
2980 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2983 if (tree1
.IsEmpty())
2991 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2994 if (tree2
.IsEmpty())
2996 /* don't check return value, there are not parent commit at first commit*/
2997 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2999 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
3001 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
3005 CAutoDiffStats stats
;
3006 if (git_diff_get_stats(stats
.GetPointer(), diff
))
3009 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
3011 statCallback(statBuf
, data
);
3013 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
3016 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
3019 if (git_patch_print(patch
, callback
, data
))
3023 pathA
.ReleaseBuffer();
3028 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
)
3030 if (UsingLibGit2(GIT_CMD_DIFF
))
3032 CAutoFILE file
= _tfsopen(patchfile
, _T("w"), SH_DENYRW
);
3035 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
, bNoPrefix
);
3040 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
, bNoPrefix
);
3041 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3045 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3047 ATLASSERT(payload
&& text
);
3048 CStringA
*str
= (CStringA
*) payload
;
3049 str
->Append(text
->ptr
, (int)text
->size
);
3050 str
->AppendChar('\n');
3053 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3055 ATLASSERT(payload
&& line
);
3056 CStringA
*str
= (CStringA
*) payload
;
3057 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3058 str
->Append(&line
->origin
, 1);
3059 str
->Append(line
->content
, (int)line
->content_len
);
3063 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3065 if (UsingLibGit2(GIT_CMD_DIFF
))
3066 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
, false);
3070 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3072 int ret
= Run(cmd
, &vector
);
3073 if (!vector
.empty())
3075 vector
.push_back(0); // vector is not NUL terminated
3076 buffer
->Append((char *)&vector
[0]);
3082 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3084 if (UsingLibGit2(GIT_CMD_REVERT
))
3086 CAutoRepository
repo(GetGitRepository());
3091 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3094 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3095 revert_opts
.mainline
= parent
;
3096 int result
= git_revert(repo
, commit
, &revert_opts
);
3098 return !result
? 0 : -1;
3104 merge
.Format(_T("-m %d "), parent
);
3105 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR
)merge
, (LPCTSTR
)hash
.ToString());
3106 gitLastErr
= cmd
+ _T("\n");
3107 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3117 int CGit::DeleteRef(const CString
& reference
)
3119 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3121 CAutoRepository
repo(GetGitRepository());
3126 if (reference
.Right(3) == _T("^{}"))
3127 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3129 refA
= CUnicodeUtils::GetUTF8(reference
);
3132 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3136 if (git_reference_is_tag(ref
))
3137 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3138 else if (git_reference_is_branch(ref
))
3139 result
= git_branch_delete(ref
);
3140 else if (git_reference_is_remote(ref
))
3141 result
= git_branch_delete(ref
);
3143 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3149 CString cmd
, shortname
;
3150 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3151 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)shortname
);
3152 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3153 cmd
.Format(_T("git.exe tag -d -- %s"), (LPCTSTR
)shortname
);
3154 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3155 cmd
.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR
)shortname
);
3158 gitLastErr
= L
"unsupported reference type: " + reference
;
3162 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3170 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3172 if (!PathFileExists(filename
))
3175 CAutoFILE pFile
= _tfsopen(filename
, _T("r"), SH_DENYWR
);
3178 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3179 return true; // load no further files
3185 char s
[8196] = { 0 };
3186 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3189 str
+= CStringA(s
, read
);
3191 msg
+= CUnicodeUtils::GetUnicode(str
);
3192 msg
.Replace(_T("\r\n"), _T("\n"));
3193 msg
.TrimRight(_T("\n"));
3196 return true; // load no further files
3199 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3202 return GetInitAddList(result
);
3208 count
= filterlist
->GetCount();
3210 CString head
= _T("HEAD");
3212 head
= _T("HEAD~1");
3214 for (int i
= 0; i
< count
; ++i
)
3218 if (ms_bCygwinGit
|| ms_bMsys2Git
)
3220 // Prevent showing all files as modified when using cygwin's git
3222 cmd
= _T("git.exe status --");
3224 cmd
.Format(_T("git.exe status -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3229 // also list staged files which will be in the commit
3230 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3233 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3235 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3238 if (Run(cmd
, &cmdout
, &cmdErr
))
3240 int last
= cmdErr
.RevertFind(0, -1);
3242 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3243 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3246 out
.append(cmdout
, 0);
3248 result
.ParserFromLog(out
);
3250 std::map
<CString
, int> duplicateMap
;
3251 for (int i
= 0; i
< result
.GetCount(); ++i
)
3252 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), i
));
3254 // handle delete conflict case, when remote : modified, local : deleted.
3255 for (int i
= 0; i
< count
; ++i
)
3261 cmd
= _T("git.exe ls-files -u -t -z");
3263 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3267 CTGitPathList conflictlist
;
3268 conflictlist
.ParserFromLog(cmdout
);
3269 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3271 auto existing
= duplicateMap
.find(conflictlist
[j
].GetGitPathString());
3272 if (existing
!= duplicateMap
.end())
3274 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3275 p
.m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3279 result
.AddPath(conflictlist
[j
]);
3280 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3285 // handle source files of file renames/moves (issue #860)
3286 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3287 for (int i
= 0; i
< count
; ++i
)
3293 cmd
= _T("git.exe ls-files -d -z");
3295 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3299 CTGitPathList deletelist
;
3300 deletelist
.ParserFromLog(cmdout
, true);
3301 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3303 auto existing
= duplicateMap
.find(deletelist
[j
].GetGitPathString());
3304 if (existing
== duplicateMap
.end())
3306 result
.AddPath(deletelist
[j
]);
3307 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3311 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3312 p
.m_Action
|= CTGitPath::LOGACTIONS_MISSING
;
3320 int CGit::IsRebaseRunning()
3323 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3326 if (PathIsDirectory(adminDir
+ L
"rebase-apply") || PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3331 void CGit::GetBisectTerms(CString
* good
, CString
* bad
)
3333 static CString lastGood
;
3334 static CString lastBad
;
3335 static ULONGLONG lastRead
= 0;
3345 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3346 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3347 // as we only read a small file the performance effects should be negligible
3348 if (lastRead
+ 5000 > GetTickCount64())
3356 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir
, adminDir
))
3359 CString termsFile
= adminDir
+ L
"BISECT_TERMS";
3361 _tfopen_s(fp
.GetPointer(), termsFile
, L
"rb");
3364 char badA
[MAX_PATH
] = { 0 };
3365 fgets(badA
, MAX_PATH
, fp
);
3366 size_t len
= strlen(badA
);
3367 if (len
> 0 && badA
[len
- 1] == '\n')
3368 badA
[len
- 1] = '\0';
3369 char goodA
[MAX_PATH
] = { 0 };
3370 fgets(goodA
, MAX_PATH
, fp
);
3371 len
= strlen(goodA
);
3372 if (len
> 0 && goodA
[len
- 1] == '\n')
3373 goodA
[len
- 1] = '\0';
3374 lastGood
= CUnicodeUtils::GetUnicode(goodA
);
3375 lastBad
= CUnicodeUtils::GetUnicode(badA
);
3376 lastRead
= GetTickCount64();
3379 int CGit::GetGitVersion(CString
* versiondebug
, CString
* errStr
)
3381 CString version
, err
;
3382 if (Run(_T("git.exe --version"), &version
, &err
, CP_UTF8
))
3392 *versiondebug
= version
;
3396 CString str
= version
.Tokenize(_T("."), start
);
3397 int space
= str
.ReverseFind(_T(' '));
3398 str
= str
.Mid(space
+ 1, start
);
3402 version
= version
.Mid(start
);
3405 str
= version
.Tokenize(_T("."), start
);
3406 ver
|= (_ttol(str
) & 0xFF) << 16;
3408 str
= version
.Tokenize(_T("."), start
);
3409 ver
|= (_ttol(str
) & 0xFF) << 8;
3411 str
= version
.Tokenize(_T("."), start
);
3412 ver
|= (_ttol(str
) & 0xFF);