1
// TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - 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.
24 #include "GitForWindows.h"
25 #include "UnicodeUtils.h"
29 #include "FormatMessageWrapper.h"
30 #include "SmartHandle.h"
31 #include "MassiveGitTaskBase.h"
32 #include "git2/sys/filter.h"
33 #include "git2/sys/transport.h"
34 #include "../libgit2/filter-filter.h"
35 #include "../libgit2/ssh-wintunnel.h"
37 static int CalculateDiffSimilarityIndexThreshold(DWORD index
)
39 if (index
< 0 || index
> 100)
44 bool CGit::ms_bCygwinGit
= (CRegDWORD(L
"Software\\TortoiseGit\\CygwinHack", FALSE
) == TRUE
);
45 bool CGit::ms_bMsys2Git
= (CRegDWORD(L
"Software\\TortoiseGit\\Msys2Hack", FALSE
) == TRUE
);
46 int CGit::ms_iSimilarityIndexThreshold
= CalculateDiffSimilarityIndexThreshold(CRegDWORD(L
"Software\\TortoiseGit\\DiffSimilarityIndexThreshold", 50));
47 int CGit::m_LogEncode
=CP_UTF8
;
48 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
50 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
52 if (!path
|| !buf
|| buflen
== 0)
55 const wchar_t* base
= path
;
56 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
58 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
61 *buf
= L
'\0'; /* reserved a byte via initial subtract */
63 while (*path
== term
|| *path
== L
';')
66 return (path
!= base
) ? path
: nullptr;
69 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
71 TCHAR buf
[MAX_PATH
] = { 0 };
73 // search in all paths defined in PATH
74 while ((env
= nextpath(env
, buf
, _countof(buf
) - 1)) != nullptr && *buf
)
76 TCHAR
* pfin
= buf
+ wcslen(buf
) - 1;
78 // ensure trailing slash
79 if (*pfin
!= L
'/' && *pfin
!= L
'\\')
80 wcscpy_s(++pfin
, 2, L
"\\"); // we have enough space left, MAX_PATH-1 is used in nextpath above
82 const size_t len
= wcslen(buf
);
84 if ((len
+ filename
.GetLength()) < _countof(buf
))
85 wcscpy_s(pfin
+ 1, _countof(buf
) - len
, filename
);
89 if (PathFileExists(buf
))
100 static BOOL
FindGitPath()
103 _wgetenv_s(&size
, nullptr, 0, L
"PATH");
107 auto env
= std::make_unique
<TCHAR
[]>(size
);
110 _wgetenv_s(&size
, env
.get(), size
, L
"PATH");
112 CString gitExeDirectory
= FindFileOnPath(L
"git.exe", env
.get(), true);
113 if (!gitExeDirectory
.IsEmpty())
115 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
116 CGit::ms_LastMsysGitDir
.TrimRight(L
'\\');
117 if (CStringUtils::EndsWith(CGit::ms_LastMsysGitDir
, L
"\\mingw32\\bin") || CStringUtils::EndsWith(CGit::ms_LastMsysGitDir
, L
"\\mingw64\\bin"))
119 // prefer cmd directory as early Git for Windows 2.x releases only had this
120 CString installRoot
= CGit::ms_LastMsysGitDir
.Left(CGit::ms_LastMsysGitDir
.GetLength() - (int)wcslen(L
"\\mingw64\\bin")) + L
"\\cmd\\git.exe";
121 if (PathFileExists(installRoot
))
122 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Left(CGit::ms_LastMsysGitDir
.GetLength() - (int)wcslen(L
"\\mingw64\\bin")) + L
"\\cmd";
124 if (CStringUtils::EndsWith(CGit::ms_LastMsysGitDir
, L
"\\cmd"))
126 // often the msysgit\cmd folder is on the %PATH%, but
127 // that git.exe does not work, so try to guess the bin folder
128 if (PathFileExists(CGit::ms_LastMsysGitDir
.Left(CGit::ms_LastMsysGitDir
.GetLength() - (int)wcslen(L
"\\cmd")) + L
"\\bin\\git.exe"))
129 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Left(CGit::ms_LastMsysGitDir
.GetLength() - (int)wcslen(L
"\\cmd")) + L
"\\bin";
137 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
139 CString filename
= executable
;
141 if (!CStringUtils::EndsWith(executable
, L
".exe"))
144 if (PathFileExists(filename
))
147 filename
= FindFileOnPath(filename
, env
);
148 if (!filename
.IsEmpty())
154 static bool g_bSortLogical
;
155 static bool g_bSortLocalBranchesFirst
;
156 static bool g_bSortTagsReversed
;
157 static git_cred_acquire_cb g_Git2CredCallback
;
158 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
160 static void GetSortOptions()
162 #ifdef GTEST_INCLUDE_GTEST_GTEST_H_
163 g_bSortLogical
= true;
164 g_bSortLocalBranchesFirst
= true;
165 g_bSortTagsReversed
= false;
167 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
169 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
170 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
171 if (g_bSortLocalBranchesFirst
)
172 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
173 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
174 if (!g_bSortTagsReversed
)
175 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
179 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
182 return StrCmpLogicalW(left
, right
) < 0;
183 return StrCmpI(left
, right
) < 0;
186 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
188 return LogicalComparePredicate(right
, left
);
191 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
193 if (g_bSortLocalBranchesFirst
)
195 bool leftIsRemote
= CStringUtils::StartsWith(left
, L
"remotes/");
196 bool rightIsRemote
= CStringUtils::StartsWith(right
, L
"remotes/");
198 if (leftIsRemote
&& !rightIsRemote
)
200 else if (!leftIsRemote
&& rightIsRemote
)
203 return LogicalComparePredicate(left
, right
);
206 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
208 CString
CGit::ms_LastMsysGitDir
;
209 CString
CGit::ms_MsysGitRootDir
;
210 int CGit::ms_LastMsysGitVersion
= 0;
217 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
218 m_IsGitDllInited
= false;
220 m_GitSimpleListDiff
=0;
221 m_IsUseGitDLL
= !!CRegDWORD(L
"Software\\TortoiseGit\\UsingGitDLL",1);
222 m_IsUseLibGit2
= !!CRegDWORD(L
"Software\\TortoiseGit\\UseLibgit2", TRUE
);
223 m_IsUseLibGit2_mask
= CRegDWORD(L
"Software\\TortoiseGit\\UseLibgit2_mask", DEFAULT_USE_LIBGIT2_MASK
);
225 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
228 this->m_bInitialized
=false;
230 m_critGitDllSec
.Init();
231 m_critSecThreadMap
.Init();
238 git_close_diff(m_GitDiff
);
241 if(this->m_GitSimpleListDiff
)
243 git_close_diff(m_GitSimpleListDiff
);
244 m_GitSimpleListDiff
=0;
246 git_libgit2_shutdown();
247 m_critSecThreadMap
.Term();
248 m_critGitDllSec
.Term();
251 bool CGit::IsBranchNameValid(const CString
& branchname
)
253 if (CStringUtils::StartsWith(branchname
, L
"-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
255 if (branchname
.FindOneOf(L
"\"|<>") >= 0) // not valid on Windows
257 if (branchname
== L
"HEAD") // Branch name HEAD is discouraged since Git v2.16.0, see https://github.com/git/git/commit/a625b092cc59940521789fe8a3ff69c8d6b14eb2
259 CStringA branchA
= CUnicodeUtils::GetUTF8(L
"refs/heads/" + branchname
);
260 return !!git_reference_is_valid_name(branchA
);
263 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
* piOut
, HANDLE
* hReadOut
, HANDLE
* hErrReadOut
, const CString
* StdioFile
)
265 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
, hWriteIn
, hReadIn
;
266 CAutoFile hStdioFile
;
268 SECURITY_ATTRIBUTES sa
= { 0 };
269 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
270 sa
.bInheritHandle
=TRUE
;
271 if (!CreatePipe(hReadIn
.GetPointer(), hWriteIn
.GetPointer(), &sa
, 0))
273 CString err
= CFormatMessageWrapper();
274 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stdin pipe: %s\n", (LPCTSTR
)err
.Trim());
275 return TGIT_GIT_ERROR_OPEN_PIP
;
277 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
279 CString err
= CFormatMessageWrapper();
280 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stdout pipe: %s\n", (LPCTSTR
)err
.Trim());
281 return TGIT_GIT_ERROR_OPEN_PIP
;
283 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
285 CString err
= CFormatMessageWrapper();
286 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stderr pipe: %s\n", (LPCTSTR
)err
.Trim());
287 return TGIT_GIT_ERROR_OPEN_PIP
;
291 hStdioFile
= CreateFile(*StdioFile
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
293 STARTUPINFO si
= { 0 };
294 PROCESS_INFORMATION pi
= { 0 };
295 si
.cb
=sizeof(STARTUPINFO
);
296 si
.hStdInput
= hReadIn
;
298 si
.hStdError
= hWriteErr
;
300 si
.hStdError
= hWrite
;
302 si
.hStdOutput
=hStdioFile
;
304 si
.hStdOutput
=hWrite
;
306 si
.wShowWindow
=SW_HIDE
;
307 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
309 LPTSTR pEnv
= m_Environment
;
310 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
311 dwFlags
|= CREATE_NEW_PROCESS_GROUP
| DETACHED_PROCESS
;
313 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
315 bool startsWithGit
= CStringUtils::StartsWith(cmd
, L
"git");
316 if (ms_bMsys2Git
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
318 cmd
.Replace(L
"\\", L
"\\\\\\\\");
319 cmd
.Replace(L
"\"", L
"\\\"");
320 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\bash.exe\" -c \"/usr/bin/" + cmd
+ L
'"';
322 else if (ms_bCygwinGit
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
324 cmd
.Replace(L
'\\', L
'/');
325 cmd
.Replace(L
"\"", L
"\\\"");
326 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\bash.exe\" -c \"/bin/" + cmd
+ L
'"';
328 else if (startsWithGit
|| CStringUtils::StartsWith(cmd
, L
"bash"))
330 int firstSpace
= cmd
.Find(L
' ');
332 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
'\\' + cmd
.Left(firstSpace
) + L
'"' + cmd
.Mid(firstSpace
);
334 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
'\\' + cmd
+ L
'"';
337 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": executing %s\n", (LPCTSTR
)cmd
);
338 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
340 CString err
= CFormatMessageWrapper();
341 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": error while executing command: %s\n", (LPCTSTR
)err
.Trim());
342 return TGIT_GIT_ERROR_CREATE_PROCESS
;
345 // Close the pipe handle so the child process stops reading.
346 hWriteIn
.CloseHandle();
353 *hReadOut
= hRead
.Detach();
355 *hErrReadOut
= hReadErr
.Detach();
358 //Must use sperate function to convert ANSI str to union code string
359 //Because A2W use stack as internal convert buffer.
360 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
367 len
= (int)strlen((const char*)p
);
372 int currentContentLen
= str
->GetLength();
373 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
374 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
375 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
378 // This method was originally used to check for orphaned branches
379 BOOL
CGit::CanParseRev(CString ref
)
385 if (Run(L
"git.exe rev-parse --revs-only " + ref
, &cmdout
, CP_UTF8
))
393 // Checks if we have an orphaned HEAD
394 BOOL
CGit::IsInitRepos()
397 if (GetHash(hash
, L
"HEAD") != 0)
399 return hash
.IsEmpty() ? TRUE
: FALSE
;
402 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
404 PASYNCREADSTDERRTHREADARGS pDataArray
;
405 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
408 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
409 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
411 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
419 void CGit::KillRelatedThreads(CWinThread
* thread
)
421 CAutoLocker
lock(m_critSecThreadMap
);
422 auto it
= m_AsyncReadStdErrThreadMap
.find(thread
->m_nThreadID
);
423 if (it
!= m_AsyncReadStdErrThreadMap
.cend())
425 TerminateThread(it
->second
, (DWORD
)-1);
426 m_AsyncReadStdErrThreadMap
.erase(it
);
428 TerminateThread(thread
->m_hThread
, (DWORD
)-1);
432 int CGit::Run(CGitCall
* pcall
)
434 PROCESS_INFORMATION pi
;
435 CAutoGeneralHandle hRead
, hReadErr
;
436 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
437 return TGIT_GIT_ERROR_CREATE_PROCESS
;
439 CAutoGeneralHandle
piThread(std::move(pi
.hThread
));
440 CAutoGeneralHandle
piProcess(std::move(pi
.hProcess
));
442 ASYNCREADSTDERRTHREADARGS threadArguments
;
443 threadArguments
.fileHandle
= hReadErr
;
444 threadArguments
.pcall
= pcall
;
445 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
449 CAutoLocker
lock(m_critSecThreadMap
);
450 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
454 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
456 while (ReadFile(hRead
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
458 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
459 if(!bAborted
)//For now, flush output when command aborted.
460 if(pcall
->OnOutputData(data
,readnumber
))
468 WaitForSingleObject(thread
, INFINITE
);
470 CAutoLocker
lock(m_critSecThreadMap
);
471 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
474 WaitForSingleObject(pi
.hProcess
, INFINITE
);
477 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
479 CString err
= CFormatMessageWrapper();
480 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not get exit code: %s\n", (LPCTSTR
)err
.Trim());
481 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
484 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": process exited: %d\n", exitcode
);
488 class CGitCall_ByteVector
: public CGitCall
491 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= nullptr) : CGitCall(cmd
),m_pvector(pvector
), m_pvectorErr(pvectorErr
) {}
492 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
494 if (!m_pvector
|| size
== 0)
496 size_t oldsize
=m_pvector
->size();
497 m_pvector
->resize(m_pvector
->size()+size
);
498 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
501 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
503 if (!m_pvectorErr
|| size
== 0)
505 size_t oldsize
= m_pvectorErr
->size();
506 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
507 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
510 BYTE_VECTOR
* m_pvector
;
511 BYTE_VECTOR
* m_pvectorErr
;
513 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
515 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
518 int CGit::Run(CString cmd
, CString
* output
, int code
)
522 ret
= Run(cmd
, output
, &err
, code
);
524 if (output
&& !err
.IsEmpty())
526 if (!output
->IsEmpty())
533 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
535 BYTE_VECTOR vector
, vectorErr
;
538 ret
= Run(cmd
, &vector
, &vectorErr
);
540 ret
= Run(cmd
, &vector
);
543 StringAppend(output
, vector
.data(), code
);
547 vectorErr
.push_back(0);
548 StringAppend(outputErr
, vectorErr
.data(), code
);
554 class CGitCallCb
: public CGitCall
557 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
, BYTE_VECTOR
* pvectorErr
= nullptr)
560 , m_pvectorErr(pvectorErr
)
563 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
568 int oldEndPos
= m_buffer
.GetLength();
569 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
570 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
572 // Break into lines and feed to m_recv
574 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
576 m_recv(m_buffer
.Left(eolPos
));
577 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
582 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
584 if (!m_pvectorErr
|| size
== 0)
586 size_t oldsize
= m_pvectorErr
->size();
587 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
588 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
592 virtual void OnEnd() override
594 if (!m_buffer
.IsEmpty())
596 m_buffer
.Empty(); // Just for sure
600 GitReceiverFunc m_recv
;
602 BYTE_VECTOR
* m_pvectorErr
;
605 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
, CString
* outputErr
)
609 BYTE_VECTOR vectorErr
;
610 CGitCallCb
call(cmd
, recv
, &vectorErr
);
611 int ret
= Run(&call
);
612 vectorErr
.push_back(0);
613 StringAppend(outputErr
, vectorErr
.data());
617 CGitCallCb
call(cmd
, recv
);
621 CString
CGit::GetUserName(void)
624 env
.CopyProcessEnvironment();
625 CString envname
= env
.GetEnv(L
"GIT_AUTHOR_NAME");
626 if (!envname
.IsEmpty())
628 return GetConfigValue(L
"user.name");
630 CString
CGit::GetUserEmail(void)
633 env
.CopyProcessEnvironment();
634 CString envmail
= env
.GetEnv(L
"GIT_AUTHOR_EMAIL");
635 if (!envmail
.IsEmpty())
638 return GetConfigValue(L
"user.email");
641 CString
CGit::GetConfigValue(const CString
& name
, const CString
& def
, bool wantBool
)
644 if(this->m_IsUseGitDLL
)
646 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
655 key
= CUnicodeUtils::GetUTF8(name
);
659 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
662 catch (const char *msg
)
664 ::MessageBox(nullptr, L
"Could not get config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
668 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
674 cmd
.Format(L
"git.exe config%s %s", wantBool
? L
" --bool" : L
"", (LPCTSTR
)name
);
675 if (Run(cmd
, &configValue
, nullptr, CP_UTF8
))
677 if (configValue
.IsEmpty())
679 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
683 bool CGit::GetConfigValueBool(const CString
& name
, const bool def
)
685 CString configValue
= GetConfigValue(name
, def
? L
"true" : L
"false", true);
686 configValue
.MakeLower();
688 if (configValue
== L
"true" || configValue
== L
"on" || configValue
== L
"yes" || StrToInt(configValue
) != 0)
694 int CGit::GetConfigValueInt32(const CString
& name
, const int def
)
696 CString configValue
= GetConfigValue(name
);
698 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
703 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
705 if(this->m_IsUseGitDLL
)
707 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
715 CStringA keya
, valuea
;
716 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
717 valuea
= CUnicodeUtils::GetUTF8(value
);
721 return [=]() { return get_set_config(keya
, valuea
, type
); }();
723 catch (const char *msg
)
725 ::MessageBox(nullptr, L
"Could not set config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
736 option
= L
"--global";
739 option
= L
"--system";
744 CString mangledValue
= value
;
745 mangledValue
.Replace(L
"\\\"", L
"\\\\\"");
746 mangledValue
.Replace(L
"\"", L
"\\\"");
747 cmd
.Format(L
"git.exe config %s %s \"%s\"", (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
749 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
755 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
757 if(this->m_IsUseGitDLL
)
759 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
768 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
772 return [=]() { return get_set_config(keya
, nullptr, type
); }();
774 catch (const char *msg
)
776 ::MessageBox(nullptr, L
"Could not unset config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
787 option
= L
"--global";
790 option
= L
"--system";
795 cmd
.Format(L
"git.exe config %s --unset %s", (LPCTSTR
)option
, (LPCTSTR
)key
);
797 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
803 CString
CGit::GetCurrentBranch(bool fallback
)
806 //Run(L"git.exe branch", &branch);
808 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
809 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
810 return L
"(no branch)";
815 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
817 if (localBranch
.IsEmpty())
821 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
822 pullRemote
= GetConfigValue(configName
);
824 //Select pull-branch from current branch
825 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
826 pullBranch
= StripRefName(GetConfigValue(configName
));
829 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
832 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
834 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
837 void CGit::GetRemotePushBranch(const CString
& localBranch
, CString
& pushRemote
, CString
& pushBranch
)
839 if (localBranch
.IsEmpty())
844 configName
.Format(L
"branch.%s.pushremote", (LPCTSTR
)localBranch
);
845 pushRemote
= g_Git
.GetConfigValue(configName
);
846 if (pushRemote
.IsEmpty())
848 pushRemote
= g_Git
.GetConfigValue(L
"remote.pushdefault");
849 if (pushRemote
.IsEmpty())
851 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
852 pushRemote
= g_Git
.GetConfigValue(configName
);
856 configName
.Format(L
"branch.%s.pushbranch", (LPCTSTR
)localBranch
);
857 pushBranch
= g_Git
.GetConfigValue(configName
); // do not strip branch name (for gerrit), see issue #1609)
858 if (pushBranch
.IsEmpty())
860 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
861 pushBranch
= CGit::StripRefName(g_Git
.GetConfigValue(configName
));
865 CString
CGit::GetFullRefName(const CString
& shortRefName
)
869 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
870 if (Run(cmd
, &refName
, nullptr, CP_UTF8
) != 0)
871 return CString();//Error
872 return refName
.TrimRight();
875 CString
CGit::StripRefName(CString refName
)
877 if (CStringUtils::StartsWith(refName
, L
"refs/heads/"))
878 refName
= refName
.Mid((int)wcslen(L
"refs/heads/"));
879 else if (CStringUtils::StartsWith(refName
, L
"refs/"))
880 refName
= refName
.Mid((int)wcslen(L
"refs/"));
881 return refName
.TrimRight();
884 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
886 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
888 if ( sProjectRoot
.IsEmpty() )
892 if (!GitAdminDir::GetWorktreeAdminDirPath(sProjectRoot
, sDotGitPath
))
895 CString sHeadFile
= sDotGitPath
+ L
"HEAD";
897 CAutoFILE pFile
= _wfsopen(sHeadFile
.GetString(), L
"r", SH_DENYWR
);
901 char s
[MAX_PATH
] = {0};
902 fgets(s
, sizeof(s
), pFile
);
904 const char *pfx
= "ref: refs/heads/";
905 const size_t len
= strlen(pfx
);
907 if ( !strncmp(s
, pfx
, len
) )
909 //# We're on a branch. It might not exist. But
910 //# HEAD looks good enough to be a branch.
911 CStringA
utf8Branch(s
+ len
);
912 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
913 sBranchOut
.TrimRight(L
" \r\n\t");
915 if ( sBranchOut
.IsEmpty() )
920 CStringA
utf8Hash(s
);
921 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
922 unicodeHash
.TrimRight(L
" \r\n\t");
923 if (CGitHash::IsValidSHA1(unicodeHash
))
924 sBranchOut
= unicodeHash
;
926 //# Assume this is a detached head.
927 sBranchOut
= L
"HEAD";
932 //# Assume this is a detached head.
941 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
944 log
.Format(L
"#<%c>%%x00", LOG_REV_ITEM_BEGIN
);
948 log
.Format(L
"#<%c>%%an%%x00", LOG_REV_AUTHOR_NAME
);
950 log
.Format(L
"#<%c>%%ae%%x00", LOG_REV_AUTHOR_EMAIL
);
952 log
.Format(L
"#<%c>%%ai%%x00", LOG_REV_AUTHOR_DATE
);
954 log
.Format(L
"#<%c>%%cn%%x00", LOG_REV_COMMIT_NAME
);
956 log
.Format(L
"#<%c>%%ce%%x00", LOG_REV_COMMIT_EMAIL
);
958 log
.Format(L
"#<%c>%%ci%%x00", LOG_REV_COMMIT_DATE
);
960 log
.Format(L
"#<%c>%%b%%x00", LOG_REV_COMMIT_BODY
);
964 log
.Format(L
"#<%c>%%m%%H%%x00", LOG_REV_COMMIT_HASH
);
966 log
.Format(L
"#<%c>%%P%%x00", LOG_REV_COMMIT_PARENT
);
968 log
.Format(L
"#<%c>%%s%%x00", LOG_REV_COMMIT_SUBJECT
);
973 log
.Format(L
"#<%c>%%x00", LOG_REV_COMMIT_FILE
);
979 CString
CGit::GetLogCmd(CString range
, const CTGitPath
* path
, int mask
, CFilterData
* Filter
, int logOrderBy
)
983 if(mask
& LOG_INFO_STAT
)
984 param
+= L
" --numstat";
985 if(mask
& LOG_INFO_FILESTATE
)
988 if(mask
& LOG_INFO_BOUNDARY
)
989 param
+= L
" --left-right --boundary";
991 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
997 if (mask
& CGit::LOG_INFO_BASIC_REFS
)
999 param
+= L
" --branches";
1000 param
+= L
" --tags";
1001 param
+= L
" --remotes";
1002 param
+= L
" --glob=stas[h]"; // require at least one glob operator
1003 param
+= L
" --glob=bisect";
1007 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
1009 param
+= L
" --branches";
1013 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
1014 param
.AppendFormat(L
" -C%d%%", ms_iSimilarityIndexThreshold
);
1016 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
1017 param
.AppendFormat(L
" -M%d%%", ms_iSimilarityIndexThreshold
);
1019 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
1020 param
+= L
" --first-parent";
1022 if(mask
& CGit::LOG_INFO_NO_MERGE
)
1023 param
+= L
" --no-merges";
1025 if(mask
& CGit::LOG_INFO_FOLLOW
)
1026 param
+= L
" --follow";
1028 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
1031 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
1032 param
+= L
" --full-diff";
1034 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
1035 param
+= L
" --simplify-by-decoration";
1039 if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_N_YEARS
)
1041 CTime now
= CTime::GetCurrentTime();
1042 CTime time
= CTime(now
.GetYear(), now
.GetMonth(), now
.GetDay(), 0, 0, 0);
1043 __time64_t substract
= 86400;
1045 switch (Filter
->m_NumberOfLogsScale
)
1047 case CFilterData::SHOW_LAST_N_YEARS
:
1050 case CFilterData::SHOW_LAST_N_MONTHS
:
1053 case CFilterData::SHOW_LAST_N_WEEKS
:
1057 Filter
->m_From
= (DWORD
)time
.GetTime() - (Filter
->m_NumberOfLogs
* substract
);
1059 if (Filter
->m_NumberOfLogsScale
== CFilterData::SHOW_LAST_N_COMMITS
)
1060 param
.AppendFormat(L
" -n%ld", Filter
->m_NumberOfLogs
);
1061 else if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_SEL_DATE
&& Filter
->m_From
> 0)
1062 param
.AppendFormat(L
" --max-age=%I64u", Filter
->m_From
);
1065 if( Filter
&& (Filter
->m_To
!= -1))
1066 param
.AppendFormat(L
" --min-age=%I64u", Filter
->m_To
);
1068 if (logOrderBy
== LOG_ORDER_TOPOORDER
|| (mask
& CGit::LOG_ORDER_TOPOORDER
))
1069 param
+= L
" --topo-order";
1070 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1071 param
+= L
" --date-order";
1076 file
.Format(L
" \"%s\"", (LPCTSTR
)path
->GetGitPathString());
1077 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1078 cmd
.Format(L
"-z%s %s --parents --%s", (LPCTSTR
)param
, (LPCTSTR
)range
, (LPCTSTR
)file
);
1083 void GetTempPath(CString
&path
)
1085 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1087 DWORD dwBufSize
=BUFSIZE
;
1088 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1089 lpPathBuffer
); // buffer for path
1090 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1092 path
.Format(L
"%s", lpPathBuffer
);
1094 CString
GetTempFile()
1096 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1098 DWORD dwBufSize
=BUFSIZE
;
1099 TCHAR szTempName
[BUFSIZE
] = { 0 };
1102 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1103 lpPathBuffer
); // buffer for path
1104 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1107 // Create a temporary file.
1108 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1109 TEXT("Patch"), // temp file name prefix
1110 0, // create unique name
1111 szTempName
); // buffer for name
1116 return CString(szTempName
);
1119 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1121 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1122 if (result
== 0) return 0;
1123 if (!lpBuffer
|| (result
+ 13 > nBufferLength
))
1130 wcscat_s(lpBuffer
, nBufferLength
, L
"TortoiseGit\\");
1131 CreateDirectory(lpBuffer
, nullptr);
1136 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1138 PROCESS_INFORMATION pi
;
1139 CAutoGeneralHandle hReadErr
;
1140 if (RunAsync(cmd
, &pi
, nullptr, hReadErr
.GetPointer(), &filename
))
1141 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1143 CAutoGeneralHandle
piThread(std::move(pi
.hThread
));
1144 CAutoGeneralHandle
piProcess(std::move(pi
.hProcess
));
1146 BYTE_VECTOR stderrVector
;
1147 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1148 ASYNCREADSTDERRTHREADARGS threadArguments
;
1149 threadArguments
.fileHandle
= hReadErr
;
1150 threadArguments
.pcall
= &pcall
;
1151 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1155 CAutoLocker
lock(m_critSecThreadMap
);
1156 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
1159 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1163 WaitForSingleObject(thread
, INFINITE
);
1165 CAutoLocker
lock(m_critSecThreadMap
);
1166 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
1169 stderrVector
.push_back(0);
1170 StringAppend(stdErr
, stderrVector
.data(), CP_UTF8
);
1173 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1175 CString err
= CFormatMessageWrapper();
1176 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not get exit code: %s\n", (LPCTSTR
)err
.Trim());
1177 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1180 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": process exited: %d\n", exitcode
);
1185 CAutoRepository
CGit::GetGitRepository() const
1187 return CAutoRepository(GetGitPathStringA(m_CurrentDir
));
1190 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1194 // no need to parse a ref if it's already a 40-byte hash
1195 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1197 hash
= CGitHash(friendname
);
1201 int isHeadOrphan
= git_repository_head_unborn(repo
);
1202 if (isHeadOrphan
!= 0)
1205 if (isHeadOrphan
== 1)
1211 CAutoObject gitObject
;
1212 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1215 hash
= git_object_id(gitObject
);
1220 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1222 // no need to parse a ref if it's already a 40-byte hash
1223 if (CGitHash::IsValidSHA1(friendname
))
1225 hash
= CGitHash(friendname
);
1231 CAutoRepository
repo(GetGitRepository());
1235 return GetHash(repo
, hash
, friendname
, true);
1239 CString branch
= FixBranchName(friendname
);
1240 if (friendname
== L
"FETCH_HEAD" && branch
.IsEmpty())
1241 branch
= friendname
;
1243 cmd
.Format(L
"git.exe rev-parse %s", (LPCTSTR
)branch
);
1245 int ret
= Run(cmd
, &gitLastErr
, nullptr, CP_UTF8
);
1246 hash
= CGitHash(gitLastErr
.Trim());
1249 else if (friendname
== L
"HEAD") // special check for unborn branch
1251 CString currentbranch
;
1252 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1261 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1266 if (Run(L
"git.exe ls-files -s -t -z", &cmdout
))
1269 if (outputlist
.ParserFromLsFile(cmdout
))
1271 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1272 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1276 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1280 if (ignoreSpaceAtEol
)
1281 ignore
+= L
" --ignore-space-at-eol";
1282 if (ignoreSpaceChange
)
1283 ignore
+= L
" --ignore-space-change";
1285 ignore
+= L
" --ignore-all-space";
1286 if (ignoreBlankLines
)
1287 ignore
+= L
" --ignore-blank-lines";
1289 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1291 if(rev1
== GIT_REV_ZERO
)
1292 cmd
.Format(L
"git.exe diff -r --raw -C%d%% -M%d%% --numstat -z %s %s --", ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
, (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1294 cmd
.Format(L
"git.exe diff -r -R --raw -C%d%% -M%d%% --numstat -z %s %s --", ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
, (LPCTSTR
)ignore
, (LPCTSTR
)rev1
);
1297 cmd
.Format(L
"git.exe diff-tree -r --raw -C%d%% -M%d%% --numstat -z %s %s %s --", ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
, (LPCTSTR
)ignore
, (LPCTSTR
)rev2
, (LPCTSTR
)rev1
);
1303 return outputlist
.ParserFromLog(out
);
1306 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1308 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1309 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1313 int CGit::GetTagList(STRING_VECTOR
&list
)
1315 size_t prevCount
= list
.size();
1316 if (this->m_IsUseLibGit2
)
1318 CAutoRepository
repo(GetGitRepository());
1322 CAutoStrArray tag_names
;
1324 if (git_tag_list(tag_names
, repo
))
1327 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1329 CStringA
tagName(tag_names
->strings
[i
]);
1330 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1333 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1339 int ret
= Run(L
"git.exe tag -l", [&](const CStringA
& lineA
)
1341 if (lineA
.IsEmpty())
1343 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1346 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1347 else if (ret
== 1 && IsInitRepos())
1353 CString
CGit::GetGitLastErr(const CString
& msg
)
1355 if (this->m_IsUseLibGit2
)
1356 return GetLibGit2LastErr(msg
);
1357 else if (gitLastErr
.IsEmpty())
1358 return msg
+ L
"\nUnknown git.exe error.";
1361 CString lastError
= gitLastErr
;
1363 return msg
+ L
'\n' + lastError
;
1367 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1369 if (UsingLibGit2(cmd
))
1370 return GetLibGit2LastErr(msg
);
1371 else if (gitLastErr
.IsEmpty())
1372 return msg
+ L
"\nUnknown git.exe error.";
1375 CString lastError
= gitLastErr
;
1377 return msg
+ L
'\n' + lastError
;
1381 CString
CGit::GetLibGit2LastErr()
1383 const git_error
*libgit2err
= giterr_last();
1386 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1388 return L
"libgit2 returned: " + lastError
;
1391 return L
"An error occoured in libgit2, but no message is available.";
1394 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1397 return msg
+ L
'\n' + GetLibGit2LastErr();
1398 return GetLibGit2LastErr();
1401 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1403 if (branchName
== L
"FETCH_HEAD")
1404 branchName
= DerefFetchHead();
1408 CString
CGit::FixBranchName(const CString
& branchName
)
1410 CString tempBranchName
= branchName
;
1411 FixBranchName_Mod(tempBranchName
);
1412 return tempBranchName
;
1415 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1419 CAutoRepository
repo(GetGitRepository());
1421 return true; // TODO: optimize error reporting
1423 CAutoReference tagRef
;
1424 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1427 CAutoReference branchRef
;
1428 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1435 cmd
.Format(L
"git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s", (LPCTSTR
)name
, (LPCTSTR
)name
);
1438 Run(cmd
, [&](const CStringA
& lineA
)
1440 if (lineA
.IsEmpty())
1445 return (refCnt
<= 1);
1448 bool CGit::IsLocalBranch(const CString
& shortName
)
1451 GetBranchList(list
, nullptr, CGit::BRANCH_LOCAL
);
1452 return std::find(list
.cbegin(), list
.cend(), shortName
) != list
.cend();
1455 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1459 CAutoRepository
repo(GetGitRepository());
1461 return false; // TODO: optimize error reporting
1465 prefix
= L
"refs/heads/";
1467 prefix
= L
"refs/tags/";
1470 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1476 CString cmd
, output
;
1478 cmd
= L
"git.exe show-ref ";
1484 cmd
+= L
"refs/heads/" + name
;
1485 cmd
+= L
" refs/tags/" + name
;
1487 int ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1490 if (!output
.IsEmpty())
1497 CString
CGit::DerefFetchHead()
1500 GitAdminDir::GetWorktreeAdminDirPath(m_CurrentDir
, dotGitPath
);
1501 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1502 int forMergeLineCount
= 0;
1504 std::string hashToReturn
;
1505 while(getline(fetchHeadFile
, line
))
1507 //Tokenize this line
1508 std::string::size_type prevPos
= 0;
1509 std::string::size_type pos
= line
.find('\t');
1510 if(pos
== std::string::npos
) continue; //invalid line
1512 std::string hash
= line
.substr(0, pos
);
1513 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1515 bool forMerge
= pos
== prevPos
;
1516 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1518 //std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1523 hashToReturn
= hash
;
1524 ++forMergeLineCount
;
1525 if(forMergeLineCount
> 1)
1526 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1530 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1533 int CGit::GetBranchList(STRING_VECTOR
&list
, int *current
, BRANCH_TYPE type
, bool skipCurrent
/*false*/)
1535 size_t prevCount
= list
.size();
1538 bool headIsDetached
= false;
1541 CAutoRepository
repo(GetGitRepository());
1545 if (git_repository_head_detached(repo
) == 1)
1546 headIsDetached
= true;
1548 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1550 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1551 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1552 flags
= GIT_BRANCH_ALL
;
1553 else if (type
& BRANCH_REMOTE
)
1554 flags
= GIT_BRANCH_REMOTE
;
1556 CAutoBranchIterator it
;
1557 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1561 git_branch_t branchType
;
1562 while (git_branch_next(ref
.GetPointer(), &branchType
, it
) == 0)
1564 const char * name
= nullptr;
1565 if (git_branch_name(&name
, ref
))
1568 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1569 if (branchType
& GIT_BRANCH_REMOTE
)
1570 list
.push_back(L
"remotes/" + branchname
);
1573 if (git_branch_is_head(ref
))
1579 list
.push_back(branchname
);
1586 CString cmd
= L
"git.exe branch --no-color";
1588 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1590 else if (type
& BRANCH_REMOTE
)
1593 ret
= Run(cmd
, [&](CStringA lineA
)
1595 lineA
.Trim(" \r\n\t");
1596 if (lineA
.IsEmpty())
1598 if (lineA
.Find(" -> ") >= 0)
1599 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1601 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1602 if (lineA
[0] == '*')
1606 branch
= branch
.Mid((int)wcslen(L
"* "));
1609 // check whether HEAD is detached
1610 CString currentHead
;
1611 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1613 headIsDetached
= true;
1617 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1618 branch
= L
"remotes/" + branch
;
1619 list
.push_back(branch
);
1621 if (ret
== 1 && IsInitRepos())
1625 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1626 list
.push_back(L
"FETCH_HEAD");
1628 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1630 if (current
&& !headIsDetached
&& !skipCurrent
)
1632 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1645 int CGit::GetRefsCommitIsOn(STRING_VECTOR
& list
, const CGitHash
& hash
, bool includeTags
, bool includeBranches
, BRANCH_TYPE type
)
1647 if (!includeTags
&& !includeBranches
|| hash
.IsEmpty())
1650 size_t prevCount
= list
.size();
1653 CAutoRepository
repo(GetGitRepository());
1657 CAutoReferenceIterator it
;
1658 if (git_reference_iterator_new(it
.GetPointer(), repo
))
1661 auto checkDescendent
= [&list
, &hash
, &repo
](const git_oid
* oid
, const git_reference
* ref
) {
1664 if (git_oid_equal(oid
, hash
) || git_graph_descendant_of(repo
, oid
, hash
) == 1)
1666 const char* name
= git_reference_name(ref
);
1670 list
.push_back(CUnicodeUtils::GetUnicode(name
));
1675 while (git_reference_next(ref
.GetPointer(), it
) == 0)
1677 if (git_reference_is_tag(ref
))
1683 if (git_tag_lookup(tag
.GetPointer(), repo
, git_reference_target(ref
)) == 0)
1686 if (git_tag_peel(obj
.GetPointer(), tag
) < 0)
1688 checkDescendent(git_object_id(obj
), ref
);
1692 else if (git_reference_is_remote(ref
))
1694 if (!includeBranches
|| !(type
& BRANCH_REMOTE
))
1697 else if (git_reference_is_branch(ref
))
1699 if (!includeBranches
|| !(type
& GIT_BRANCH_LOCAL
))
1705 if (git_reference_type(ref
) == GIT_REF_SYMBOLIC
)
1707 CAutoReference peeledRef
;
1708 if (git_reference_resolve(peeledRef
.GetPointer(), ref
) < 0)
1711 checkDescendent(git_reference_target(peeledRef
), ref
);
1715 checkDescendent(git_reference_target(ref
), ref
);
1720 if (includeBranches
)
1722 CString cmd
= L
"git.exe branch --no-color";
1723 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1725 else if (type
& BRANCH_REMOTE
)
1727 cmd
+= L
" --contains " + hash
.ToString();
1729 if (Run(cmd
, [&](CStringA lineA
)
1731 lineA
.Trim(" \r\n\t");
1732 if (lineA
.IsEmpty())
1734 if (lineA
.Find(" -> ") >= 0) // normalize symbolic refs: "refs/origin/HEAD -> refs/origin/master" to "refs/origin/HEAD"
1735 lineA
.Truncate(lineA
.Find(" -> "));
1737 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1738 if (lineA
[0] == '*')
1740 branch
= branch
.Mid((int)wcslen(L
"* "));
1741 CString currentHead
;
1742 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1746 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1747 branch
= L
"refs/remotes/" + branch
;
1748 else if (CStringUtils::StartsWith(branch
, L
"remotes/"))
1749 branch
= L
"refs/" + branch
;
1751 branch
= L
"refs/heads/" + branch
;
1752 list
.push_back(branch
);
1759 CString cmd
= L
"git.exe tag --contains " + hash
.ToString();
1760 if (Run(cmd
, [&list
](CStringA lineA
)
1762 if (lineA
.IsEmpty())
1764 list
.push_back(L
"refs/tags/" + CUnicodeUtils::GetUnicode(lineA
));
1770 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1771 list
.erase(std::unique(list
.begin() + prevCount
, list
.end()), list
.end());
1776 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1778 size_t prevCount
= list
.size();
1779 if (this->m_IsUseLibGit2
)
1781 CAutoRepository
repo(GetGitRepository());
1785 CAutoStrArray remotes
;
1786 if (git_remote_list(remotes
, repo
))
1789 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1791 CStringA
remote(remotes
->strings
[i
]);
1792 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1795 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1800 return Run(L
"git.exe remote", [&](const CStringA
& lineA
)
1802 if (lineA
.IsEmpty())
1804 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1808 int CGit::GetRemoteTags(const CString
& remote
, REF_VECTOR
& list
)
1810 size_t prevCount
= list
.size();
1811 if (UsingLibGit2(GIT_CMD_FETCH
))
1813 CAutoRepository
repo(GetGitRepository());
1817 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1818 CAutoRemote gitremote
;
1819 // first try with a named remote (e.g. "origin")
1820 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1822 // retry with repository located at a specific url
1823 if (git_remote_create_anonymous(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1827 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1828 callbacks
.credentials
= g_Git2CredCallback
;
1829 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1830 git_proxy_options proxy
= GIT_PROXY_OPTIONS_INIT
;
1831 proxy
.type
= GIT_PROXY_AUTO
;
1832 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
, &proxy
, nullptr) < 0)
1835 const git_remote_head
** heads
= nullptr;
1837 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1840 for (size_t i
= 0; i
< size
; i
++)
1842 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1844 if (!GetShortName(ref
, shortname
, L
"refs/tags/"))
1846 list
.emplace_back(TGitRef
{ shortname
, &heads
[i
]->oid
});
1848 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1853 cmd
.Format(L
"git.exe ls-remote -t \"%s\"", (LPCTSTR
)remote
);
1854 gitLastErr
= cmd
+ L
'\n';
1855 if (Run(cmd
, [&](CStringA lineA
)
1858 hash
.ConvertFromStrA(lineA
.Left(GIT_HASH_SIZE
* 2));
1859 lineA
= lineA
.Mid(GIT_HASH_SIZE
* 2 + (int)wcslen(L
"\trefs/tags/")); // sha1, tab + refs/tags/
1860 if (!lineA
.IsEmpty())
1861 list
.emplace_back(TGitRef
{ CUnicodeUtils::GetUnicode(lineA
), hash
});
1864 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1868 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1870 if (UsingLibGit2(GIT_CMD_PUSH
))
1872 CAutoRepository
repo(GetGitRepository());
1876 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1878 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1881 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1882 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1883 callbacks
.credentials
= g_Git2CredCallback
;
1884 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1885 std::vector
<CStringA
> refspecs
;
1886 for (const auto& ref
: list
)
1887 refspecs
.push_back(CUnicodeUtils::GetUTF8(L
":" + ref
));
1889 std::vector
<char*> vc
;
1890 vc
.reserve(refspecs
.size());
1891 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1892 git_strarray specs
= { vc
.data(), vc
.size() };
1894 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1899 CMassiveGitTaskBase
mgtPush(L
"push " + sRemote
, FALSE
);
1900 for (const auto& ref
: list
)
1901 mgtPush
.AddFile(L
':' + ref
);
1903 BOOL cancel
= FALSE
;
1904 mgtPush
.Execute(cancel
);
1910 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1912 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1913 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1917 int CGit::GetRefList(STRING_VECTOR
&list
)
1919 size_t prevCount
= list
.size();
1920 if (this->m_IsUseLibGit2
)
1922 CAutoRepository
repo(GetGitRepository());
1926 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1929 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1934 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1936 int start
= lineA
.Find(L
' ');
1937 ASSERT(start
== 2 * GIT_HASH_SIZE
);
1941 CString name
= CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1));
1942 if (list
.empty() || name
!= *list
.crbegin() + L
"^{}")
1943 list
.push_back(name
);
1946 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1947 else if (ret
== 1 && IsInitRepos())
1952 typedef struct map_each_ref_payload
{
1953 git_repository
* repo
;
1954 MAP_HASH_NAME
* map
;
1955 } map_each_ref_payload
;
1957 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1959 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1961 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1963 CAutoObject gitObject
;
1964 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1965 return (git_reference_is_remote(ref
) && git_reference_type(ref
) == GIT_REF_SYMBOLIC
) ? 0 : 1; // don't bail out for symbolic remote references ("git.exe show-ref -d" also doesn't complain), cf. issue #2926
1967 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1969 str
+= L
"^{}"; // deref tag
1970 CAutoObject derefedTag
;
1971 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1973 gitObject
.Swap(derefedTag
);
1976 (*payloadContent
->map
)[git_object_id(gitObject
)].push_back(str
);
1980 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1984 map_each_ref_payload payloadContent
= { repo
, &map
};
1986 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1989 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1991 std::sort(it
->second
.begin(), it
->second
.end());
1997 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1999 if (this->m_IsUseLibGit2
)
2001 CAutoRepository
repo(GetGitRepository());
2005 return GetMapHashToFriendName(repo
, map
);
2008 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
2010 int start
= lineA
.Find(L
' ');
2011 ASSERT(start
== 2 * GIT_HASH_SIZE
);
2016 hash
.ConvertFromStrA(lineA
);
2017 map
[hash
].push_back(CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1)));
2020 if (ret
== 1 && IsInitRepos())
2025 int CGit::GuessRefForHash(CString
& ref
, const CGitHash
& hash
)
2028 if (GetMapHashToFriendName(map
))
2031 auto it
= map
.find(hash
);
2032 if (it
== map
.cend())
2034 ref
= hash
.ToString().Left(GetShortHASHLength());
2038 const auto& reflist
= it
->second
;
2039 for (const auto& reftype
: { L
"refs/heads/", L
"refs/remotes/", L
"refs/tags/" })
2041 auto found
= std::find_if(reflist
.cbegin(), reflist
.cend(), [&reftype
](const auto& ref
) { return CStringUtils::StartsWith(ref
, reftype
); });
2042 if (found
== reflist
.cend())
2045 GetShortName(*found
, ref
, reftype
);
2049 ref
= hash
.ToString().Left(GetShortHASHLength());
2053 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
2055 CAutoConfig
config(true);
2056 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, nullptr, FALSE
) < 0)
2058 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
2060 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
2061 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
2062 // extract branch name from config key
2063 key
= key
.Mid((int)wcslen(L
"branch."), key
.GetLength() - (int)wcslen(L
"branch.") - (int)wcslen(L
".description"));
2064 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
2069 static void SetLibGit2SearchPath(int level
, const CString
&value
)
2071 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
2072 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, (LPCSTR
)valueA
);
2075 static void SetLibGit2TemplatePath(const CString
&value
)
2077 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
2078 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, (LPCSTR
)valueA
);
2081 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2083 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, L
"", FALSE
);
2084 CString str
= msysdir
;
2085 if (!str
.IsEmpty() && PathFileExists(str
+ L
"\\git.exe"))
2087 CGit::ms_LastMsysGitDir
= str
;
2091 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": git.exe not exists: %s\n", (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2095 // first, search PATH if git/bin directory is already present
2098 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": FindGitPath() => %s\n", (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2099 msysdir
= CGit::ms_LastMsysGitDir
;
2104 if (FindGitForWindows(str
))
2107 CGit::ms_LastMsysGitDir
= str
;
2115 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2120 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": CheckMsysGitDir(%d)\n", bFallback
);
2121 this->m_Environment
.clear();
2122 m_Environment
.CopyProcessEnvironment();
2124 // Git for Windows 2.10.1 and 2.10.2 require LC_ALL to be set, see https://tortoisegit.org/issue/2859 and https://github.com/git-for-windows/git/issues/945,
2125 // because MSys2 changed the default to "ASCII". SO, make sure we have a proper default set
2126 if (m_Environment
.GetEnv(L
"LC_ALL").IsEmpty())
2127 m_Environment
.SetEnv(L
"LC_ALL", L
"C");
2129 // set HOME if not set already
2131 _wgetenv_s(&homesize
, nullptr, 0, L
"HOME");
2133 m_Environment
.SetEnv(L
"HOME", GetHomeDirectory());
2136 CString sshclient
= CRegString(L
"Software\\TortoiseGit\\SSH");
2137 if (sshclient
.IsEmpty())
2138 sshclient
= CRegString(L
"Software\\TortoiseGit\\SSH", L
"", FALSE
, HKEY_LOCAL_MACHINE
);
2140 if(!sshclient
.IsEmpty())
2142 m_Environment
.SetEnv(L
"GIT_SSH", sshclient
);
2143 if (CStringUtils::EndsWithI(sshclient
, L
"tortoisegitplink") || CStringUtils::EndsWithI(sshclient
, L
"tortoisegitplink.exe"))
2144 m_Environment
.SetEnv(L
"GIT_SSH_VARIANT", L
"ssh");
2145 m_Environment
.SetEnv(L
"SVN_SSH", sshclient
);
2149 TCHAR sPlink
[MAX_PATH
] = {0};
2150 GetModuleFileName(nullptr, sPlink
, _countof(sPlink
));
2151 LPTSTR ptr
= wcsrchr(sPlink
, L
'\\');
2153 wcscpy_s(ptr
+ 1, _countof(sPlink
) - (ptr
- sPlink
+ 1), L
"TortoiseGitPlink.exe");
2154 m_Environment
.SetEnv(L
"GIT_SSH", sPlink
);
2155 m_Environment
.SetEnv(L
"GIT_SSH_VARIANT", L
"ssh");
2156 m_Environment
.SetEnv(L
"SVN_SSH", sPlink
);
2161 TCHAR sAskPass
[MAX_PATH
] = {0};
2162 GetModuleFileName(nullptr, sAskPass
, _countof(sAskPass
));
2163 LPTSTR ptr
= wcsrchr(sAskPass
, L
'\\');
2166 wcscpy_s(ptr
+ 1, _countof(sAskPass
) - (ptr
- sAskPass
+ 1), L
"SshAskPass.exe");
2167 m_Environment
.SetEnv(L
"DISPLAY",L
":9999");
2168 m_Environment
.SetEnv(L
"SSH_ASKPASS",sAskPass
);
2169 m_Environment
.SetEnv(L
"GIT_ASKPASS",sAskPass
);
2170 m_Environment
.SetEnv(L
"GIT_ASK_YESNO", sAskPass
);
2174 if (!FindAndSetGitExePath(bFallback
))
2178 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ L
"\\..\\");
2179 static const CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2180 static const int prefixes_len
[] = { 8, 8, 0 };
2181 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2187 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2188 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2192 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
2193 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ L
"\\..\\..");
2194 CGit::ms_MsysGitRootDir
= msysGitDir
;
2196 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, L
"", FALSE
) != g_Git
.GetGitSystemConfig())
2197 CRegString(REG_SYSTEM_GITCONFIGPATH
, L
"", FALSE
) = g_Git
.GetGitSystemConfig();
2199 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ms_LastMsysGitDir = %s\n", (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2200 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ms_MsysGitRootDir = %s\n", (LPCTSTR
)CGit::ms_MsysGitRootDir
);
2201 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": System config = %s\n", (LPCTSTR
)g_Git
.GetGitSystemConfig());
2202 if (!ms_bCygwinGit
&& !ms_bMsys2Git
)
2204 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ProgramData config = %s\n", (LPCTSTR
)g_Git
.GetGitProgramDataConfig());
2205 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitProgramDataConfig()).GetContainingDirectory().GetWinPathString());
2208 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2210 // Configure libgit2 search paths
2211 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2212 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2213 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2214 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(L
"GIT_SSH"), g_Git
.m_Environment
.GetEnv(L
"PATH")), g_Git
.m_Environment
); }, 0 };
2215 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2216 git_transport_register("ssh+git", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2217 git_transport_register("git+ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2218 git_libgit2_opts(GIT_OPT_SET_USER_AGENT
, "TortoiseGit libgit2");
2219 if (!(ms_bCygwinGit
|| ms_bMsys2Git
))
2220 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ L
"share\\git-core\\templates");
2222 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ L
"usr\\share\\git-core\\templates");
2224 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2225 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, L
"", FALSE
));
2227 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2228 // register filter only once
2229 if (!git_filter_lookup("filter"))
2232 for (const CString
& binDirPrefix
: { L
"\\..\\usr\\bin", L
"\\..\\bin", L
"" })
2234 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2235 if (PathFileExists(possibleShExe
))
2238 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2239 sh
.Format(L
"\"%s\"", (LPCTSTR
)temp
);
2240 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2241 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - (int)wcslen(L
"\\sh.exe")));
2246 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2247 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2248 CString gitExecPath
= CGit::ms_MsysGitRootDir
;
2249 gitExecPath
.Append(L
"libexec\\git-core");
2250 m_Environment
.AddToPath(gitExecPath
);
2252 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2257 m_bInitialized
= TRUE
;
2261 CString
CGit::GetHomeDirectory() const
2263 const wchar_t * homeDir
= wget_windows_home_directory();
2264 return CString(homeDir
, (int)wcslen(homeDir
));
2267 CString
CGit::GetGitLocalConfig() const
2270 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2275 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2277 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2280 CString
CGit::GetGitGlobalConfig() const
2282 return g_Git
.GetHomeDirectory() + L
"\\.gitconfig";
2285 CString
CGit::GetGitGlobalXDGConfigPath() const
2287 return g_Git
.GetHomeDirectory() + L
"\\.config\\git";
2290 CString
CGit::GetGitGlobalXDGConfig() const
2292 return g_Git
.GetGitGlobalXDGConfigPath() + L
"\\config";
2295 CString
CGit::GetGitProgramDataConfig() const
2297 const wchar_t* programdataConfig
= wget_program_data_config();
2298 return CString(programdataConfig
);
2301 CString
CGit::GetGitSystemConfig() const
2303 const wchar_t * systemConfig
= wget_msysgit_etc();
2304 return CString(systemConfig
, (int)wcslen(systemConfig
));
2307 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2309 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2311 CAutoRepository
repo(GetGitRepository());
2315 if (git_repository_head_unborn(repo
))
2318 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2319 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2320 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2322 CAutoStatusList status
;
2323 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2326 return (0 == git_status_list_entrycount(status
));
2329 if (Run(L
"git.exe rev-parse --verify HEAD", nullptr, nullptr, CP_UTF8
))
2332 if (Run(L
"git.exe update-index --ignore-submodules --refresh", nullptr, nullptr, CP_UTF8
))
2335 if (Run(L
"git.exe diff-files --quiet --ignore-submodules", nullptr, nullptr, CP_UTF8
))
2338 if (!stagedOk
&& Run(L
"git.exe diff-index --cached --quiet HEAD --ignore-submodules --", nullptr, nullptr, CP_UTF8
))
2343 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2345 for (int i
= 0; i
< list
.GetCount(); ++i
)
2347 if (Revert(commit
, (CTGitPath
&)list
[i
], err
))
2352 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2354 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2356 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2358 err
.Format(L
"Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists.", (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2364 // if the filenames only differ in case, we have to pass "-f"
2365 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2368 cmd
.Format(L
"git.exe mv %s-- \"%s\" \"%s\"", (LPCTSTR
)force
, (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2369 if (Run(cmd
, &err
, CP_UTF8
))
2375 cmd
.Format(L
"git.exe rm -f --cached -- \"%s\"", (LPCTSTR
)path
.GetGitPathString());
2376 if (Run(cmd
, &err
, CP_UTF8
))
2381 cmd
.Format(L
"git.exe checkout %s -f -- \"%s\"", (LPCTSTR
)commit
, (LPCWSTR
)path
.GetGitOldPathString());
2382 if (Run(cmd
, &err
, CP_UTF8
))
2385 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2386 { //To init git repository, there are not HEAD, so we can use git reset command
2388 cmd
.Format(L
"git.exe rm -f --cached -- \"%s\"", (LPCTSTR
)path
.GetGitPathString());
2390 if (Run(cmd
, &err
, CP_UTF8
))
2396 cmd
.Format(L
"git.exe checkout %s -f -- \"%s\"", (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitPathString());
2397 if (Run(cmd
, &err
, CP_UTF8
))
2401 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2404 cmd
.Format(L
"git.exe add -f -- \"%s\"", (LPCTSTR
)path
.GetGitPathString());
2405 if (Run(cmd
, &err
, CP_UTF8
))
2412 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2417 if (git_repository_index(index
.GetPointer(), repo
))
2420 return git_index_has_conflicts(index
);
2423 int CGit::HasWorkingTreeConflicts()
2425 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2427 CAutoRepository
repo(GetGitRepository());
2431 return HasWorkingTreeConflicts(repo
);
2436 if (Run(L
"git.exe ls-files -u -t -z", &output
, &gitLastErr
, CP_UTF8
))
2439 return output
.IsEmpty() ? 0 : 1;
2442 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2444 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2446 CAutoRepository
repo(GetGitRepository());
2450 CGitHash fromHash
, toHash
, baseHash
;
2451 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2454 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2458 if (git_merge_base(&baseOid
, repo
, toHash
, fromHash
))
2464 *commonAncestor
= baseHash
;
2466 return fromHash
== baseHash
;
2470 CGitHash basehash
,hash
;
2472 cmd
.Format(L
"git.exe merge-base %s %s", (LPCTSTR
)FixBranchName(to
), (LPCTSTR
)FixBranchName(from
));
2475 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2477 basehash
= base
.Trim();
2479 GetHash(hash
, from
);
2482 *commonAncestor
= basehash
;
2484 return hash
== basehash
;
2487 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2490 for (int i
= 0; i
< 4; ++i
)
2493 ret
|= static_cast<const unsigned char*>(hash
)[i
];
2498 int CGit::RefreshGitIndex()
2501 GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
);
2502 // HACK: don't use internal update-index if we have a git-lfs enabled repository as the libgit version fails when executing the filter, issue #3220
2503 if (g_Git
.m_IsUseGitDLL
&& !PathFileExists(adminDir
+ L
"lfs"))
2505 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2508 g_Git
.CheckAndInitDll();
2510 int result
= git_update_index();
2522 return Run(L
"git.exe update-index --refresh", nullptr, nullptr, CP_UTF8
);
2525 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2527 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2529 CAutoRepository
repo(GetGitRepository());
2534 if (GetHash(repo
, hash
, Refname
))
2538 if (git_commit_lookup(commit
.GetPointer(), repo
, hash
))
2542 if (git_commit_tree(tree
.GetPointer(), commit
))
2545 CAutoTreeEntry entry
;
2546 int ret
= git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()));
2550 if (git_tree_entry_filemode(entry
) == GIT_FILEMODE_COMMIT
)
2552 giterr_set_str(GITERR_NONE
, "The requested object is a submodule and not a file.");
2557 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2560 CAutoFILE file
= _wfsopen(outputfile
, L
"wb", SH_DENYWR
);
2561 if (file
== nullptr)
2563 giterr_set_str(GITERR_NONE
, "Could not create file.");
2567 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2569 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2571 giterr_set_str(GITERR_OS
, "Could not write to file.");
2577 else if (g_Git
.m_IsUseGitDLL
)
2579 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2582 g_Git
.CheckAndInitDll();
2583 CStringA ref
, patha
, outa
;
2584 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2585 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2586 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2587 ::DeleteFile(outputfile
);
2588 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2589 outa
.ReleaseBuffer();
2593 catch (const char * msg
)
2595 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2600 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2607 cmd
.Format(L
"git.exe cat-file -p %s:\"%s\"", (LPCTSTR
)Refname
, (LPCTSTR
)path
.GetGitPathString());
2609 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2613 void CEnvironment::clear()
2619 bool CEnvironment::empty()
2621 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2624 CEnvironment::operator LPTSTR()
2631 CEnvironment::operator LPWSTR
*()
2636 void CEnvironment::CopyProcessEnvironment()
2640 TCHAR
*porig
= GetEnvironmentStrings();
2642 while(*p
!=0 || *(p
+1) !=0)
2643 this->push_back(*p
++);
2649 FreeEnvironmentStrings(porig
);
2652 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2655 for (size_t i
= 0; i
< size(); ++i
)
2659 CString sname
= str
.Tokenize(L
"=", start
);
2660 if(sname
.CompareNoCase(name
) == 0)
2661 return &(*this)[i
+start
];
2667 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2670 for (i
= 0; i
< size(); ++i
)
2672 CString str
= &(*this)[i
];
2674 CString sname
= str
.Tokenize(L
"=", start
);
2675 if(sname
.CompareNoCase(name
) == 0)
2682 if (!value
) // as we haven't found the variable we want to remove, just return
2684 if (i
== 0) // make inserting into an empty environment work
2686 this->push_back(L
'\0');
2689 i
-= 1; // roll back terminate \0\0
2690 this->push_back(L
'\0');
2693 CEnvironment::iterator it
;
2697 while(*it
&& i
<size())
2704 if (value
== nullptr) // remove the variable
2716 this->insert(it
,*name
++);
2721 this->insert(it
, L
'=');
2727 this->insert(it
,*value
++);
2734 void CEnvironment::AddToPath(CString value
)
2736 value
.TrimRight(L
'\\');
2737 if (value
.IsEmpty())
2740 CString path
= GetEnv(L
"PATH").TrimRight(L
';') + L
';';
2742 // do not double add paths to %PATH%
2743 if (path
.Find(value
+ L
';') >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2748 SetEnv(L
"PATH", path
);
2751 int CGit::GetGitEncode(TCHAR
* configkey
)
2753 CString str
=GetConfigValue(configkey
);
2758 return CUnicodeUtils::GetCPCode(str
);
2761 int CGit::GetShortHASHLength() const
2766 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2770 REF_TYPE type
= CGit::UNKNOWN
;
2772 if (CGit::GetShortName(str
, shortname
, L
"refs/heads/"))
2773 type
= CGit::LOCAL_BRANCH
;
2774 else if (CGit::GetShortName(str
, shortname
, L
"refs/remotes/"))
2775 type
= CGit::REMOTE_BRANCH
;
2776 else if (CStringUtils::EndsWith(str
, L
"^{}") && CGit::GetShortName(str
, shortname
, L
"refs/tags/"))
2777 type
= CGit::ANNOTATED_TAG
;
2778 else if (CGit::GetShortName(str
, shortname
, L
"refs/tags/"))
2780 else if (CGit::GetShortName(str
, shortname
, L
"refs/stash"))
2783 shortname
= L
"stash";
2785 else if (CGit::GetShortName(str
, shortname
, L
"refs/bisect/"))
2789 g_Git
.GetBisectTerms(&bisectGood
, &bisectBad
);
2791 if (CStringUtils::StartsWith(shortname
, bisectGood
) && ((c
= shortname
.GetAt(bisectGood
.GetLength())) == '-' || c
== '\0'))
2793 type
= CGit::BISECT_GOOD
;
2794 shortname
= bisectGood
;
2797 if (CStringUtils::StartsWith(shortname
, bisectBad
) && ((c
= shortname
.GetAt(bisectBad
.GetLength())) == '-' || c
== '\0'))
2799 type
= CGit::BISECT_BAD
;
2800 shortname
= bisectBad
;
2803 if (CStringUtils::StartsWith(shortname
, L
"skip") && ((c
= shortname
.GetAt(4)) == '-' || c
== '\0'))
2805 type
= CGit::BISECT_SKIP
;
2806 shortname
= L
"skip";
2809 else if (CGit::GetShortName(str
, shortname
, L
"refs/notes/"))
2811 else if (CGit::GetShortName(str
, shortname
, L
"refs/"))
2812 type
= CGit::UNKNOWN
;
2815 type
= CGit::UNKNOWN
;
2825 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2827 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2830 void CGit::SetGit2CredentialCallback(void* callback
)
2832 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2835 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2837 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2840 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const CString
& rev1
, const CString
& rev2
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
2843 if (rev2
== GitRev::GetWorkingCopy())
2844 cmd
.Format(L
"git.exe diff --stat%s -p %s --", bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
);
2845 else if (rev1
== GitRev::GetWorkingCopy())
2846 cmd
.Format(L
"git.exe diff -R --stat%s -p %s --", bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev2
);
2857 if (diffContext
>= 0)
2858 unified
.Format(L
" --unified=%d", diffContext
);
2859 cmd
.Format(L
"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
);
2862 if (!path
.IsEmpty())
2865 cmd
+= path
.GetGitPathString();
2872 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2874 ATLASSERT(payload
&& text
);
2875 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2876 fwrite("\n", 1, 1, (FILE *)payload
);
2879 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2881 ATLASSERT(payload
&& line
);
2882 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2883 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2884 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2888 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2890 ATLASSERT(repo
&& identifier
&& tree
);
2892 /* try to resolve identifier */
2894 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2898 return GIT_ENOTFOUND
;
2901 switch (git_object_type(obj
))
2904 *tree
= (git_tree
*)obj
.Detach();
2906 case GIT_OBJ_COMMIT
:
2907 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2910 err
= GIT_ENOTFOUND
;
2916 /* use libgit2 get unified diff */
2917 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const CString
& revOld
, const CString
& revNew
, std::function
<void(const git_buf
*, void*)> statCallback
, git_diff_line_cb callback
, void* data
, bool /* bMerge */, bool bNoPrefix
)
2919 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2920 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2922 CAutoRepository
repo(g_Git
.GetGitRepository());
2926 int isHeadOrphan
= git_repository_head_unborn(repo
);
2927 if (isHeadOrphan
== 1)
2929 else if (isHeadOrphan
!= 0)
2932 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2933 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2934 char *buf
= pathA
.GetBuffer();
2935 if (!pathA
.IsEmpty())
2937 opts
.pathspec
.strings
= &buf
;
2938 opts
.pathspec
.count
= 1;
2942 opts
.new_prefix
= "";
2943 opts
.old_prefix
= "";
2947 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2952 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2955 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2958 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2961 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2964 if (git_diff_merge(diff
, diff2
))
2969 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2972 if (tree1
.IsEmpty())
2980 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2983 if (tree2
.IsEmpty())
2985 /* don't check return value, there are not parent commit at first commit*/
2986 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2988 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2990 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2994 CAutoDiffStats stats
;
2995 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2998 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
3000 statCallback(statBuf
, data
);
3002 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
3005 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
3008 if (git_patch_print(patch
, callback
, data
))
3012 pathA
.ReleaseBuffer();
3017 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const CString
& rev1
, const CString
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
3019 if (UsingLibGit2(GIT_CMD_DIFF
))
3021 CAutoFILE file
= _wfsopen(patchfile
, L
"wb", SH_DENYRW
);
3024 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
, bNoPrefix
);
3029 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
, bNoPrefix
);
3031 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3035 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3037 ATLASSERT(payload
&& text
);
3038 CStringA
*str
= (CStringA
*) payload
;
3039 str
->Append(text
->ptr
, (int)text
->size
);
3040 str
->AppendChar('\n');
3043 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3045 ATLASSERT(payload
&& line
);
3046 CStringA
*str
= (CStringA
*) payload
;
3047 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3048 str
->Append(&line
->origin
, 1);
3049 str
->Append(line
->content
, (int)line
->content_len
);
3053 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const CString
& rev1
, const CString
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3055 if (UsingLibGit2(GIT_CMD_DIFF
))
3056 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
, false);
3060 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3062 int ret
= Run(cmd
, &vector
);
3063 if (!vector
.empty())
3065 vector
.push_back(0); // vector is not NUL terminated
3066 buffer
->Append((char*)vector
.data());
3072 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3074 if (UsingLibGit2(GIT_CMD_REVERT
))
3076 CAutoRepository
repo(GetGitRepository());
3081 if (git_commit_lookup(commit
.GetPointer(), repo
, hash
))
3084 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3085 revert_opts
.mainline
= parent
;
3086 int result
= git_revert(repo
, commit
, &revert_opts
);
3088 return !result
? 0 : -1;
3094 merge
.Format(L
"-m %d ", parent
);
3095 cmd
.Format(L
"git.exe revert --no-edit --no-commit %s%s", (LPCTSTR
)merge
, (LPCTSTR
)hash
.ToString());
3096 gitLastErr
= cmd
+ L
'\n';
3097 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3107 int CGit::DeleteRef(const CString
& reference
)
3109 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3111 CAutoRepository
repo(GetGitRepository());
3116 if (CStringUtils::EndsWith(reference
, L
"^{}"))
3117 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3119 refA
= CUnicodeUtils::GetUTF8(reference
);
3122 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3126 if (git_reference_is_tag(ref
))
3127 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3128 else if (git_reference_is_branch(ref
))
3129 result
= git_branch_delete(ref
);
3130 else if (git_reference_is_remote(ref
))
3131 result
= git_branch_delete(ref
);
3133 result
= git_reference_delete(ref
);
3139 CString cmd
, shortname
;
3140 if (GetShortName(reference
, shortname
, L
"refs/heads/"))
3141 cmd
.Format(L
"git.exe branch -D -- %s", (LPCTSTR
)shortname
);
3142 else if (GetShortName(reference
, shortname
, L
"refs/tags/"))
3143 cmd
.Format(L
"git.exe tag -d -- %s", (LPCTSTR
)shortname
);
3144 else if (GetShortName(reference
, shortname
, L
"refs/remotes/"))
3145 cmd
.Format(L
"git.exe branch -r -D -- %s", (LPCTSTR
)shortname
);
3148 gitLastErr
= L
"unsupported reference type: " + reference
;
3153 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3161 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3163 if (!PathFileExists(filename
))
3166 CAutoFILE pFile
= _wfsopen(filename
, L
"rb", SH_DENYWR
);
3169 ::MessageBox(nullptr, L
"Could not open " + filename
, L
"TortoiseGit", MB_ICONERROR
);
3170 return true; // load no further files
3176 char s
[8196] = { 0 };
3177 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3180 str
+= CStringA(s
, read
);
3182 msg
+= CUnicodeUtils::GetUnicode(str
);
3183 msg
.Replace(L
"\r\n", L
"\n");
3184 msg
.TrimRight(L
'\n');
3187 return true; // load no further files
3190 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, const CTGitPathList
* filterlist
, bool includedStaged
/* = false */)
3193 return GetInitAddList(result
);
3199 count
= filterlist
->GetCount();
3200 ATLASSERT(count
> 0);
3202 CString head
= L
"HEAD";
3206 CString gitStatusParams
;
3207 if (ms_LastMsysGitVersion
>= ConvertVersionToInt(2, 17, 0))
3208 gitStatusParams
= L
" --no-ahead-behind";
3210 for (int i
= 0; i
< count
; ++i
)
3212 ATLASSERT(!filterlist
|| !(*filterlist
)[i
].GetGitPathString().IsEmpty()); // pathspec must not be empty, be compatible with Git >= 2.16.0
3215 if (ms_bCygwinGit
|| ms_bMsys2Git
)
3217 // Prevent showing all files as modified when using cygwin's git
3219 cmd
.Format(L
"git.exe status%s --", (LPCTSTR
)gitStatusParams
);
3221 cmd
.Format(L
"git.exe status%s -- \"%s\"", (LPCTSTR
)gitStatusParams
, (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3226 // also list staged files which will be in the commit
3227 if (includedStaged
|| !filterlist
)
3228 Run(L
"git.exe diff-index --cached --raw " + head
+ L
" --numstat -C -M -z --", &cmdout
);
3231 cmd
.Format(L
"git.exe diff-index --cached --raw %s --numstat -C -M -z -- \"%s\"", (LPCTSTR
)head
, (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3236 cmd
.Format(L
"git.exe diff-index --raw %s --numstat -C%d%% -M%d%% -z --", (LPCTSTR
)head
, ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
);
3238 cmd
.Format(L
"git.exe diff-index --raw %s --numstat -C%d%% -M%d%% -z -- \"%s\"", (LPCTSTR
)head
, ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
, (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3241 if (Run(cmd
, &cmdout
, &cmdErr
))
3243 size_t last
= cmdErr
.RevertFind(0);
3245 if (last
!= BYTE_VECTOR::npos
)
3246 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)(cmdErr
.size() - last
) - 1);
3247 else if (!cmdErr
.empty())
3248 CGit::StringAppend(&str
, cmdErr
.data(), CP_UTF8
, (int)cmdErr
.size() - 1);
3250 str
.Format(L
"\"%s\" exited with an error code, but did not output any error message", (LPCTSTR
)cmd
);
3251 MessageBox(nullptr, str
, L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
3254 out
.append(cmdout
, 0);
3256 result
.ParserFromLog(out
);
3258 std::map
<CString
, int> duplicateMap
;
3259 for (int i
= 0; i
< result
.GetCount(); ++i
)
3260 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), i
));
3262 // handle delete conflict case, when remote : modified, local : deleted.
3263 for (int i
= 0; i
< count
; ++i
)
3269 cmd
= L
"git.exe ls-files -u -t -z";
3271 cmd
.Format(L
"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3275 CTGitPathList conflictlist
;
3276 conflictlist
.ParserFromLog(cmdout
);
3277 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3279 auto existing
= duplicateMap
.find(conflictlist
[j
].GetGitPathString());
3280 if (existing
!= duplicateMap
.end())
3282 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3283 p
.m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3287 result
.AddPath(conflictlist
[j
]);
3288 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3293 // handle source files of file renames/moves (issue #860)
3294 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3295 for (int i
= 0; i
< count
; ++i
)
3301 cmd
= L
"git.exe ls-files -d -z";
3303 cmd
.Format(L
"git.exe ls-files -d -z -- \"%s\"", (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3307 CTGitPathList deletelist
;
3308 deletelist
.ParserFromLog(cmdout
, true);
3309 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3311 auto existing
= duplicateMap
.find(deletelist
[j
].GetGitPathString());
3312 if (existing
== duplicateMap
.end())
3314 result
.AddPath(deletelist
[j
]);
3315 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3319 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3320 p
.m_Action
|= CTGitPath::LOGACTIONS_MISSING
;
3328 int CGit::IsRebaseRunning()
3331 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3334 if (PathIsDirectory(adminDir
+ L
"rebase-apply") || PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3339 void CGit::GetBisectTerms(CString
* good
, CString
* bad
)
3341 static CString lastGood
;
3342 static CString lastBad
;
3343 static ULONGLONG lastRead
= 0;
3353 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3354 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3355 // as we only read a small file the performance effects should be negligible
3356 if (lastRead
+ 5000 > GetTickCount64())
3364 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir
, adminDir
))
3367 CString termsFile
= adminDir
+ L
"BISECT_TERMS";
3369 _wfopen_s(fp
.GetPointer(), termsFile
, L
"rb");
3372 char badA
[MAX_PATH
] = { 0 };
3373 fgets(badA
, sizeof(badA
), fp
);
3374 size_t len
= strlen(badA
);
3375 if (len
> 0 && badA
[len
- 1] == '\n')
3376 badA
[len
- 1] = '\0';
3377 char goodA
[MAX_PATH
] = { 0 };
3378 fgets(goodA
, sizeof(goodA
), fp
);
3379 len
= strlen(goodA
);
3380 if (len
> 0 && goodA
[len
- 1] == '\n')
3381 goodA
[len
- 1] = '\0';
3382 lastGood
= CUnicodeUtils::GetUnicode(goodA
);
3383 lastBad
= CUnicodeUtils::GetUnicode(badA
);
3384 lastRead
= GetTickCount64();
3387 int CGit::GetGitVersion(CString
* versiondebug
, CString
* errStr
)
3389 CString version
, err
;
3390 if (Run(L
"git.exe --version", &version
, &err
, CP_UTF8
))
3399 *versiondebug
= version
;
3404 CString str
= version
.Tokenize(L
".", start
);
3405 int space
= str
.ReverseFind(L
' ');
3406 str
= str
.Mid(space
+ 1, start
);
3410 version
= version
.Mid(start
);
3413 str
= version
.Tokenize(L
".", start
);
3414 ver
|= (_wtol(str
) & 0xFF) << 16;
3416 str
= version
.Tokenize(L
".", start
);
3417 ver
|= (_wtol(str
) & 0xFF) << 8;
3419 str
= version
.Tokenize(L
".", start
);
3420 ver
|= (_wtol(str
) & 0xFF);
3431 int CGit::GetGitNotes(const CGitHash
& hash
, CString
& notes
)
3433 CAutoRepository
repo(GetGitRepository());
3438 int ret
= git_note_read(note
.GetPointer(), repo
, nullptr, hash
);
3439 if (ret
== GIT_ENOTFOUND
)
3446 notes
= CUnicodeUtils::GetUnicode(git_note_message(note
));
3450 int CGit::SetGitNotes(const CGitHash
& hash
, const CString
& notes
)
3452 CAutoRepository
repo(GetGitRepository());
3456 CAutoSignature signature
;
3457 if (git_signature_default(signature
.GetPointer(), repo
) < 0)
3461 if (git_note_create(&oid
, repo
, nullptr, signature
, signature
, hash
, CUnicodeUtils::GetUTF8(notes
), 1) < 0)