1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - 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"
27 #include "FormatMessageWrapper.h"
28 #include "SmartHandle.h"
29 #include "MassiveGitTaskBase.h"
30 #include "git2/sys/filter.h"
31 #include "git2/sys/transport.h"
32 #include "../libgit2/filter-filter.h"
33 #include "../libgit2/ssh-wintunnel.h"
35 bool CGit::ms_bCygwinGit
= (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE
) == TRUE
);
36 int CGit::m_LogEncode
=CP_UTF8
;
37 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
39 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
41 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
44 const wchar_t* base
= path
;
45 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
47 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
50 *buf
= L
'\0'; /* reserved a byte via initial subtract */
52 while (*path
== term
|| *path
== L
';')
55 return (path
!= base
) ? path
: NULL
;
58 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
61 return _tstat(lpszFileName
, &st
) == 0;
64 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
66 TCHAR buf
[MAX_PATH
] = { 0 };
68 // search in all paths defined in PATH
69 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
71 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
73 // ensure trailing slash
74 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
75 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
77 const size_t len
= _tcslen(buf
);
79 if ((len
+ filename
.GetLength()) < MAX_PATH
)
80 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
95 static BOOL
FindGitPath()
98 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
102 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
105 _tgetenv_s(&size
, env
, size
, _T("PATH"));
107 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
108 if (!gitExeDirectory
.IsEmpty())
110 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
111 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
112 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
114 // often the msysgit\cmd folder is on the %PATH%, but
115 // that git.exe does not work, so try to guess the bin folder
116 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
117 if (FileExists(binDir
))
118 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
126 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
128 CString filename
= executable
;
130 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
131 filename
+= _T(".exe");
133 if (FileExists(filename
))
136 filename
= FindFileOnPath(filename
, env
);
137 if (!filename
.IsEmpty())
143 static bool g_bSortLogical
;
144 static bool g_bSortLocalBranchesFirst
;
145 static bool g_bSortTagsReversed
;
146 static git_cred_acquire_cb g_Git2CredCallback
;
147 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
149 static void GetSortOptions()
151 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
153 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
154 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
155 if (g_bSortLocalBranchesFirst
)
156 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
157 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
158 if (!g_bSortTagsReversed
)
159 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
162 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
165 return StrCmpLogicalW(left
, right
) < 0;
166 return StrCmpI(left
, right
) < 0;
169 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
172 return StrCmpLogicalW(left
, right
) > 0;
173 return StrCmpI(left
, right
) > 0;
176 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
178 if (g_bSortLocalBranchesFirst
)
180 int leftIsRemote
= left
.Find(_T("remotes/"));
181 int rightIsRemote
= right
.Find(_T("remotes/"));
183 if (leftIsRemote
== 0 && rightIsRemote
< 0)
185 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
189 return StrCmpLogicalW(left
, right
) < 0;
190 return StrCmpI(left
, right
) < 0;
193 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
195 CString
CGit::ms_LastMsysGitDir
;
196 int CGit::ms_LastMsysGitVersion
= 0;
202 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
203 m_CurrentDir
.ReleaseBuffer();
204 m_IsGitDllInited
= false;
206 m_GitSimpleListDiff
=0;
207 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
208 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
209 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
211 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
214 this->m_bInitialized
=false;
216 m_critGitDllSec
.Init();
223 git_close_diff(m_GitDiff
);
226 if(this->m_GitSimpleListDiff
)
228 git_close_diff(m_GitSimpleListDiff
);
229 m_GitSimpleListDiff
=0;
233 bool CGit::IsBranchNameValid(const CString
& branchname
)
235 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
237 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
239 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
240 return !!git_reference_is_valid_name(branchA
);
243 static bool IsPowerShell(CString cmd
)
246 int powerShellPos
= cmd
.Find(_T("powershell"));
247 if (powerShellPos
< 0)
250 // found the word powershell, check that it is the command and not any parameter
251 int end
= cmd
.GetLength();
252 if (cmd
.Find(_T('"')) == 0)
254 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
255 if (secondDoubleQuote
> 0)
256 end
= secondDoubleQuote
;
260 int firstSpace
= cmd
.Find(_T(' '));
265 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
268 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
270 SECURITY_ATTRIBUTES sa
;
271 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
272 CAutoGeneralHandle hStdioFile
;
274 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
275 sa
.lpSecurityDescriptor
=NULL
;
276 sa
.bInheritHandle
=TRUE
;
277 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
279 CString err
= CFormatMessageWrapper();
280 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
281 return TGIT_GIT_ERROR_OPEN_PIP
;
283 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
285 CString err
= CFormatMessageWrapper();
286 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
287 return TGIT_GIT_ERROR_OPEN_PIP
;
292 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
293 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
296 STARTUPINFO si
= { 0 };
297 PROCESS_INFORMATION pi
;
298 si
.cb
=sizeof(STARTUPINFO
);
301 si
.hStdError
= hWriteErr
;
303 si
.hStdError
= hWrite
;
305 si
.hStdOutput
=hStdioFile
;
307 si
.hStdOutput
=hWrite
;
309 si
.wShowWindow
=SW_HIDE
;
310 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
312 LPTSTR pEnv
= m_Environment
;
313 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
315 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
317 // 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,
318 // 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)
319 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
320 if (IsPowerShell(cmd
))
321 dwFlags
|= CREATE_NEW_CONSOLE
;
323 dwFlags
|= DETACHED_PROCESS
;
325 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
326 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
328 if (ms_bCygwinGit
&& cmd
.Find(_T("git")) == 0)
330 cmd
.Replace(_T('\\'), _T('/'));
331 cmd
.Replace(_T("\""), _T("\\\""));
332 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
334 else if(cmd
.Find(_T("git")) == 0)
336 int firstSpace
= cmd
.Find(_T(" "));
338 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
340 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
343 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
344 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
346 CString err
= CFormatMessageWrapper();
347 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
348 return TGIT_GIT_ERROR_CREATE_PROCESS
;
356 *hReadOut
= hRead
.Detach();
358 *hErrReadOut
= hReadErr
.Detach();
362 //Must use sperate function to convert ANSI str to union code string
363 //Becuase A2W use stack as internal convert buffer.
364 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
371 len
= (int)strlen((const char*)p
);
376 int currentContentLen
= str
->GetLength();
377 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
378 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
379 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
382 // This method was originally used to check for orphaned branches
383 BOOL
CGit::CanParseRev(CString ref
)
389 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
399 // Checks if we have an orphaned HEAD
400 BOOL
CGit::IsInitRepos()
403 if (GetHash(hash
, _T("HEAD")) != 0)
405 return hash
.IsEmpty() ? TRUE
: FALSE
;
408 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
410 PASYNCREADSTDERRTHREADARGS pDataArray
;
411 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
414 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
415 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
417 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
424 int CGit::Run(CGitCall
* pcall
)
426 PROCESS_INFORMATION pi
;
427 CAutoGeneralHandle hRead
, hReadErr
;
428 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
429 return TGIT_GIT_ERROR_CREATE_PROCESS
;
431 CAutoGeneralHandle
piThread(pi
.hThread
);
432 CAutoGeneralHandle
piProcess(pi
.hProcess
);
434 ASYNCREADSTDERRTHREADARGS threadArguments
;
435 threadArguments
.fileHandle
= hReadErr
;
436 threadArguments
.pcall
= pcall
;
437 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
440 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
442 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
444 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
445 if(!bAborted
)//For now, flush output when command aborted.
446 if(pcall
->OnOutputData(data
,readnumber
))
453 WaitForSingleObject(thread
, INFINITE
);
455 WaitForSingleObject(pi
.hProcess
, INFINITE
);
458 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
460 CString err
= CFormatMessageWrapper();
461 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
462 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
465 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
469 class CGitCall_ByteVector
: public CGitCall
472 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
473 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
475 if (!m_pvector
|| size
== 0)
477 size_t oldsize
=m_pvector
->size();
478 m_pvector
->resize(m_pvector
->size()+size
);
479 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
482 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
484 if (!m_pvectorErr
|| size
== 0)
486 size_t oldsize
= m_pvectorErr
->size();
487 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
488 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
491 BYTE_VECTOR
* m_pvector
;
492 BYTE_VECTOR
* m_pvectorErr
;
495 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
497 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
500 int CGit::Run(CString cmd
, CString
* output
, int code
)
504 ret
= Run(cmd
, output
, &err
, code
);
506 if (output
&& !err
.IsEmpty())
508 if (!output
->IsEmpty())
515 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
517 BYTE_VECTOR vector
, vectorErr
;
520 ret
= Run(cmd
, &vector
, &vectorErr
);
522 ret
= Run(cmd
, &vector
);
525 StringAppend(output
, &(vector
[0]), code
);
529 vectorErr
.push_back(0);
530 StringAppend(outputErr
, &(vectorErr
[0]), code
);
536 class CGitCallCb
: public CGitCall
539 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
541 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
546 int oldEndPos
= m_buffer
.GetLength();
547 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
548 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
550 // Break into lines and feed to m_recv
552 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
554 m_recv(m_buffer
.Left(eolPos
));
555 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
560 virtual bool OnOutputErrData(const BYTE
*, size_t) override
562 return false; // Ignore error output for now
565 virtual void OnEnd() override
567 if (!m_buffer
.IsEmpty())
569 m_buffer
.Empty(); // Just for sure
573 GitReceiverFunc m_recv
;
577 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
579 CGitCallCb
call(cmd
, recv
);
583 CString
CGit::GetUserName(void)
586 env
.CopyProcessEnvironment();
587 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
588 if (!envname
.IsEmpty())
590 return GetConfigValue(L
"user.name");
592 CString
CGit::GetUserEmail(void)
595 env
.CopyProcessEnvironment();
596 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
597 if (!envmail
.IsEmpty())
600 return GetConfigValue(L
"user.email");
603 CString
CGit::GetConfigValue(const CString
& name
)
606 if(this->m_IsUseGitDLL
)
608 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
617 key
= CUnicodeUtils::GetUTF8(name
);
621 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
624 catch (const char *msg
)
626 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
630 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
636 cmd
.Format(L
"git.exe config %s", name
);
637 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
638 if (configValue
.IsEmpty())
640 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
644 bool CGit::GetConfigValueBool(const CString
& name
)
646 CString configValue
= GetConfigValue(name
);
647 configValue
.MakeLower();
649 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
655 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
657 CString configValue
= GetConfigValue(name
);
659 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
664 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
666 if(this->m_IsUseGitDLL
)
668 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
677 CStringA keya
, valuea
;
678 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
679 valuea
= CUnicodeUtils::GetUTF8(value
);
683 return [=]() { return get_set_config(keya
, valuea
, type
); }();
685 catch (const char *msg
)
687 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
698 option
= _T("--global");
701 option
= _T("--system");
706 CString mangledValue
= value
;
707 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
708 mangledValue
.Replace(_T("\""), _T("\\\""));
709 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, mangledValue
);
711 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
719 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
721 if(this->m_IsUseGitDLL
)
723 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
732 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
736 return [=]() { return get_set_config(keya
, nullptr, type
); }();
738 catch (const char *msg
)
740 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
751 option
= _T("--global");
754 option
= _T("--system");
759 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
761 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
769 CString
CGit::GetCurrentBranch(bool fallback
)
772 //Run(_T("git.exe branch"),&branch);
774 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
775 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
777 return _T("(no branch)");
784 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
786 if (localBranch
.IsEmpty())
790 configName
.Format(L
"branch.%s.remote", localBranch
);
791 pullRemote
= GetConfigValue(configName
);
793 //Select pull-branch from current branch
794 configName
.Format(L
"branch.%s.merge", localBranch
);
795 pullBranch
= StripRefName(GetConfigValue(configName
));
798 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
801 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
803 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
806 CString
CGit::GetFullRefName(const CString
& shortRefName
)
810 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
811 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
812 return CString();//Error
814 return refName
.Tokenize(L
"\n", iStart
);
817 CString
CGit::StripRefName(CString refName
)
819 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
820 refName
= refName
.Mid(11);
821 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
822 refName
= refName
.Mid(5);
824 return refName
.Tokenize(_T("\n"),start
);
827 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
829 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
831 if ( sProjectRoot
.IsEmpty() )
835 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
838 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
841 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
849 fgets(s
, sizeof(s
), pFile
);
853 const char *pfx
= "ref: refs/heads/";
854 const int len
= 16;//strlen(pfx)
856 if ( !strncmp(s
, pfx
, len
) )
858 //# We're on a branch. It might not exist. But
859 //# HEAD looks good enough to be a branch.
860 CStringA
utf8Branch(s
+ len
);
861 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
862 sBranchOut
.TrimRight(_T(" \r\n\t"));
864 if ( sBranchOut
.IsEmpty() )
869 CStringA
utf8Hash(s
);
870 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
871 unicodeHash
.TrimRight(_T(" \r\n\t"));
872 if (CGitHash::IsValidSHA1(unicodeHash
))
873 sBranchOut
= unicodeHash
;
875 //# Assume this is a detached head.
876 sBranchOut
= _T("HEAD");
881 //# Assume this is a detached head.
890 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
893 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
897 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
899 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
901 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
903 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
905 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
907 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
909 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
913 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
915 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
917 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
922 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
928 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
935 CString file
= _T(" --");
938 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
941 num
.Format(_T("-n%d"),count
);
945 if(mask
& LOG_INFO_STAT
)
946 param
+= _T(" --numstat ");
947 if(mask
& LOG_INFO_FILESTATE
)
948 param
+= _T(" --raw ");
950 if(mask
& LOG_INFO_FULLHISTORY
)
951 param
+= _T(" --full-history ");
953 if(mask
& LOG_INFO_BOUNDARY
)
954 param
+= _T(" --left-right --boundary ");
956 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
957 param
+= _T(" --all ");
959 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
960 param
+= _T(" --branches ");
962 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
965 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
968 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
969 param
+= _T(" --first-parent ");
971 if(mask
& CGit::LOG_INFO_NO_MERGE
)
972 param
+= _T(" --no-merges ");
974 if(mask
& CGit::LOG_INFO_FOLLOW
)
975 param
+= _T(" --follow ");
977 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
980 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
981 param
+= _T(" --full-diff ");
983 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
984 param
+= _T(" --simplify-by-decoration ");
990 if( Filter
&& (Filter
->m_From
!= -1))
992 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
996 if( Filter
&& (Filter
->m_To
!= -1))
998 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
1002 bool isgrep
= false;
1003 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1005 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
1010 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1012 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
1017 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1019 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
1024 if(Filter
&& isgrep
)
1026 if(!Filter
->m_IsRegex
)
1027 param
+= _T(" --fixed-strings ");
1029 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1032 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1033 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1034 param
+= _T(" --topo-order");
1035 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1036 param
+= _T(" --date-order");
1038 if(paramonly
) //tgit.dll.Git.cpp:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1039 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1043 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1044 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1053 void GetTempPath(CString
&path
)
1055 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1057 DWORD dwBufSize
=BUFSIZE
;
1058 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1059 lpPathBuffer
); // buffer for path
1060 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1064 path
.Format(_T("%s"),lpPathBuffer
);
1066 CString
GetTempFile()
1068 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1070 DWORD dwBufSize
=BUFSIZE
;
1071 TCHAR szTempName
[BUFSIZE
] = { 0 };
1074 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1075 lpPathBuffer
); // buffer for path
1076 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1080 // Create a temporary file.
1081 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1082 TEXT("Patch"), // temp file name prefix
1083 0, // create unique name
1084 szTempName
); // buffer for name
1092 return CString(szTempName
);
1096 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1098 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1099 if (result
== 0) return 0;
1100 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1107 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1108 CreateDirectory(lpBuffer
, NULL
);
1113 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1116 PROCESS_INFORMATION pi
;
1117 si
.cb
=sizeof(STARTUPINFO
);
1118 GetStartupInfo(&si
);
1120 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1121 psa
.bInheritHandle
=TRUE
;
1123 HANDLE hReadErr
, hWriteErr
;
1124 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1126 CString err
= CFormatMessageWrapper();
1127 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1128 return TGIT_GIT_ERROR_OPEN_PIP
;
1131 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1132 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1134 if (houtfile
== INVALID_HANDLE_VALUE
)
1136 CString err
= CFormatMessageWrapper();
1137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1138 CloseHandle(hReadErr
);
1139 CloseHandle(hWriteErr
);
1140 return TGIT_GIT_ERROR_OPEN_PIP
;
1143 si
.wShowWindow
= SW_HIDE
;
1144 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1145 si
.hStdOutput
= houtfile
;
1146 si
.hStdError
= hWriteErr
;
1148 LPTSTR pEnv
= m_Environment
;
1149 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1151 if(cmd
.Find(_T("git")) == 0)
1152 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1154 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1155 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1157 CString err
= CFormatMessageWrapper();
1158 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1160 CloseHandle(hReadErr
);
1161 CloseHandle(hWriteErr
);
1162 CloseHandle(houtfile
);
1163 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1166 BYTE_VECTOR stderrVector
;
1167 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1169 ASYNCREADSTDERRTHREADARGS threadArguments
;
1170 threadArguments
.fileHandle
= hReadErr
;
1171 threadArguments
.pcall
= &pcall
;
1172 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1174 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1176 CloseHandle(hWriteErr
);
1177 CloseHandle(hReadErr
);
1180 WaitForSingleObject(thread
, INFINITE
);
1182 stderrVector
.push_back(0);
1183 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1186 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1188 CString err
= CFormatMessageWrapper();
1189 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1190 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1193 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1195 CloseHandle(pi
.hThread
);
1196 CloseHandle(pi
.hProcess
);
1197 CloseHandle(houtfile
);
1201 git_repository
* CGit::GetGitRepository() const
1203 git_repository
* repo
= nullptr;
1204 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1208 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1212 // no need to parse a ref if it's already a 40-byte hash
1213 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1215 hash
= CGitHash(friendname
);
1219 int isHeadOrphan
= git_repository_head_unborn(repo
);
1220 if (isHeadOrphan
!= 0)
1223 if (isHeadOrphan
== 1)
1229 CAutoObject gitObject
;
1230 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1233 const git_oid
* oid
= git_object_id(gitObject
);
1237 hash
= CGitHash((char *)oid
->id
);
1242 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1244 // no need to parse a ref if it's already a 40-byte hash
1245 if (CGitHash::IsValidSHA1(friendname
))
1247 hash
= CGitHash(friendname
);
1253 CAutoRepository
repo(GetGitRepository());
1257 return GetHash(repo
, hash
, friendname
, true);
1261 CString branch
= FixBranchName(friendname
);
1262 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1263 branch
= friendname
;
1265 cmd
.Format(_T("git.exe rev-parse %s"), branch
);
1267 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1268 hash
= CGitHash(gitLastErr
.Trim());
1271 else if (friendname
== _T("HEAD")) // special check for unborn branch
1274 if (GetCurrentBranchFromFile(m_CurrentDir
, branch
))
1283 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1288 cmd
=_T("git.exe ls-files -s -t -z");
1290 if (Run(cmd
, &cmdout
))
1293 if (outputlist
.ParserFromLsFile(cmdout
))
1295 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1296 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1300 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1304 if (ignoreSpaceAtEol
)
1305 ignore
+= _T(" --ignore-space-at-eol");
1306 if (ignoreSpaceChange
)
1307 ignore
+= _T(" --ignore-space-change");
1309 ignore
+= _T(" --ignore-all-space");
1310 if (ignoreBlankLines
)
1311 ignore
+= _T(" --ignore-blank-lines");
1313 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1316 if(rev1
== GIT_REV_ZERO
)
1317 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1319 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1323 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1330 return outputlist
.ParserFromLog(out
);
1333 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1335 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1336 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1340 int CGit::GetTagList(STRING_VECTOR
&list
)
1342 if (this->m_IsUseLibGit2
)
1344 CAutoRepository
repo(GetGitRepository());
1348 CAutoStrArray tag_names
;
1350 if (git_tag_list(tag_names
, repo
))
1353 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1355 CStringA
tagName(tag_names
->strings
[i
]);
1356 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1359 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1365 CString cmd
, output
;
1366 cmd
=_T("git.exe tag -l");
1367 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1374 one
=output
.Tokenize(_T("\n"),pos
);
1376 list
.push_back(one
);
1378 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1380 else if (ret
== 1 && IsInitRepos())
1386 CString
CGit::GetGitLastErr(const CString
& msg
)
1388 if (this->m_IsUseLibGit2
)
1389 return GetLibGit2LastErr(msg
);
1390 else if (gitLastErr
.IsEmpty())
1391 return msg
+ _T("\nUnknown git.exe error.");
1394 CString lastError
= gitLastErr
;
1396 return msg
+ _T("\n") + lastError
;
1400 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1402 if (UsingLibGit2(cmd
))
1403 return GetLibGit2LastErr(msg
);
1404 else if (gitLastErr
.IsEmpty())
1405 return msg
+ _T("\nUnknown git.exe error.");
1408 CString lastError
= gitLastErr
;
1410 return msg
+ _T("\n") + lastError
;
1414 CString
CGit::GetLibGit2LastErr()
1416 const git_error
*libgit2err
= giterr_last();
1419 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1421 return _T("libgit2 returned: ") + lastError
;
1424 return _T("An error occoured in libgit2, but no message is available.");
1427 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1430 return msg
+ _T("\n") + GetLibGit2LastErr();
1431 return GetLibGit2LastErr();
1434 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1436 if(branchName
== "FETCH_HEAD")
1437 branchName
= DerefFetchHead();
1441 CString
CGit::FixBranchName(const CString
& branchName
)
1443 CString tempBranchName
= branchName
;
1444 FixBranchName_Mod(tempBranchName
);
1445 return tempBranchName
;
1448 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1452 CAutoRepository
repo(GetGitRepository());
1454 return true; // TODO: optimize error reporting
1456 CAutoReference tagRef
;
1457 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1460 CAutoReference branchRef
;
1461 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1470 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1471 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1477 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1487 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1491 CAutoRepository
repo(GetGitRepository());
1493 return false; // TODO: optimize error reporting
1497 prefix
= _T("refs/heads/");
1499 prefix
= _T("refs/tags/");
1502 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1508 CString cmd
, output
;
1510 cmd
= _T("git.exe show-ref ");
1512 cmd
+= _T("--heads ");
1514 cmd
+= _T("--tags ");
1516 cmd
+= _T("refs/heads/") + name
;
1517 cmd
+= _T(" refs/tags/") + name
;
1519 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1522 if (!output
.IsEmpty())
1529 CString
CGit::DerefFetchHead()
1532 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1533 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1534 int forMergeLineCount
= 0;
1536 std::string hashToReturn
;
1537 while(getline(fetchHeadFile
, line
))
1539 //Tokenize this line
1540 std::string::size_type prevPos
= 0;
1541 std::string::size_type pos
= line
.find('\t');
1542 if(pos
== std::string::npos
) continue; //invalid line
1544 std::string hash
= line
.substr(0, pos
);
1545 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1547 bool forMerge
= pos
== prevPos
;
1548 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1550 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1555 hashToReturn
= hash
;
1556 ++forMergeLineCount
;
1557 if(forMergeLineCount
> 1)
1558 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1562 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1565 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1571 CAutoRepository
repo(GetGitRepository());
1575 if (git_repository_head_detached(repo
) == 1)
1576 cur
= _T("(detached from ");
1578 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1580 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1581 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1582 flags
= GIT_BRANCH_ALL
;
1583 else if (type
& BRANCH_REMOTE
)
1584 flags
= GIT_BRANCH_REMOTE
;
1586 CAutoBranchIterator it
;
1587 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1590 git_reference
* ref
= nullptr;
1591 git_branch_t branchType
;
1592 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1594 CAutoReference
autoRef(ref
);
1595 const char * name
= nullptr;
1596 if (git_branch_name(&name
, ref
))
1599 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1600 if (branchType
& GIT_BRANCH_REMOTE
)
1601 list
.push_back(_T("remotes/") + branchname
);
1604 if (git_branch_is_head(ref
))
1606 list
.push_back(branchname
);
1613 CString cmd
, output
;
1614 cmd
= _T("git.exe branch --no-color");
1616 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1618 else if (type
& BRANCH_REMOTE
)
1621 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1628 one
= output
.Tokenize(_T("\n"), pos
);
1629 one
.Trim(L
" \r\n\t");
1630 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1631 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1632 if (one
[0] == _T('*'))
1637 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1639 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1640 one
= _T("remotes/") + one
;
1641 list
.push_back(one
);
1645 else if (ret
== 1 && IsInitRepos())
1649 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1650 list
.push_back(L
"FETCH_HEAD");
1652 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1654 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1656 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1669 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1671 if (this->m_IsUseLibGit2
)
1673 CAutoRepository
repo(GetGitRepository());
1677 CAutoStrArray remotes
;
1678 if (git_remote_list(remotes
, repo
))
1681 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1683 CStringA
remote(remotes
->strings
[i
]);
1684 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1687 std::sort(list
.begin(), list
.end());
1694 CString cmd
, output
;
1695 cmd
=_T("git.exe remote");
1696 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1703 one
=output
.Tokenize(_T("\n"),pos
);
1705 list
.push_back(one
);
1712 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1714 if (UsingLibGit2(GIT_CMD_FETCH
))
1716 CAutoRepository
repo(GetGitRepository());
1720 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1722 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1725 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1726 callbacks
.credentials
= g_Git2CredCallback
;
1727 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1728 git_remote_set_callbacks(remote
, &callbacks
);
1729 if (git_remote_connect(remote
, GIT_DIRECTION_FETCH
) < 0)
1732 const git_remote_head
** heads
= nullptr;
1734 if (git_remote_ls(&heads
, &size
, remote
) < 0)
1737 for (size_t i
= 0; i
< size
; i
++)
1739 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1741 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1743 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1744 if (shortname
.Find(_T("^{}")) >= 1)
1746 list
.push_back(shortname
);
1748 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1752 CString cmd
, out
, err
;
1753 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1754 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1756 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1763 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1764 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1765 if (one
.Find(_T("^{}")) >= 1)
1768 list
.push_back(one
);
1770 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1774 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1776 if (UsingLibGit2(GIT_CMD_PUSH
))
1778 CAutoRepository
repo(GetGitRepository());
1782 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1784 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1787 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1788 callbacks
.credentials
= g_Git2CredCallback
;
1789 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1790 git_remote_set_callbacks(remote
, &callbacks
);
1791 if (git_remote_connect(remote
, GIT_DIRECTION_PUSH
) < 0)
1794 std::vector
<CStringA
> refspecs
;
1795 for (auto ref
: list
)
1796 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1798 std::vector
<char*> vc
;
1799 vc
.reserve(refspecs
.size());
1800 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1801 git_strarray specs
= { &vc
[0], vc
.size() };
1803 if (git_remote_push(remote
, &specs
, nullptr) < 0)
1808 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1809 for (auto ref
: list
)
1811 CString refspec
= _T(":") + ref
;
1812 mgtPush
.AddFile(refspec
);
1815 BOOL cancel
= FALSE
;
1816 mgtPush
.Execute(cancel
);
1822 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1824 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1825 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1829 int CGit::GetRefList(STRING_VECTOR
&list
)
1831 if (this->m_IsUseLibGit2
)
1833 CAutoRepository
repo(GetGitRepository());
1837 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1840 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1846 CString cmd
, output
;
1847 cmd
=_T("git.exe show-ref -d");
1848 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1855 one
=output
.Tokenize(_T("\n"),pos
);
1856 int start
=one
.Find(_T(" "),0);
1860 name
=one
.Right(one
.GetLength()-start
-1);
1861 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1862 list
.push_back(name
);
1865 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1867 else if (ret
== 1 && IsInitRepos())
1873 typedef struct map_each_ref_payload
{
1874 git_repository
* repo
;
1875 MAP_HASH_NAME
* map
;
1876 } map_each_ref_payload
;
1878 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1880 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1882 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1884 CAutoObject gitObject
;
1885 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1888 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1890 str
+= _T("^{}"); // deref tag
1891 CAutoObject derefedTag
;
1892 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1894 gitObject
.Swap(derefedTag
);
1897 const git_oid
* oid
= git_object_id(gitObject
);
1901 CGitHash
hash((char *)oid
->id
);
1902 (*payloadContent
->map
)[hash
].push_back(str
);
1906 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1910 map_each_ref_payload payloadContent
= { repo
, &map
};
1912 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1915 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1917 std::sort(it
->second
.begin(), it
->second
.end());
1923 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1925 if (this->m_IsUseLibGit2
)
1927 CAutoRepository
repo(GetGitRepository());
1931 return GetMapHashToFriendName(repo
, map
);
1935 CString cmd
, output
;
1936 cmd
=_T("git.exe show-ref -d");
1937 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1944 one
=output
.Tokenize(_T("\n"),pos
);
1945 int start
=one
.Find(_T(" "),0);
1949 name
=one
.Right(one
.GetLength()-start
-1);
1952 hash
=one
.Left(start
);
1954 map
[CGitHash(hash
)].push_back(name
);
1958 else if (ret
== 1 && IsInitRepos())
1964 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1966 CAutoConfig
config(true);
1967 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1969 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1971 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1972 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1973 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1974 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1979 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1981 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1982 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1985 static void SetLibGit2TemplatePath(const CString
&value
)
1987 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1988 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1991 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1998 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
1999 this->m_Environment
.clear();
2000 m_Environment
.CopyProcessEnvironment();
2001 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2004 size_t homesize
,size
;
2006 // set HOME if not set already
2007 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
2009 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2012 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2013 if (sshclient
.IsEmpty())
2014 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2016 if(!sshclient
.IsEmpty())
2018 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2019 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2023 TCHAR sPlink
[MAX_PATH
] = {0};
2024 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
2025 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2027 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
2028 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2029 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2034 TCHAR sAskPass
[MAX_PATH
] = {0};
2035 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
2036 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2039 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2040 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2041 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2042 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2046 // add git/bin path to PATH
2048 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
2049 CString str
= msysdir
;
2050 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
2052 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2056 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2057 str
= msyslocalinstalldir
;
2058 str
.TrimRight(_T("\\"));
2061 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2062 str
= msysinstalldir
;
2063 str
.TrimRight(_T("\\"));
2065 if ( !str
.IsEmpty() )
2069 CGit::ms_LastMsysGitDir
= str
;
2074 // search PATH if git/bin directory is already present
2075 if ( FindGitPath() )
2077 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
2078 m_bInitialized
= TRUE
;
2079 msysdir
= CGit::ms_LastMsysGitDir
;
2089 CGit::ms_LastMsysGitDir
= str
;
2092 // check for git.exe existance (maybe it was deinstalled in the meantime)
2093 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
2095 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2099 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
2100 // Configure libgit2 search paths
2102 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
2103 msysGitDir
.ReleaseBuffer();
2104 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
2105 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2106 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2107 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition
= { [](git_smart_subtransport
**out
, git_transport
* owner
) -> 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 };
2108 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2109 CString msysGitTemplateDir
;
2111 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
2113 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\usr\\share\\git-core\\templates"));
2114 msysGitTemplateDir
.ReleaseBuffer();
2115 SetLibGit2TemplatePath(msysGitTemplateDir
);
2118 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
2121 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
2123 m_Environment
.SetEnv(_T("PATH"), path
);
2125 CString str1
= m_Environment
.GetEnv(_T("PATH"));
2127 CString sOldPath
= oldpath
;
2130 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2131 // register filter only once
2132 if (!git_filter_lookup("filter"))
2134 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir
+ L
"\\sh.exe\"", m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2139 m_bInitialized
= TRUE
;
2143 CString
CGit::GetHomeDirectory() const
2145 const wchar_t * homeDir
= wget_windows_home_directory();
2146 return CString(homeDir
, (int)wcslen(homeDir
));
2149 CString
CGit::GetGitLocalConfig() const
2152 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2153 path
+= _T("config");
2157 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2159 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2162 CString
CGit::GetGitGlobalConfig() const
2164 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2167 CString
CGit::GetGitGlobalXDGConfigPath() const
2169 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2172 CString
CGit::GetGitGlobalXDGConfig() const
2174 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2177 CString
CGit::GetGitSystemConfig() const
2179 const wchar_t * systemConfig
= wget_msysgit_etc();
2180 return CString(systemConfig
, (int)wcslen(systemConfig
));
2183 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2185 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2187 CAutoRepository repo
= GetGitRepository();
2191 if (git_repository_head_unborn(repo
))
2194 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2195 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2196 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2198 CAutoStatusList status
;
2199 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2202 return (0 == git_status_list_entrycount(status
));
2207 cmd
=_T("git.exe rev-parse --verify HEAD");
2209 if(Run(cmd
,&out
,CP_UTF8
))
2212 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2213 if(Run(cmd
,&out
,CP_UTF8
))
2216 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2217 if(Run(cmd
,&out
,CP_UTF8
))
2220 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2221 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2226 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2229 for (int i
= 0; i
< list
.GetCount(); ++i
)
2231 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2237 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2241 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2243 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2245 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2249 // if the filenames only differ in case, we have to pass "-f"
2250 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2252 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2253 if (Run(cmd
, &err
, CP_UTF8
))
2256 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2257 if (Run(cmd
, &err
, CP_UTF8
))
2260 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2261 { //To init git repository, there are not HEAD, so we can use git reset command
2262 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2264 if (Run(cmd
, &err
, CP_UTF8
))
2269 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2270 if (Run(cmd
, &err
, CP_UTF8
))
2274 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2276 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2277 if (Run(cmd
, &err
, CP_UTF8
))
2284 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2289 if (git_repository_index(index
.GetPointer(), repo
))
2292 return git_index_has_conflicts(index
);
2295 int CGit::HasWorkingTreeConflicts()
2297 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2299 CAutoRepository
repo(GetGitRepository());
2303 return HasWorkingTreeConflicts(repo
);
2306 CString cmd
= _T("git.exe ls-files -u -t -z");
2309 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2312 return output
.IsEmpty() ? 0 : 1;
2315 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2317 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2319 CAutoRepository
repo(GetGitRepository());
2323 CGitHash fromHash
, toHash
, baseHash
;
2324 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2327 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2331 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2334 baseHash
= baseOid
.id
;
2337 *commonAncestor
= baseHash
;
2339 return fromHash
== baseHash
;
2343 CGitHash basehash
,hash
;
2345 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2347 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2351 basehash
= base
.Trim();
2353 GetHash(hash
, from
);
2356 *commonAncestor
= basehash
;
2358 return hash
== basehash
;
2361 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2364 for (int i
= 0; i
< 4; ++i
)
2367 ret
|= hash
.m_hash
[i
];
2372 int CGit::RefreshGitIndex()
2374 if(g_Git
.m_IsUseGitDLL
)
2376 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2379 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2390 cmd
=_T("git.exe update-index --refresh");
2391 return Run(cmd
, &output
, CP_UTF8
);
2395 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2397 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2399 CAutoRepository
repo(GetGitRepository());
2404 if (GetHash(repo
, hash
, Refname
))
2408 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2412 if (git_commit_tree(tree
.GetPointer(), commit
))
2415 CAutoTreeEntry entry
;
2416 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2420 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2423 FILE *file
= nullptr;
2424 _tfopen_s(&file
, outputfile
, _T("wb"));
2425 if (file
== nullptr)
2427 giterr_set_str(GITERR_NONE
, "Could not create file.");
2431 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2436 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2438 giterr_set_str(GITERR_OS
, "Could not write to file.");
2447 else if (g_Git
.m_IsUseGitDLL
)
2449 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2452 g_Git
.CheckAndInitDll();
2453 CStringA ref
, patha
, outa
;
2454 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2455 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2456 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2457 ::DeleteFile(outputfile
);
2458 return git_checkout_file(ref
, patha
, outa
);
2461 catch (const char * msg
)
2463 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2468 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2475 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2476 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2480 void CEnvironment::clear()
2485 bool CEnvironment::empty()
2487 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2490 CEnvironment::operator LPTSTR()
2494 return &__super::at(0);
2497 void CEnvironment::CopyProcessEnvironment()
2501 TCHAR
*porig
= GetEnvironmentStrings();
2503 while(*p
!=0 || *(p
+1) !=0)
2504 this->push_back(*p
++);
2506 push_back(_T('\0'));
2507 push_back(_T('\0'));
2509 FreeEnvironmentStrings(porig
);
2512 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2515 for (size_t i
= 0; i
< size(); ++i
)
2519 CString sname
= str
.Tokenize(_T("="),start
);
2520 if(sname
.CompareNoCase(name
) == 0)
2522 return &(*this)[i
+start
];
2529 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2532 for (i
= 0; i
< size(); ++i
)
2534 CString str
= &(*this)[i
];
2536 CString sname
= str
.Tokenize(_T("="),start
);
2537 if(sname
.CompareNoCase(name
) == 0)
2546 if (!value
) // as we haven't found the variable we want to remove, just return
2548 if (i
== 0) // make inserting into an empty environment work
2550 this->push_back(_T('\0'));
2553 i
-= 1; // roll back terminate \0\0
2554 this->push_back(_T('\0'));
2557 CEnvironment::iterator it
;
2561 while(*it
&& i
<size())
2568 if (value
== nullptr) // remove the variable
2576 this->insert(it
,*name
++);
2581 this->insert(it
, _T('='));
2587 this->insert(it
,*value
++);
2594 int CGit::GetGitEncode(TCHAR
* configkey
)
2596 CString str
=GetConfigValue(configkey
);
2601 return CUnicodeUtils::GetCPCode(str
);
2605 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2611 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2616 diff
= GetGitDiff();
2618 git_open_diff(&diff
, arg
);
2622 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2633 isStat
= !!strstr(arg
, "stat");
2638 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2640 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2649 for (int j
= 0; j
< count
; ++j
)
2658 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2659 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2660 &mode
,&IsBin
,&inc
,&dec
);
2662 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2663 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2665 path
.SetFromGit(strnewname
,&stroldname
);
2666 path
.ParserAction((BYTE
)mode
);
2670 path
.m_StatAdd
=_T("-");
2671 path
.m_StatDel
=_T("-");
2675 path
.m_StatAdd
.Format(_T("%d"),inc
);
2676 path
.m_StatDel
.Format(_T("%d"),dec
);
2678 PathList
->AddPath(path
);
2680 git_diff_flush(diff
);
2683 git_close_diff(diff
);
2688 int CGit::GetShortHASHLength() const
2693 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2697 REF_TYPE type
= CGit::UNKNOWN
;
2699 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2701 type
= CGit::LOCAL_BRANCH
;
2704 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2706 type
= CGit::REMOTE_BRANCH
;
2708 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2712 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2715 shortname
=_T("stash");
2717 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2719 if (shortname
.Find(_T("good")) == 0)
2721 type
= CGit::BISECT_GOOD
;
2722 shortname
= _T("good");
2725 if (shortname
.Find(_T("bad")) == 0)
2727 type
= CGit::BISECT_BAD
;
2728 shortname
= _T("bad");
2731 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2735 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2737 type
= CGit::UNKNOWN
;
2741 type
= CGit::UNKNOWN
;
2751 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2753 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2756 void CGit::SetGit2CredentialCallback(void* callback
)
2758 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2761 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2763 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2766 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2769 if (rev2
== GitRev::GetWorkingCopy())
2770 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2771 else if (rev1
== GitRev::GetWorkingCopy())
2772 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2783 if (diffContext
>= 0)
2784 unified
.Format(_T(" --unified=%d"), diffContext
);
2785 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2788 if (!path
.IsEmpty())
2791 cmd
+= path
.GetGitPathString();
2798 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2800 ATLASSERT(payload
&& text
);
2801 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2802 fwrite("\n", 1, 1, (FILE *)payload
);
2805 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2807 ATLASSERT(payload
&& line
);
2808 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2809 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2810 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2814 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2816 ATLASSERT(repo
&& identifier
&& tree
);
2818 /* try to resolve identifier */
2820 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2824 return GIT_ENOTFOUND
;
2827 switch (git_object_type(obj
))
2830 *tree
= (git_tree
*)obj
.Detach();
2832 case GIT_OBJ_COMMIT
:
2833 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2836 err
= GIT_ENOTFOUND
;
2842 /* use libgit2 get unified diff */
2843 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 */)
2845 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2846 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2848 CAutoRepository
repo(g_Git
.GetGitRepository());
2852 int isHeadOrphan
= git_repository_head_unborn(repo
);
2853 if (isHeadOrphan
== 1)
2855 else if (isHeadOrphan
!= 0)
2858 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2859 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2860 char *buf
= pathA
.GetBuffer();
2861 if (!pathA
.IsEmpty())
2863 opts
.pathspec
.strings
= &buf
;
2864 opts
.pathspec
.count
= 1;
2868 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2873 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2876 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2879 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2882 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2885 if (git_diff_merge(diff
, diff2
))
2890 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2893 if (tree1
.IsEmpty())
2901 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2904 if (tree2
.IsEmpty())
2906 /* don't check return value, there are not parent commit at first commit*/
2907 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2909 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2911 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2915 CAutoDiffStats stats
;
2916 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2919 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2921 statCallback(statBuf
, data
);
2923 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2926 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2929 if (git_patch_print(patch
, callback
, data
))
2933 pathA
.ReleaseBuffer();
2938 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2940 if (UsingLibGit2(GIT_CMD_DIFF
))
2942 FILE *file
= nullptr;
2943 _tfopen_s(&file
, patchfile
, _T("w"));
2944 if (file
== nullptr)
2946 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
);
2953 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2954 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2958 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
2960 ATLASSERT(payload
&& text
);
2961 CStringA
*str
= (CStringA
*) payload
;
2962 str
->Append(text
->ptr
, (int)text
->size
);
2963 str
->AppendChar('\n');
2966 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2968 ATLASSERT(payload
&& line
);
2969 CStringA
*str
= (CStringA
*) payload
;
2970 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2971 str
->Append(&line
->origin
, 1);
2972 str
->Append(line
->content
, (int)line
->content_len
);
2976 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2978 if (UsingLibGit2(GIT_CMD_DIFF
))
2979 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
);
2983 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2985 int ret
= Run(cmd
, &vector
);
2986 if (!vector
.empty())
2988 vector
.push_back(0); // vector is not NUL terminated
2989 buffer
->Append((char *)&vector
[0]);
2995 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2997 if (UsingLibGit2(GIT_CMD_REVERT
))
2999 CAutoRepository
repo(GetGitRepository());
3004 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3007 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3008 revert_opts
.mainline
= parent
;
3009 int result
= git_revert(repo
, commit
, &revert_opts
);
3011 return !result
? 0 : -1;
3017 merge
.Format(_T("-m %d "), parent
);
3018 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
3019 gitLastErr
= cmd
+ _T("\n");
3020 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3032 int CGit::DeleteRef(const CString
& reference
)
3034 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3036 CAutoRepository
repo(GetGitRepository());
3041 if (reference
.Right(3) == _T("^{}"))
3042 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3044 refA
= CUnicodeUtils::GetUTF8(reference
);
3047 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3051 if (git_reference_is_tag(ref
))
3052 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3053 else if (git_reference_is_branch(ref
))
3054 result
= git_branch_delete(ref
);
3055 else if (git_reference_is_remote(ref
))
3056 result
= git_branch_delete(ref
);
3058 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3064 CString cmd
, shortname
;
3065 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3066 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
3067 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3068 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
3069 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3070 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
3073 gitLastErr
= L
"unsupported reference type: " + reference
;
3077 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3085 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3087 if (PathFileExists(filename
))
3089 FILE *pFile
= nullptr;
3090 _tfopen_s(&pFile
, filename
, _T("r"));
3096 char s
[8196] = { 0 };
3097 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3100 str
+= CStringA(s
, read
);
3103 msg
= CUnicodeUtils::GetUnicode(str
);
3104 msg
.Replace(_T("\r\n"), _T("\n"));
3105 msg
.TrimRight(_T("\n"));
3109 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3110 return true; // load no further files
3115 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3118 return GetInitAddList(result
);
3124 count
= filterlist
->GetCount();
3126 CString head
= _T("HEAD");
3128 head
= _T("HEAD~1");
3130 for (int i
= 0; i
< count
; ++i
)
3136 // Prevent showing all files as modified when using cygwin's git
3138 cmd
= _T("git.exe status --");
3140 cmd
.Format(_T("git.exe status -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3145 // also list staged files which will be in the commit
3146 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3149 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3151 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3154 if (Run(cmd
, &cmdout
, &cmdErr
))
3156 int last
= cmdErr
.RevertFind(0, -1);
3158 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3159 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3162 out
.append(cmdout
, 0);
3164 result
.ParserFromLog(out
);
3166 // handle delete conflict case, when remote : modified, local : deleted.
3167 for (int i
= 0; i
< count
; ++i
)
3173 cmd
= _T("git.exe ls-files -u -t -z");
3175 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3179 CTGitPathList conflictlist
;
3180 conflictlist
.ParserFromLog(cmdout
);
3181 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3183 CTGitPath
* p
= result
.LookForGitPath(conflictlist
[j
].GetGitPathString());
3185 p
->m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3187 result
.AddPath(conflictlist
[j
]);
3191 // handle source files of file renames/moves (issue #860)
3192 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3193 for (int i
= 0; i
< count
; ++i
)
3199 cmd
= _T("git.exe ls-files -d -z");
3201 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3205 CTGitPathList deletelist
;
3206 deletelist
.ParserFromLog(cmdout
, true);
3207 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3209 CTGitPath
* p
= result
.LookForGitPath(deletelist
[j
].GetGitPathString());
3211 result
.AddPath(deletelist
[j
]);