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"
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
== NULL
|| buf
== NULL
|| 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
: NULL
;
60 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
63 return _tstat(lpszFileName
, &st
) == 0;
66 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
68 TCHAR buf
[MAX_PATH
] = { 0 };
70 // search in all paths defined in PATH
71 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
73 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
75 // ensure trailing slash
76 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
77 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
79 const size_t len
= _tcslen(buf
);
81 if ((len
+ filename
.GetLength()) < MAX_PATH
)
82 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
97 static BOOL
FindGitPath()
100 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
104 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
107 _tgetenv_s(&size
, env
, size
, _T("PATH"));
109 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
110 if (!gitExeDirectory
.IsEmpty())
112 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
113 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
114 if (CGit::ms_LastMsysGitDir
.GetLength() > 12 && (CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw64\\bin")))
116 // prefer cmd directory as early Git for Windows 2.x releases only had this
117 CString installRoot
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd\\git.exe");
118 if (FileExists(installRoot
))
119 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd");
121 if (CGit::ms_LastMsysGitDir
.GetLength() > 4 && CGit::ms_LastMsysGitDir
.Right(4) == _T("\\cmd"))
123 // often the msysgit\cmd folder is on the %PATH%, but
124 // that git.exe does not work, so try to guess the bin folder
125 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
126 if (FileExists(binDir
))
127 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
135 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
137 CString filename
= executable
;
139 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
140 filename
+= _T(".exe");
142 if (FileExists(filename
))
145 filename
= FindFileOnPath(filename
, env
);
146 if (!filename
.IsEmpty())
152 static bool g_bSortLogical
;
153 static bool g_bSortLocalBranchesFirst
;
154 static bool g_bSortTagsReversed
;
155 static git_cred_acquire_cb g_Git2CredCallback
;
156 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
158 static void GetSortOptions()
160 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
162 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
163 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
164 if (g_bSortLocalBranchesFirst
)
165 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
166 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
167 if (!g_bSortTagsReversed
)
168 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
171 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
174 return StrCmpLogicalW(left
, right
) < 0;
175 return StrCmpI(left
, right
) < 0;
178 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
181 return StrCmpLogicalW(left
, right
) > 0;
182 return StrCmpI(left
, right
) > 0;
185 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
187 if (g_bSortLocalBranchesFirst
)
189 int leftIsRemote
= left
.Find(_T("remotes/"));
190 int rightIsRemote
= right
.Find(_T("remotes/"));
192 if (leftIsRemote
== 0 && rightIsRemote
< 0)
194 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
198 return StrCmpLogicalW(left
, right
) < 0;
199 return StrCmpI(left
, right
) < 0;
202 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
204 CString
CGit::ms_LastMsysGitDir
;
205 CString
CGit::ms_MsysGitRootDir
;
206 int CGit::ms_LastMsysGitVersion
= 0;
212 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
213 m_IsGitDllInited
= false;
215 m_GitSimpleListDiff
=0;
216 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
217 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
218 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
220 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
223 this->m_bInitialized
=false;
225 m_critGitDllSec
.Init();
232 git_close_diff(m_GitDiff
);
235 if(this->m_GitSimpleListDiff
)
237 git_close_diff(m_GitSimpleListDiff
);
238 m_GitSimpleListDiff
=0;
242 bool CGit::IsBranchNameValid(const CString
& branchname
)
244 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
246 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
248 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
249 return !!git_reference_is_valid_name(branchA
);
252 static bool IsPowerShell(CString cmd
)
255 int powerShellPos
= cmd
.Find(_T("powershell"));
256 if (powerShellPos
< 0)
259 // found the word powershell, check that it is the command and not any parameter
260 int end
= cmd
.GetLength();
261 if (cmd
.Find(_T('"')) == 0)
263 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
264 if (secondDoubleQuote
> 0)
265 end
= secondDoubleQuote
;
269 int firstSpace
= cmd
.Find(_T(' '));
274 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
277 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
279 SECURITY_ATTRIBUTES sa
;
280 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
281 CAutoGeneralHandle hStdioFile
;
283 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
284 sa
.lpSecurityDescriptor
=NULL
;
285 sa
.bInheritHandle
=TRUE
;
286 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
288 CString err
= CFormatMessageWrapper();
289 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
290 return TGIT_GIT_ERROR_OPEN_PIP
;
292 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
294 CString err
= CFormatMessageWrapper();
295 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
296 return TGIT_GIT_ERROR_OPEN_PIP
;
301 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
302 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
305 STARTUPINFO si
= { 0 };
306 PROCESS_INFORMATION pi
;
307 si
.cb
=sizeof(STARTUPINFO
);
310 si
.hStdError
= hWriteErr
;
312 si
.hStdError
= hWrite
;
314 si
.hStdOutput
=hStdioFile
;
316 si
.hStdOutput
=hWrite
;
318 si
.wShowWindow
=SW_HIDE
;
319 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
321 LPTSTR pEnv
= m_Environment
;
322 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
324 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
326 // 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,
327 // 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)
328 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
329 if (IsPowerShell(cmd
))
330 dwFlags
|= CREATE_NEW_CONSOLE
;
332 dwFlags
|= DETACHED_PROCESS
;
334 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
335 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
337 if (ms_bMsys2Git
&& cmd
.Find(_T("git")) == 0 && cmd
.Find(L
"git.exe config ") == -1)
339 cmd
.Replace(_T("\\"), _T("\\\\\\\\"));
340 cmd
.Replace(_T("\""), _T("\\\""));
341 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/usr/bin/") + cmd
+ _T('"');
343 else if (ms_bCygwinGit
&& cmd
.Find(_T("git")) == 0 && cmd
.Find(L
"git.exe config ") == -1)
345 cmd
.Replace(_T('\\'), _T('/'));
346 cmd
.Replace(_T("\""), _T("\\\""));
347 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
349 else if(cmd
.Find(_T("git")) == 0)
351 int firstSpace
= cmd
.Find(_T(" "));
353 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
355 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
358 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
359 if(!CreateProcess(nullptr, cmd
.GetBuffer(), nullptr, nullptr, TRUE
, dwFlags
, pEnv
, m_CurrentDir
.GetBuffer(), &si
, &pi
))
361 CString err
= CFormatMessageWrapper();
362 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), (LPCTSTR
)err
.Trim());
363 return TGIT_GIT_ERROR_CREATE_PROCESS
;
371 *hReadOut
= hRead
.Detach();
373 *hErrReadOut
= hReadErr
.Detach();
377 //Must use sperate function to convert ANSI str to union code string
378 //Becuase A2W use stack as internal convert buffer.
379 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
386 len
= (int)strlen((const char*)p
);
391 int currentContentLen
= str
->GetLength();
392 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
393 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
394 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
397 // This method was originally used to check for orphaned branches
398 BOOL
CGit::CanParseRev(CString ref
)
404 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
414 // Checks if we have an orphaned HEAD
415 BOOL
CGit::IsInitRepos()
418 if (GetHash(hash
, _T("HEAD")) != 0)
420 return hash
.IsEmpty() ? TRUE
: FALSE
;
423 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
425 PASYNCREADSTDERRTHREADARGS pDataArray
;
426 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
429 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
430 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
432 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
439 int CGit::Run(CGitCall
* pcall
)
441 PROCESS_INFORMATION pi
;
442 CAutoGeneralHandle hRead
, hReadErr
;
443 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
444 return TGIT_GIT_ERROR_CREATE_PROCESS
;
446 CAutoGeneralHandle
piThread(pi
.hThread
);
447 CAutoGeneralHandle
piProcess(pi
.hProcess
);
449 ASYNCREADSTDERRTHREADARGS threadArguments
;
450 threadArguments
.fileHandle
= hReadErr
;
451 threadArguments
.pcall
= pcall
;
452 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
455 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
457 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
459 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
460 if(!bAborted
)//For now, flush output when command aborted.
461 if(pcall
->OnOutputData(data
,readnumber
))
468 WaitForSingleObject(thread
, INFINITE
);
470 WaitForSingleObject(pi
.hProcess
, INFINITE
);
473 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
475 CString err
= CFormatMessageWrapper();
476 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
477 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
480 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
484 class CGitCall_ByteVector
: public CGitCall
487 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
488 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
490 if (!m_pvector
|| size
== 0)
492 size_t oldsize
=m_pvector
->size();
493 m_pvector
->resize(m_pvector
->size()+size
);
494 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
497 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
499 if (!m_pvectorErr
|| size
== 0)
501 size_t oldsize
= m_pvectorErr
->size();
502 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
503 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
506 BYTE_VECTOR
* m_pvector
;
507 BYTE_VECTOR
* m_pvectorErr
;
510 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
512 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
515 int CGit::Run(CString cmd
, CString
* output
, int code
)
519 ret
= Run(cmd
, output
, &err
, code
);
521 if (output
&& !err
.IsEmpty())
523 if (!output
->IsEmpty())
530 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
532 BYTE_VECTOR vector
, vectorErr
;
535 ret
= Run(cmd
, &vector
, &vectorErr
);
537 ret
= Run(cmd
, &vector
);
540 StringAppend(output
, &(vector
[0]), code
);
544 vectorErr
.push_back(0);
545 StringAppend(outputErr
, &(vectorErr
[0]), code
);
551 class CGitCallCb
: public CGitCall
554 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
556 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
561 int oldEndPos
= m_buffer
.GetLength();
562 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
563 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
565 // Break into lines and feed to m_recv
567 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
569 m_recv(m_buffer
.Left(eolPos
));
570 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
575 virtual bool OnOutputErrData(const BYTE
*, size_t) override
577 return false; // Ignore error output for now
580 virtual void OnEnd() override
582 if (!m_buffer
.IsEmpty())
584 m_buffer
.Empty(); // Just for sure
588 GitReceiverFunc m_recv
;
592 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
594 CGitCallCb
call(cmd
, recv
);
598 CString
CGit::GetUserName(void)
601 env
.CopyProcessEnvironment();
602 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
603 if (!envname
.IsEmpty())
605 return GetConfigValue(L
"user.name");
607 CString
CGit::GetUserEmail(void)
610 env
.CopyProcessEnvironment();
611 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
612 if (!envmail
.IsEmpty())
615 return GetConfigValue(L
"user.email");
618 CString
CGit::GetConfigValue(const CString
& name
)
621 if(this->m_IsUseGitDLL
)
623 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
632 key
= CUnicodeUtils::GetUTF8(name
);
636 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
639 catch (const char *msg
)
641 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
645 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
651 cmd
.Format(L
"git.exe config %s", (LPCTSTR
)name
);
652 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
653 if (configValue
.IsEmpty())
655 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
659 bool CGit::GetConfigValueBool(const CString
& name
)
661 CString configValue
= GetConfigValue(name
);
662 configValue
.MakeLower();
664 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
670 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
672 CString configValue
= GetConfigValue(name
);
674 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
679 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
681 if(this->m_IsUseGitDLL
)
683 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
692 CStringA keya
, valuea
;
693 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
694 valuea
= CUnicodeUtils::GetUTF8(value
);
698 return [=]() { return get_set_config(keya
, valuea
, type
); }();
700 catch (const char *msg
)
702 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
713 option
= _T("--global");
716 option
= _T("--system");
721 CString mangledValue
= value
;
722 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
723 mangledValue
.Replace(_T("\""), _T("\\\""));
724 cmd
.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR
)option
, (LPCTSTR
)key
, (LPCTSTR
)mangledValue
);
726 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
734 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
736 if(this->m_IsUseGitDLL
)
738 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
747 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
751 return [=]() { return get_set_config(keya
, nullptr, type
); }();
753 catch (const char *msg
)
755 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
766 option
= _T("--global");
769 option
= _T("--system");
774 cmd
.Format(_T("git.exe config %s --unset %s"), (LPCTSTR
)option
, (LPCTSTR
)key
);
776 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
784 CString
CGit::GetCurrentBranch(bool fallback
)
787 //Run(_T("git.exe branch"),&branch);
789 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
790 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
792 return _T("(no branch)");
799 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
801 if (localBranch
.IsEmpty())
805 configName
.Format(L
"branch.%s.remote", (LPCTSTR
)localBranch
);
806 pullRemote
= GetConfigValue(configName
);
808 //Select pull-branch from current branch
809 configName
.Format(L
"branch.%s.merge", (LPCTSTR
)localBranch
);
810 pullBranch
= StripRefName(GetConfigValue(configName
));
813 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
816 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
818 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
821 CString
CGit::GetFullRefName(const CString
& shortRefName
)
825 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR
)shortRefName
);
826 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
827 return CString();//Error
829 return refName
.Tokenize(L
"\n", iStart
);
832 CString
CGit::StripRefName(CString refName
)
834 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
835 refName
= refName
.Mid(11);
836 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
837 refName
= refName
.Mid(5);
839 return refName
.Tokenize(_T("\n"),start
);
842 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
844 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
846 if ( sProjectRoot
.IsEmpty() )
850 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
853 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
856 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
864 fgets(s
, sizeof(s
), pFile
);
868 const char *pfx
= "ref: refs/heads/";
869 const int len
= 16;//strlen(pfx)
871 if ( !strncmp(s
, pfx
, len
) )
873 //# We're on a branch. It might not exist. But
874 //# HEAD looks good enough to be a branch.
875 CStringA
utf8Branch(s
+ len
);
876 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
877 sBranchOut
.TrimRight(_T(" \r\n\t"));
879 if ( sBranchOut
.IsEmpty() )
884 CStringA
utf8Hash(s
);
885 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
886 unicodeHash
.TrimRight(_T(" \r\n\t"));
887 if (CGitHash::IsValidSHA1(unicodeHash
))
888 sBranchOut
= unicodeHash
;
890 //# Assume this is a detached head.
891 sBranchOut
= _T("HEAD");
896 //# Assume this is a detached head.
905 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
908 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
912 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
914 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
916 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
918 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
920 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
922 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
924 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
928 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
930 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
932 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
937 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
943 CString
CGit::GetLogCmd(const CString
& range
, const CTGitPath
* path
, int mask
, bool paramonly
,
950 CString file
= _T(" --");
953 file
.Format(_T(" -- \"%s\""), (LPCTSTR
)path
->GetGitPathString());
957 if(mask
& LOG_INFO_STAT
)
958 param
+= _T(" --numstat ");
959 if(mask
& LOG_INFO_FILESTATE
)
960 param
+= _T(" --raw ");
962 if(mask
& LOG_INFO_FULLHISTORY
)
963 param
+= _T(" --full-history ");
965 if(mask
& LOG_INFO_BOUNDARY
)
966 param
+= _T(" --left-right --boundary ");
968 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
969 param
+= _T(" --all ");
971 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
972 param
+= _T(" --branches ");
974 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
977 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
980 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
981 param
+= _T(" --first-parent ");
983 if(mask
& CGit::LOG_INFO_NO_MERGE
)
984 param
+= _T(" --no-merges ");
986 if(mask
& CGit::LOG_INFO_FOLLOW
)
987 param
+= _T(" --follow ");
989 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
992 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
993 param
+= _T(" --full-diff ");
995 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
996 param
+= _T(" --simplify-by-decoration ");
1002 if (Filter
&& Filter
->m_NumberOfLogs
> 0)
1003 num
.Format(_T("-n%d"), Filter
->m_NumberOfLogs
);
1005 if( Filter
&& (Filter
->m_From
!= -1))
1007 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
1011 if( Filter
&& (Filter
->m_To
!= -1))
1013 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
1017 bool isgrep
= false;
1018 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1020 st1
.Format(_T(" --author=\"%s\"" ), (LPCTSTR
)Filter
->m_Author
);
1025 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1027 st1
.Format(_T(" --committer=\"%s\"" ), (LPCTSTR
)Filter
->m_Author
);
1032 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1034 st1
.Format(_T(" --grep=\"%s\"" ), (LPCTSTR
)Filter
->m_MessageFilter
);
1039 if(Filter
&& isgrep
)
1041 if(!Filter
->m_IsRegex
)
1042 param
+= _T(" --fixed-strings ");
1044 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1047 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1048 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1049 param
+= _T(" --topo-order");
1050 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1051 param
+= _T(" --date-order");
1053 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
1054 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), (LPCTSTR
)num
, (LPCTSTR
)param
);
1058 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1059 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1060 (LPCTSTR
)num
, (LPCTSTR
)param
, (LPCTSTR
)log
);
1068 void GetTempPath(CString
&path
)
1070 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1072 DWORD dwBufSize
=BUFSIZE
;
1073 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1074 lpPathBuffer
); // buffer for path
1075 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1079 path
.Format(_T("%s"),lpPathBuffer
);
1081 CString
GetTempFile()
1083 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1085 DWORD dwBufSize
=BUFSIZE
;
1086 TCHAR szTempName
[BUFSIZE
] = { 0 };
1089 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1090 lpPathBuffer
); // buffer for path
1091 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1095 // Create a temporary file.
1096 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1097 TEXT("Patch"), // temp file name prefix
1098 0, // create unique name
1099 szTempName
); // buffer for name
1107 return CString(szTempName
);
1111 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1113 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1114 if (result
== 0) return 0;
1115 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1122 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1123 CreateDirectory(lpBuffer
, NULL
);
1128 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1131 PROCESS_INFORMATION pi
;
1132 si
.cb
=sizeof(STARTUPINFO
);
1133 GetStartupInfo(&si
);
1135 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1136 psa
.bInheritHandle
=TRUE
;
1138 HANDLE hReadErr
, hWriteErr
;
1139 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1141 CString err
= CFormatMessageWrapper();
1142 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), (LPCTSTR
)err
.Trim());
1143 return TGIT_GIT_ERROR_OPEN_PIP
;
1146 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1147 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1149 if (houtfile
== INVALID_HANDLE_VALUE
)
1151 CString err
= CFormatMessageWrapper();
1152 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), (LPCTSTR
)err
.Trim());
1153 CloseHandle(hReadErr
);
1154 CloseHandle(hWriteErr
);
1155 return TGIT_GIT_ERROR_OPEN_PIP
;
1158 si
.wShowWindow
= SW_HIDE
;
1159 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1160 si
.hStdOutput
= houtfile
;
1161 si
.hStdError
= hWriteErr
;
1163 LPTSTR pEnv
= m_Environment
;
1164 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1166 if(cmd
.Find(_T("git")) == 0)
1167 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1169 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), (LPCTSTR
)cmd
);
1170 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1172 CString err
= CFormatMessageWrapper();
1173 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), (LPCTSTR
)err
.Trim());
1175 CloseHandle(hReadErr
);
1176 CloseHandle(hWriteErr
);
1177 CloseHandle(houtfile
);
1178 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1181 BYTE_VECTOR stderrVector
;
1182 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1184 ASYNCREADSTDERRTHREADARGS threadArguments
;
1185 threadArguments
.fileHandle
= hReadErr
;
1186 threadArguments
.pcall
= &pcall
;
1187 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1189 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1191 CloseHandle(hWriteErr
);
1192 CloseHandle(hReadErr
);
1195 WaitForSingleObject(thread
, INFINITE
);
1197 stderrVector
.push_back(0);
1198 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1201 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1203 CString err
= CFormatMessageWrapper();
1204 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), (LPCTSTR
)err
.Trim());
1205 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1208 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1210 CloseHandle(pi
.hThread
);
1211 CloseHandle(pi
.hProcess
);
1212 CloseHandle(houtfile
);
1216 git_repository
* CGit::GetGitRepository() const
1218 git_repository
* repo
= nullptr;
1219 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1223 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1227 // no need to parse a ref if it's already a 40-byte hash
1228 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1230 hash
= CGitHash(friendname
);
1234 int isHeadOrphan
= git_repository_head_unborn(repo
);
1235 if (isHeadOrphan
!= 0)
1238 if (isHeadOrphan
== 1)
1244 CAutoObject gitObject
;
1245 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1248 const git_oid
* oid
= git_object_id(gitObject
);
1252 hash
= CGitHash((char *)oid
->id
);
1257 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1259 // no need to parse a ref if it's already a 40-byte hash
1260 if (CGitHash::IsValidSHA1(friendname
))
1262 hash
= CGitHash(friendname
);
1268 CAutoRepository
repo(GetGitRepository());
1272 return GetHash(repo
, hash
, friendname
, true);
1276 CString branch
= FixBranchName(friendname
);
1277 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1278 branch
= friendname
;
1280 cmd
.Format(_T("git.exe rev-parse %s"), (LPCTSTR
)branch
);
1282 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1283 hash
= CGitHash(gitLastErr
.Trim());
1286 else if (friendname
== _T("HEAD")) // special check for unborn branch
1288 CString currentbranch
;
1289 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1298 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1303 cmd
=_T("git.exe ls-files -s -t -z");
1305 if (Run(cmd
, &cmdout
))
1308 if (outputlist
.ParserFromLsFile(cmdout
))
1310 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1311 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1315 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1319 if (ignoreSpaceAtEol
)
1320 ignore
+= _T(" --ignore-space-at-eol");
1321 if (ignoreSpaceChange
)
1322 ignore
+= _T(" --ignore-space-change");
1324 ignore
+= _T(" --ignore-all-space");
1325 if (ignoreBlankLines
)
1326 ignore
+= _T(" --ignore-blank-lines");
1328 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1331 if(rev1
== GIT_REV_ZERO
)
1332 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
);
1334 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev1
);
1338 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR
)ignore
, (LPCTSTR
)rev2
, (LPCTSTR
)rev1
);
1345 return outputlist
.ParserFromLog(out
);
1348 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1350 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1351 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1355 int CGit::GetTagList(STRING_VECTOR
&list
)
1357 if (this->m_IsUseLibGit2
)
1359 CAutoRepository
repo(GetGitRepository());
1363 CAutoStrArray tag_names
;
1365 if (git_tag_list(tag_names
, repo
))
1368 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1370 CStringA
tagName(tag_names
->strings
[i
]);
1371 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1374 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1380 CString cmd
, output
;
1381 cmd
=_T("git.exe tag -l");
1382 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1389 one
=output
.Tokenize(_T("\n"),pos
);
1391 list
.push_back(one
);
1393 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1395 else if (ret
== 1 && IsInitRepos())
1401 CString
CGit::GetGitLastErr(const CString
& msg
)
1403 if (this->m_IsUseLibGit2
)
1404 return GetLibGit2LastErr(msg
);
1405 else if (gitLastErr
.IsEmpty())
1406 return msg
+ _T("\nUnknown git.exe error.");
1409 CString lastError
= gitLastErr
;
1411 return msg
+ _T("\n") + lastError
;
1415 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1417 if (UsingLibGit2(cmd
))
1418 return GetLibGit2LastErr(msg
);
1419 else if (gitLastErr
.IsEmpty())
1420 return msg
+ _T("\nUnknown git.exe error.");
1423 CString lastError
= gitLastErr
;
1425 return msg
+ _T("\n") + lastError
;
1429 CString
CGit::GetLibGit2LastErr()
1431 const git_error
*libgit2err
= giterr_last();
1434 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1436 return _T("libgit2 returned: ") + lastError
;
1439 return _T("An error occoured in libgit2, but no message is available.");
1442 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1445 return msg
+ _T("\n") + GetLibGit2LastErr();
1446 return GetLibGit2LastErr();
1449 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1451 if(branchName
== "FETCH_HEAD")
1452 branchName
= DerefFetchHead();
1456 CString
CGit::FixBranchName(const CString
& branchName
)
1458 CString tempBranchName
= branchName
;
1459 FixBranchName_Mod(tempBranchName
);
1460 return tempBranchName
;
1463 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1467 CAutoRepository
repo(GetGitRepository());
1469 return true; // TODO: optimize error reporting
1471 CAutoReference tagRef
;
1472 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1475 CAutoReference branchRef
;
1476 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1485 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR
)name
, (LPCTSTR
)name
);
1486 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1492 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1502 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1506 CAutoRepository
repo(GetGitRepository());
1508 return false; // TODO: optimize error reporting
1512 prefix
= _T("refs/heads/");
1514 prefix
= _T("refs/tags/");
1517 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1523 CString cmd
, output
;
1525 cmd
= _T("git.exe show-ref ");
1527 cmd
+= _T("--heads ");
1529 cmd
+= _T("--tags ");
1531 cmd
+= _T("refs/heads/") + name
;
1532 cmd
+= _T(" refs/tags/") + name
;
1534 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1537 if (!output
.IsEmpty())
1544 CString
CGit::DerefFetchHead()
1547 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1548 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1549 int forMergeLineCount
= 0;
1551 std::string hashToReturn
;
1552 while(getline(fetchHeadFile
, line
))
1554 //Tokenize this line
1555 std::string::size_type prevPos
= 0;
1556 std::string::size_type pos
= line
.find('\t');
1557 if(pos
== std::string::npos
) continue; //invalid line
1559 std::string hash
= line
.substr(0, pos
);
1560 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1562 bool forMerge
= pos
== prevPos
;
1563 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1565 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1570 hashToReturn
= hash
;
1571 ++forMergeLineCount
;
1572 if(forMergeLineCount
> 1)
1573 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1577 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1580 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1584 bool headIsDetached
= false;
1587 CAutoRepository
repo(GetGitRepository());
1591 if (git_repository_head_detached(repo
) == 1)
1592 headIsDetached
= true;
1594 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1596 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1597 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1598 flags
= GIT_BRANCH_ALL
;
1599 else if (type
& BRANCH_REMOTE
)
1600 flags
= GIT_BRANCH_REMOTE
;
1602 CAutoBranchIterator it
;
1603 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1606 git_reference
* ref
= nullptr;
1607 git_branch_t branchType
;
1608 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1610 CAutoReference
autoRef(ref
);
1611 const char * name
= nullptr;
1612 if (git_branch_name(&name
, ref
))
1615 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1616 if (branchType
& GIT_BRANCH_REMOTE
)
1617 list
.push_back(_T("remotes/") + branchname
);
1620 if (git_branch_is_head(ref
))
1622 list
.push_back(branchname
);
1629 CString cmd
, output
;
1630 cmd
= _T("git.exe branch --no-color");
1632 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1634 else if (type
& BRANCH_REMOTE
)
1637 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1644 one
= output
.Tokenize(_T("\n"), pos
);
1645 one
.Trim(L
" \r\n\t");
1646 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1647 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1648 if (one
[0] == _T('*'))
1653 // check whether HEAD is detached
1654 CString currentHead
;
1655 if (one
.Left(1) == _T("(") && GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, currentHead
) == 1)
1657 headIsDetached
= true;
1661 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1662 one
= _T("remotes/") + one
;
1663 list
.push_back(one
);
1666 else if (ret
== 1 && IsInitRepos())
1670 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1671 list
.push_back(L
"FETCH_HEAD");
1673 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1675 if (current
&& !headIsDetached
)
1677 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1690 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1692 if (this->m_IsUseLibGit2
)
1694 CAutoRepository
repo(GetGitRepository());
1698 CAutoStrArray remotes
;
1699 if (git_remote_list(remotes
, repo
))
1702 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1704 CStringA
remote(remotes
->strings
[i
]);
1705 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1708 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1715 CString cmd
, output
;
1716 cmd
=_T("git.exe remote");
1717 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1724 one
=output
.Tokenize(_T("\n"),pos
);
1726 list
.push_back(one
);
1733 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1735 if (UsingLibGit2(GIT_CMD_FETCH
))
1737 CAutoRepository
repo(GetGitRepository());
1741 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1742 CAutoRemote gitremote
;
1743 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1746 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1747 callbacks
.credentials
= g_Git2CredCallback
;
1748 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1749 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
, &callbacks
) < 0)
1752 const git_remote_head
** heads
= nullptr;
1754 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1757 for (size_t i
= 0; i
< size
; i
++)
1759 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1761 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1763 // do not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1764 if (ref
.Find(_T("^{}")) >= 1)
1766 list
.push_back(shortname
);
1768 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1772 CString cmd
, out
, err
;
1773 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), (LPCTSTR
)remote
);
1774 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1776 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1783 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1784 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1785 if (one
.Find(_T("^{}")) >= 1)
1788 list
.push_back(one
);
1790 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1794 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1796 if (UsingLibGit2(GIT_CMD_PUSH
))
1798 CAutoRepository
repo(GetGitRepository());
1802 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1804 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1807 git_push_options pushOpts
= GIT_PUSH_OPTIONS_INIT
;
1808 git_remote_callbacks
& callbacks
= pushOpts
.callbacks
;
1809 callbacks
.credentials
= g_Git2CredCallback
;
1810 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1811 std::vector
<CStringA
> refspecs
;
1812 for (auto ref
: list
)
1813 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1815 std::vector
<char*> vc
;
1816 vc
.reserve(refspecs
.size());
1817 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1818 git_strarray specs
= { &vc
[0], vc
.size() };
1820 if (git_remote_push(remote
, &specs
, &pushOpts
) < 0)
1825 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1826 for (auto ref
: list
)
1828 CString refspec
= _T(":") + ref
;
1829 mgtPush
.AddFile(refspec
);
1832 BOOL cancel
= FALSE
;
1833 mgtPush
.Execute(cancel
);
1839 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1841 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1842 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1846 int CGit::GetRefList(STRING_VECTOR
&list
)
1848 if (this->m_IsUseLibGit2
)
1850 CAutoRepository
repo(GetGitRepository());
1854 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1857 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1863 CString cmd
, output
;
1864 cmd
=_T("git.exe show-ref -d");
1865 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1872 one
=output
.Tokenize(_T("\n"),pos
);
1873 int start
=one
.Find(_T(" "),0);
1877 name
=one
.Right(one
.GetLength()-start
-1);
1878 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1879 list
.push_back(name
);
1882 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1884 else if (ret
== 1 && IsInitRepos())
1890 typedef struct map_each_ref_payload
{
1891 git_repository
* repo
;
1892 MAP_HASH_NAME
* map
;
1893 } map_each_ref_payload
;
1895 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1897 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1899 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1901 CAutoObject gitObject
;
1902 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1905 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1907 str
+= _T("^{}"); // deref tag
1908 CAutoObject derefedTag
;
1909 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1911 gitObject
.Swap(derefedTag
);
1914 const git_oid
* oid
= git_object_id(gitObject
);
1918 CGitHash
hash((char *)oid
->id
);
1919 (*payloadContent
->map
)[hash
].push_back(str
);
1923 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1927 map_each_ref_payload payloadContent
= { repo
, &map
};
1929 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1932 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1934 std::sort(it
->second
.begin(), it
->second
.end());
1940 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1942 if (this->m_IsUseLibGit2
)
1944 CAutoRepository
repo(GetGitRepository());
1948 return GetMapHashToFriendName(repo
, map
);
1952 CString cmd
, output
;
1953 cmd
=_T("git.exe show-ref -d");
1954 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1961 one
=output
.Tokenize(_T("\n"),pos
);
1962 int start
=one
.Find(_T(" "),0);
1966 name
=one
.Right(one
.GetLength()-start
-1);
1969 hash
=one
.Left(start
);
1971 map
[CGitHash(hash
)].push_back(name
);
1975 else if (ret
== 1 && IsInitRepos())
1981 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1983 CAutoConfig
config(true);
1984 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1986 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1988 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1989 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1990 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1991 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1996 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1998 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1999 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
2002 static void SetLibGit2TemplatePath(const CString
&value
)
2004 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
2005 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
2008 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2010 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
2011 CString str
= msysdir
;
2012 if (!str
.IsEmpty() && FileExists(str
+ _T("\\git.exe")))
2014 CGit::ms_LastMsysGitDir
= str
;
2018 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2022 // first, search PATH if git/bin directory is already present
2025 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2026 msysdir
= CGit::ms_LastMsysGitDir
;
2031 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2032 str
= msyslocalinstalldir
;
2033 str
.TrimRight(_T("\\"));
2037 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2038 str
= msysinstalldir
;
2039 str
.TrimRight(_T("\\"));
2044 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2045 str
= msysinstalldir
;
2046 str
.TrimRight(_T("\\"));
2050 if (FileExists(str
+ _T("\\bin\\git.exe")))
2052 else if (FileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR
)str
);
2060 CGit::ms_LastMsysGitDir
= str
;
2065 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2069 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2076 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2077 this->m_Environment
.clear();
2078 m_Environment
.CopyProcessEnvironment();
2079 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2081 // set HOME if not set already
2083 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
2085 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2088 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2089 if (sshclient
.IsEmpty())
2090 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2092 if(!sshclient
.IsEmpty())
2094 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2095 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2099 TCHAR sPlink
[MAX_PATH
] = {0};
2100 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
2101 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2103 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPlink.exe"));
2104 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2105 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2110 TCHAR sAskPass
[MAX_PATH
] = {0};
2111 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
2112 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2115 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2116 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2117 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2118 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2122 if (!FindAndSetGitExePath(bFallback
))
2126 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2127 static CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2128 static int prefixes_len
[] = { 8, 8, 0 };
2129 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2135 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2136 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2140 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
2141 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\.."));
2142 CGit::ms_MsysGitRootDir
= msysGitDir
;
2144 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2145 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2147 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR
)CGit::ms_LastMsysGitDir
);
2148 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR
)CGit::ms_MsysGitRootDir
);
2149 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), (LPCTSTR
)g_Git
.GetGitSystemConfig());
2151 // Configure libgit2 search paths
2152 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2153 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2154 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2155 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 };
2156 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2157 if (!(ms_bCygwinGit
|| ms_bMsys2Git
))
2158 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2160 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2162 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2163 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2165 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2166 // register filter only once
2167 if (!git_filter_lookup("filter"))
2169 static CString binDirPrefixes
[] = { L
"\\..\\usr\\bin", L
"\\..\\bin", L
"" };
2171 for (const CString
& binDirPrefix
: binDirPrefixes
)
2173 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2174 if (PathFileExists(possibleShExe
))
2177 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2178 sh
.Format(L
"\"%s\"", (LPCTSTR
)temp
);
2179 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2180 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2184 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2189 m_bInitialized
= TRUE
;
2193 CString
CGit::GetHomeDirectory() const
2195 const wchar_t * homeDir
= wget_windows_home_directory();
2196 return CString(homeDir
, (int)wcslen(homeDir
));
2199 CString
CGit::GetGitLocalConfig() const
2202 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2203 path
+= _T("config");
2207 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2209 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2212 CString
CGit::GetGitGlobalConfig() const
2214 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2217 CString
CGit::GetGitGlobalXDGConfigPath() const
2219 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2222 CString
CGit::GetGitGlobalXDGConfig() const
2224 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2227 CString
CGit::GetGitSystemConfig() const
2229 const wchar_t * systemConfig
= wget_msysgit_etc();
2230 return CString(systemConfig
, (int)wcslen(systemConfig
));
2233 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2235 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2237 CAutoRepository repo
= GetGitRepository();
2241 if (git_repository_head_unborn(repo
))
2244 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2245 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2246 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2248 CAutoStatusList status
;
2249 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2252 return (0 == git_status_list_entrycount(status
));
2257 cmd
=_T("git.exe rev-parse --verify HEAD");
2259 if(Run(cmd
,&out
,CP_UTF8
))
2262 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2263 if(Run(cmd
,&out
,CP_UTF8
))
2266 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2267 if(Run(cmd
,&out
,CP_UTF8
))
2270 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2271 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2276 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2279 for (int i
= 0; i
< list
.GetCount(); ++i
)
2281 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2287 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2291 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2293 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2295 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2299 // if the filenames only differ in case, we have to pass "-f"
2300 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2302 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR
)force
, (LPCTSTR
)path
.GetGitPathString(), (LPCTSTR
)path
.GetGitOldPathString());
2303 if (Run(cmd
, &err
, CP_UTF8
))
2306 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitOldPathString());
2307 if (Run(cmd
, &err
, CP_UTF8
))
2310 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2311 { //To init git repository, there are not HEAD, so we can use git reset command
2312 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2314 if (Run(cmd
, &err
, CP_UTF8
))
2319 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR
)commit
, (LPCTSTR
)path
.GetGitPathString());
2320 if (Run(cmd
, &err
, CP_UTF8
))
2324 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2326 cmd
.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR
)path
.GetGitPathString());
2327 if (Run(cmd
, &err
, CP_UTF8
))
2334 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2339 if (git_repository_index(index
.GetPointer(), repo
))
2342 return git_index_has_conflicts(index
);
2345 int CGit::HasWorkingTreeConflicts()
2347 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2349 CAutoRepository
repo(GetGitRepository());
2353 return HasWorkingTreeConflicts(repo
);
2356 CString cmd
= _T("git.exe ls-files -u -t -z");
2359 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2362 return output
.IsEmpty() ? 0 : 1;
2365 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2367 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2369 CAutoRepository
repo(GetGitRepository());
2373 CGitHash fromHash
, toHash
, baseHash
;
2374 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2377 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2381 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2384 baseHash
= baseOid
.id
;
2387 *commonAncestor
= baseHash
;
2389 return fromHash
== baseHash
;
2393 CGitHash basehash
,hash
;
2395 cmd
.Format(_T("git.exe merge-base %s %s"), (LPCTSTR
)FixBranchName(to
), (LPCTSTR
)FixBranchName(from
));
2397 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2401 basehash
= base
.Trim();
2403 GetHash(hash
, from
);
2406 *commonAncestor
= basehash
;
2408 return hash
== basehash
;
2411 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2414 for (int i
= 0; i
< 4; ++i
)
2417 ret
|= hash
.m_hash
[i
];
2422 int CGit::RefreshGitIndex()
2424 if(g_Git
.m_IsUseGitDLL
)
2426 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2429 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2440 cmd
=_T("git.exe update-index --refresh");
2441 return Run(cmd
, &output
, CP_UTF8
);
2445 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2447 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2449 CAutoRepository
repo(GetGitRepository());
2454 if (GetHash(repo
, hash
, Refname
))
2458 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2462 if (git_commit_tree(tree
.GetPointer(), commit
))
2465 CAutoTreeEntry entry
;
2466 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2470 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2473 FILE *file
= nullptr;
2474 _tfopen_s(&file
, outputfile
, _T("wb"));
2475 if (file
== nullptr)
2477 giterr_set_str(GITERR_NONE
, "Could not create file.");
2481 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2486 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2488 giterr_set_str(GITERR_OS
, "Could not write to file.");
2497 else if (g_Git
.m_IsUseGitDLL
)
2499 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2502 g_Git
.CheckAndInitDll();
2503 CStringA ref
, patha
, outa
;
2504 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2505 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2506 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2507 ::DeleteFile(outputfile
);
2508 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2509 outa
.ReleaseBuffer();
2513 catch (const char * msg
)
2515 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2520 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2527 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR
)Refname
, (LPCTSTR
)path
.GetGitPathString());
2528 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2532 void CEnvironment::clear()
2537 bool CEnvironment::empty()
2539 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2542 CEnvironment::operator LPTSTR()
2546 return &__super::at(0);
2549 void CEnvironment::CopyProcessEnvironment()
2553 TCHAR
*porig
= GetEnvironmentStrings();
2555 while(*p
!=0 || *(p
+1) !=0)
2556 this->push_back(*p
++);
2558 push_back(_T('\0'));
2559 push_back(_T('\0'));
2561 FreeEnvironmentStrings(porig
);
2564 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2567 for (size_t i
= 0; i
< size(); ++i
)
2571 CString sname
= str
.Tokenize(_T("="),start
);
2572 if(sname
.CompareNoCase(name
) == 0)
2574 return &(*this)[i
+start
];
2581 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2584 for (i
= 0; i
< size(); ++i
)
2586 CString str
= &(*this)[i
];
2588 CString sname
= str
.Tokenize(_T("="),start
);
2589 if(sname
.CompareNoCase(name
) == 0)
2598 if (!value
) // as we haven't found the variable we want to remove, just return
2600 if (i
== 0) // make inserting into an empty environment work
2602 this->push_back(_T('\0'));
2605 i
-= 1; // roll back terminate \0\0
2606 this->push_back(_T('\0'));
2609 CEnvironment::iterator it
;
2613 while(*it
&& i
<size())
2620 if (value
== nullptr) // remove the variable
2628 this->insert(it
,*name
++);
2633 this->insert(it
, _T('='));
2639 this->insert(it
,*value
++);
2646 void CEnvironment::AddToPath(CString value
)
2648 value
.TrimRight(L
"\\");
2649 if (value
.IsEmpty())
2652 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2654 // do not double add paths to %PATH%
2655 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2660 SetEnv(L
"PATH", path
);
2663 int CGit::GetGitEncode(TCHAR
* configkey
)
2665 CString str
=GetConfigValue(configkey
);
2670 return CUnicodeUtils::GetCPCode(str
);
2674 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2680 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2685 diff
= GetGitDiff();
2687 git_open_diff(&diff
, arg
);
2691 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2702 isStat
= !!strstr(arg
, "stat");
2707 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2709 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2718 for (int j
= 0; j
< count
; ++j
)
2727 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2728 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2729 &mode
,&IsBin
,&inc
,&dec
);
2731 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2732 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2734 path
.SetFromGit(strnewname
,&stroldname
);
2735 path
.ParserAction((BYTE
)mode
);
2739 path
.m_StatAdd
=_T("-");
2740 path
.m_StatDel
=_T("-");
2744 path
.m_StatAdd
.Format(_T("%d"),inc
);
2745 path
.m_StatDel
.Format(_T("%d"),dec
);
2747 PathList
->AddPath(path
);
2749 git_diff_flush(diff
);
2752 git_close_diff(diff
);
2757 int CGit::GetShortHASHLength() const
2762 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2766 REF_TYPE type
= CGit::UNKNOWN
;
2768 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2770 type
= CGit::LOCAL_BRANCH
;
2773 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2775 type
= CGit::REMOTE_BRANCH
;
2777 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2781 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2784 shortname
=_T("stash");
2786 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2788 if (shortname
.Find(_T("good")) == 0)
2790 type
= CGit::BISECT_GOOD
;
2791 shortname
= _T("good");
2794 if (shortname
.Find(_T("bad")) == 0)
2796 type
= CGit::BISECT_BAD
;
2797 shortname
= _T("bad");
2800 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2804 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2806 type
= CGit::UNKNOWN
;
2810 type
= CGit::UNKNOWN
;
2820 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2822 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2825 void CGit::SetGit2CredentialCallback(void* callback
)
2827 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2830 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2832 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2835 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2838 if (rev2
== GitRev::GetWorkingCopy())
2839 cmd
.Format(_T("git.exe diff --stat -p %s --"), (LPCTSTR
)rev1
);
2840 else if (rev1
== GitRev::GetWorkingCopy())
2841 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), (LPCTSTR
)rev2
);
2852 if (diffContext
>= 0)
2853 unified
.Format(_T(" --unified=%d"), diffContext
);
2854 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), (LPCTSTR
)merge
, (LPCTSTR
)unified
, (LPCTSTR
)rev1
, (LPCTSTR
)rev2
);
2857 if (!path
.IsEmpty())
2860 cmd
+= path
.GetGitPathString();
2867 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2869 ATLASSERT(payload
&& text
);
2870 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2871 fwrite("\n", 1, 1, (FILE *)payload
);
2874 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2876 ATLASSERT(payload
&& line
);
2877 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2878 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2879 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2883 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2885 ATLASSERT(repo
&& identifier
&& tree
);
2887 /* try to resolve identifier */
2889 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2893 return GIT_ENOTFOUND
;
2896 switch (git_object_type(obj
))
2899 *tree
= (git_tree
*)obj
.Detach();
2901 case GIT_OBJ_COMMIT
:
2902 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2905 err
= GIT_ENOTFOUND
;
2911 /* use libgit2 get unified diff */
2912 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 */)
2914 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2915 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2917 CAutoRepository
repo(g_Git
.GetGitRepository());
2921 int isHeadOrphan
= git_repository_head_unborn(repo
);
2922 if (isHeadOrphan
== 1)
2924 else if (isHeadOrphan
!= 0)
2927 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2928 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2929 char *buf
= pathA
.GetBuffer();
2930 if (!pathA
.IsEmpty())
2932 opts
.pathspec
.strings
= &buf
;
2933 opts
.pathspec
.count
= 1;
2937 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2942 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2945 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2948 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2951 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2954 if (git_diff_merge(diff
, diff2
))
2959 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2962 if (tree1
.IsEmpty())
2970 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2973 if (tree2
.IsEmpty())
2975 /* don't check return value, there are not parent commit at first commit*/
2976 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2978 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2980 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2984 CAutoDiffStats stats
;
2985 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2988 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2990 statCallback(statBuf
, data
);
2992 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2995 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2998 if (git_patch_print(patch
, callback
, data
))
3002 pathA
.ReleaseBuffer();
3007 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
3009 if (UsingLibGit2(GIT_CMD_DIFF
))
3011 FILE *file
= nullptr;
3012 _tfopen_s(&file
, patchfile
, _T("w"));
3013 if (file
== nullptr)
3015 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
);
3022 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3023 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3027 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3029 ATLASSERT(payload
&& text
);
3030 CStringA
*str
= (CStringA
*) payload
;
3031 str
->Append(text
->ptr
, (int)text
->size
);
3032 str
->AppendChar('\n');
3035 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3037 ATLASSERT(payload
&& line
);
3038 CStringA
*str
= (CStringA
*) payload
;
3039 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3040 str
->Append(&line
->origin
, 1);
3041 str
->Append(line
->content
, (int)line
->content_len
);
3045 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3047 if (UsingLibGit2(GIT_CMD_DIFF
))
3048 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
);
3052 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3054 int ret
= Run(cmd
, &vector
);
3055 if (!vector
.empty())
3057 vector
.push_back(0); // vector is not NUL terminated
3058 buffer
->Append((char *)&vector
[0]);
3064 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3066 if (UsingLibGit2(GIT_CMD_REVERT
))
3068 CAutoRepository
repo(GetGitRepository());
3073 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3076 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3077 revert_opts
.mainline
= parent
;
3078 int result
= git_revert(repo
, commit
, &revert_opts
);
3080 return !result
? 0 : -1;
3086 merge
.Format(_T("-m %d "), parent
);
3087 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR
)merge
, (LPCTSTR
)hash
.ToString());
3088 gitLastErr
= cmd
+ _T("\n");
3089 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3101 int CGit::DeleteRef(const CString
& reference
)
3103 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3105 CAutoRepository
repo(GetGitRepository());
3110 if (reference
.Right(3) == _T("^{}"))
3111 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3113 refA
= CUnicodeUtils::GetUTF8(reference
);
3116 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3120 if (git_reference_is_tag(ref
))
3121 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3122 else if (git_reference_is_branch(ref
))
3123 result
= git_branch_delete(ref
);
3124 else if (git_reference_is_remote(ref
))
3125 result
= git_branch_delete(ref
);
3127 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3133 CString cmd
, shortname
;
3134 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3135 cmd
.Format(_T("git.exe branch -D -- %s"), (LPCTSTR
)shortname
);
3136 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3137 cmd
.Format(_T("git.exe tag -d -- %s"), (LPCTSTR
)shortname
);
3138 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3139 cmd
.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR
)shortname
);
3142 gitLastErr
= L
"unsupported reference type: " + reference
;
3146 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3154 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3156 if (PathFileExists(filename
))
3158 FILE *pFile
= nullptr;
3159 _tfopen_s(&pFile
, filename
, _T("r"));
3165 char s
[8196] = { 0 };
3166 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3169 str
+= CStringA(s
, read
);
3172 msg
= CUnicodeUtils::GetUnicode(str
);
3173 msg
.Replace(_T("\r\n"), _T("\n"));
3174 msg
.TrimRight(_T("\n"));
3178 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3179 return true; // load no further files
3184 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3187 return GetInitAddList(result
);
3193 count
= filterlist
->GetCount();
3195 CString head
= _T("HEAD");
3197 head
= _T("HEAD~1");
3199 for (int i
= 0; i
< count
; ++i
)
3203 if (ms_bCygwinGit
|| ms_bMsys2Git
)
3205 // Prevent showing all files as modified when using cygwin's git
3207 cmd
= _T("git.exe status --");
3209 cmd
.Format(_T("git.exe status -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3214 // also list staged files which will be in the commit
3215 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3218 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3220 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3223 if (Run(cmd
, &cmdout
, &cmdErr
))
3225 int last
= cmdErr
.RevertFind(0, -1);
3227 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3228 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3231 out
.append(cmdout
, 0);
3233 result
.ParserFromLog(out
);
3235 // handle delete conflict case, when remote : modified, local : deleted.
3236 for (int i
= 0; i
< count
; ++i
)
3242 cmd
= _T("git.exe ls-files -u -t -z");
3244 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3248 CTGitPathList conflictlist
;
3249 conflictlist
.ParserFromLog(cmdout
);
3250 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3252 CTGitPath
* p
= result
.LookForGitPath(conflictlist
[j
].GetGitPathString());
3254 p
->m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3256 result
.AddPath(conflictlist
[j
]);
3260 // handle source files of file renames/moves (issue #860)
3261 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3262 for (int i
= 0; i
< count
; ++i
)
3268 cmd
= _T("git.exe ls-files -d -z");
3270 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR
)(*filterlist
)[i
].GetGitPathString());
3274 CTGitPathList deletelist
;
3275 deletelist
.ParserFromLog(cmdout
, true);
3276 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3278 CTGitPath
* p
= result
.LookForGitPath(deletelist
[j
].GetGitPathString());
3280 result
.AddPath(deletelist
[j
]);