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 int CGit::m_LogEncode
=CP_UTF8
;
38 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
40 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
42 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
45 const wchar_t* base
= path
;
46 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
48 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
51 *buf
= L
'\0'; /* reserved a byte via initial subtract */
53 while (*path
== term
|| *path
== L
';')
56 return (path
!= base
) ? path
: NULL
;
59 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
62 return _tstat(lpszFileName
, &st
) == 0;
65 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
67 TCHAR buf
[MAX_PATH
] = { 0 };
69 // search in all paths defined in PATH
70 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
72 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
74 // ensure trailing slash
75 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
76 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
78 const size_t len
= _tcslen(buf
);
80 if ((len
+ filename
.GetLength()) < MAX_PATH
)
81 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
96 static BOOL
FindGitPath()
99 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
103 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
106 _tgetenv_s(&size
, env
, size
, _T("PATH"));
108 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
109 if (!gitExeDirectory
.IsEmpty())
111 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
112 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
113 if (CGit::ms_LastMsysGitDir
.GetLength() > 12 && (CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir
.Right(12) == _T("\\mingw64\\bin")))
115 // prefer cmd directory as early Git for Windows 2.x releases only had this
116 CString installRoot
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd\\git.exe");
117 if (FileExists(installRoot
))
118 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 12) + _T("\\cmd");
120 if (CGit::ms_LastMsysGitDir
.GetLength() > 4 && CGit::ms_LastMsysGitDir
.Right(4) == _T("\\cmd"))
122 // often the msysgit\cmd folder is on the %PATH%, but
123 // that git.exe does not work, so try to guess the bin folder
124 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
125 if (FileExists(binDir
))
126 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
134 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
136 CString filename
= executable
;
138 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
139 filename
+= _T(".exe");
141 if (FileExists(filename
))
144 filename
= FindFileOnPath(filename
, env
);
145 if (!filename
.IsEmpty())
151 static bool g_bSortLogical
;
152 static bool g_bSortLocalBranchesFirst
;
153 static bool g_bSortTagsReversed
;
154 static git_cred_acquire_cb g_Git2CredCallback
;
155 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
157 static void GetSortOptions()
159 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
161 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
162 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
163 if (g_bSortLocalBranchesFirst
)
164 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
165 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
166 if (!g_bSortTagsReversed
)
167 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
170 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
173 return StrCmpLogicalW(left
, right
) < 0;
174 return StrCmpI(left
, right
) < 0;
177 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
180 return StrCmpLogicalW(left
, right
) > 0;
181 return StrCmpI(left
, right
) > 0;
184 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
186 if (g_bSortLocalBranchesFirst
)
188 int leftIsRemote
= left
.Find(_T("remotes/"));
189 int rightIsRemote
= right
.Find(_T("remotes/"));
191 if (leftIsRemote
== 0 && rightIsRemote
< 0)
193 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
197 return StrCmpLogicalW(left
, right
) < 0;
198 return StrCmpI(left
, right
) < 0;
201 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
203 CString
CGit::ms_LastMsysGitDir
;
204 CString
CGit::ms_MsysGitRootDir
;
205 int CGit::ms_LastMsysGitVersion
= 0;
211 GetCurrentDirectory(MAX_PATH
, CStrBuf(m_CurrentDir
, MAX_PATH
));
212 m_IsGitDllInited
= false;
214 m_GitSimpleListDiff
=0;
215 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
216 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
217 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
219 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
222 this->m_bInitialized
=false;
224 m_critGitDllSec
.Init();
231 git_close_diff(m_GitDiff
);
234 if(this->m_GitSimpleListDiff
)
236 git_close_diff(m_GitSimpleListDiff
);
237 m_GitSimpleListDiff
=0;
241 bool CGit::IsBranchNameValid(const CString
& branchname
)
243 if (branchname
.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
245 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
247 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
248 return !!git_reference_is_valid_name(branchA
);
251 static bool IsPowerShell(CString cmd
)
254 int powerShellPos
= cmd
.Find(_T("powershell"));
255 if (powerShellPos
< 0)
258 // found the word powershell, check that it is the command and not any parameter
259 int end
= cmd
.GetLength();
260 if (cmd
.Find(_T('"')) == 0)
262 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
263 if (secondDoubleQuote
> 0)
264 end
= secondDoubleQuote
;
268 int firstSpace
= cmd
.Find(_T(' '));
273 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
276 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
278 SECURITY_ATTRIBUTES sa
;
279 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
280 CAutoGeneralHandle hStdioFile
;
282 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
283 sa
.lpSecurityDescriptor
=NULL
;
284 sa
.bInheritHandle
=TRUE
;
285 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
287 CString err
= CFormatMessageWrapper();
288 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
289 return TGIT_GIT_ERROR_OPEN_PIP
;
291 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
293 CString err
= CFormatMessageWrapper();
294 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
295 return TGIT_GIT_ERROR_OPEN_PIP
;
300 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
301 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
304 STARTUPINFO si
= { 0 };
305 PROCESS_INFORMATION pi
;
306 si
.cb
=sizeof(STARTUPINFO
);
309 si
.hStdError
= hWriteErr
;
311 si
.hStdError
= hWrite
;
313 si
.hStdOutput
=hStdioFile
;
315 si
.hStdOutput
=hWrite
;
317 si
.wShowWindow
=SW_HIDE
;
318 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
320 LPTSTR pEnv
= m_Environment
;
321 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
323 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
325 // 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,
326 // 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)
327 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
328 if (IsPowerShell(cmd
))
329 dwFlags
|= CREATE_NEW_CONSOLE
;
331 dwFlags
|= DETACHED_PROCESS
;
333 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
334 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
336 if (ms_bCygwinGit
&& cmd
.Find(_T("git")) == 0 && cmd
.Find(L
"git.exe config ") == -1)
338 cmd
.Replace(_T('\\'), _T('/'));
339 cmd
.Replace(_T("\""), _T("\\\""));
340 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
342 else if(cmd
.Find(_T("git")) == 0)
344 int firstSpace
= cmd
.Find(_T(" "));
346 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
348 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
351 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
352 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
354 CString err
= CFormatMessageWrapper();
355 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
356 return TGIT_GIT_ERROR_CREATE_PROCESS
;
364 *hReadOut
= hRead
.Detach();
366 *hErrReadOut
= hReadErr
.Detach();
370 //Must use sperate function to convert ANSI str to union code string
371 //Becuase A2W use stack as internal convert buffer.
372 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
379 len
= (int)strlen((const char*)p
);
384 int currentContentLen
= str
->GetLength();
385 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
386 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
387 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
390 // This method was originally used to check for orphaned branches
391 BOOL
CGit::CanParseRev(CString ref
)
397 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
407 // Checks if we have an orphaned HEAD
408 BOOL
CGit::IsInitRepos()
411 if (GetHash(hash
, _T("HEAD")) != 0)
413 return hash
.IsEmpty() ? TRUE
: FALSE
;
416 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
418 PASYNCREADSTDERRTHREADARGS pDataArray
;
419 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
422 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
423 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
425 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
432 int CGit::Run(CGitCall
* pcall
)
434 PROCESS_INFORMATION pi
;
435 CAutoGeneralHandle hRead
, hReadErr
;
436 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
437 return TGIT_GIT_ERROR_CREATE_PROCESS
;
439 CAutoGeneralHandle
piThread(pi
.hThread
);
440 CAutoGeneralHandle
piProcess(pi
.hProcess
);
442 ASYNCREADSTDERRTHREADARGS threadArguments
;
443 threadArguments
.fileHandle
= hReadErr
;
444 threadArguments
.pcall
= pcall
;
445 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
448 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
450 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
452 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
453 if(!bAborted
)//For now, flush output when command aborted.
454 if(pcall
->OnOutputData(data
,readnumber
))
461 WaitForSingleObject(thread
, INFINITE
);
463 WaitForSingleObject(pi
.hProcess
, INFINITE
);
466 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
468 CString err
= CFormatMessageWrapper();
469 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
470 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
473 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
477 class CGitCall_ByteVector
: public CGitCall
480 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
481 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
483 if (!m_pvector
|| size
== 0)
485 size_t oldsize
=m_pvector
->size();
486 m_pvector
->resize(m_pvector
->size()+size
);
487 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
490 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
492 if (!m_pvectorErr
|| size
== 0)
494 size_t oldsize
= m_pvectorErr
->size();
495 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
496 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
499 BYTE_VECTOR
* m_pvector
;
500 BYTE_VECTOR
* m_pvectorErr
;
503 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
505 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
508 int CGit::Run(CString cmd
, CString
* output
, int code
)
512 ret
= Run(cmd
, output
, &err
, code
);
514 if (output
&& !err
.IsEmpty())
516 if (!output
->IsEmpty())
523 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
525 BYTE_VECTOR vector
, vectorErr
;
528 ret
= Run(cmd
, &vector
, &vectorErr
);
530 ret
= Run(cmd
, &vector
);
533 StringAppend(output
, &(vector
[0]), code
);
537 vectorErr
.push_back(0);
538 StringAppend(outputErr
, &(vectorErr
[0]), code
);
544 class CGitCallCb
: public CGitCall
547 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
549 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
554 int oldEndPos
= m_buffer
.GetLength();
555 memcpy(m_buffer
.GetBuffer(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
556 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
558 // Break into lines and feed to m_recv
560 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
562 m_recv(m_buffer
.Left(eolPos
));
563 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
568 virtual bool OnOutputErrData(const BYTE
*, size_t) override
570 return false; // Ignore error output for now
573 virtual void OnEnd() override
575 if (!m_buffer
.IsEmpty())
577 m_buffer
.Empty(); // Just for sure
581 GitReceiverFunc m_recv
;
585 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
587 CGitCallCb
call(cmd
, recv
);
591 CString
CGit::GetUserName(void)
594 env
.CopyProcessEnvironment();
595 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
596 if (!envname
.IsEmpty())
598 return GetConfigValue(L
"user.name");
600 CString
CGit::GetUserEmail(void)
603 env
.CopyProcessEnvironment();
604 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
605 if (!envmail
.IsEmpty())
608 return GetConfigValue(L
"user.email");
611 CString
CGit::GetConfigValue(const CString
& name
)
614 if(this->m_IsUseGitDLL
)
616 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
625 key
= CUnicodeUtils::GetUTF8(name
);
629 if (git_get_config(key
, CStrBufA(value
, 4096), 4096))
632 catch (const char *msg
)
634 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
638 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
644 cmd
.Format(L
"git.exe config %s", name
);
645 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
646 if (configValue
.IsEmpty())
648 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
652 bool CGit::GetConfigValueBool(const CString
& name
)
654 CString configValue
= GetConfigValue(name
);
655 configValue
.MakeLower();
657 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
663 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
665 CString configValue
= GetConfigValue(name
);
667 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
672 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
674 if(this->m_IsUseGitDLL
)
676 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
685 CStringA keya
, valuea
;
686 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
687 valuea
= CUnicodeUtils::GetUTF8(value
);
691 return [=]() { return get_set_config(keya
, valuea
, type
); }();
693 catch (const char *msg
)
695 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
706 option
= _T("--global");
709 option
= _T("--system");
714 CString mangledValue
= value
;
715 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
716 mangledValue
.Replace(_T("\""), _T("\\\""));
717 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, mangledValue
);
719 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
727 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
729 if(this->m_IsUseGitDLL
)
731 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
740 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
744 return [=]() { return get_set_config(keya
, nullptr, type
); }();
746 catch (const char *msg
)
748 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
759 option
= _T("--global");
762 option
= _T("--system");
767 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
769 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
777 CString
CGit::GetCurrentBranch(bool fallback
)
780 //Run(_T("git.exe branch"),&branch);
782 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
783 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
785 return _T("(no branch)");
792 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
794 if (localBranch
.IsEmpty())
798 configName
.Format(L
"branch.%s.remote", localBranch
);
799 pullRemote
= GetConfigValue(configName
);
801 //Select pull-branch from current branch
802 configName
.Format(L
"branch.%s.merge", localBranch
);
803 pullBranch
= StripRefName(GetConfigValue(configName
));
806 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
809 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
811 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
814 CString
CGit::GetFullRefName(const CString
& shortRefName
)
818 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
819 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
820 return CString();//Error
822 return refName
.Tokenize(L
"\n", iStart
);
825 CString
CGit::StripRefName(CString refName
)
827 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
828 refName
= refName
.Mid(11);
829 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
830 refName
= refName
.Mid(5);
832 return refName
.Tokenize(_T("\n"),start
);
835 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
837 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
839 if ( sProjectRoot
.IsEmpty() )
843 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
846 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
849 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
857 fgets(s
, sizeof(s
), pFile
);
861 const char *pfx
= "ref: refs/heads/";
862 const int len
= 16;//strlen(pfx)
864 if ( !strncmp(s
, pfx
, len
) )
866 //# We're on a branch. It might not exist. But
867 //# HEAD looks good enough to be a branch.
868 CStringA
utf8Branch(s
+ len
);
869 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
870 sBranchOut
.TrimRight(_T(" \r\n\t"));
872 if ( sBranchOut
.IsEmpty() )
877 CStringA
utf8Hash(s
);
878 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
879 unicodeHash
.TrimRight(_T(" \r\n\t"));
880 if (CGitHash::IsValidSHA1(unicodeHash
))
881 sBranchOut
= unicodeHash
;
883 //# Assume this is a detached head.
884 sBranchOut
= _T("HEAD");
889 //# Assume this is a detached head.
898 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
901 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
905 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
907 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
909 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
911 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
913 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
915 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
917 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
921 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
923 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
925 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
930 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
936 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
943 CString file
= _T(" --");
946 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
949 num
.Format(_T("-n%d"),count
);
953 if(mask
& LOG_INFO_STAT
)
954 param
+= _T(" --numstat ");
955 if(mask
& LOG_INFO_FILESTATE
)
956 param
+= _T(" --raw ");
958 if(mask
& LOG_INFO_FULLHISTORY
)
959 param
+= _T(" --full-history ");
961 if(mask
& LOG_INFO_BOUNDARY
)
962 param
+= _T(" --left-right --boundary ");
964 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
965 param
+= _T(" --all ");
967 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
968 param
+= _T(" --branches ");
970 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
973 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
976 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
977 param
+= _T(" --first-parent ");
979 if(mask
& CGit::LOG_INFO_NO_MERGE
)
980 param
+= _T(" --no-merges ");
982 if(mask
& CGit::LOG_INFO_FOLLOW
)
983 param
+= _T(" --follow ");
985 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
988 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
989 param
+= _T(" --full-diff ");
991 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
992 param
+= _T(" --simplify-by-decoration ");
998 if( Filter
&& (Filter
->m_From
!= -1))
1000 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
1004 if( Filter
&& (Filter
->m_To
!= -1))
1006 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
1010 bool isgrep
= false;
1011 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1013 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
1018 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1020 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
1025 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1027 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
1032 if(Filter
&& isgrep
)
1034 if(!Filter
->m_IsRegex
)
1035 param
+= _T(" --fixed-strings ");
1037 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1040 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1041 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1042 param
+= _T(" --topo-order");
1043 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1044 param
+= _T(" --date-order");
1046 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
1047 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1051 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1052 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1061 void GetTempPath(CString
&path
)
1063 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1065 DWORD dwBufSize
=BUFSIZE
;
1066 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1067 lpPathBuffer
); // buffer for path
1068 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1072 path
.Format(_T("%s"),lpPathBuffer
);
1074 CString
GetTempFile()
1076 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1078 DWORD dwBufSize
=BUFSIZE
;
1079 TCHAR szTempName
[BUFSIZE
] = { 0 };
1082 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1083 lpPathBuffer
); // buffer for path
1084 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1088 // Create a temporary file.
1089 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1090 TEXT("Patch"), // temp file name prefix
1091 0, // create unique name
1092 szTempName
); // buffer for name
1100 return CString(szTempName
);
1104 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1106 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1107 if (result
== 0) return 0;
1108 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1115 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1116 CreateDirectory(lpBuffer
, NULL
);
1121 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1124 PROCESS_INFORMATION pi
;
1125 si
.cb
=sizeof(STARTUPINFO
);
1126 GetStartupInfo(&si
);
1128 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1129 psa
.bInheritHandle
=TRUE
;
1131 HANDLE hReadErr
, hWriteErr
;
1132 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1134 CString err
= CFormatMessageWrapper();
1135 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1136 return TGIT_GIT_ERROR_OPEN_PIP
;
1139 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1140 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1142 if (houtfile
== INVALID_HANDLE_VALUE
)
1144 CString err
= CFormatMessageWrapper();
1145 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1146 CloseHandle(hReadErr
);
1147 CloseHandle(hWriteErr
);
1148 return TGIT_GIT_ERROR_OPEN_PIP
;
1151 si
.wShowWindow
= SW_HIDE
;
1152 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1153 si
.hStdOutput
= houtfile
;
1154 si
.hStdError
= hWriteErr
;
1156 LPTSTR pEnv
= m_Environment
;
1157 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1159 if(cmd
.Find(_T("git")) == 0)
1160 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1162 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1163 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1165 CString err
= CFormatMessageWrapper();
1166 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1168 CloseHandle(hReadErr
);
1169 CloseHandle(hWriteErr
);
1170 CloseHandle(houtfile
);
1171 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1174 BYTE_VECTOR stderrVector
;
1175 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1177 ASYNCREADSTDERRTHREADARGS threadArguments
;
1178 threadArguments
.fileHandle
= hReadErr
;
1179 threadArguments
.pcall
= &pcall
;
1180 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1182 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1184 CloseHandle(hWriteErr
);
1185 CloseHandle(hReadErr
);
1188 WaitForSingleObject(thread
, INFINITE
);
1190 stderrVector
.push_back(0);
1191 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1194 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1196 CString err
= CFormatMessageWrapper();
1197 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1198 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1201 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1203 CloseHandle(pi
.hThread
);
1204 CloseHandle(pi
.hProcess
);
1205 CloseHandle(houtfile
);
1209 git_repository
* CGit::GetGitRepository() const
1211 git_repository
* repo
= nullptr;
1212 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1216 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1220 // no need to parse a ref if it's already a 40-byte hash
1221 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1223 hash
= CGitHash(friendname
);
1227 int isHeadOrphan
= git_repository_head_unborn(repo
);
1228 if (isHeadOrphan
!= 0)
1231 if (isHeadOrphan
== 1)
1237 CAutoObject gitObject
;
1238 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1241 const git_oid
* oid
= git_object_id(gitObject
);
1245 hash
= CGitHash((char *)oid
->id
);
1250 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1252 // no need to parse a ref if it's already a 40-byte hash
1253 if (CGitHash::IsValidSHA1(friendname
))
1255 hash
= CGitHash(friendname
);
1261 CAutoRepository
repo(GetGitRepository());
1265 return GetHash(repo
, hash
, friendname
, true);
1269 CString branch
= FixBranchName(friendname
);
1270 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1271 branch
= friendname
;
1273 cmd
.Format(_T("git.exe rev-parse %s"), branch
);
1275 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1276 hash
= CGitHash(gitLastErr
.Trim());
1279 else if (friendname
== _T("HEAD")) // special check for unborn branch
1281 CString currentbranch
;
1282 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1291 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1296 cmd
=_T("git.exe ls-files -s -t -z");
1298 if (Run(cmd
, &cmdout
))
1301 if (outputlist
.ParserFromLsFile(cmdout
))
1303 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1304 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1308 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1312 if (ignoreSpaceAtEol
)
1313 ignore
+= _T(" --ignore-space-at-eol");
1314 if (ignoreSpaceChange
)
1315 ignore
+= _T(" --ignore-space-change");
1317 ignore
+= _T(" --ignore-all-space");
1318 if (ignoreBlankLines
)
1319 ignore
+= _T(" --ignore-blank-lines");
1321 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1324 if(rev1
== GIT_REV_ZERO
)
1325 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1327 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1331 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1338 return outputlist
.ParserFromLog(out
);
1341 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1343 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1344 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1348 int CGit::GetTagList(STRING_VECTOR
&list
)
1350 if (this->m_IsUseLibGit2
)
1352 CAutoRepository
repo(GetGitRepository());
1356 CAutoStrArray tag_names
;
1358 if (git_tag_list(tag_names
, repo
))
1361 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1363 CStringA
tagName(tag_names
->strings
[i
]);
1364 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1367 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1373 CString cmd
, output
;
1374 cmd
=_T("git.exe tag -l");
1375 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1382 one
=output
.Tokenize(_T("\n"),pos
);
1384 list
.push_back(one
);
1386 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1388 else if (ret
== 1 && IsInitRepos())
1394 CString
CGit::GetGitLastErr(const CString
& msg
)
1396 if (this->m_IsUseLibGit2
)
1397 return GetLibGit2LastErr(msg
);
1398 else if (gitLastErr
.IsEmpty())
1399 return msg
+ _T("\nUnknown git.exe error.");
1402 CString lastError
= gitLastErr
;
1404 return msg
+ _T("\n") + lastError
;
1408 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1410 if (UsingLibGit2(cmd
))
1411 return GetLibGit2LastErr(msg
);
1412 else if (gitLastErr
.IsEmpty())
1413 return msg
+ _T("\nUnknown git.exe error.");
1416 CString lastError
= gitLastErr
;
1418 return msg
+ _T("\n") + lastError
;
1422 CString
CGit::GetLibGit2LastErr()
1424 const git_error
*libgit2err
= giterr_last();
1427 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1429 return _T("libgit2 returned: ") + lastError
;
1432 return _T("An error occoured in libgit2, but no message is available.");
1435 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1438 return msg
+ _T("\n") + GetLibGit2LastErr();
1439 return GetLibGit2LastErr();
1442 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1444 if(branchName
== "FETCH_HEAD")
1445 branchName
= DerefFetchHead();
1449 CString
CGit::FixBranchName(const CString
& branchName
)
1451 CString tempBranchName
= branchName
;
1452 FixBranchName_Mod(tempBranchName
);
1453 return tempBranchName
;
1456 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1460 CAutoRepository
repo(GetGitRepository());
1462 return true; // TODO: optimize error reporting
1464 CAutoReference tagRef
;
1465 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1468 CAutoReference branchRef
;
1469 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1478 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1479 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1485 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1495 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1499 CAutoRepository
repo(GetGitRepository());
1501 return false; // TODO: optimize error reporting
1505 prefix
= _T("refs/heads/");
1507 prefix
= _T("refs/tags/");
1510 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1516 CString cmd
, output
;
1518 cmd
= _T("git.exe show-ref ");
1520 cmd
+= _T("--heads ");
1522 cmd
+= _T("--tags ");
1524 cmd
+= _T("refs/heads/") + name
;
1525 cmd
+= _T(" refs/tags/") + name
;
1527 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1530 if (!output
.IsEmpty())
1537 CString
CGit::DerefFetchHead()
1540 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1541 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1542 int forMergeLineCount
= 0;
1544 std::string hashToReturn
;
1545 while(getline(fetchHeadFile
, line
))
1547 //Tokenize this line
1548 std::string::size_type prevPos
= 0;
1549 std::string::size_type pos
= line
.find('\t');
1550 if(pos
== std::string::npos
) continue; //invalid line
1552 std::string hash
= line
.substr(0, pos
);
1553 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1555 bool forMerge
= pos
== prevPos
;
1556 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1558 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1563 hashToReturn
= hash
;
1564 ++forMergeLineCount
;
1565 if(forMergeLineCount
> 1)
1566 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1570 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1573 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1579 CAutoRepository
repo(GetGitRepository());
1583 if (git_repository_head_detached(repo
) == 1)
1584 cur
= _T("(detached from ");
1586 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1588 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1589 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1590 flags
= GIT_BRANCH_ALL
;
1591 else if (type
& BRANCH_REMOTE
)
1592 flags
= GIT_BRANCH_REMOTE
;
1594 CAutoBranchIterator it
;
1595 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1598 git_reference
* ref
= nullptr;
1599 git_branch_t branchType
;
1600 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1602 CAutoReference
autoRef(ref
);
1603 const char * name
= nullptr;
1604 if (git_branch_name(&name
, ref
))
1607 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1608 if (branchType
& GIT_BRANCH_REMOTE
)
1609 list
.push_back(_T("remotes/") + branchname
);
1612 if (git_branch_is_head(ref
))
1614 list
.push_back(branchname
);
1621 CString cmd
, output
;
1622 cmd
= _T("git.exe branch --no-color");
1624 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1626 else if (type
& BRANCH_REMOTE
)
1629 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1636 one
= output
.Tokenize(_T("\n"), pos
);
1637 one
.Trim(L
" \r\n\t");
1638 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1639 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1640 if (one
[0] == _T('*'))
1645 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1647 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1648 one
= _T("remotes/") + one
;
1649 list
.push_back(one
);
1653 else if (ret
== 1 && IsInitRepos())
1657 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1658 list
.push_back(L
"FETCH_HEAD");
1660 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1662 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1664 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1677 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1679 if (this->m_IsUseLibGit2
)
1681 CAutoRepository
repo(GetGitRepository());
1685 CAutoStrArray remotes
;
1686 if (git_remote_list(remotes
, repo
))
1689 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1691 CStringA
remote(remotes
->strings
[i
]);
1692 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1695 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1702 CString cmd
, output
;
1703 cmd
=_T("git.exe remote");
1704 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1711 one
=output
.Tokenize(_T("\n"),pos
);
1713 list
.push_back(one
);
1720 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1722 if (UsingLibGit2(GIT_CMD_FETCH
))
1724 CAutoRepository
repo(GetGitRepository());
1728 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1729 CAutoRemote gitremote
;
1730 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1733 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1734 callbacks
.credentials
= g_Git2CredCallback
;
1735 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1736 git_remote_set_callbacks(gitremote
, &callbacks
);
1737 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
) < 0)
1740 const git_remote_head
** heads
= nullptr;
1742 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1745 for (size_t i
= 0; i
< size
; i
++)
1747 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1749 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1751 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1752 if (shortname
.Find(_T("^{}")) >= 1)
1754 list
.push_back(shortname
);
1756 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1760 CString cmd
, out
, err
;
1761 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1762 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1764 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1771 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1772 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1773 if (one
.Find(_T("^{}")) >= 1)
1776 list
.push_back(one
);
1778 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1782 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1784 if (UsingLibGit2(GIT_CMD_PUSH
))
1786 CAutoRepository
repo(GetGitRepository());
1790 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1792 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1795 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1796 callbacks
.credentials
= g_Git2CredCallback
;
1797 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1798 git_remote_set_callbacks(remote
, &callbacks
);
1799 if (git_remote_connect(remote
, GIT_DIRECTION_PUSH
) < 0)
1802 std::vector
<CStringA
> refspecs
;
1803 for (auto ref
: list
)
1804 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1806 std::vector
<char*> vc
;
1807 vc
.reserve(refspecs
.size());
1808 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1809 git_strarray specs
= { &vc
[0], vc
.size() };
1811 if (git_remote_push(remote
, &specs
, nullptr) < 0)
1816 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1817 for (auto ref
: list
)
1819 CString refspec
= _T(":") + ref
;
1820 mgtPush
.AddFile(refspec
);
1823 BOOL cancel
= FALSE
;
1824 mgtPush
.Execute(cancel
);
1830 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1832 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1833 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1837 int CGit::GetRefList(STRING_VECTOR
&list
)
1839 if (this->m_IsUseLibGit2
)
1841 CAutoRepository
repo(GetGitRepository());
1845 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1848 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1854 CString cmd
, output
;
1855 cmd
=_T("git.exe show-ref -d");
1856 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1863 one
=output
.Tokenize(_T("\n"),pos
);
1864 int start
=one
.Find(_T(" "),0);
1868 name
=one
.Right(one
.GetLength()-start
-1);
1869 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1870 list
.push_back(name
);
1873 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1875 else if (ret
== 1 && IsInitRepos())
1881 typedef struct map_each_ref_payload
{
1882 git_repository
* repo
;
1883 MAP_HASH_NAME
* map
;
1884 } map_each_ref_payload
;
1886 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1888 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1890 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1892 CAutoObject gitObject
;
1893 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1896 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1898 str
+= _T("^{}"); // deref tag
1899 CAutoObject derefedTag
;
1900 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1902 gitObject
.Swap(derefedTag
);
1905 const git_oid
* oid
= git_object_id(gitObject
);
1909 CGitHash
hash((char *)oid
->id
);
1910 (*payloadContent
->map
)[hash
].push_back(str
);
1914 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1918 map_each_ref_payload payloadContent
= { repo
, &map
};
1920 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1923 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1925 std::sort(it
->second
.begin(), it
->second
.end());
1931 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1933 if (this->m_IsUseLibGit2
)
1935 CAutoRepository
repo(GetGitRepository());
1939 return GetMapHashToFriendName(repo
, map
);
1943 CString cmd
, output
;
1944 cmd
=_T("git.exe show-ref -d");
1945 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1952 one
=output
.Tokenize(_T("\n"),pos
);
1953 int start
=one
.Find(_T(" "),0);
1957 name
=one
.Right(one
.GetLength()-start
-1);
1960 hash
=one
.Left(start
);
1962 map
[CGitHash(hash
)].push_back(name
);
1966 else if (ret
== 1 && IsInitRepos())
1972 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1974 CAutoConfig
config(true);
1975 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1977 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1979 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1980 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1981 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1982 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1987 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1989 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1990 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1993 static void SetLibGit2TemplatePath(const CString
&value
)
1995 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1996 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1999 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2001 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
2002 CString str
= msysdir
;
2003 if (!str
.IsEmpty() && FileExists(str
+ _T("\\git.exe")))
2005 CGit::ms_LastMsysGitDir
= str
;
2009 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2013 // first, search PATH if git/bin directory is already present
2016 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
2017 msysdir
= CGit::ms_LastMsysGitDir
;
2022 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2023 str
= msyslocalinstalldir
;
2024 str
.TrimRight(_T("\\"));
2028 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2029 str
= msysinstalldir
;
2030 str
.TrimRight(_T("\\"));
2035 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2036 str
= msysinstalldir
;
2037 str
.TrimRight(_T("\\"));
2041 if (FileExists(str
+ _T("\\bin\\git.exe")))
2043 else if (FileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2047 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), str
);
2051 CGit::ms_LastMsysGitDir
= str
;
2056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2060 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2067 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2068 this->m_Environment
.clear();
2069 m_Environment
.CopyProcessEnvironment();
2070 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2072 // set HOME if not set already
2074 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
2076 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2079 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2080 if (sshclient
.IsEmpty())
2081 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2083 if(!sshclient
.IsEmpty())
2085 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2086 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2090 TCHAR sPlink
[MAX_PATH
] = {0};
2091 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
2092 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2094 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
2095 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2096 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2101 TCHAR sAskPass
[MAX_PATH
] = {0};
2102 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
2103 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2106 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2107 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2108 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2109 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2113 if (!FindAndSetGitExePath(bFallback
))
2117 PathCanonicalize(CStrBuf(msysGitDir
, MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2118 static CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2119 static int prefixes_len
[] = { 8, 8, 0 };
2120 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2126 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2127 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2131 CGit::ms_MsysGitRootDir
= msysGitDir
;
2133 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2134 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2136 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
2137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), CGit::ms_MsysGitRootDir
);
2138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), g_Git
.GetGitSystemConfig());
2140 // Configure libgit2 search paths
2141 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2142 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2143 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2144 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 };
2145 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2147 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2149 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2151 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2152 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2154 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2155 // register filter only once
2156 if (!git_filter_lookup("filter"))
2158 static CString binDirPrefixes
[] = { L
"", L
"\\..\\bin", L
"\\..\\usr\\bin" };
2160 for (const CString
& binDirPrefix
: binDirPrefixes
)
2162 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2163 if (PathFileExists(possibleShExe
))
2166 PathCanonicalize(CStrBuf(temp
, MAX_PATH
), possibleShExe
);
2167 sh
.Format(L
"\"%s\"", temp
);
2168 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2169 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2173 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2178 m_bInitialized
= TRUE
;
2182 CString
CGit::GetHomeDirectory() const
2184 const wchar_t * homeDir
= wget_windows_home_directory();
2185 return CString(homeDir
, (int)wcslen(homeDir
));
2188 CString
CGit::GetGitLocalConfig() const
2191 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2192 path
+= _T("config");
2196 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2198 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2201 CString
CGit::GetGitGlobalConfig() const
2203 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2206 CString
CGit::GetGitGlobalXDGConfigPath() const
2208 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2211 CString
CGit::GetGitGlobalXDGConfig() const
2213 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2216 CString
CGit::GetGitSystemConfig() const
2218 const wchar_t * systemConfig
= wget_msysgit_etc();
2219 return CString(systemConfig
, (int)wcslen(systemConfig
));
2222 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2224 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2226 CAutoRepository repo
= GetGitRepository();
2230 if (git_repository_head_unborn(repo
))
2233 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2234 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2235 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2237 CAutoStatusList status
;
2238 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2241 return (0 == git_status_list_entrycount(status
));
2246 cmd
=_T("git.exe rev-parse --verify HEAD");
2248 if(Run(cmd
,&out
,CP_UTF8
))
2251 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2252 if(Run(cmd
,&out
,CP_UTF8
))
2255 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2256 if(Run(cmd
,&out
,CP_UTF8
))
2259 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2260 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2265 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2268 for (int i
= 0; i
< list
.GetCount(); ++i
)
2270 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2276 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2280 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2282 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2284 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2288 // if the filenames only differ in case, we have to pass "-f"
2289 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2291 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2292 if (Run(cmd
, &err
, CP_UTF8
))
2295 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2296 if (Run(cmd
, &err
, CP_UTF8
))
2299 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2300 { //To init git repository, there are not HEAD, so we can use git reset command
2301 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2303 if (Run(cmd
, &err
, CP_UTF8
))
2308 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2309 if (Run(cmd
, &err
, CP_UTF8
))
2313 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2315 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2316 if (Run(cmd
, &err
, CP_UTF8
))
2323 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2328 if (git_repository_index(index
.GetPointer(), repo
))
2331 return git_index_has_conflicts(index
);
2334 int CGit::HasWorkingTreeConflicts()
2336 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2338 CAutoRepository
repo(GetGitRepository());
2342 return HasWorkingTreeConflicts(repo
);
2345 CString cmd
= _T("git.exe ls-files -u -t -z");
2348 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2351 return output
.IsEmpty() ? 0 : 1;
2354 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2356 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2358 CAutoRepository
repo(GetGitRepository());
2362 CGitHash fromHash
, toHash
, baseHash
;
2363 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2366 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2370 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2373 baseHash
= baseOid
.id
;
2376 *commonAncestor
= baseHash
;
2378 return fromHash
== baseHash
;
2382 CGitHash basehash
,hash
;
2384 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2386 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2390 basehash
= base
.Trim();
2392 GetHash(hash
, from
);
2395 *commonAncestor
= basehash
;
2397 return hash
== basehash
;
2400 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2403 for (int i
= 0; i
< 4; ++i
)
2406 ret
|= hash
.m_hash
[i
];
2411 int CGit::RefreshGitIndex()
2413 if(g_Git
.m_IsUseGitDLL
)
2415 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2418 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2429 cmd
=_T("git.exe update-index --refresh");
2430 return Run(cmd
, &output
, CP_UTF8
);
2434 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2436 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2438 CAutoRepository
repo(GetGitRepository());
2443 if (GetHash(repo
, hash
, Refname
))
2447 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2451 if (git_commit_tree(tree
.GetPointer(), commit
))
2454 CAutoTreeEntry entry
;
2455 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2459 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2462 FILE *file
= nullptr;
2463 _tfopen_s(&file
, outputfile
, _T("wb"));
2464 if (file
== nullptr)
2466 giterr_set_str(GITERR_NONE
, "Could not create file.");
2470 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2475 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2477 giterr_set_str(GITERR_OS
, "Could not write to file.");
2486 else if (g_Git
.m_IsUseGitDLL
)
2488 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2491 g_Git
.CheckAndInitDll();
2492 CStringA ref
, patha
, outa
;
2493 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2494 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2495 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2496 ::DeleteFile(outputfile
);
2497 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2498 outa
.ReleaseBuffer();
2502 catch (const char * msg
)
2504 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2509 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2516 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2517 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2521 void CEnvironment::clear()
2526 bool CEnvironment::empty()
2528 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2531 CEnvironment::operator LPTSTR()
2535 return &__super::at(0);
2538 void CEnvironment::CopyProcessEnvironment()
2542 TCHAR
*porig
= GetEnvironmentStrings();
2544 while(*p
!=0 || *(p
+1) !=0)
2545 this->push_back(*p
++);
2547 push_back(_T('\0'));
2548 push_back(_T('\0'));
2550 FreeEnvironmentStrings(porig
);
2553 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2556 for (size_t i
= 0; i
< size(); ++i
)
2560 CString sname
= str
.Tokenize(_T("="),start
);
2561 if(sname
.CompareNoCase(name
) == 0)
2563 return &(*this)[i
+start
];
2570 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2573 for (i
= 0; i
< size(); ++i
)
2575 CString str
= &(*this)[i
];
2577 CString sname
= str
.Tokenize(_T("="),start
);
2578 if(sname
.CompareNoCase(name
) == 0)
2587 if (!value
) // as we haven't found the variable we want to remove, just return
2589 if (i
== 0) // make inserting into an empty environment work
2591 this->push_back(_T('\0'));
2594 i
-= 1; // roll back terminate \0\0
2595 this->push_back(_T('\0'));
2598 CEnvironment::iterator it
;
2602 while(*it
&& i
<size())
2609 if (value
== nullptr) // remove the variable
2617 this->insert(it
,*name
++);
2622 this->insert(it
, _T('='));
2628 this->insert(it
,*value
++);
2635 void CEnvironment::AddToPath(CString value
)
2637 value
.TrimRight(L
"\\");
2638 if (value
.IsEmpty())
2641 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2643 // do not double add paths to %PATH%
2644 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2649 SetEnv(L
"PATH", path
);
2652 int CGit::GetGitEncode(TCHAR
* configkey
)
2654 CString str
=GetConfigValue(configkey
);
2659 return CUnicodeUtils::GetCPCode(str
);
2663 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2669 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2674 diff
= GetGitDiff();
2676 git_open_diff(&diff
, arg
);
2680 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2691 isStat
= !!strstr(arg
, "stat");
2696 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2698 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2707 for (int j
= 0; j
< count
; ++j
)
2716 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2717 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2718 &mode
,&IsBin
,&inc
,&dec
);
2720 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2721 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2723 path
.SetFromGit(strnewname
,&stroldname
);
2724 path
.ParserAction((BYTE
)mode
);
2728 path
.m_StatAdd
=_T("-");
2729 path
.m_StatDel
=_T("-");
2733 path
.m_StatAdd
.Format(_T("%d"),inc
);
2734 path
.m_StatDel
.Format(_T("%d"),dec
);
2736 PathList
->AddPath(path
);
2738 git_diff_flush(diff
);
2741 git_close_diff(diff
);
2746 int CGit::GetShortHASHLength() const
2751 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2755 REF_TYPE type
= CGit::UNKNOWN
;
2757 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2759 type
= CGit::LOCAL_BRANCH
;
2762 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2764 type
= CGit::REMOTE_BRANCH
;
2766 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2770 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2773 shortname
=_T("stash");
2775 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2777 if (shortname
.Find(_T("good")) == 0)
2779 type
= CGit::BISECT_GOOD
;
2780 shortname
= _T("good");
2783 if (shortname
.Find(_T("bad")) == 0)
2785 type
= CGit::BISECT_BAD
;
2786 shortname
= _T("bad");
2789 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2793 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2795 type
= CGit::UNKNOWN
;
2799 type
= CGit::UNKNOWN
;
2809 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2811 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2814 void CGit::SetGit2CredentialCallback(void* callback
)
2816 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2819 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2821 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2824 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2827 if (rev2
== GitRev::GetWorkingCopy())
2828 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2829 else if (rev1
== GitRev::GetWorkingCopy())
2830 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2841 if (diffContext
>= 0)
2842 unified
.Format(_T(" --unified=%d"), diffContext
);
2843 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2846 if (!path
.IsEmpty())
2849 cmd
+= path
.GetGitPathString();
2856 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2858 ATLASSERT(payload
&& text
);
2859 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2860 fwrite("\n", 1, 1, (FILE *)payload
);
2863 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2865 ATLASSERT(payload
&& line
);
2866 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2867 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2868 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2872 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2874 ATLASSERT(repo
&& identifier
&& tree
);
2876 /* try to resolve identifier */
2878 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2882 return GIT_ENOTFOUND
;
2885 switch (git_object_type(obj
))
2888 *tree
= (git_tree
*)obj
.Detach();
2890 case GIT_OBJ_COMMIT
:
2891 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2894 err
= GIT_ENOTFOUND
;
2900 /* use libgit2 get unified diff */
2901 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 */)
2903 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2904 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2906 CAutoRepository
repo(g_Git
.GetGitRepository());
2910 int isHeadOrphan
= git_repository_head_unborn(repo
);
2911 if (isHeadOrphan
== 1)
2913 else if (isHeadOrphan
!= 0)
2916 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2917 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2918 char *buf
= pathA
.GetBuffer();
2919 if (!pathA
.IsEmpty())
2921 opts
.pathspec
.strings
= &buf
;
2922 opts
.pathspec
.count
= 1;
2926 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2931 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2934 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2937 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2940 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2943 if (git_diff_merge(diff
, diff2
))
2948 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2951 if (tree1
.IsEmpty())
2959 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2962 if (tree2
.IsEmpty())
2964 /* don't check return value, there are not parent commit at first commit*/
2965 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2967 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2969 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2973 CAutoDiffStats stats
;
2974 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2977 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2979 statCallback(statBuf
, data
);
2981 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2984 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2987 if (git_patch_print(patch
, callback
, data
))
2991 pathA
.ReleaseBuffer();
2996 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2998 if (UsingLibGit2(GIT_CMD_DIFF
))
3000 FILE *file
= nullptr;
3001 _tfopen_s(&file
, patchfile
, _T("w"));
3002 if (file
== nullptr)
3004 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
);
3011 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3012 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3016 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3018 ATLASSERT(payload
&& text
);
3019 CStringA
*str
= (CStringA
*) payload
;
3020 str
->Append(text
->ptr
, (int)text
->size
);
3021 str
->AppendChar('\n');
3024 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3026 ATLASSERT(payload
&& line
);
3027 CStringA
*str
= (CStringA
*) payload
;
3028 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3029 str
->Append(&line
->origin
, 1);
3030 str
->Append(line
->content
, (int)line
->content_len
);
3034 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3036 if (UsingLibGit2(GIT_CMD_DIFF
))
3037 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
);
3041 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3043 int ret
= Run(cmd
, &vector
);
3044 if (!vector
.empty())
3046 vector
.push_back(0); // vector is not NUL terminated
3047 buffer
->Append((char *)&vector
[0]);
3053 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3055 if (UsingLibGit2(GIT_CMD_REVERT
))
3057 CAutoRepository
repo(GetGitRepository());
3062 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3065 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3066 revert_opts
.mainline
= parent
;
3067 int result
= git_revert(repo
, commit
, &revert_opts
);
3069 return !result
? 0 : -1;
3075 merge
.Format(_T("-m %d "), parent
);
3076 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
3077 gitLastErr
= cmd
+ _T("\n");
3078 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3090 int CGit::DeleteRef(const CString
& reference
)
3092 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3094 CAutoRepository
repo(GetGitRepository());
3099 if (reference
.Right(3) == _T("^{}"))
3100 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3102 refA
= CUnicodeUtils::GetUTF8(reference
);
3105 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3109 if (git_reference_is_tag(ref
))
3110 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3111 else if (git_reference_is_branch(ref
))
3112 result
= git_branch_delete(ref
);
3113 else if (git_reference_is_remote(ref
))
3114 result
= git_branch_delete(ref
);
3116 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3122 CString cmd
, shortname
;
3123 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3124 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
3125 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3126 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
3127 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3128 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
3131 gitLastErr
= L
"unsupported reference type: " + reference
;
3135 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3143 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3145 if (PathFileExists(filename
))
3147 FILE *pFile
= nullptr;
3148 _tfopen_s(&pFile
, filename
, _T("r"));
3154 char s
[8196] = { 0 };
3155 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3158 str
+= CStringA(s
, read
);
3161 msg
= CUnicodeUtils::GetUnicode(str
);
3162 msg
.Replace(_T("\r\n"), _T("\n"));
3163 msg
.TrimRight(_T("\n"));
3167 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3168 return true; // load no further files
3173 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3176 return GetInitAddList(result
);
3182 count
= filterlist
->GetCount();
3184 CString head
= _T("HEAD");
3186 head
= _T("HEAD~1");
3188 for (int i
= 0; i
< count
; ++i
)
3194 // Prevent showing all files as modified when using cygwin's git
3196 cmd
= _T("git.exe status --");
3198 cmd
.Format(_T("git.exe status -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3203 // also list staged files which will be in the commit
3204 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3207 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3209 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3212 if (Run(cmd
, &cmdout
, &cmdErr
))
3214 int last
= cmdErr
.RevertFind(0, -1);
3216 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3217 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3220 out
.append(cmdout
, 0);
3222 result
.ParserFromLog(out
);
3224 // handle delete conflict case, when remote : modified, local : deleted.
3225 for (int i
= 0; i
< count
; ++i
)
3231 cmd
= _T("git.exe ls-files -u -t -z");
3233 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3237 CTGitPathList conflictlist
;
3238 conflictlist
.ParserFromLog(cmdout
);
3239 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3241 CTGitPath
* p
= result
.LookForGitPath(conflictlist
[j
].GetGitPathString());
3243 p
->m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3245 result
.AddPath(conflictlist
[j
]);
3249 // handle source files of file renames/moves (issue #860)
3250 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3251 for (int i
= 0; i
< count
; ++i
)
3257 cmd
= _T("git.exe ls-files -d -z");
3259 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3263 CTGitPathList deletelist
;
3264 deletelist
.ParserFromLog(cmdout
, true);
3265 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3267 CTGitPath
* p
= result
.LookForGitPath(deletelist
[j
].GetGitPathString());
3269 result
.AddPath(deletelist
[j
]);