1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "GitForWindows.h"
24 #include "UnicodeUtils.h"
28 #include "FormatMessageWrapper.h"
29 #include "SmartHandle.h"
30 #include "MassiveGitTaskBase.h"
31 #include "git2/sys/filter.h"
32 #include "git2/sys/transport.h"
33 #include "../libgit2/filter-filter.h"
34 #include "../libgit2/ssh-wintunnel.h"
36 bool CGit::ms_bCygwinGit
= (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE
) == TRUE
);
37 bool CGit::ms_bMsys2Git
= (CRegDWORD(_T("Software\\TortoiseGit\\Msys2Hack"), FALSE
) == TRUE
);
38 int CGit::m_LogEncode
=CP_UTF8
;
39 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
41 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
43 if (!path
|| !buf
|| buflen
== 0)
46 const wchar_t* base
= path
;
47 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
49 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
52 *buf
= L
'\0'; /* reserved a byte via initial subtract */
54 while (*path
== term
|| *path
== L
';')
57 return (path
!= base
) ? path
: nullptr;
60 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
62 TCHAR buf
[MAX_PATH
] = { 0 };
64 // search in all paths defined in PATH
65 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != nullptr && *buf
)
67 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
69 // ensure trailing slash
70 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
71 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
73 const size_t len
= _tcslen(buf
);
75 if ((len
+ filename
.GetLength()) < MAX_PATH
)
76 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
80 if (PathFileExists(buf
))
91 static BOOL
FindGitPath()
94 _tgetenv_s(&size
, nullptr, 0, _T("PATH"));
98 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
101 _tgetenv_s(&size
, env
, size
, _T("PATH"));
103 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
104 if (!gitExeDirectory
.IsEmpty())
106 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
107 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
108 if (CGit::ms_LastMsysGitDir
.GetLength() > 12 && (CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw64\\bin")))
110 // prefer cmd directory as early Git for Windows 2.x releases only had this
111 CString installRoot
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd\\git.exe");
112 if (PathFileExists(installRoot
))
113 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd");
115 if (CGit::ms_LastMsysGitDir
.GetLength() > 4 && CGit::ms_LastMsysGitDir
.Right(4) == _T("\\cmd"))
117 // often the msysgit\cmd folder is on the %PATH%, but
118 // that git.exe does not work, so try to guess the bin folder
119 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
120 if (PathFileExists(binDir
))
121 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
129 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
131 CString filename
= executable
;
133 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
134 filename
+= _T(".exe");
136 if (PathFileExists(filename
))
139 filename
= FindFileOnPath(filename
, env
);
140 if (!filename
.IsEmpty())
146 static bool g_bSortLogical
;
147 static bool g_bSortLocalBranchesFirst
;
148 static bool g_bSortTagsReversed
;
149 static git_cred_acquire_cb g_Git2CredCallback
;
150 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
152 static void GetSortOptions()
154 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
156 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
157 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
158 if (g_bSortLocalBranchesFirst
)
159 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
160 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
161 if (!g_bSortTagsReversed
)
162 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
165 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
168 return StrCmpLogicalW(left
, right
) < 0;
169 return StrCmpI(left
, right
) < 0;
172 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
175 return StrCmpLogicalW(left
, right
) > 0;
176 return StrCmpI(left
, right
) > 0;
179 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
181 if (g_bSortLocalBranchesFirst
)
183 int leftIsRemote
= left
.Find(_T("remotes/"));
184 int rightIsRemote
= right
.Find(_T("remotes/"));
186 if (leftIsRemote
== 0 && rightIsRemote
< 0)
188 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
192 return StrCmpLogicalW(left
, right
) < 0;
193 return StrCmpI(left
, right
) < 0;
196 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
198 CString
CGit::ms_LastMsysGitDir
;
199 CString
CGit::ms_MsysGitRootDir
;
200 int CGit::ms_LastMsysGitVersion
= 0;
207 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
208 m_IsGitDllInited
= false;
210 m_GitSimpleListDiff
=0;
211 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
212 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
213 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
215 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
218 this->m_bInitialized
=false;
220 m_critGitDllSec
.Init();
221 m_critSecThreadMap
.Init();
228 git_close_diff(m_GitDiff
);
231 if(this->m_GitSimpleListDiff
)
233 git_close_diff(m_GitSimpleListDiff
);
234 m_GitSimpleListDiff
=0;
236 git_libgit2_shutdown();
237 m_critSecThreadMap
.Term();
238 m_critGitDllSec
.Term();
241 bool CGit::IsBranchNameValid(const CString
& branchname
)
243 if (branchname
.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
245 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
247 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
248 return !!git_reference_is_valid_name(branchA
);
251 static bool IsPowerShell(CString cmd
)
254 int powerShellPos
= cmd
.Find(_T("powershell"));
255 if (powerShellPos
< 0)
258 // found the word powershell, check that it is the command and not any parameter
259 int end
= cmd
.GetLength();
260 if (end
> 0 && cmd
[0] == L
'"')
262 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
263 if (secondDoubleQuote
> 0)
264 end
= secondDoubleQuote
;
268 int firstSpace
= cmd
.Find(_T(' '));
273 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
276 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
278 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
279 CAutoFile hStdioFile
;
281 SECURITY_ATTRIBUTES sa
= { 0 };
282 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
283 sa
.bInheritHandle
=TRUE
;
284 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
286 CString err
= CFormatMessageWrapper();
287 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
288 return TGIT_GIT_ERROR_OPEN_PIP
;
290 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
292 CString err
= CFormatMessageWrapper();
293 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
294 return TGIT_GIT_ERROR_OPEN_PIP
;
298 hStdioFile
= CreateFile(*StdioFile
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &sa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
300 STARTUPINFO si
= { 0 };
301 PROCESS_INFORMATION pi
= { 0 };
302 si
.cb
=sizeof(STARTUPINFO
);
305 si
.hStdError
= hWriteErr
;
307 si
.hStdError
= hWrite
;
309 si
.hStdOutput
=hStdioFile
;
311 si
.hStdOutput
=hWrite
;
313 si
.wShowWindow
=SW_HIDE
;
314 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
316 LPTSTR pEnv
= m_Environment
;
317 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
319 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
321 // CREATE_NEW_CONSOLE makes git (but not ssh.exe, see issue #2257) recognize that it has no console in order to launch askpass to ask for the password,
322 // DETACHED_PROCESS which was originally used here has the same effect (but works with git.exe AND ssh.exe), however, it prevents PowerShell from working (cf. issue #2143)
323 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
324 if (IsPowerShell(cmd
))
325 dwFlags
|= CREATE_NEW_CONSOLE
;
327 dwFlags
|= DETACHED_PROCESS
;
329 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
331 bool startsWithGit
= CStringUtils::StartsWith(cmd
, L
"git");
332 if (ms_bMsys2Git
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
334 cmd
.Replace(_T("\\"), _T("\\\\\\\\"));
335 cmd
.Replace(_T("\""), _T("\\\""));
336 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/usr/bin/") + cmd
+ _T('"');
338 else if (ms_bCygwinGit
&& startsWithGit
&& !CStringUtils::StartsWith(cmd
, L
"git.exe config "))
340 cmd
.Replace(_T('\\'), _T('/'));
341 cmd
.Replace(_T("\""), _T("\\\""));
342 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
344 else if (startsWithGit
|| CStringUtils::StartsWith(cmd
, L
"bash"))
346 int firstSpace
= cmd
.Find(_T(" "));
348 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
350 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
353 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
354 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
356 CString err
= CFormatMessageWrapper();
357 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), (LPCTSTR
)err
.Trim());
358 return TGIT_GIT_ERROR_CREATE_PROCESS
;
366 *hReadOut
= hRead
.Detach();
368 *hErrReadOut
= hReadErr
.Detach();
371 //Must use sperate function to convert ANSI str to union code string
372 //Becuase A2W use stack as internal convert buffer.
373 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
380 len
= (int)strlen((const char*)p
);
385 int currentContentLen
= str
->GetLength();
386 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
387 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
388 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
391 // This method was originally used to check for orphaned branches
392 BOOL
CGit::CanParseRev(CString ref
)
398 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
406 // Checks if we have an orphaned HEAD
407 BOOL
CGit::IsInitRepos()
410 if (GetHash(hash
, _T("HEAD")) != 0)
412 return hash
.IsEmpty() ? TRUE
: FALSE
;
415 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
417 PASYNCREADSTDERRTHREADARGS pDataArray
;
418 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
421 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
422 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
424 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
432 void CGit::KillRelatedThreads(CWinThread
* thread
)
434 CAutoLocker
lock(m_critSecThreadMap
);
435 auto it
= m_AsyncReadStdErrThreadMap
.find(thread
->m_nThreadID
);
436 if (it
!= m_AsyncReadStdErrThreadMap
.cend())
438 TerminateThread(it
->second
, (DWORD
)-1);
439 m_AsyncReadStdErrThreadMap
.erase(it
);
441 TerminateThread(thread
->m_hThread
, (DWORD
)-1);
445 int CGit::Run(CGitCall
* pcall
)
447 PROCESS_INFORMATION pi
;
448 CAutoGeneralHandle hRead
, hReadErr
;
449 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
450 return TGIT_GIT_ERROR_CREATE_PROCESS
;
452 CAutoGeneralHandle
piThread(pi
.hThread
);
453 CAutoGeneralHandle
piProcess(pi
.hProcess
);
455 ASYNCREADSTDERRTHREADARGS threadArguments
;
456 threadArguments
.fileHandle
= hReadErr
;
457 threadArguments
.pcall
= pcall
;
458 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
462 CAutoLocker
lock(m_critSecThreadMap
);
463 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
467 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
469 while (ReadFile(hRead
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, nullptr))
471 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
472 if(!bAborted
)//For now, flush output when command aborted.
473 if(pcall
->OnOutputData(data
,readnumber
))
481 WaitForSingleObject(thread
, INFINITE
);
483 CAutoLocker
lock(m_critSecThreadMap
);
484 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
487 WaitForSingleObject(pi
.hProcess
, INFINITE
);
490 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
492 CString err
= CFormatMessageWrapper();
493 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
494 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
497 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
501 class CGitCall_ByteVector
: public CGitCall
504 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= nullptr) : CGitCall(cmd
),m_pvector(pvector
), m_pvectorErr(pvectorErr
) {}
505 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
507 if (!m_pvector
|| size
== 0)
509 size_t oldsize
=m_pvector
->size();
510 m_pvector
->resize(m_pvector
->size()+size
);
511 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
514 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
516 if (!m_pvectorErr
|| size
== 0)
518 size_t oldsize
= m_pvectorErr
->size();
519 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
520 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
523 BYTE_VECTOR
* m_pvector
;
524 BYTE_VECTOR
* m_pvectorErr
;
526 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
528 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
531 int CGit::Run(CString cmd
, CString
* output
, int code
)
535 ret
= Run(cmd
, output
, &err
, code
);
537 if (output
&& !err
.IsEmpty())
539 if (!output
->IsEmpty())
546 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
548 BYTE_VECTOR vector
, vectorErr
;
551 ret
= Run(cmd
, &vector
, &vectorErr
);
553 ret
= Run(cmd
, &vector
);
556 StringAppend(output
, &(vector
[0]), code
);
560 vectorErr
.push_back(0);
561 StringAppend(outputErr
, &(vectorErr
[0]), code
);
567 class CGitCallCb
: public CGitCall
570 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
, BYTE_VECTOR
* pvectorErr
= nullptr)
573 , m_pvectorErr(pvectorErr
)
576 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
581 int oldEndPos
= m_buffer
.GetLength();
582 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
583 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
585 // Break into lines and feed to m_recv
587 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
589 m_recv(m_buffer
.Left(eolPos
));
590 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
595 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
) override
597 if (!m_pvectorErr
|| size
== 0)
599 size_t oldsize
= m_pvectorErr
->size();
600 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
601 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
605 virtual void OnEnd() override
607 if (!m_buffer
.IsEmpty())
609 m_buffer
.Empty(); // Just for sure
613 GitReceiverFunc m_recv
;
615 BYTE_VECTOR
* m_pvectorErr
;
618 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
, CString
* outputErr
)
622 BYTE_VECTOR vectorErr
;
623 CGitCallCb
call(cmd
, recv
, &vectorErr
);
624 int ret
= Run(&call
);
625 vectorErr
.push_back(0);
626 StringAppend(outputErr
, &(vectorErr
[0]));
630 CGitCallCb
call(cmd
, recv
);
634 CString
CGit::GetUserName(void)
637 env
.CopyProcessEnvironment();
638 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
639 if (!envname
.IsEmpty())
641 return GetConfigValue(L
"user.name");
643 CString
CGit::GetUserEmail(void)
646 env
.CopyProcessEnvironment();
647 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
648 if (!envmail
.IsEmpty())
651 return GetConfigValue(L
"user.email");
654 CString
CGit::GetConfigValue(const CString
& name
, const CString
& def
, bool wantBool
)
657 if(this->m_IsUseGitDLL
)
659 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
668 key
= CUnicodeUtils::GetUTF8(name
);
672 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
675 catch (const char *msg
)
677 ::MessageBox(nullptr, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
681 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
687 cmd
.Format(L
"git.exe config%s %s", wantBool
? _T(" --bool") : _T(""), (LPCTSTR
)name
);
688 if (Run(cmd
, &configValue
, nullptr, CP_UTF8
))
690 if (configValue
.IsEmpty())
692 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
696 bool CGit::GetConfigValueBool(const CString
& name
, const bool def
)
698 CString configValue
= GetConfigValue(name
, def
? _T("true") : _T("false"), true);
699 configValue
.MakeLower();
701 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
707 int CGit::GetConfigValueInt32(const CString
& name
, const int def
)
709 CString configValue
= GetConfigValue(name
);
711 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
716 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
718 if(this->m_IsUseGitDLL
)
720 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
728 CStringA keya
, valuea
;
729 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
730 valuea
= CUnicodeUtils::GetUTF8(value
);
734 return [=]() { return get_set_config(keya
, valuea
, type
); }();
736 catch (const char *msg
)
738 ::MessageBox(nullptr, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
749 option
= _T("--global");
752 option
= _T("--system");
757 CString mangledValue
= value
;
758 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
759 mangledValue
.Replace(_T("\""), _T("\\\""));
760 cmd
.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
762 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
768 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
770 if(this->m_IsUseGitDLL
)
772 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
781 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
785 return [=]() { return get_set_config(keya
, nullptr, type
); }();
787 catch (const char *msg
)
789 ::MessageBox(nullptr, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
800 option
= _T("--global");
803 option
= _T("--system");
808 cmd
.Format(_T("git.exe config %s --unset %s"), (LPCTSTR
)option
, (LPCTSTR
)key
);
810 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
816 CString
CGit::GetCurrentBranch(bool fallback
)
819 //Run(_T("git.exe branch"),&branch);
821 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
822 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
823 return _T("(no branch)");
828 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
830 if (localBranch
.IsEmpty())
834 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
835 pullRemote
= GetConfigValue(configName
);
837 //Select pull-branch from current branch
838 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
839 pullBranch
= StripRefName(GetConfigValue(configName
));
842 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
845 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
847 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
850 void CGit::GetRemotePushBranch(const CString
& localBranch
, CString
& pushRemote
, CString
& pushBranch
)
852 if (localBranch
.IsEmpty())
857 configName
.Format(L
"branch.%s.pushremote", (LPCTSTR
)localBranch
);
858 pushRemote
= g_Git
.GetConfigValue(configName
);
859 if (pushRemote
.IsEmpty())
861 pushRemote
= g_Git
.GetConfigValue(L
"remote.pushdefault");
862 if (pushRemote
.IsEmpty())
864 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
865 pushRemote
= g_Git
.GetConfigValue(configName
);
869 configName
.Format(L
"branch.%s.pushbranch", (LPCTSTR
)localBranch
);
870 pushBranch
= g_Git
.GetConfigValue(configName
); // do not strip branch name (for gerrit), see issue #1609)
871 if (pushBranch
.IsEmpty())
873 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
874 pushBranch
= CGit::StripRefName(g_Git
.GetConfigValue(configName
));
878 CString
CGit::GetFullRefName(const CString
& shortRefName
)
882 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
883 if (Run(cmd
, &refName
, nullptr, CP_UTF8
) != 0)
884 return CString();//Error
885 return refName
.TrimRight();
888 CString
CGit::StripRefName(CString refName
)
890 if (CStringUtils::StartsWith(refName
, L
"refs/heads/"))
891 refName
= refName
.Mid(11);
892 else if (CStringUtils::StartsWith(refName
, L
"refs/"))
893 refName
= refName
.Mid(5);
894 return refName
.TrimRight();
897 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
899 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
901 if ( sProjectRoot
.IsEmpty() )
905 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
908 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
910 CAutoFILE pFile
= _tfsopen(sHeadFile
.GetString(), _T("r"), SH_DENYWR
);
915 fgets(s
, sizeof(s
), pFile
);
917 const char *pfx
= "ref: refs/heads/";
918 const int len
= 16;//strlen(pfx)
920 if ( !strncmp(s
, pfx
, len
) )
922 //# We're on a branch. It might not exist. But
923 //# HEAD looks good enough to be a branch.
924 CStringA
utf8Branch(s
+ len
);
925 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
926 sBranchOut
.TrimRight(_T(" \r\n\t"));
928 if ( sBranchOut
.IsEmpty() )
933 CStringA
utf8Hash(s
);
934 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
935 unicodeHash
.TrimRight(_T(" \r\n\t"));
936 if (CGitHash::IsValidSHA1(unicodeHash
))
937 sBranchOut
= unicodeHash
;
939 //# Assume this is a detached head.
940 sBranchOut
= _T("HEAD");
945 //# Assume this is a detached head.
954 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
957 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
961 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
963 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
965 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
967 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
969 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
971 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
973 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
977 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
979 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
981 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
986 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
992 CString
CGit::GetLogCmd(const CString
& range
, const CTGitPath
* path
, int mask
, CFilterData
* Filter
, int logOrderBy
)
996 if(mask
& LOG_INFO_STAT
)
997 param
+= _T(" --numstat");
998 if(mask
& LOG_INFO_FILESTATE
)
999 param
+= _T(" --raw");
1001 if(mask
& LOG_INFO_FULLHISTORY
)
1002 param
+= _T(" --full-history");
1004 if(mask
& LOG_INFO_BOUNDARY
)
1005 param
+= _T(" --left-right --boundary");
1007 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
1008 param
+= _T(" --all");
1010 if (mask
& CGit::LOG_INFO_BASIC_REFS
)
1012 param
+= _T(" --branches");
1013 param
+= _T(" --tags");
1014 param
+= _T(" --remotes");
1015 param
+= _T(" --glob=stas[h]"); // require at least one glob operator
1016 param
+= _T(" --glob=bisect");
1019 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
1020 param
+= _T(" --branches");
1022 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
1025 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
1028 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
1029 param
+= _T(" --first-parent");
1031 if(mask
& CGit::LOG_INFO_NO_MERGE
)
1032 param
+= _T(" --no-merges");
1034 if(mask
& CGit::LOG_INFO_FOLLOW
)
1035 param
+= _T(" --follow");
1037 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
1040 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
1041 param
+= _T(" --full-diff");
1043 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
1044 param
+= _T(" --simplify-by-decoration");
1048 if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_N_YEARS
)
1050 CTime now
= CTime::GetCurrentTime();
1051 CTime time
= CTime(now
.GetYear(), now
.GetMonth(), now
.GetDay(), 0, 0, 0);
1052 __time64_t substract
= 86400;
1054 switch (Filter
->m_NumberOfLogsScale
)
1056 case CFilterData::SHOW_LAST_N_YEARS
:
1059 case CFilterData::SHOW_LAST_N_MONTHS
:
1062 case CFilterData::SHOW_LAST_N_WEEKS
:
1066 Filter
->m_From
= (DWORD
)time
.GetTime() - (Filter
->m_NumberOfLogs
* substract
);
1068 if (Filter
->m_NumberOfLogsScale
== CFilterData::SHOW_LAST_N_COMMITS
)
1069 param
.AppendFormat(L
" -n%ld", Filter
->m_NumberOfLogs
);
1070 else if (Filter
->m_NumberOfLogsScale
>= CFilterData::SHOW_LAST_SEL_DATE
&& Filter
->m_From
> 0)
1071 param
.AppendFormat(L
" --max-age=%I64u", Filter
->m_From
);
1074 if( Filter
&& (Filter
->m_To
!= -1))
1075 param
.AppendFormat(L
" --min-age=%I64u", Filter
->m_To
);
1077 bool isgrep
= false;
1078 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1080 param
.AppendFormat(L
" --author=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1084 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1086 param
.AppendFormat(L
" --committer=\"%s\"", (LPCTSTR
)Filter
->m_Author
);
1090 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1092 param
.AppendFormat(L
" --grep=\"%s\"", (LPCTSTR
)Filter
->m_MessageFilter
);
1096 if(Filter
&& isgrep
)
1098 if(!Filter
->m_IsRegex
)
1099 param
+= _T(" --fixed-strings");
1101 param
+= _T(" --regexp-ignore-case --extended-regexp");
1104 if (logOrderBy
== LOG_ORDER_TOPOORDER
|| (mask
& CGit::LOG_ORDER_TOPOORDER
))
1105 param
+= _T(" --topo-order");
1106 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1107 param
+= _T(" --date-order");
1112 file
.Format(_T(" \"%s\""), (LPCTSTR
)path
->GetGitPathString());
1113 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1114 cmd
.Format(_T("--ignore-this-parameter -z%s %s --parents --%s"), (LPCTSTR
)param
, (LPCTSTR
)range
, (LPCTSTR
)file
);
1119 void GetTempPath(CString
&path
)
1121 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1123 DWORD dwBufSize
=BUFSIZE
;
1124 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1125 lpPathBuffer
); // buffer for path
1126 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1128 path
.Format(_T("%s"),lpPathBuffer
);
1130 CString
GetTempFile()
1132 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1134 DWORD dwBufSize
=BUFSIZE
;
1135 TCHAR szTempName
[BUFSIZE
] = { 0 };
1138 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1139 lpPathBuffer
); // buffer for path
1140 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1142 // Create a temporary file.
1143 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1144 TEXT("Patch"), // temp file name prefix
1145 0, // create unique name
1146 szTempName
); // buffer for name
1151 return CString(szTempName
);
1154 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1156 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1157 if (result
== 0) return 0;
1158 if (!lpBuffer
|| (result
+ 13 > nBufferLength
))
1165 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1166 CreateDirectory(lpBuffer
, nullptr);
1171 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1174 PROCESS_INFORMATION pi
;
1175 si
.cb
=sizeof(STARTUPINFO
);
1176 GetStartupInfo(&si
);
1178 SECURITY_ATTRIBUTES psa
= {sizeof(psa
), nullptr, TRUE
};
1179 psa
.bInheritHandle
=TRUE
;
1181 CAutoGeneralHandle hReadErr
, hWriteErr
;
1182 if (!CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &psa
, 0))
1184 CString err
= CFormatMessageWrapper();
1185 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
1186 return TGIT_GIT_ERROR_OPEN_PIP
;
1189 CAutoFile houtfile
= CreateFile(filename
, GENERIC_WRITE
, FILE_SHARE_READ
| FILE_SHARE_WRITE
, &psa
, CREATE_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, nullptr);
1192 CString err
= CFormatMessageWrapper();
1193 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
1194 return TGIT_GIT_ERROR_OPEN_PIP
;
1197 si
.wShowWindow
= SW_HIDE
;
1198 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1199 si
.hStdOutput
= houtfile
;
1200 si
.hStdError
= hWriteErr
;
1202 LPTSTR pEnv
= m_Environment
;
1203 DWORD dwFlags
= CREATE_UNICODE_ENVIRONMENT
;
1205 if (CStringUtils::StartsWith(cmd
, L
"git"))
1207 int firstSpace
= cmd
.Find(L
' ');
1209 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\" + cmd
.Left(firstSpace
) + L
'"' + cmd
.Mid(firstSpace
);
1211 cmd
= L
'"' + CGit::ms_LastMsysGitDir
+ L
"\\" + cmd
+ L
'"';
1214 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
1215 if (!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
1217 CString err
= CFormatMessageWrapper();
1218 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), (LPCTSTR
)err
.Trim());
1220 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1223 CAutoGeneralHandle
piThread(pi
.hThread
);
1224 CAutoGeneralHandle
piProcess(pi
.hProcess
);
1226 BYTE_VECTOR stderrVector
;
1227 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1228 ASYNCREADSTDERRTHREADARGS threadArguments
;
1229 threadArguments
.fileHandle
= hReadErr
;
1230 threadArguments
.pcall
= &pcall
;
1231 CAutoGeneralHandle thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1235 CAutoLocker
lock(m_critSecThreadMap
);
1236 m_AsyncReadStdErrThreadMap
[GetCurrentThreadId()] = thread
;
1239 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1241 hWriteErr
.CloseHandle();
1242 hReadErr
.CloseHandle();
1246 WaitForSingleObject(thread
, INFINITE
);
1248 CAutoLocker
lock(m_critSecThreadMap
);
1249 m_AsyncReadStdErrThreadMap
.erase(GetCurrentThreadId());
1252 stderrVector
.push_back(0);
1253 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1256 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1258 CString err
= CFormatMessageWrapper();
1259 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
1260 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1263 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1268 CAutoRepository
CGit::GetGitRepository() const
1270 return CAutoRepository(GetGitPathStringA(m_CurrentDir
));
1273 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1277 // no need to parse a ref if it's already a 40-byte hash
1278 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1280 hash
= CGitHash(friendname
);
1284 int isHeadOrphan
= git_repository_head_unborn(repo
);
1285 if (isHeadOrphan
!= 0)
1288 if (isHeadOrphan
== 1)
1294 CAutoObject gitObject
;
1295 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1298 const git_oid
* oid
= git_object_id(gitObject
);
1302 hash
= CGitHash((char *)oid
->id
);
1307 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1309 // no need to parse a ref if it's already a 40-byte hash
1310 if (CGitHash::IsValidSHA1(friendname
))
1312 hash
= CGitHash(friendname
);
1318 CAutoRepository
repo(GetGitRepository());
1322 return GetHash(repo
, hash
, friendname
, true);
1326 CString branch
= FixBranchName(friendname
);
1327 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1328 branch
= friendname
;
1330 cmd
.Format(_T("git.exe rev-parse %s"), (LPCTSTR
)branch
);
1332 int ret
= Run(cmd
, &gitLastErr
, nullptr, CP_UTF8
);
1333 hash
= CGitHash(gitLastErr
.Trim());
1336 else if (friendname
== _T("HEAD")) // special check for unborn branch
1338 CString currentbranch
;
1339 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1348 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1353 cmd
=_T("git.exe ls-files -s -t -z");
1355 if (Run(cmd
, &cmdout
))
1358 if (outputlist
.ParserFromLsFile(cmdout
))
1360 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1361 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1365 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1369 if (ignoreSpaceAtEol
)
1370 ignore
+= _T(" --ignore-space-at-eol");
1371 if (ignoreSpaceChange
)
1372 ignore
+= _T(" --ignore-space-change");
1374 ignore
+= _T(" --ignore-all-space");
1375 if (ignoreBlankLines
)
1376 ignore
+= _T(" --ignore-blank-lines");
1378 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1381 if(rev1
== GIT_REV_ZERO
)
1382 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1384 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev1
);
1387 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
, (LPCTSTR
)rev1
);
1393 return outputlist
.ParserFromLog(out
);
1396 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1398 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1399 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1403 int CGit::GetTagList(STRING_VECTOR
&list
)
1405 size_t prevCount
= list
.size();
1406 if (this->m_IsUseLibGit2
)
1408 CAutoRepository
repo(GetGitRepository());
1412 CAutoStrArray tag_names
;
1414 if (git_tag_list(tag_names
, repo
))
1417 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1419 CStringA
tagName(tag_names
->strings
[i
]);
1420 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1423 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1429 int ret
= Run(L
"git.exe tag -l", [&](const CStringA
& lineA
)
1431 if (lineA
.IsEmpty())
1433 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1436 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1437 else if (ret
== 1 && IsInitRepos())
1443 CString
CGit::GetGitLastErr(const CString
& msg
)
1445 if (this->m_IsUseLibGit2
)
1446 return GetLibGit2LastErr(msg
);
1447 else if (gitLastErr
.IsEmpty())
1448 return msg
+ _T("\nUnknown git.exe error.");
1451 CString lastError
= gitLastErr
;
1453 return msg
+ _T("\n") + lastError
;
1457 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1459 if (UsingLibGit2(cmd
))
1460 return GetLibGit2LastErr(msg
);
1461 else if (gitLastErr
.IsEmpty())
1462 return msg
+ _T("\nUnknown git.exe error.");
1465 CString lastError
= gitLastErr
;
1467 return msg
+ _T("\n") + lastError
;
1471 CString
CGit::GetLibGit2LastErr()
1473 const git_error
*libgit2err
= giterr_last();
1476 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1478 return _T("libgit2 returned: ") + lastError
;
1481 return _T("An error occoured in libgit2, but no message is available.");
1484 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1487 return msg
+ _T("\n") + GetLibGit2LastErr();
1488 return GetLibGit2LastErr();
1491 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1493 if(branchName
== "FETCH_HEAD")
1494 branchName
= DerefFetchHead();
1498 CString
CGit::FixBranchName(const CString
& branchName
)
1500 CString tempBranchName
= branchName
;
1501 FixBranchName_Mod(tempBranchName
);
1502 return tempBranchName
;
1505 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1509 CAutoRepository
repo(GetGitRepository());
1511 return true; // TODO: optimize error reporting
1513 CAutoReference tagRef
;
1514 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1517 CAutoReference branchRef
;
1518 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1525 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR
)name
, (LPCTSTR
)name
);
1528 Run(cmd
, [&](const CStringA
& lineA
)
1530 if (lineA
.IsEmpty())
1535 return (refCnt
<= 1);
1538 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1542 CAutoRepository
repo(GetGitRepository());
1544 return false; // TODO: optimize error reporting
1548 prefix
= _T("refs/heads/");
1550 prefix
= _T("refs/tags/");
1553 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1559 CString cmd
, output
;
1561 cmd
= _T("git.exe show-ref ");
1563 cmd
+= _T("--heads ");
1565 cmd
+= _T("--tags ");
1567 cmd
+= _T("refs/heads/") + name
;
1568 cmd
+= _T(" refs/tags/") + name
;
1570 int ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1573 if (!output
.IsEmpty())
1580 CString
CGit::DerefFetchHead()
1583 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1584 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1585 int forMergeLineCount
= 0;
1587 std::string hashToReturn
;
1588 while(getline(fetchHeadFile
, line
))
1590 //Tokenize this line
1591 std::string::size_type prevPos
= 0;
1592 std::string::size_type pos
= line
.find('\t');
1593 if(pos
== std::string::npos
) continue; //invalid line
1595 std::string hash
= line
.substr(0, pos
);
1596 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1598 bool forMerge
= pos
== prevPos
;
1599 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1601 //std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1606 hashToReturn
= hash
;
1607 ++forMergeLineCount
;
1608 if(forMergeLineCount
> 1)
1609 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1613 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1616 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1618 size_t prevCount
= list
.size();
1621 bool headIsDetached
= false;
1624 CAutoRepository
repo(GetGitRepository());
1628 if (git_repository_head_detached(repo
) == 1)
1629 headIsDetached
= true;
1631 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1633 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1634 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1635 flags
= GIT_BRANCH_ALL
;
1636 else if (type
& BRANCH_REMOTE
)
1637 flags
= GIT_BRANCH_REMOTE
;
1639 CAutoBranchIterator it
;
1640 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1643 git_reference
* ref
= nullptr;
1644 git_branch_t branchType
;
1645 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1647 CAutoReference
autoRef(ref
);
1648 const char * name
= nullptr;
1649 if (git_branch_name(&name
, ref
))
1652 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1653 if (branchType
& GIT_BRANCH_REMOTE
)
1654 list
.push_back(_T("remotes/") + branchname
);
1657 if (git_branch_is_head(ref
))
1659 list
.push_back(branchname
);
1666 CString cmd
= L
"git.exe branch --no-color";
1668 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1670 else if (type
& BRANCH_REMOTE
)
1673 ret
= Run(cmd
, [&](CStringA lineA
)
1675 lineA
.Trim(" \r\n\t");
1676 if (lineA
.IsEmpty())
1678 if (lineA
.Find(" -> ") >= 0)
1679 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1681 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1682 if (lineA
[0] == '*')
1684 branch
= branch
.Mid(2);
1687 // check whether HEAD is detached
1688 CString currentHead
;
1689 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1691 headIsDetached
= true;
1695 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1696 branch
= L
"remotes/" + branch
;
1697 list
.push_back(branch
);
1699 if (ret
== 1 && IsInitRepos())
1703 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1704 list
.push_back(L
"FETCH_HEAD");
1706 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1708 if (current
&& !headIsDetached
)
1710 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1723 int CGit::GetRefsCommitIsOn(STRING_VECTOR
& list
, const CGitHash
& hash
, bool includeTags
, bool includeBranches
, BRANCH_TYPE type
)
1725 if (!includeTags
&& !includeBranches
|| hash
.IsEmpty())
1728 size_t prevCount
= list
.size();
1731 CAutoRepository
repo(GetGitRepository());
1735 CAutoReferenceIterator it
;
1736 if (git_reference_iterator_new(it
.GetPointer(), repo
))
1739 auto checkDescendent
= [&list
, &hash
, &repo
](const git_oid
* oid
, const git_reference
* ref
) {
1740 if (git_oid_equal(oid
, (const git_oid
*)hash
.m_hash
) || git_graph_descendant_of(repo
, oid
, (const git_oid
*)hash
.m_hash
) == 1)
1742 const char* name
= git_reference_name(ref
);
1746 list
.push_back(CUnicodeUtils::GetUnicode(name
));
1751 while (git_reference_next(ref
.GetPointer(), it
) == 0)
1753 const git_oid
* oid
= git_reference_target(ref
);
1754 if (git_reference_is_tag(ref
))
1760 if (git_tag_lookup(tag
.GetPointer(), repo
, oid
) == 0)
1763 git_tag_peel(obj
.GetPointer(), tag
);
1764 checkDescendent(git_object_id(obj
), ref
);
1768 else if (git_reference_is_remote(ref
))
1770 if (!includeBranches
|| !(type
& BRANCH_REMOTE
))
1773 else if (git_reference_is_branch(ref
))
1775 if (!includeBranches
|| !(type
& GIT_BRANCH_LOCAL
))
1781 checkDescendent(oid
, ref
);
1786 if (includeBranches
)
1788 CString cmd
= L
"git.exe branch --no-color";
1789 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1791 else if (type
& BRANCH_REMOTE
)
1793 cmd
+= L
" --contains " + hash
.ToString();
1795 if (Run(cmd
, [&](CStringA lineA
)
1797 lineA
.Trim(" \r\n\t");
1798 if (lineA
.IsEmpty())
1800 if (lineA
.Find(" -> ") >= 0)
1801 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1803 CString branch
= CUnicodeUtils::GetUnicode(lineA
);
1804 if (lineA
[0] == '*')
1806 branch
= branch
.Mid(2);
1807 CString currentHead
;
1808 if (branch
[0] == L
'(' && GetCurrentBranchFromFile(m_CurrentDir
, currentHead
) == 1)
1812 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1813 branch
= L
"refs/remotes/" + branch
;
1814 else if (CStringUtils::StartsWith(branch
, L
"remotes/"))
1815 branch
= L
"refs/" + branch
;
1817 branch
= L
"refs/heads/" + branch
;
1818 list
.push_back(branch
);
1825 CString cmd
= L
"git.exe tag --contains " + hash
.ToString();
1826 if (Run(cmd
, [&list
](CStringA lineA
)
1828 if (lineA
.IsEmpty())
1830 list
.push_back(L
"refs/tags/" + CUnicodeUtils::GetUnicode(lineA
));
1836 std::sort(list
.begin() + prevCount
, list
.end(), LogicalCompareBranchesPredicate
);
1837 list
.erase(std::unique(list
.begin() + prevCount
, list
.end()), list
.end());
1842 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1844 size_t prevCount
= list
.size();
1845 if (this->m_IsUseLibGit2
)
1847 CAutoRepository
repo(GetGitRepository());
1851 CAutoStrArray remotes
;
1852 if (git_remote_list(remotes
, repo
))
1855 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1857 CStringA
remote(remotes
->strings
[i
]);
1858 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1861 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
1866 return Run(L
"git.exe remote", [&](const CStringA
& lineA
)
1868 if (lineA
.IsEmpty())
1870 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1874 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1876 size_t prevCount
= list
.size();
1877 if (UsingLibGit2(GIT_CMD_FETCH
))
1879 CAutoRepository
repo(GetGitRepository());
1883 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1884 CAutoRemote gitremote
;
1885 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1888 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1889 callbacks
.credentials
= g_Git2CredCallback
;
1890 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1891 git_proxy_options proxy
= GIT_PROXY_OPTIONS_INIT
;
1892 proxy
.type
= GIT_PROXY_AUTO
;
1893 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
, &proxy
, nullptr) < 0)
1896 const git_remote_head
** heads
= nullptr;
1898 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1901 for (size_t i
= 0; i
< size
; i
++)
1903 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1905 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1907 // do not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1908 if (ref
.Find(_T("^{}")) >= 1)
1910 list
.push_back(shortname
);
1912 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1917 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), (LPCTSTR
)remote
);
1918 gitLastErr
= cmd
+ L
'\n';
1919 if (Run(cmd
, [&](CStringA lineA
)
1921 lineA
= lineA
.Mid(51); // sha1, tab + refs/tags/
1922 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1923 if (lineA
.Find("^{}") >= 1)
1925 if (!lineA
.IsEmpty())
1926 list
.push_back(CUnicodeUtils::GetUnicode(lineA
));
1929 std::sort(list
.begin() + prevCount
, list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1933 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1935 if (UsingLibGit2(GIT_CMD_PUSH
))
1937 CAutoRepository
repo(GetGitRepository());
1941 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1943 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1946 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1947 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1948 callbacks
.credentials
= g_Git2CredCallback
;
1949 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1950 std::vector
<CStringA
> refspecs
;
1951 for (const auto& ref
: list
)
1952 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1954 std::vector
<char*> vc
;
1955 vc
.reserve(refspecs
.size());
1956 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1957 git_strarray specs
= { &vc
[0], vc
.size() };
1959 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1964 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1965 for (const auto& ref
: list
)
1967 CString refspec
= _T(":") + ref
;
1968 mgtPush
.AddFile(refspec
);
1971 BOOL cancel
= FALSE
;
1972 mgtPush
.Execute(cancel
);
1978 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1980 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1981 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1985 int CGit::GetRefList(STRING_VECTOR
&list
)
1987 size_t prevCount
= list
.size();
1988 if (this->m_IsUseLibGit2
)
1990 CAutoRepository
repo(GetGitRepository());
1994 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1997 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
2002 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
2004 int start
= lineA
.Find(L
' ');
2005 ASSERT(start
== 40);
2009 CString name
= CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1));
2010 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
2011 list
.push_back(name
);
2014 std::sort(list
.begin() + prevCount
, list
.end(), LogicalComparePredicate
);
2015 else if (ret
== 1 && IsInitRepos())
2020 typedef struct map_each_ref_payload
{
2021 git_repository
* repo
;
2022 MAP_HASH_NAME
* map
;
2023 } map_each_ref_payload
;
2025 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
2027 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
2029 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
2031 CAutoObject gitObject
;
2032 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
2035 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
2037 str
+= _T("^{}"); // deref tag
2038 CAutoObject derefedTag
;
2039 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
2041 gitObject
.Swap(derefedTag
);
2044 const git_oid
* oid
= git_object_id(gitObject
);
2048 CGitHash
hash((char *)oid
->id
);
2049 (*payloadContent
->map
)[hash
].push_back(str
);
2053 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
2057 map_each_ref_payload payloadContent
= { repo
, &map
};
2059 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
2062 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
2064 std::sort(it
->second
.begin(), it
->second
.end());
2070 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
2072 if (this->m_IsUseLibGit2
)
2074 CAutoRepository
repo(GetGitRepository());
2078 return GetMapHashToFriendName(repo
, map
);
2081 int ret
= Run(L
"git.exe show-ref -d", [&](const CStringA
& lineA
)
2083 int start
= lineA
.Find(L
' ');
2084 ASSERT(start
== 40);
2089 hash
.ConvertFromStrA(lineA
);
2090 map
[hash
].push_back(CUnicodeUtils::GetUnicode(lineA
.Mid(start
+ 1)));
2093 if (ret
== 1 && IsInitRepos())
2098 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
2100 CAutoConfig
config(true);
2101 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
2103 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
2105 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
2106 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
2107 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
2108 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
2113 static void SetLibGit2SearchPath(int level
, const CString
&value
)
2115 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
2116 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
2119 static void SetLibGit2TemplatePath(const CString
&value
)
2121 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
2122 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
2125 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2127 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
2128 CString str
= msysdir
;
2129 if (!str
.IsEmpty() && PathFileExists(str
+ _T("\\git.exe")))
2131 CGit::ms_LastMsysGitDir
= str
;
2135 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2139 // first, search PATH if git/bin directory is already present
2142 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2143 msysdir
= CGit::ms_LastMsysGitDir
;
2148 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2149 str
= msyslocalinstalldir
;
2150 str
.TrimRight(_T("\\"));
2154 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2155 str
= msysinstalldir
;
2156 str
.TrimRight(_T("\\"));
2161 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2162 str
= msysinstalldir
;
2163 str
.TrimRight(_T("\\"));
2167 if (PathFileExists(str
+ _T("\\bin\\git.exe")))
2169 else if (PathFileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2173 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR
)str
);
2177 CGit::ms_LastMsysGitDir
= str
;
2182 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2186 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2191 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2192 this->m_Environment
.clear();
2193 m_Environment
.CopyProcessEnvironment();
2195 // set HOME if not set already
2197 _tgetenv_s(&homesize
, nullptr, 0, _T("HOME"));
2199 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2202 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2203 if (sshclient
.IsEmpty())
2204 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2206 if(!sshclient
.IsEmpty())
2208 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2209 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2213 TCHAR sPlink
[MAX_PATH
] = {0};
2214 GetModuleFileName(nullptr, sPlink
, _countof(sPlink
));
2215 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2217 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPlink.exe"));
2218 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2219 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2224 TCHAR sAskPass
[MAX_PATH
] = {0};
2225 GetModuleFileName(nullptr, sAskPass
, _countof(sAskPass
));
2226 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2229 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2230 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2231 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2232 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2236 if (!FindAndSetGitExePath(bFallback
))
2240 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2241 static const CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2242 static const int prefixes_len
[] = { 8, 8, 0 };
2243 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2249 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2250 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2254 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
2255 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\.."));
2256 CGit::ms_MsysGitRootDir
= msysGitDir
;
2258 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2259 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2261 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2262 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR
)CGit::ms_MsysGitRootDir
);
2263 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), (LPCTSTR
)g_Git
.GetGitSystemConfig());
2264 if (!ms_bCygwinGit
&& !ms_bMsys2Git
)
2266 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) L
": ProgramData config = %s\n", (LPCTSTR
)g_Git
.GetGitProgramDataConfig());
2267 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitProgramDataConfig()).GetContainingDirectory().GetWinPathString());
2270 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2272 // Configure libgit2 search paths
2273 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2274 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2275 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2276 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition
= { [](git_smart_subtransport
**out
, git_transport
* owner
, void*) -> int { return git_smart_subtransport_ssh_wintunnel(out
, owner
, FindExecutableOnPath(g_Git
.m_Environment
.GetEnv(_T("GIT_SSH")), g_Git
.m_Environment
.GetEnv(_T("PATH"))), g_Git
.m_Environment
); }, 0 };
2277 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2278 git_transport_register("ssh+git", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2279 git_transport_register("git+ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2280 git_libgit2_opts(GIT_OPT_SET_USER_AGENT
, "TortoiseGit libgit2");
2281 if (!(ms_bCygwinGit
|| ms_bMsys2Git
))
2282 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2284 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2286 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2287 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2289 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2290 // register filter only once
2291 if (!git_filter_lookup("filter"))
2294 for (const CString
& binDirPrefix
: { L
"\\..\\usr\\bin", L
"\\..\\bin", L
"" })
2296 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2297 if (PathFileExists(possibleShExe
))
2300 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2301 sh
.Format(L
"\"%s\"", (LPCTSTR
)temp
);
2302 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2303 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2308 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2309 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2310 CString gitExecPath
= CGit::ms_MsysGitRootDir
;
2311 gitExecPath
.Append(_T("libexec\\git-core"));
2312 m_Environment
.AddToPath(gitExecPath
);
2314 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2319 m_bInitialized
= TRUE
;
2323 CString
CGit::GetHomeDirectory() const
2325 const wchar_t * homeDir
= wget_windows_home_directory();
2326 return CString(homeDir
, (int)wcslen(homeDir
));
2329 CString
CGit::GetGitLocalConfig() const
2332 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2333 path
+= _T("config");
2337 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2339 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2342 CString
CGit::GetGitGlobalConfig() const
2344 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2347 CString
CGit::GetGitGlobalXDGConfigPath() const
2349 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2352 CString
CGit::GetGitGlobalXDGConfig() const
2354 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2357 CString
CGit::GetGitProgramDataConfig() const
2359 const wchar_t* programdataConfig
= wget_program_data_config();
2360 return CString(programdataConfig
);
2363 CString
CGit::GetGitSystemConfig() const
2365 const wchar_t * systemConfig
= wget_msysgit_etc();
2366 return CString(systemConfig
, (int)wcslen(systemConfig
));
2369 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2371 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2373 CAutoRepository
repo(GetGitRepository());
2377 if (git_repository_head_unborn(repo
))
2380 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2381 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2382 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2384 CAutoStatusList status
;
2385 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2388 return (0 == git_status_list_entrycount(status
));
2393 cmd
=_T("git.exe rev-parse --verify HEAD");
2395 if(Run(cmd
,&out
,CP_UTF8
))
2398 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2399 if(Run(cmd
,&out
,CP_UTF8
))
2402 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2403 if(Run(cmd
,&out
,CP_UTF8
))
2406 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2407 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2412 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2414 for (int i
= 0; i
< list
.GetCount(); ++i
)
2416 if (Revert(commit
, (CTGitPath
&)list
[i
], err
))
2421 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2425 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2427 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2429 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2435 // if the filenames only differ in case, we have to pass "-f"
2436 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2438 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR
)force
, (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2439 if (Run(cmd
, &err
, CP_UTF8
))
2444 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2445 if (Run(cmd
, &err
, CP_UTF8
))
2449 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitOldPathString());
2450 if (Run(cmd
, &err
, CP_UTF8
))
2453 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2454 { //To init git repository, there are not HEAD, so we can use git reset command
2455 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2457 if (Run(cmd
, &err
, CP_UTF8
))
2462 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitPathString());
2463 if (Run(cmd
, &err
, CP_UTF8
))
2467 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2469 cmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2470 if (Run(cmd
, &err
, CP_UTF8
))
2477 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2482 if (git_repository_index(index
.GetPointer(), repo
))
2485 return git_index_has_conflicts(index
);
2488 int CGit::HasWorkingTreeConflicts()
2490 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2492 CAutoRepository
repo(GetGitRepository());
2496 return HasWorkingTreeConflicts(repo
);
2499 CString cmd
= _T("git.exe ls-files -u -t -z");
2502 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2505 return output
.IsEmpty() ? 0 : 1;
2508 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2510 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2512 CAutoRepository
repo(GetGitRepository());
2516 CGitHash fromHash
, toHash
, baseHash
;
2517 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2520 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2524 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2527 baseHash
= baseOid
.id
;
2530 *commonAncestor
= baseHash
;
2532 return fromHash
== baseHash
;
2536 CGitHash basehash
,hash
;
2538 cmd
.Format(_T("git.exe merge-base %s %s"), (LPCTSTR
)FixBranchName(to
), (LPCTSTR
)FixBranchName(from
));
2540 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2542 basehash
= base
.Trim();
2544 GetHash(hash
, from
);
2547 *commonAncestor
= basehash
;
2549 return hash
== basehash
;
2552 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2555 for (int i
= 0; i
< 4; ++i
)
2558 ret
|= hash
.m_hash
[i
];
2563 int CGit::RefreshGitIndex()
2565 if(g_Git
.m_IsUseGitDLL
)
2567 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2570 int result
= [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2584 cmd
=_T("git.exe update-index --refresh");
2585 return Run(cmd
, &output
, CP_UTF8
);
2589 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2591 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2593 CAutoRepository
repo(GetGitRepository());
2598 if (GetHash(repo
, hash
, Refname
))
2602 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2606 if (git_commit_tree(tree
.GetPointer(), commit
))
2609 CAutoTreeEntry entry
;
2610 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2614 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2617 CAutoFILE file
= _tfsopen(outputfile
, _T("wb"), SH_DENYWR
);
2618 if (file
== nullptr)
2620 giterr_set_str(GITERR_NONE
, "Could not create file.");
2624 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2626 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2628 giterr_set_str(GITERR_OS
, "Could not write to file.");
2634 else if (g_Git
.m_IsUseGitDLL
)
2636 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2639 g_Git
.CheckAndInitDll();
2640 CStringA ref
, patha
, outa
;
2641 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2642 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2643 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2644 ::DeleteFile(outputfile
);
2645 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2646 outa
.ReleaseBuffer();
2650 catch (const char * msg
)
2652 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2657 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2664 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR
)Refname
, (LPCTSTR
)path
.GetGitPathString());
2665 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2669 void CEnvironment::clear()
2675 bool CEnvironment::empty()
2677 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2680 CEnvironment::operator LPTSTR()
2684 return &__super::at(0);
2687 CEnvironment::operator LPWSTR
*()
2692 void CEnvironment::CopyProcessEnvironment()
2696 TCHAR
*porig
= GetEnvironmentStrings();
2698 while(*p
!=0 || *(p
+1) !=0)
2699 this->push_back(*p
++);
2701 push_back(_T('\0'));
2702 push_back(_T('\0'));
2703 baseptr
= &__super::at(0);
2705 FreeEnvironmentStrings(porig
);
2708 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2711 for (size_t i
= 0; i
< size(); ++i
)
2715 CString sname
= str
.Tokenize(_T("="),start
);
2716 if(sname
.CompareNoCase(name
) == 0)
2717 return &(*this)[i
+start
];
2723 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2726 for (i
= 0; i
< size(); ++i
)
2728 CString str
= &(*this)[i
];
2730 CString sname
= str
.Tokenize(_T("="),start
);
2731 if(sname
.CompareNoCase(name
) == 0)
2738 if (!value
) // as we haven't found the variable we want to remove, just return
2740 if (i
== 0) // make inserting into an empty environment work
2742 this->push_back(_T('\0'));
2745 i
-= 1; // roll back terminate \0\0
2746 this->push_back(_T('\0'));
2749 CEnvironment::iterator it
;
2753 while(*it
&& i
<size())
2760 if (value
== nullptr) // remove the variable
2766 baseptr
= &__super::at(0);
2772 this->insert(it
,*name
++);
2777 this->insert(it
, _T('='));
2783 this->insert(it
,*value
++);
2787 baseptr
= &__super::at(0);
2790 void CEnvironment::AddToPath(CString value
)
2792 value
.TrimRight(L
"\\");
2793 if (value
.IsEmpty())
2796 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2798 // do not double add paths to %PATH%
2799 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2804 SetEnv(L
"PATH", path
);
2807 int CGit::GetGitEncode(TCHAR
* configkey
)
2809 CString str
=GetConfigValue(configkey
);
2814 return CUnicodeUtils::GetCPCode(str
);
2818 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2824 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2829 diff
= GetGitDiff();
2831 git_open_diff(&diff
, arg
);
2835 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2846 isStat
= !!strstr(arg
, "stat");
2851 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2853 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2862 for (int j
= 0; j
< count
; ++j
)
2871 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2872 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2873 &mode
,&IsBin
,&inc
,&dec
);
2875 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2876 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2878 path
.SetFromGit(strnewname
,&stroldname
);
2879 path
.ParserAction((BYTE
)mode
);
2883 path
.m_StatAdd
=_T("-");
2884 path
.m_StatDel
=_T("-");
2888 path
.m_StatAdd
.Format(_T("%d"),inc
);
2889 path
.m_StatDel
.Format(_T("%d"),dec
);
2891 PathList
->AddPath(path
);
2893 git_diff_flush(diff
);
2896 git_close_diff(diff
);
2901 int CGit::GetShortHASHLength() const
2906 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2910 REF_TYPE type
= CGit::UNKNOWN
;
2912 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2913 type
= CGit::LOCAL_BRANCH
;
2914 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2915 type
= CGit::REMOTE_BRANCH
;
2916 else if (str
.Right(3) == L
"^{}" && CGit::GetShortName(str
, shortname
, L
"refs/tags/"))
2917 type
= CGit::ANNOTATED_TAG
;
2918 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2920 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2923 shortname
=_T("stash");
2925 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2929 g_Git
.GetBisectTerms(&bisectGood
, &bisectBad
);
2931 if (CStringUtils::StartsWith(shortname
, bisectGood
) && ((c
= shortname
.GetAt(bisectGood
.GetLength())) == '-' || c
== '\0'))
2933 type
= CGit::BISECT_GOOD
;
2934 shortname
= bisectGood
;
2937 if (CStringUtils::StartsWith(shortname
, bisectBad
) && ((c
= shortname
.GetAt(bisectBad
.GetLength())) == '-' || c
== '\0'))
2939 type
= CGit::BISECT_BAD
;
2940 shortname
= bisectBad
;
2943 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2945 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2946 type
= CGit::UNKNOWN
;
2949 type
= CGit::UNKNOWN
;
2959 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2961 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2964 void CGit::SetGit2CredentialCallback(void* callback
)
2966 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2969 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2971 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2974 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
2977 if (rev2
== GitRev::GetWorkingCopy())
2978 cmd
.Format(_T("git.exe diff --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
);
2979 else if (rev1
== GitRev::GetWorkingCopy())
2980 cmd
.Format(_T("git.exe diff -R --stat%s -p %s --"), bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev2
);
2991 if (diffContext
>= 0)
2992 unified
.Format(_T(" --unified=%d"), diffContext
);
2993 cmd
.Format(_T("git.exe diff-tree -r -p%s%s --stat%s %s %s --"), (LPCTSTR
)merge
, (LPCTSTR
)unified
, bNoPrefix
? L
" --no-prefix" : L
"", (LPCTSTR
)rev1
, (LPCTSTR
)rev2
);
2996 if (!path
.IsEmpty())
2999 cmd
+= path
.GetGitPathString();
3006 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
3008 ATLASSERT(payload
&& text
);
3009 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
3010 fwrite("\n", 1, 1, (FILE *)payload
);
3013 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
3015 ATLASSERT(payload
&& line
);
3016 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3017 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
3018 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
3022 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
3024 ATLASSERT(repo
&& identifier
&& tree
);
3026 /* try to resolve identifier */
3028 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
3032 return GIT_ENOTFOUND
;
3035 switch (git_object_type(obj
))
3038 *tree
= (git_tree
*)obj
.Detach();
3040 case GIT_OBJ_COMMIT
:
3041 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
3044 err
= GIT_ENOTFOUND
;
3050 /* use libgit2 get unified diff */
3051 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const git_revnum_t
& revOld
, const git_revnum_t
& revNew
, std::function
<void(const git_buf
*, void*)> statCallback
, git_diff_line_cb callback
, void* data
, bool /* bMerge */, bool bNoPrefix
)
3053 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
3054 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
3056 CAutoRepository
repo(g_Git
.GetGitRepository());
3060 int isHeadOrphan
= git_repository_head_unborn(repo
);
3061 if (isHeadOrphan
== 1)
3063 else if (isHeadOrphan
!= 0)
3066 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
3067 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
3068 char *buf
= pathA
.GetBuffer();
3069 if (!pathA
.IsEmpty())
3071 opts
.pathspec
.strings
= &buf
;
3072 opts
.pathspec
.count
= 1;
3076 opts
.new_prefix
= "";
3077 opts
.old_prefix
= "";
3081 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
3086 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
3089 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
3092 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
3095 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
3098 if (git_diff_merge(diff
, diff2
))
3103 if (tree1
.IsEmpty() && tree2
.IsEmpty())
3106 if (tree1
.IsEmpty())
3114 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
3117 if (tree2
.IsEmpty())
3119 /* don't check return value, there are not parent commit at first commit*/
3120 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
3122 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
3124 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
3128 CAutoDiffStats stats
;
3129 if (git_diff_get_stats(stats
.GetPointer(), diff
))
3132 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
3134 statCallback(statBuf
, data
);
3136 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
3139 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
3142 if (git_patch_print(patch
, callback
, data
))
3146 pathA
.ReleaseBuffer();
3151 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
, bool bNoPrefix
)
3153 if (UsingLibGit2(GIT_CMD_DIFF
))
3155 CAutoFILE file
= _tfsopen(patchfile
, _T("w"), SH_DENYRW
);
3158 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
, bNoPrefix
);
3163 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
, bNoPrefix
);
3164 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3168 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3170 ATLASSERT(payload
&& text
);
3171 CStringA
*str
= (CStringA
*) payload
;
3172 str
->Append(text
->ptr
, (int)text
->size
);
3173 str
->AppendChar('\n');
3176 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3178 ATLASSERT(payload
&& line
);
3179 CStringA
*str
= (CStringA
*) payload
;
3180 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3181 str
->Append(&line
->origin
, 1);
3182 str
->Append(line
->content
, (int)line
->content_len
);
3186 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3188 if (UsingLibGit2(GIT_CMD_DIFF
))
3189 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
, false);
3193 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3195 int ret
= Run(cmd
, &vector
);
3196 if (!vector
.empty())
3198 vector
.push_back(0); // vector is not NUL terminated
3199 buffer
->Append((char *)&vector
[0]);
3205 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3207 if (UsingLibGit2(GIT_CMD_REVERT
))
3209 CAutoRepository
repo(GetGitRepository());
3214 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3217 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3218 revert_opts
.mainline
= parent
;
3219 int result
= git_revert(repo
, commit
, &revert_opts
);
3221 return !result
? 0 : -1;
3227 merge
.Format(_T("-m %d "), parent
);
3228 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR
)merge
, (LPCTSTR
)hash
.ToString());
3229 gitLastErr
= cmd
+ _T("\n");
3230 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3240 int CGit::DeleteRef(const CString
& reference
)
3242 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3244 CAutoRepository
repo(GetGitRepository());
3249 if (reference
.Right(3) == _T("^{}"))
3250 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3252 refA
= CUnicodeUtils::GetUTF8(reference
);
3255 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3259 if (git_reference_is_tag(ref
))
3260 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3261 else if (git_reference_is_branch(ref
))
3262 result
= git_branch_delete(ref
);
3263 else if (git_reference_is_remote(ref
))
3264 result
= git_branch_delete(ref
);
3266 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3272 CString cmd
, shortname
;
3273 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3274 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)shortname
);
3275 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3276 cmd
.Format(_T("git.exe tag -d -- %s"), (LPCTSTR
)shortname
);
3277 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3278 cmd
.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR
)shortname
);
3281 gitLastErr
= L
"unsupported reference type: " + reference
;
3285 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3293 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3295 if (!PathFileExists(filename
))
3298 CAutoFILE pFile
= _tfsopen(filename
, _T("r"), SH_DENYWR
);
3301 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3302 return true; // load no further files
3308 char s
[8196] = { 0 };
3309 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3312 str
+= CStringA(s
, read
);
3314 msg
+= CUnicodeUtils::GetUnicode(str
);
3315 msg
.Replace(_T("\r\n"), _T("\n"));
3316 msg
.TrimRight(_T("\n"));
3319 return true; // load no further files
3322 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3325 return GetInitAddList(result
);
3331 count
= filterlist
->GetCount();
3333 CString head
= _T("HEAD");
3335 head
= _T("HEAD~1");
3337 for (int i
= 0; i
< count
; ++i
)
3341 if (ms_bCygwinGit
|| ms_bMsys2Git
)
3343 // Prevent showing all files as modified when using cygwin's git
3345 cmd
= _T("git.exe status --");
3347 cmd
.Format(_T("git.exe status -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3352 // also list staged files which will be in the commit
3353 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3356 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3358 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3361 if (Run(cmd
, &cmdout
, &cmdErr
))
3363 int last
= cmdErr
.RevertFind(0, -1);
3365 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3366 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3369 out
.append(cmdout
, 0);
3371 result
.ParserFromLog(out
);
3373 std::map
<CString
, int> duplicateMap
;
3374 for (int i
= 0; i
< result
.GetCount(); ++i
)
3375 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), i
));
3377 // handle delete conflict case, when remote : modified, local : deleted.
3378 for (int i
= 0; i
< count
; ++i
)
3384 cmd
= _T("git.exe ls-files -u -t -z");
3386 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3390 CTGitPathList conflictlist
;
3391 conflictlist
.ParserFromLog(cmdout
);
3392 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3394 auto existing
= duplicateMap
.find(conflictlist
[j
].GetGitPathString());
3395 if (existing
!= duplicateMap
.end())
3397 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3398 p
.m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3402 result
.AddPath(conflictlist
[j
]);
3403 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3408 // handle source files of file renames/moves (issue #860)
3409 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3410 for (int i
= 0; i
< count
; ++i
)
3416 cmd
= _T("git.exe ls-files -d -z");
3418 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3422 CTGitPathList deletelist
;
3423 deletelist
.ParserFromLog(cmdout
, true);
3424 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3426 auto existing
= duplicateMap
.find(deletelist
[j
].GetGitPathString());
3427 if (existing
== duplicateMap
.end())
3429 result
.AddPath(deletelist
[j
]);
3430 duplicateMap
.insert(std::pair
<CString
, int>(result
[i
].GetGitPathString(), result
.GetCount() - 1));
3434 CTGitPath
& p
= const_cast<CTGitPath
&>(result
[existing
->second
]);
3435 p
.m_Action
|= CTGitPath::LOGACTIONS_MISSING
;
3443 int CGit::IsRebaseRunning()
3446 if (!GitAdminDir::GetAdminDirPath(g_Git
.m_CurrentDir
, adminDir
))
3449 if (PathIsDirectory(adminDir
+ L
"rebase-apply") || PathIsDirectory(adminDir
+ L
"tgitrebase.active"))
3454 void CGit::GetBisectTerms(CString
* good
, CString
* bad
)
3456 static CString lastGood
;
3457 static CString lastBad
;
3458 static ULONGLONG lastRead
= 0;
3468 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3469 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3470 // as we only read a small file the performance effects should be negligible
3471 if (lastRead
+ 5000 > GetTickCount64())
3479 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir
, adminDir
))
3482 CString termsFile
= adminDir
+ L
"BISECT_TERMS";
3484 _tfopen_s(fp
.GetPointer(), termsFile
, L
"rb");
3487 char badA
[MAX_PATH
] = { 0 };
3488 fgets(badA
, MAX_PATH
, fp
);
3489 size_t len
= strlen(badA
);
3490 if (len
> 0 && badA
[len
- 1] == '\n')
3491 badA
[len
- 1] = '\0';
3492 char goodA
[MAX_PATH
] = { 0 };
3493 fgets(goodA
, MAX_PATH
, fp
);
3494 len
= strlen(goodA
);
3495 if (len
> 0 && goodA
[len
- 1] == '\n')
3496 goodA
[len
- 1] = '\0';
3497 lastGood
= CUnicodeUtils::GetUnicode(goodA
);
3498 lastBad
= CUnicodeUtils::GetUnicode(badA
);
3499 lastRead
= GetTickCount64();
3502 int CGit::GetGitVersion(CString
* versiondebug
, CString
* errStr
)
3504 CString version
, err
;
3505 if (Run(_T("git.exe --version"), &version
, &err
, CP_UTF8
))
3514 *versiondebug
= version
;
3519 CString str
= version
.Tokenize(_T("."), start
);
3520 int space
= str
.ReverseFind(_T(' '));
3521 str
= str
.Mid(space
+ 1, start
);
3525 version
= version
.Mid(start
);
3528 str
= version
.Tokenize(_T("."), start
);
3529 ver
|= (_ttol(str
) & 0xFF) << 16;
3531 str
= version
.Tokenize(_T("."), start
);
3532 ver
|= (_ttol(str
) & 0xFF) << 8;
3534 str
= version
.Tokenize(_T("."), start
);
3535 ver
|= (_ttol(str
) & 0xFF);