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 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
110 _wgetenv_s(&size
, env
, size
, L
"PATH");
112 CString gitExeDirectory
= FindFileOnPath(L
"git.exe", env
, true);
113 if (!gitExeDirectory
.IsEmpty())
115 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
116 CGit::ms_LastMsysGitDir
.TrimRight(L
'\\');
117 if (CGit::ms_LastMsysGitDir
.GetLength() > 12 && (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
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + L
"\\cmd\\git.exe";
121 if (PathFileExists(installRoot
))
122 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + L
"\\cmd";
124 if (CGit::ms_LastMsysGitDir
.GetLength() > 4 && 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 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + L
"\\bin\\git.exe";
129 if (PathFileExists(binDir
))
130 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + L
"\\bin";
138 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
140 CString filename
= executable
;
142 if (!CStringUtils::EndsWith(executable
, L
".exe"))
145 if (PathFileExists(filename
))
148 filename
= FindFileOnPath(filename
, env
);
149 if (!filename
.IsEmpty())
155 static bool g_bSortLogical
;
156 static bool g_bSortLocalBranchesFirst
;
157 static bool g_bSortTagsReversed
;
158 static git_cred_acquire_cb g_Git2CredCallback
;
159 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
161 static void GetSortOptions()
163 #ifdef GTEST_INCLUDE_GTEST_GTEST_H_
164 g_bSortLogical
= true;
165 g_bSortLocalBranchesFirst
= true;
166 g_bSortTagsReversed
= false;
168 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
170 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
171 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
172 if (g_bSortLocalBranchesFirst
)
173 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
174 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
175 if (!g_bSortTagsReversed
)
176 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
180 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
183 return StrCmpLogicalW(left
, right
) < 0;
184 return StrCmpI(left
, right
) < 0;
187 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
189 return LogicalComparePredicate(right
, left
);
192 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
194 if (g_bSortLocalBranchesFirst
)
196 bool leftIsRemote
= CStringUtils::StartsWith(left
, L
"remotes/");
197 bool rightIsRemote
= CStringUtils::StartsWith(right
, L
"remotes/");
199 if (leftIsRemote
&& !rightIsRemote
)
201 else if (!leftIsRemote
&& rightIsRemote
)
204 return LogicalComparePredicate(left
, right
);
207 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
209 CString
CGit::ms_LastMsysGitDir
;
210 CString
CGit::ms_MsysGitRootDir
;
211 int CGit::ms_LastMsysGitVersion
= 0;
218 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
219 m_IsGitDllInited
= false;
221 m_GitSimpleListDiff
=0;
222 m_IsUseGitDLL
= !!CRegDWORD(L
"Software\\TortoiseGit\\UsingGitDLL",1);
223 m_IsUseLibGit2
= !!CRegDWORD(L
"Software\\TortoiseGit\\UseLibgit2", TRUE
);
224 m_IsUseLibGit2_mask
= CRegDWORD(L
"Software\\TortoiseGit\\UseLibgit2_mask", DEFAULT_USE_LIBGIT2_MASK
);
226 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
229 this->m_bInitialized
=false;
231 m_critGitDllSec
.Init();
232 m_critSecThreadMap
.Init();
239 git_close_diff(m_GitDiff
);
242 if(this->m_GitSimpleListDiff
)
244 git_close_diff(m_GitSimpleListDiff
);
245 m_GitSimpleListDiff
=0;
247 git_libgit2_shutdown();
248 m_critSecThreadMap
.Term();
249 m_critGitDllSec
.Term();
252 bool CGit::IsBranchNameValid(const CString
& branchname
)
254 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
256 if (branchname
.FindOneOf(L
"\"|<>") >= 0) // not valid on Windows
258 if (branchname
== L
"HEAD") // Branch name HEAD is discouraged since Git v2.16.0, see https://github.com/git/git/commit/a625b092cc59940521789fe8a3ff69c8d6b14eb2
260 CStringA branchA
= CUnicodeUtils::GetUTF8(L
"refs/heads/" + branchname
);
261 return !!git_reference_is_valid_name(branchA
);
264 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
* piOut
, HANDLE
* hReadOut
, HANDLE
* hErrReadOut
, const CString
* StdioFile
)
266 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
, hWriteIn
, hReadIn
;
267 CAutoFile hStdioFile
;
269 SECURITY_ATTRIBUTES sa
= { 0 };
270 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
271 sa
.bInheritHandle
=TRUE
;
272 if (!CreatePipe(hReadIn
.GetPointer(), hWriteIn
.GetPointer(), &sa
, 0))
274 CString err
= CFormatMessageWrapper();
275 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stdin pipe: %s\n", (LPCTSTR
)err
.Trim());
276 return TGIT_GIT_ERROR_OPEN_PIP
;
278 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
280 CString err
= CFormatMessageWrapper();
281 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stdout pipe: %s\n", (LPCTSTR
)err
.Trim());
282 return TGIT_GIT_ERROR_OPEN_PIP
;
284 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
286 CString err
= CFormatMessageWrapper();
287 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not open stderr pipe: %s\n", (LPCTSTR
)err
.Trim());
288 return TGIT_GIT_ERROR_OPEN_PIP
;
292 hStdioFile
= CreateFile(*StdioFile
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
294 STARTUPINFO si
= { 0 };
295 PROCESS_INFORMATION pi
= { 0 };
296 si
.cb
=sizeof(STARTUPINFO
);
297 si
.hStdInput
= hReadIn
;
299 si
.hStdError
= hWriteErr
;
301 si
.hStdError
= hWrite
;
303 si
.hStdOutput
=hStdioFile
;
305 si
.hStdOutput
=hWrite
;
307 si
.wShowWindow
=SW_HIDE
;
308 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
310 LPTSTR pEnv
= m_Environment
;
311 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
312 dwFlags
|= CREATE_NEW_PROCESS_GROUP
| DETACHED_PROCESS
;
314 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
316 bool startsWithGit
= CStringUtils::StartsWith(cmd
, L
"git");
317 if (ms_bMsys2Git
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
319 cmd
.Replace(L
"\\", L
"\\\\\\\\");
320 cmd
.Replace(L
"\"", L
"\\\"");
321 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\bash.exe\" -c \"/usr/bin/" + cmd
+ L
'"';
323 else if (ms_bCygwinGit
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
325 cmd
.Replace(L
'\\', L
'/');
326 cmd
.Replace(L
"\"", L
"\\\"");
327 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\bash.exe\" -c \"/bin/" + cmd
+ L
'"';
329 else if (startsWithGit
|| CStringUtils::StartsWith(cmd
, L
"bash"))
331 int firstSpace
= cmd
.Find(L
' ');
333 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
'\\' + cmd
.Left(firstSpace
) + L
'"' + cmd
.Mid(firstSpace
);
335 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
'\\' + cmd
+ L
'"';
338 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": executing %s\n", (LPCTSTR
)cmd
);
339 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
341 CString err
= CFormatMessageWrapper();
342 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": error while executing command: %s\n", (LPCTSTR
)err
.Trim());
343 return TGIT_GIT_ERROR_CREATE_PROCESS
;
346 // Close the pipe handle so the child process stops reading.
347 hWriteIn
.CloseHandle();
354 *hReadOut
= hRead
.Detach();
356 *hErrReadOut
= hReadErr
.Detach();
359 //Must use sperate function to convert ANSI str to union code string
360 //Because A2W use stack as internal convert buffer.
361 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
368 len
= (int)strlen((const char*)p
);
373 int currentContentLen
= str
->GetLength();
374 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
375 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
376 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
379 // This method was originally used to check for orphaned branches
380 BOOL
CGit::CanParseRev(CString ref
)
386 if (Run(L
"git.exe rev-parse --revs-only " + ref
, &cmdout
, CP_UTF8
))
394 // Checks if we have an orphaned HEAD
395 BOOL
CGit::IsInitRepos()
398 if (GetHash(hash
, L
"HEAD") != 0)
400 return hash
.IsEmpty() ? TRUE
: FALSE
;
403 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
405 PASYNCREADSTDERRTHREADARGS pDataArray
;
406 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
409 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
410 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
412 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
420 void CGit::KillRelatedThreads(CWinThread
* thread
)
422 CAutoLocker
lock(m_critSecThreadMap
);
423 auto it
= m_AsyncReadStdErrThreadMap
.find(thread
->m_nThreadID
);
424 if (it
!= m_AsyncReadStdErrThreadMap
.cend())
426 TerminateThread(it
->second
, (DWORD
)-1);
427 m_AsyncReadStdErrThreadMap
.erase(it
);
429 TerminateThread(thread
->m_hThread
, (DWORD
)-1);
433 int CGit::Run(CGitCall
* pcall
)
435 PROCESS_INFORMATION pi
;
436 CAutoGeneralHandle hRead
, hReadErr
;
437 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
438 return TGIT_GIT_ERROR_CREATE_PROCESS
;
440 CAutoGeneralHandle
piThread(std::move(pi
.hThread
));
441 CAutoGeneralHandle
piProcess(std::move(pi
.hProcess
));
443 ASYNCREADSTDERRTHREADARGS threadArguments
;
444 threadArguments
.fileHandle
= hReadErr
;
445 threadArguments
.pcall
= pcall
;
446 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
450 CAutoLocker
lock(m_critSecThreadMap
);
451 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
455 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
457 while (ReadFile(hRead
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
459 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
460 if(!bAborted
)//For now, flush output when command aborted.
461 if(pcall
->OnOutputData(data
,readnumber
))
469 WaitForSingleObject(thread
, INFINITE
);
471 CAutoLocker
lock(m_critSecThreadMap
);
472 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
475 WaitForSingleObject(pi
.hProcess
, INFINITE
);
478 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
480 CString err
= CFormatMessageWrapper();
481 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not get exit code: %s\n", (LPCTSTR
)err
.Trim());
482 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
485 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": process exited: %d\n", exitcode
);
489 class CGitCall_ByteVector
: public CGitCall
492 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= nullptr) : CGitCall(cmd
),m_pvector(pvector
), m_pvectorErr(pvectorErr
) {}
493 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
495 if (!m_pvector
|| size
== 0)
497 size_t oldsize
=m_pvector
->size();
498 m_pvector
->resize(m_pvector
->size()+size
);
499 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
502 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
504 if (!m_pvectorErr
|| size
== 0)
506 size_t oldsize
= m_pvectorErr
->size();
507 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
508 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
511 BYTE_VECTOR
* m_pvector
;
512 BYTE_VECTOR
* m_pvectorErr
;
514 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
516 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
519 int CGit::Run(CString cmd
, CString
* output
, int code
)
523 ret
= Run(cmd
, output
, &err
, code
);
525 if (output
&& !err
.IsEmpty())
527 if (!output
->IsEmpty())
534 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
536 BYTE_VECTOR vector
, vectorErr
;
539 ret
= Run(cmd
, &vector
, &vectorErr
);
541 ret
= Run(cmd
, &vector
);
544 StringAppend(output
, vector
.data(), code
);
548 vectorErr
.push_back(0);
549 StringAppend(outputErr
, vectorErr
.data(), code
);
555 class CGitCallCb
: public CGitCall
558 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
, BYTE_VECTOR
* pvectorErr
= nullptr)
561 , m_pvectorErr(pvectorErr
)
564 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
569 int oldEndPos
= m_buffer
.GetLength();
570 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
571 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
573 // Break into lines and feed to m_recv
575 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
577 m_recv(m_buffer
.Left(eolPos
));
578 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
583 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
585 if (!m_pvectorErr
|| size
== 0)
587 size_t oldsize
= m_pvectorErr
->size();
588 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
589 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
593 virtual void OnEnd() override
595 if (!m_buffer
.IsEmpty())
597 m_buffer
.Empty(); // Just for sure
601 GitReceiverFunc m_recv
;
603 BYTE_VECTOR
* m_pvectorErr
;
606 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
, CString
* outputErr
)
610 BYTE_VECTOR vectorErr
;
611 CGitCallCb
call(cmd
, recv
, &vectorErr
);
612 int ret
= Run(&call
);
613 vectorErr
.push_back(0);
614 StringAppend(outputErr
, vectorErr
.data());
618 CGitCallCb
call(cmd
, recv
);
622 CString
CGit::GetUserName(void)
625 env
.CopyProcessEnvironment();
626 CString envname
= env
.GetEnv(L
"GIT_AUTHOR_NAME");
627 if (!envname
.IsEmpty())
629 return GetConfigValue(L
"user.name");
631 CString
CGit::GetUserEmail(void)
634 env
.CopyProcessEnvironment();
635 CString envmail
= env
.GetEnv(L
"GIT_AUTHOR_EMAIL");
636 if (!envmail
.IsEmpty())
639 return GetConfigValue(L
"user.email");
642 CString
CGit::GetConfigValue(const CString
& name
, const CString
& def
, bool wantBool
)
645 if(this->m_IsUseGitDLL
)
647 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
656 key
= CUnicodeUtils::GetUTF8(name
);
660 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
663 catch (const char *msg
)
665 ::MessageBox(nullptr, L
"Could not get config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
669 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
675 cmd
.Format(L
"git.exe config%s %s", wantBool
? L
" --bool" : L
"", (LPCTSTR
)name
);
676 if (Run(cmd
, &configValue
, nullptr, CP_UTF8
))
678 if (configValue
.IsEmpty())
680 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
684 bool CGit::GetConfigValueBool(const CString
& name
, const bool def
)
686 CString configValue
= GetConfigValue(name
, def
? L
"true" : L
"false", true);
687 configValue
.MakeLower();
689 if (configValue
== L
"true" || configValue
== L
"on" || configValue
== L
"yes" || StrToInt(configValue
) != 0)
695 int CGit::GetConfigValueInt32(const CString
& name
, const int def
)
697 CString configValue
= GetConfigValue(name
);
699 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
704 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
706 if(this->m_IsUseGitDLL
)
708 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
716 CStringA keya
, valuea
;
717 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
718 valuea
= CUnicodeUtils::GetUTF8(value
);
722 return [=]() { return get_set_config(keya
, valuea
, type
); }();
724 catch (const char *msg
)
726 ::MessageBox(nullptr, L
"Could not set config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
737 option
= L
"--global";
740 option
= L
"--system";
745 CString mangledValue
= value
;
746 mangledValue
.Replace(L
"\\\"", L
"\\\\\"");
747 mangledValue
.Replace(L
"\"", L
"\\\"");
748 cmd
.Format(L
"git.exe config %s %s \"%s\"", (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
750 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
756 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
758 if(this->m_IsUseGitDLL
)
760 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
769 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
773 return [=]() { return get_set_config(keya
, nullptr, type
); }();
775 catch (const char *msg
)
777 ::MessageBox(nullptr, L
"Could not unset config.\nlibgit reports:\n" + CString(msg
), L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
788 option
= L
"--global";
791 option
= L
"--system";
796 cmd
.Format(L
"git.exe config %s --unset %s", (LPCTSTR
)option
, (LPCTSTR
)key
);
798 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
804 CString
CGit::GetCurrentBranch(bool fallback
)
807 //Run(L"git.exe branch", &branch);
809 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
810 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
811 return L
"(no branch)";
816 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
818 if (localBranch
.IsEmpty())
822 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
823 pullRemote
= GetConfigValue(configName
);
825 //Select pull-branch from current branch
826 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
827 pullBranch
= StripRefName(GetConfigValue(configName
));
830 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
833 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
835 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
838 void CGit::GetRemotePushBranch(const CString
& localBranch
, CString
& pushRemote
, CString
& pushBranch
)
840 if (localBranch
.IsEmpty())
845 configName
.Format(L
"branch.%s.pushremote", (LPCTSTR
)localBranch
);
846 pushRemote
= g_Git
.GetConfigValue(configName
);
847 if (pushRemote
.IsEmpty())
849 pushRemote
= g_Git
.GetConfigValue(L
"remote.pushdefault");
850 if (pushRemote
.IsEmpty())
852 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
853 pushRemote
= g_Git
.GetConfigValue(configName
);
857 configName
.Format(L
"branch.%s.pushbranch", (LPCTSTR
)localBranch
);
858 pushBranch
= g_Git
.GetConfigValue(configName
); // do not strip branch name (for gerrit), see issue #1609)
859 if (pushBranch
.IsEmpty())
861 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
862 pushBranch
= CGit::StripRefName(g_Git
.GetConfigValue(configName
));
866 CString
CGit::GetFullRefName(const CString
& shortRefName
)
870 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
871 if (Run(cmd
, &refName
, nullptr, CP_UTF8
) != 0)
872 return CString();//Error
873 return refName
.TrimRight();
876 CString
CGit::StripRefName(CString refName
)
878 if (CStringUtils::StartsWith(refName
, L
"refs/heads/"))
879 refName
= refName
.Mid(11);
880 else if (CStringUtils::StartsWith(refName
, L
"refs/"))
881 refName
= refName
.Mid(5);
882 return refName
.TrimRight();
885 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
887 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
889 if ( sProjectRoot
.IsEmpty() )
893 if (!GitAdminDir::GetWorktreeAdminDirPath(sProjectRoot
, sDotGitPath
))
896 CString sHeadFile
= sDotGitPath
+ L
"HEAD";
898 CAutoFILE pFile
= _wfsopen(sHeadFile
.GetString(), L
"r", SH_DENYWR
);
902 char s
[MAX_PATH
] = {0};
903 fgets(s
, sizeof(s
), pFile
);
905 const char *pfx
= "ref: refs/heads/";
906 const size_t len
= strlen(pfx
);
908 if ( !strncmp(s
, pfx
, len
) )
910 //# We're on a branch. It might not exist. But
911 //# HEAD looks good enough to be a branch.
912 CStringA
utf8Branch(s
+ len
);
913 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
914 sBranchOut
.TrimRight(L
" \r\n\t");
916 if ( sBranchOut
.IsEmpty() )
921 CStringA
utf8Hash(s
);
922 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
923 unicodeHash
.TrimRight(L
" \r\n\t");
924 if (CGitHash::IsValidSHA1(unicodeHash
))
925 sBranchOut
= unicodeHash
;
927 //# Assume this is a detached head.
928 sBranchOut
= L
"HEAD";
933 //# Assume this is a detached head.
942 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
945 log
.Format(L
"#<%c>%%x00", LOG_REV_ITEM_BEGIN
);
949 log
.Format(L
"#<%c>%%an%%x00", LOG_REV_AUTHOR_NAME
);
951 log
.Format(L
"#<%c>%%ae%%x00", LOG_REV_AUTHOR_EMAIL
);
953 log
.Format(L
"#<%c>%%ai%%x00", LOG_REV_AUTHOR_DATE
);
955 log
.Format(L
"#<%c>%%cn%%x00", LOG_REV_COMMIT_NAME
);
957 log
.Format(L
"#<%c>%%ce%%x00", LOG_REV_COMMIT_EMAIL
);
959 log
.Format(L
"#<%c>%%ci%%x00", LOG_REV_COMMIT_DATE
);
961 log
.Format(L
"#<%c>%%b%%x00", LOG_REV_COMMIT_BODY
);
965 log
.Format(L
"#<%c>%%m%%H%%x00", LOG_REV_COMMIT_HASH
);
967 log
.Format(L
"#<%c>%%P%%x00", LOG_REV_COMMIT_PARENT
);
969 log
.Format(L
"#<%c>%%s%%x00", LOG_REV_COMMIT_SUBJECT
);
974 log
.Format(L
"#<%c>%%x00", LOG_REV_COMMIT_FILE
);
980 CString
CGit::GetLogCmd(CString range
, const CTGitPath
* path
, int mask
, CFilterData
* Filter
, int logOrderBy
)
984 if(mask
& LOG_INFO_STAT
)
985 param
+= L
" --numstat";
986 if(mask
& LOG_INFO_FILESTATE
)
989 if(mask
& LOG_INFO_BOUNDARY
)
990 param
+= L
" --left-right --boundary";
992 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
998 if (mask
& CGit::LOG_INFO_BASIC_REFS
)
1000 param
+= L
" --branches";
1001 param
+= L
" --tags";
1002 param
+= L
" --remotes";
1003 param
+= L
" --glob=stas[h]"; // require at least one glob operator
1004 param
+= L
" --glob=bisect";
1008 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
1010 param
+= L
" --branches";
1014 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
1015 param
.AppendFormat(L
" -C%d%%", ms_iSimilarityIndexThreshold
);
1017 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
1018 param
.AppendFormat(L
" -M%d%%", ms_iSimilarityIndexThreshold
);
1020 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
1021 param
+= L
" --first-parent";
1023 if(mask
& CGit::LOG_INFO_NO_MERGE
)
1024 param
+= L
" --no-merges";
1026 if(mask
& CGit::LOG_INFO_FOLLOW
)
1027 param
+= L
" --follow";
1029 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
1032 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
1033 param
+= L
" --full-diff";
1035 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
1036 param
+= L
" --simplify-by-decoration";
1040 if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_N_YEARS
)
1042 CTime now
= CTime::GetCurrentTime();
1043 CTime time
= CTime(now
.GetYear(), now
.GetMonth(), now
.GetDay(), 0, 0, 0);
1044 __time64_t substract
= 86400;
1046 switch (Filter
->m_NumberOfLogsScale
)
1048 case CFilterData::SHOW_LAST_N_YEARS
:
1051 case CFilterData::SHOW_LAST_N_MONTHS
:
1054 case CFilterData::SHOW_LAST_N_WEEKS
:
1058 Filter
->m_From
= (DWORD
)time
.GetTime() - (Filter
->m_NumberOfLogs
* substract
);
1060 if (Filter
->m_NumberOfLogsScale
== CFilterData::SHOW_LAST_N_COMMITS
)
1061 param
.AppendFormat(L
" -n%ld", Filter
->m_NumberOfLogs
);
1062 else if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_SEL_DATE
&& Filter
->m_From
> 0)
1063 param
.AppendFormat(L
" --max-age=%I64u", Filter
->m_From
);
1066 if( Filter
&& (Filter
->m_To
!= -1))
1067 param
.AppendFormat(L
" --min-age=%I64u", Filter
->m_To
);
1069 if (logOrderBy
== LOG_ORDER_TOPOORDER
|| (mask
& CGit::LOG_ORDER_TOPOORDER
))
1070 param
+= L
" --topo-order";
1071 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1072 param
+= L
" --date-order";
1077 file
.Format(L
" \"%s\"", (LPCTSTR
)path
->GetGitPathString());
1078 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1079 cmd
.Format(L
"-z%s %s --parents --%s", (LPCTSTR
)param
, (LPCTSTR
)range
, (LPCTSTR
)file
);
1084 void GetTempPath(CString
&path
)
1086 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1088 DWORD dwBufSize
=BUFSIZE
;
1089 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1090 lpPathBuffer
); // buffer for path
1091 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1093 path
.Format(L
"%s", lpPathBuffer
);
1095 CString
GetTempFile()
1097 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1099 DWORD dwBufSize
=BUFSIZE
;
1100 TCHAR szTempName
[BUFSIZE
] = { 0 };
1103 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1104 lpPathBuffer
); // buffer for path
1105 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1108 // Create a temporary file.
1109 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1110 TEXT("Patch"), // temp file name prefix
1111 0, // create unique name
1112 szTempName
); // buffer for name
1117 return CString(szTempName
);
1120 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1122 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1123 if (result
== 0) return 0;
1124 if (!lpBuffer
|| (result
+ 13 > nBufferLength
))
1131 wcscat_s(lpBuffer
, nBufferLength
, L
"TortoiseGit\\");
1132 CreateDirectory(lpBuffer
, nullptr);
1137 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1139 PROCESS_INFORMATION pi
;
1140 CAutoGeneralHandle hReadErr
;
1141 if (RunAsync(cmd
, &pi
, nullptr, hReadErr
.GetPointer(), &filename
))
1142 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1144 CAutoGeneralHandle
piThread(std::move(pi
.hThread
));
1145 CAutoGeneralHandle
piProcess(std::move(pi
.hProcess
));
1147 BYTE_VECTOR stderrVector
;
1148 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1149 ASYNCREADSTDERRTHREADARGS threadArguments
;
1150 threadArguments
.fileHandle
= hReadErr
;
1151 threadArguments
.pcall
= &pcall
;
1152 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1156 CAutoLocker
lock(m_critSecThreadMap
);
1157 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
1160 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1164 WaitForSingleObject(thread
, INFINITE
);
1166 CAutoLocker
lock(m_critSecThreadMap
);
1167 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
1170 stderrVector
.push_back(0);
1171 StringAppend(stdErr
, stderrVector
.data(), CP_UTF8
);
1174 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1176 CString err
= CFormatMessageWrapper();
1177 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": could not get exit code: %s\n", (LPCTSTR
)err
.Trim());
1178 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1181 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": process exited: %d\n", exitcode
);
1186 CAutoRepository
CGit::GetGitRepository() const
1188 return CAutoRepository(GetGitPathStringA(m_CurrentDir
));
1191 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1195 // no need to parse a ref if it's already a 40-byte hash
1196 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1198 hash
= CGitHash(friendname
);
1202 int isHeadOrphan
= git_repository_head_unborn(repo
);
1203 if (isHeadOrphan
!= 0)
1206 if (isHeadOrphan
== 1)
1212 CAutoObject gitObject
;
1213 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1216 hash
= git_object_id(gitObject
);
1221 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1223 // no need to parse a ref if it's already a 40-byte hash
1224 if (CGitHash::IsValidSHA1(friendname
))
1226 hash
= CGitHash(friendname
);
1232 CAutoRepository
repo(GetGitRepository());
1236 return GetHash(repo
, hash
, friendname
, true);
1240 CString branch
= FixBranchName(friendname
);
1241 if (friendname
== L
"FETCH_HEAD" && branch
.IsEmpty())
1242 branch
= friendname
;
1244 cmd
.Format(L
"git.exe rev-parse %s", (LPCTSTR
)branch
);
1246 int ret
= Run(cmd
, &gitLastErr
, nullptr, CP_UTF8
);
1247 hash
= CGitHash(gitLastErr
.Trim());
1250 else if (friendname
== L
"HEAD") // special check for unborn branch
1252 CString currentbranch
;
1253 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1262 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1267 if (Run(L
"git.exe ls-files -s -t -z", &cmdout
))
1270 if (outputlist
.ParserFromLsFile(cmdout
))
1272 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1273 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1277 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1281 if (ignoreSpaceAtEol
)
1282 ignore
+= L
" --ignore-space-at-eol";
1283 if (ignoreSpaceChange
)
1284 ignore
+= L
" --ignore-space-change";
1286 ignore
+= L
" --ignore-all-space";
1287 if (ignoreBlankLines
)
1288 ignore
+= L
" --ignore-blank-lines";
1290 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1292 if(rev1
== GIT_REV_ZERO
)
1293 cmd
.Format(L
"git.exe diff -r --raw -C%d%% -M%d%% --numstat -z %s %s --", ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
, (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1295 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
);
1298 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
);
1304 return outputlist
.ParserFromLog(out
);
1307 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1309 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1310 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1314 int CGit::GetTagList(STRING_VECTOR
&list
)
1316 size_t prevCount
= list
.size();
1317 if (this->m_IsUseLibGit2
)
1319 CAutoRepository
repo(GetGitRepository());
1323 CAutoStrArray tag_names
;
1325 if (git_tag_list(tag_names
, repo
))
1328 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1330 CStringA
tagName(tag_names
->strings
[i
]);
1331 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1334 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1340 int ret
= Run(L
"git.exe tag -l", [&](const CStringA
& lineA
)
1342 if (lineA
.IsEmpty())
1344 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1347 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1348 else if (ret
== 1 && IsInitRepos())
1354 CString
CGit::GetGitLastErr(const CString
& msg
)
1356 if (this->m_IsUseLibGit2
)
1357 return GetLibGit2LastErr(msg
);
1358 else if (gitLastErr
.IsEmpty())
1359 return msg
+ L
"\nUnknown git.exe error.";
1362 CString lastError
= gitLastErr
;
1364 return msg
+ L
'\n' + lastError
;
1368 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1370 if (UsingLibGit2(cmd
))
1371 return GetLibGit2LastErr(msg
);
1372 else if (gitLastErr
.IsEmpty())
1373 return msg
+ L
"\nUnknown git.exe error.";
1376 CString lastError
= gitLastErr
;
1378 return msg
+ L
'\n' + lastError
;
1382 CString
CGit::GetLibGit2LastErr()
1384 const git_error
*libgit2err
= giterr_last();
1387 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1389 return L
"libgit2 returned: " + lastError
;
1392 return L
"An error occoured in libgit2, but no message is available.";
1395 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1398 return msg
+ L
'\n' + GetLibGit2LastErr();
1399 return GetLibGit2LastErr();
1402 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1404 if (branchName
== L
"FETCH_HEAD")
1405 branchName
= DerefFetchHead();
1409 CString
CGit::FixBranchName(const CString
& branchName
)
1411 CString tempBranchName
= branchName
;
1412 FixBranchName_Mod(tempBranchName
);
1413 return tempBranchName
;
1416 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1420 CAutoRepository
repo(GetGitRepository());
1422 return true; // TODO: optimize error reporting
1424 CAutoReference tagRef
;
1425 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1428 CAutoReference branchRef
;
1429 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1436 cmd
.Format(L
"git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s", (LPCTSTR
)name
, (LPCTSTR
)name
);
1439 Run(cmd
, [&](const CStringA
& lineA
)
1441 if (lineA
.IsEmpty())
1446 return (refCnt
<= 1);
1449 bool CGit::IsLocalBranch(const CString
& shortName
)
1452 GetBranchList(list
, nullptr, CGit::BRANCH_LOCAL
);
1453 return std::find(list
.cbegin(), list
.cend(), shortName
) != list
.cend();
1456 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1460 CAutoRepository
repo(GetGitRepository());
1462 return false; // TODO: optimize error reporting
1466 prefix
= L
"refs/heads/";
1468 prefix
= L
"refs/tags/";
1471 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1477 CString cmd
, output
;
1479 cmd
= L
"git.exe show-ref ";
1485 cmd
+= L
"refs/heads/" + name
;
1486 cmd
+= L
" refs/tags/" + name
;
1488 int ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1491 if (!output
.IsEmpty())
1498 CString
CGit::DerefFetchHead()
1501 GitAdminDir::GetWorktreeAdminDirPath(m_CurrentDir
, dotGitPath
);
1502 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1503 int forMergeLineCount
= 0;
1505 std::string hashToReturn
;
1506 while(getline(fetchHeadFile
, line
))
1508 //Tokenize this line
1509 std::string::size_type prevPos
= 0;
1510 std::string::size_type pos
= line
.find('\t');
1511 if(pos
== std::string::npos
) continue; //invalid line
1513 std::string hash
= line
.substr(0, pos
);
1514 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1516 bool forMerge
= pos
== prevPos
;
1517 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1519 //std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1524 hashToReturn
= hash
;
1525 ++forMergeLineCount
;
1526 if(forMergeLineCount
> 1)
1527 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1531 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1534 int CGit::GetBranchList(STRING_VECTOR
&list
, int *current
, BRANCH_TYPE type
, bool skipCurrent
/*false*/)
1536 size_t prevCount
= list
.size();
1539 bool headIsDetached
= false;
1542 CAutoRepository
repo(GetGitRepository());
1546 if (git_repository_head_detached(repo
) == 1)
1547 headIsDetached
= true;
1549 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1551 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1552 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1553 flags
= GIT_BRANCH_ALL
;
1554 else if (type
& BRANCH_REMOTE
)
1555 flags
= GIT_BRANCH_REMOTE
;
1557 CAutoBranchIterator it
;
1558 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1562 git_branch_t branchType
;
1563 while (git_branch_next(ref
.GetPointer(), &branchType
, it
) == 0)
1565 const char * name
= nullptr;
1566 if (git_branch_name(&name
, ref
))
1569 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1570 if (branchType
& GIT_BRANCH_REMOTE
)
1571 list
.push_back(L
"remotes/" + branchname
);
1574 if (git_branch_is_head(ref
))
1580 list
.push_back(branchname
);
1587 CString cmd
= L
"git.exe branch --no-color";
1589 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1591 else if (type
& BRANCH_REMOTE
)
1594 ret
= Run(cmd
, [&](CStringA lineA
)
1596 lineA
.Trim(" \r\n\t");
1597 if (lineA
.IsEmpty())
1599 if (lineA
.Find(" -> ") >= 0)
1600 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1602 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1603 if (lineA
[0] == '*')
1607 branch
= branch
.Mid(2);
1610 // check whether HEAD is detached
1611 CString currentHead
;
1612 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1614 headIsDetached
= true;
1618 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1619 branch
= L
"remotes/" + branch
;
1620 list
.push_back(branch
);
1622 if (ret
== 1 && IsInitRepos())
1626 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1627 list
.push_back(L
"FETCH_HEAD");
1629 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1631 if (current
&& !headIsDetached
&& !skipCurrent
)
1633 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1646 int CGit::GetRefsCommitIsOn(STRING_VECTOR
& list
, const CGitHash
& hash
, bool includeTags
, bool includeBranches
, BRANCH_TYPE type
)
1648 if (!includeTags
&& !includeBranches
|| hash
.IsEmpty())
1651 size_t prevCount
= list
.size();
1654 CAutoRepository
repo(GetGitRepository());
1658 CAutoReferenceIterator it
;
1659 if (git_reference_iterator_new(it
.GetPointer(), repo
))
1662 auto checkDescendent
= [&list
, &hash
, &repo
](const git_oid
* oid
, const git_reference
* ref
) {
1665 if (git_oid_equal(oid
, hash
) || git_graph_descendant_of(repo
, oid
, hash
) == 1)
1667 const char* name
= git_reference_name(ref
);
1671 list
.push_back(CUnicodeUtils::GetUnicode(name
));
1676 while (git_reference_next(ref
.GetPointer(), it
) == 0)
1678 if (git_reference_is_tag(ref
))
1684 if (git_tag_lookup(tag
.GetPointer(), repo
, git_reference_target(ref
)) == 0)
1687 if (git_tag_peel(obj
.GetPointer(), tag
) < 0)
1689 checkDescendent(git_object_id(obj
), ref
);
1693 else if (git_reference_is_remote(ref
))
1695 if (!includeBranches
|| !(type
& BRANCH_REMOTE
))
1698 else if (git_reference_is_branch(ref
))
1700 if (!includeBranches
|| !(type
& GIT_BRANCH_LOCAL
))
1706 if (git_reference_type(ref
) == GIT_REF_SYMBOLIC
)
1708 CAutoReference peeledRef
;
1709 if (git_reference_resolve(peeledRef
.GetPointer(), ref
) < 0)
1712 checkDescendent(git_reference_target(peeledRef
), ref
);
1716 checkDescendent(git_reference_target(ref
), ref
);
1721 if (includeBranches
)
1723 CString cmd
= L
"git.exe branch --no-color";
1724 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1726 else if (type
& BRANCH_REMOTE
)
1728 cmd
+= L
" --contains " + hash
.ToString();
1730 if (Run(cmd
, [&](CStringA lineA
)
1732 lineA
.Trim(" \r\n\t");
1733 if (lineA
.IsEmpty())
1735 if (lineA
.Find(" -> ") >= 0) // normalize symbolic refs: "refs/origin/HEAD -> refs/origin/master" to "refs/origin/HEAD"
1736 lineA
.Truncate(lineA
.Find(" -> "));
1738 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1739 if (lineA
[0] == '*')
1741 branch
= branch
.Mid(2);
1742 CString currentHead
;
1743 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1747 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1748 branch
= L
"refs/remotes/" + branch
;
1749 else if (CStringUtils::StartsWith(branch
, L
"remotes/"))
1750 branch
= L
"refs/" + branch
;
1752 branch
= L
"refs/heads/" + branch
;
1753 list
.push_back(branch
);
1760 CString cmd
= L
"git.exe tag --contains " + hash
.ToString();
1761 if (Run(cmd
, [&list
](CStringA lineA
)
1763 if (lineA
.IsEmpty())
1765 list
.push_back(L
"refs/tags/" + CUnicodeUtils::GetUnicode(lineA
));
1771 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1772 list
.erase(std::unique(list
.begin() + prevCount
, list
.end()), list
.end());
1777 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1779 size_t prevCount
= list
.size();
1780 if (this->m_IsUseLibGit2
)
1782 CAutoRepository
repo(GetGitRepository());
1786 CAutoStrArray remotes
;
1787 if (git_remote_list(remotes
, repo
))
1790 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1792 CStringA
remote(remotes
->strings
[i
]);
1793 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1796 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1801 return Run(L
"git.exe remote", [&](const CStringA
& lineA
)
1803 if (lineA
.IsEmpty())
1805 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1809 int CGit::GetRemoteTags(const CString
& remote
, REF_VECTOR
& list
)
1811 size_t prevCount
= list
.size();
1812 if (UsingLibGit2(GIT_CMD_FETCH
))
1814 CAutoRepository
repo(GetGitRepository());
1818 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1819 CAutoRemote gitremote
;
1820 // first try with a named remote (e.g. "origin")
1821 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1823 // retry with repository located at a specific url
1824 if (git_remote_create_anonymous(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1828 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1829 callbacks
.credentials
= g_Git2CredCallback
;
1830 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1831 git_proxy_options proxy
= GIT_PROXY_OPTIONS_INIT
;
1832 proxy
.type
= GIT_PROXY_AUTO
;
1833 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
, &proxy
, nullptr) < 0)
1836 const git_remote_head
** heads
= nullptr;
1838 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1841 for (size_t i
= 0; i
< size
; i
++)
1843 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1845 if (!GetShortName(ref
, shortname
, L
"refs/tags/"))
1847 list
.emplace_back(TGitRef
{ shortname
, &heads
[i
]->oid
});
1849 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1854 cmd
.Format(L
"git.exe ls-remote -t \"%s\"", (LPCTSTR
)remote
);
1855 gitLastErr
= cmd
+ L
'\n';
1856 if (Run(cmd
, [&](CStringA lineA
)
1859 hash
.ConvertFromStrA(lineA
.Mid(0, GIT_HASH_SIZE
* 2));
1860 lineA
= lineA
.Mid(51); // sha1, tab + refs/tags/
1861 if (!lineA
.IsEmpty())
1862 list
.emplace_back(TGitRef
{ CUnicodeUtils::GetUnicode(lineA
), hash
});
1865 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1869 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1871 if (UsingLibGit2(GIT_CMD_PUSH
))
1873 CAutoRepository
repo(GetGitRepository());
1877 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1879 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1882 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1883 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1884 callbacks
.credentials
= g_Git2CredCallback
;
1885 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1886 std::vector
<CStringA
> refspecs
;
1887 for (const auto& ref
: list
)
1888 refspecs
.push_back(CUnicodeUtils::GetUTF8(L
":" + ref
));
1890 std::vector
<char*> vc
;
1891 vc
.reserve(refspecs
.size());
1892 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1893 git_strarray specs
= { vc
.data(), vc
.size() };
1895 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1900 CMassiveGitTaskBase
mgtPush(L
"push " + sRemote
, FALSE
);
1901 for (const auto& ref
: list
)
1902 mgtPush
.AddFile(L
':' + ref
);
1904 BOOL cancel
= FALSE
;
1905 mgtPush
.Execute(cancel
);
1911 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1913 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1914 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1918 int CGit::GetRefList(STRING_VECTOR
&list
)
1920 size_t prevCount
= list
.size();
1921 if (this->m_IsUseLibGit2
)
1923 CAutoRepository
repo(GetGitRepository());
1927 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1930 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1935 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
1937 int start
= lineA
.Find(L
' ');
1938 ASSERT(start
== 2 * GIT_HASH_SIZE
);
1942 CString name
= CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1));
1943 if (list
.empty() || name
!= *list
.crbegin() + L
"^{}")
1944 list
.push_back(name
);
1947 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1948 else if (ret
== 1 && IsInitRepos())
1953 typedef struct map_each_ref_payload
{
1954 git_repository
* repo
;
1955 MAP_HASH_NAME
* map
;
1956 } map_each_ref_payload
;
1958 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1960 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1962 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1964 CAutoObject gitObject
;
1965 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1966 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
1968 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1970 str
+= L
"^{}"; // deref tag
1971 CAutoObject derefedTag
;
1972 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1974 gitObject
.Swap(derefedTag
);
1977 (*payloadContent
->map
)[git_object_id(gitObject
)].push_back(str
);
1981 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1985 map_each_ref_payload payloadContent
= { repo
, &map
};
1987 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1990 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1992 std::sort(it
->second
.begin(), it
->second
.end());
1998 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
2000 if (this->m_IsUseLibGit2
)
2002 CAutoRepository
repo(GetGitRepository());
2006 return GetMapHashToFriendName(repo
, map
);
2009 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
2011 int start
= lineA
.Find(L
' ');
2012 ASSERT(start
== 2 * GIT_HASH_SIZE
);
2017 hash
.ConvertFromStrA(lineA
);
2018 map
[hash
].push_back(CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1)));
2021 if (ret
== 1 && IsInitRepos())
2026 int CGit::GuessRefForHash(CString
& ref
, const CGitHash
& hash
)
2029 if (GetMapHashToFriendName(map
))
2032 auto it
= map
.find(hash
);
2033 if (it
== map
.cend())
2035 ref
= hash
.ToString();
2039 const auto& reflist
= it
->second
;
2040 for (const auto& reftype
: { L
"refs/heads/", L
"refs/remotes/", L
"refs/tags/" })
2042 auto found
= std::find_if(reflist
.cbegin(), reflist
.cend(), [&reftype
](const auto& ref
) { return CStringUtils::StartsWith(ref
, reftype
); });
2043 if (found
== reflist
.cend())
2046 GetShortName(*found
, ref
, reftype
);
2050 ref
= hash
.ToString();
2054 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
2056 CAutoConfig
config(true);
2057 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, nullptr, FALSE
) < 0)
2059 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
2061 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
2062 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
2063 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .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
)
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 cmd
.Format(L
"git.exe diff-index --cached --raw %s --numstat -C%d%% -M%d%% -z --", (LPCTSTR
)head
, ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
);
3231 cmd
.Format(L
"git.exe diff-index --raw %s --numstat -C%d%% -M%d%% -z --", (LPCTSTR
)head
, ms_iSimilarityIndexThreshold
, ms_iSimilarityIndexThreshold
);
3233 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());
3236 if (Run(cmd
, &cmdout
, &cmdErr
))
3238 size_t last
= cmdErr
.RevertFind(0);
3240 if (last
!= BYTE_VECTOR::npos
)
3241 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)(cmdErr
.size() - last
) - 1);
3242 else if (!cmdErr
.empty())
3243 CGit::StringAppend(&str
, cmdErr
.data(), CP_UTF8
, (int)cmdErr
.size() - 1);
3245 str
.Format(L
"\"%s\" exited with an error code, but did not output any error message", (LPCTSTR
)cmd
);
3246 MessageBox(nullptr, str
, L
"TortoiseGit", MB_OK
| MB_ICONERROR
);
3249 out
.append(cmdout
, 0);
3251 result
.ParserFromLog(out
);
3253 std::map
<CString
, int> duplicateMap
;
3254 for (int i
= 0; i
< result
.GetCount(); ++i
)
3255 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), i
));
3257 // handle delete conflict case, when remote : modified, local : deleted.
3258 for (int i
= 0; i
< count
; ++i
)
3264 cmd
= L
"git.exe ls-files -u -t -z";
3266 cmd
.Format(L
"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3270 CTGitPathList conflictlist
;
3271 conflictlist
.ParserFromLog(cmdout
);
3272 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3274 auto existing
= duplicateMap
.find(conflictlist
[j
].GetGitPathString());
3275 if (existing
!= duplicateMap
.end())
3277 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3278 p
.m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3282 result
.AddPath(conflictlist
[j
]);
3283 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3288 // handle source files of file renames/moves (issue #860)
3289 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3290 for (int i
= 0; i
< count
; ++i
)
3296 cmd
= L
"git.exe ls-files -d -z";
3298 cmd
.Format(L
"git.exe ls-files -d -z -- \"%s\"", (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3302 CTGitPathList deletelist
;
3303 deletelist
.ParserFromLog(cmdout
, true);
3304 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3306 auto existing
= duplicateMap
.find(deletelist
[j
].GetGitPathString());
3307 if (existing
== duplicateMap
.end())
3309 result
.AddPath(deletelist
[j
]);
3310 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3314 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3315 p
.m_Action
|= CTGitPath::LOGACTIONS_MISSING
;
3323 int CGit::IsRebaseRunning()
3326 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3329 if (PathIsDirectory(adminDir
+ L
"rebase-apply") || PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3334 void CGit::GetBisectTerms(CString
* good
, CString
* bad
)
3336 static CString lastGood
;
3337 static CString lastBad
;
3338 static ULONGLONG lastRead
= 0;
3348 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3349 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3350 // as we only read a small file the performance effects should be negligible
3351 if (lastRead
+ 5000 > GetTickCount64())
3359 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir
, adminDir
))
3362 CString termsFile
= adminDir
+ L
"BISECT_TERMS";
3364 _wfopen_s(fp
.GetPointer(), termsFile
, L
"rb");
3367 char badA
[MAX_PATH
] = { 0 };
3368 fgets(badA
, sizeof(badA
), fp
);
3369 size_t len
= strlen(badA
);
3370 if (len
> 0 && badA
[len
- 1] == '\n')
3371 badA
[len
- 1] = '\0';
3372 char goodA
[MAX_PATH
] = { 0 };
3373 fgets(goodA
, sizeof(goodA
), fp
);
3374 len
= strlen(goodA
);
3375 if (len
> 0 && goodA
[len
- 1] == '\n')
3376 goodA
[len
- 1] = '\0';
3377 lastGood
= CUnicodeUtils::GetUnicode(goodA
);
3378 lastBad
= CUnicodeUtils::GetUnicode(badA
);
3379 lastRead
= GetTickCount64();
3382 int CGit::GetGitVersion(CString
* versiondebug
, CString
* errStr
)
3384 CString version
, err
;
3385 if (Run(L
"git.exe --version", &version
, &err
, CP_UTF8
))
3394 *versiondebug
= version
;
3399 CString str
= version
.Tokenize(L
".", start
);
3400 int space
= str
.ReverseFind(L
' ');
3401 str
= str
.Mid(space
+ 1, start
);
3405 version
= version
.Mid(start
);
3408 str
= version
.Tokenize(L
".", start
);
3409 ver
|= (_wtol(str
) & 0xFF) << 16;
3411 str
= version
.Tokenize(L
".", start
);
3412 ver
|= (_wtol(str
) & 0xFF) << 8;
3414 str
= version
.Tokenize(L
".", start
);
3415 ver
|= (_wtol(str
) & 0xFF);
3426 int CGit::GetGitNotes(const CGitHash
& hash
, CString
& notes
)
3428 CAutoRepository
repo(GetGitRepository());
3433 int ret
= git_note_read(note
.GetPointer(), repo
, nullptr, hash
);
3434 if (ret
== GIT_ENOTFOUND
)
3441 notes
= CUnicodeUtils::GetUnicode(git_note_message(note
));
3445 int CGit::SetGitNotes(const CGitHash
& hash
, const CString
& notes
)
3447 CAutoRepository
repo(GetGitRepository());
3451 CAutoSignature signature
;
3452 if (git_signature_default(signature
.GetPointer(), repo
) < 0)
3456 if (git_note_create(&oid
, repo
, nullptr, signature
, signature
, hash
, CUnicodeUtils::GetUTF8(notes
), 1) < 0)