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
, m_CurrentDir
.GetBuffer(MAX_PATH
));
212 m_CurrentDir
.ReleaseBuffer();
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"), 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"), 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_bCygwinGit
&& cmd
.Find(_T("git")) == 0)
339 cmd
.Replace(_T('\\'), _T('/'));
340 cmd
.Replace(_T("\""), _T("\\\""));
341 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
343 else if(cmd
.Find(_T("git")) == 0)
345 int firstSpace
= cmd
.Find(_T(" "));
347 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
349 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
352 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
353 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
355 CString err
= CFormatMessageWrapper();
356 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
357 return TGIT_GIT_ERROR_CREATE_PROCESS
;
365 *hReadOut
= hRead
.Detach();
367 *hErrReadOut
= hReadErr
.Detach();
371 //Must use sperate function to convert ANSI str to union code string
372 //Becuase A2W use stack as internal convert buffer.
373 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
380 len
= (int)strlen((const char*)p
);
385 int currentContentLen
= str
->GetLength();
386 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
387 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
388 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
391 // This method was originally used to check for orphaned branches
392 BOOL
CGit::CanParseRev(CString ref
)
398 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
408 // Checks if we have an orphaned HEAD
409 BOOL
CGit::IsInitRepos()
412 if (GetHash(hash
, _T("HEAD")) != 0)
414 return hash
.IsEmpty() ? TRUE
: FALSE
;
417 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
419 PASYNCREADSTDERRTHREADARGS pDataArray
;
420 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
423 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
424 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
426 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
433 int CGit::Run(CGitCall
* pcall
)
435 PROCESS_INFORMATION pi
;
436 CAutoGeneralHandle hRead
, hReadErr
;
437 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
438 return TGIT_GIT_ERROR_CREATE_PROCESS
;
440 CAutoGeneralHandle
piThread(pi
.hThread
);
441 CAutoGeneralHandle
piProcess(pi
.hProcess
);
443 ASYNCREADSTDERRTHREADARGS threadArguments
;
444 threadArguments
.fileHandle
= hReadErr
;
445 threadArguments
.pcall
= pcall
;
446 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
449 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
451 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
453 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
454 if(!bAborted
)//For now, flush output when command aborted.
455 if(pcall
->OnOutputData(data
,readnumber
))
462 WaitForSingleObject(thread
, INFINITE
);
464 WaitForSingleObject(pi
.hProcess
, INFINITE
);
467 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
469 CString err
= CFormatMessageWrapper();
470 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
471 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
474 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
478 class CGitCall_ByteVector
: public CGitCall
481 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
482 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
484 if (!m_pvector
|| size
== 0)
486 size_t oldsize
=m_pvector
->size();
487 m_pvector
->resize(m_pvector
->size()+size
);
488 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
491 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
493 if (!m_pvectorErr
|| size
== 0)
495 size_t oldsize
= m_pvectorErr
->size();
496 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
497 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
500 BYTE_VECTOR
* m_pvector
;
501 BYTE_VECTOR
* m_pvectorErr
;
504 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
506 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
509 int CGit::Run(CString cmd
, CString
* output
, int code
)
513 ret
= Run(cmd
, output
, &err
, code
);
515 if (output
&& !err
.IsEmpty())
517 if (!output
->IsEmpty())
524 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
526 BYTE_VECTOR vector
, vectorErr
;
529 ret
= Run(cmd
, &vector
, &vectorErr
);
531 ret
= Run(cmd
, &vector
);
534 StringAppend(output
, &(vector
[0]), code
);
538 vectorErr
.push_back(0);
539 StringAppend(outputErr
, &(vectorErr
[0]), code
);
545 class CGitCallCb
: public CGitCall
548 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
550 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
555 int oldEndPos
= m_buffer
.GetLength();
556 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
557 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
559 // Break into lines and feed to m_recv
561 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
563 m_recv(m_buffer
.Left(eolPos
));
564 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
569 virtual bool OnOutputErrData(const BYTE
*, size_t) override
571 return false; // Ignore error output for now
574 virtual void OnEnd() override
576 if (!m_buffer
.IsEmpty())
578 m_buffer
.Empty(); // Just for sure
582 GitReceiverFunc m_recv
;
586 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
588 CGitCallCb
call(cmd
, recv
);
592 CString
CGit::GetUserName(void)
595 env
.CopyProcessEnvironment();
596 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
597 if (!envname
.IsEmpty())
599 return GetConfigValue(L
"user.name");
601 CString
CGit::GetUserEmail(void)
604 env
.CopyProcessEnvironment();
605 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
606 if (!envmail
.IsEmpty())
609 return GetConfigValue(L
"user.email");
612 CString
CGit::GetConfigValue(const CString
& name
)
615 if(this->m_IsUseGitDLL
)
617 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
626 key
= CUnicodeUtils::GetUTF8(name
);
630 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
633 catch (const char *msg
)
635 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
639 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
645 cmd
.Format(L
"git.exe config %s", name
);
646 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
647 if (configValue
.IsEmpty())
649 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
653 bool CGit::GetConfigValueBool(const CString
& name
)
655 CString configValue
= GetConfigValue(name
);
656 configValue
.MakeLower();
658 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
664 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
666 CString configValue
= GetConfigValue(name
);
668 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
673 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
675 if(this->m_IsUseGitDLL
)
677 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
686 CStringA keya
, valuea
;
687 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
688 valuea
= CUnicodeUtils::GetUTF8(value
);
692 return [=]() { return get_set_config(keya
, valuea
, type
); }();
694 catch (const char *msg
)
696 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
707 option
= _T("--global");
710 option
= _T("--system");
715 CString mangledValue
= value
;
716 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
717 mangledValue
.Replace(_T("\""), _T("\\\""));
718 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, mangledValue
);
720 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
728 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
730 if(this->m_IsUseGitDLL
)
732 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
741 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
745 return [=]() { return get_set_config(keya
, nullptr, type
); }();
747 catch (const char *msg
)
749 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
760 option
= _T("--global");
763 option
= _T("--system");
768 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
770 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
778 CString
CGit::GetCurrentBranch(bool fallback
)
781 //Run(_T("git.exe branch"),&branch);
783 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
784 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
786 return _T("(no branch)");
793 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
795 if (localBranch
.IsEmpty())
799 configName
.Format(L
"branch.%s.remote", localBranch
);
800 pullRemote
= GetConfigValue(configName
);
802 //Select pull-branch from current branch
803 configName
.Format(L
"branch.%s.merge", localBranch
);
804 pullBranch
= StripRefName(GetConfigValue(configName
));
807 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
810 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
812 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
815 CString
CGit::GetFullRefName(const CString
& shortRefName
)
819 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
820 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
821 return CString();//Error
823 return refName
.Tokenize(L
"\n", iStart
);
826 CString
CGit::StripRefName(CString refName
)
828 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
829 refName
= refName
.Mid(11);
830 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
831 refName
= refName
.Mid(5);
833 return refName
.Tokenize(_T("\n"),start
);
836 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
838 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
840 if ( sProjectRoot
.IsEmpty() )
844 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
847 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
850 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
858 fgets(s
, sizeof(s
), pFile
);
862 const char *pfx
= "ref: refs/heads/";
863 const int len
= 16;//strlen(pfx)
865 if ( !strncmp(s
, pfx
, len
) )
867 //# We're on a branch. It might not exist. But
868 //# HEAD looks good enough to be a branch.
869 CStringA
utf8Branch(s
+ len
);
870 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
871 sBranchOut
.TrimRight(_T(" \r\n\t"));
873 if ( sBranchOut
.IsEmpty() )
878 CStringA
utf8Hash(s
);
879 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
880 unicodeHash
.TrimRight(_T(" \r\n\t"));
881 if (CGitHash::IsValidSHA1(unicodeHash
))
882 sBranchOut
= unicodeHash
;
884 //# Assume this is a detached head.
885 sBranchOut
= _T("HEAD");
890 //# Assume this is a detached head.
899 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
902 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
906 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
908 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
910 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
912 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
914 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
916 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
918 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
922 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
924 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
926 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
931 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
937 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
944 CString file
= _T(" --");
947 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
950 num
.Format(_T("-n%d"),count
);
954 if(mask
& LOG_INFO_STAT
)
955 param
+= _T(" --numstat ");
956 if(mask
& LOG_INFO_FILESTATE
)
957 param
+= _T(" --raw ");
959 if(mask
& LOG_INFO_FULLHISTORY
)
960 param
+= _T(" --full-history ");
962 if(mask
& LOG_INFO_BOUNDARY
)
963 param
+= _T(" --left-right --boundary ");
965 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
966 param
+= _T(" --all ");
968 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
969 param
+= _T(" --branches ");
971 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
974 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
977 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
978 param
+= _T(" --first-parent ");
980 if(mask
& CGit::LOG_INFO_NO_MERGE
)
981 param
+= _T(" --no-merges ");
983 if(mask
& CGit::LOG_INFO_FOLLOW
)
984 param
+= _T(" --follow ");
986 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
989 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
990 param
+= _T(" --full-diff ");
992 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
993 param
+= _T(" --simplify-by-decoration ");
999 if( Filter
&& (Filter
->m_From
!= -1))
1001 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
1005 if( Filter
&& (Filter
->m_To
!= -1))
1007 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
1011 bool isgrep
= false;
1012 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1014 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
1019 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1021 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
1026 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1028 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
1033 if(Filter
&& isgrep
)
1035 if(!Filter
->m_IsRegex
)
1036 param
+= _T(" --fixed-strings ");
1038 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1041 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1042 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1043 param
+= _T(" --topo-order");
1044 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1045 param
+= _T(" --date-order");
1047 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
1048 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1052 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1053 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1062 void GetTempPath(CString
&path
)
1064 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1066 DWORD dwBufSize
=BUFSIZE
;
1067 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1068 lpPathBuffer
); // buffer for path
1069 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1073 path
.Format(_T("%s"),lpPathBuffer
);
1075 CString
GetTempFile()
1077 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1079 DWORD dwBufSize
=BUFSIZE
;
1080 TCHAR szTempName
[BUFSIZE
] = { 0 };
1083 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1084 lpPathBuffer
); // buffer for path
1085 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1089 // Create a temporary file.
1090 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1091 TEXT("Patch"), // temp file name prefix
1092 0, // create unique name
1093 szTempName
); // buffer for name
1101 return CString(szTempName
);
1105 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1107 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1108 if (result
== 0) return 0;
1109 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1116 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1117 CreateDirectory(lpBuffer
, NULL
);
1122 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1125 PROCESS_INFORMATION pi
;
1126 si
.cb
=sizeof(STARTUPINFO
);
1127 GetStartupInfo(&si
);
1129 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1130 psa
.bInheritHandle
=TRUE
;
1132 HANDLE hReadErr
, hWriteErr
;
1133 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1135 CString err
= CFormatMessageWrapper();
1136 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1137 return TGIT_GIT_ERROR_OPEN_PIP
;
1140 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1141 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1143 if (houtfile
== INVALID_HANDLE_VALUE
)
1145 CString err
= CFormatMessageWrapper();
1146 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1147 CloseHandle(hReadErr
);
1148 CloseHandle(hWriteErr
);
1149 return TGIT_GIT_ERROR_OPEN_PIP
;
1152 si
.wShowWindow
= SW_HIDE
;
1153 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1154 si
.hStdOutput
= houtfile
;
1155 si
.hStdError
= hWriteErr
;
1157 LPTSTR pEnv
= m_Environment
;
1158 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1160 if(cmd
.Find(_T("git")) == 0)
1161 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1163 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1164 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1166 CString err
= CFormatMessageWrapper();
1167 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1169 CloseHandle(hReadErr
);
1170 CloseHandle(hWriteErr
);
1171 CloseHandle(houtfile
);
1172 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1175 BYTE_VECTOR stderrVector
;
1176 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1178 ASYNCREADSTDERRTHREADARGS threadArguments
;
1179 threadArguments
.fileHandle
= hReadErr
;
1180 threadArguments
.pcall
= &pcall
;
1181 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1183 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1185 CloseHandle(hWriteErr
);
1186 CloseHandle(hReadErr
);
1189 WaitForSingleObject(thread
, INFINITE
);
1191 stderrVector
.push_back(0);
1192 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1195 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1197 CString err
= CFormatMessageWrapper();
1198 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1199 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1202 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1204 CloseHandle(pi
.hThread
);
1205 CloseHandle(pi
.hProcess
);
1206 CloseHandle(houtfile
);
1210 git_repository
* CGit::GetGitRepository() const
1212 git_repository
* repo
= nullptr;
1213 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1217 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1221 // no need to parse a ref if it's already a 40-byte hash
1222 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1224 hash
= CGitHash(friendname
);
1228 int isHeadOrphan
= git_repository_head_unborn(repo
);
1229 if (isHeadOrphan
!= 0)
1232 if (isHeadOrphan
== 1)
1238 CAutoObject gitObject
;
1239 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1242 const git_oid
* oid
= git_object_id(gitObject
);
1246 hash
= CGitHash((char *)oid
->id
);
1251 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1253 // no need to parse a ref if it's already a 40-byte hash
1254 if (CGitHash::IsValidSHA1(friendname
))
1256 hash
= CGitHash(friendname
);
1262 CAutoRepository
repo(GetGitRepository());
1266 return GetHash(repo
, hash
, friendname
, true);
1270 CString branch
= FixBranchName(friendname
);
1271 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1272 branch
= friendname
;
1274 cmd
.Format(_T("git.exe rev-parse %s"), branch
);
1276 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1277 hash
= CGitHash(gitLastErr
.Trim());
1280 else if (friendname
== _T("HEAD")) // special check for unborn branch
1282 CString currentbranch
;
1283 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1292 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1297 cmd
=_T("git.exe ls-files -s -t -z");
1299 if (Run(cmd
, &cmdout
))
1302 if (outputlist
.ParserFromLsFile(cmdout
))
1304 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1305 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1309 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1313 if (ignoreSpaceAtEol
)
1314 ignore
+= _T(" --ignore-space-at-eol");
1315 if (ignoreSpaceChange
)
1316 ignore
+= _T(" --ignore-space-change");
1318 ignore
+= _T(" --ignore-all-space");
1319 if (ignoreBlankLines
)
1320 ignore
+= _T(" --ignore-blank-lines");
1322 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1325 if(rev1
== GIT_REV_ZERO
)
1326 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1328 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1332 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1339 return outputlist
.ParserFromLog(out
);
1342 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1344 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1345 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1349 int CGit::GetTagList(STRING_VECTOR
&list
)
1351 if (this->m_IsUseLibGit2
)
1353 CAutoRepository
repo(GetGitRepository());
1357 CAutoStrArray tag_names
;
1359 if (git_tag_list(tag_names
, repo
))
1362 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1364 CStringA
tagName(tag_names
->strings
[i
]);
1365 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1368 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1374 CString cmd
, output
;
1375 cmd
=_T("git.exe tag -l");
1376 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1383 one
=output
.Tokenize(_T("\n"),pos
);
1385 list
.push_back(one
);
1387 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1389 else if (ret
== 1 && IsInitRepos())
1395 CString
CGit::GetGitLastErr(const CString
& msg
)
1397 if (this->m_IsUseLibGit2
)
1398 return GetLibGit2LastErr(msg
);
1399 else if (gitLastErr
.IsEmpty())
1400 return msg
+ _T("\nUnknown git.exe error.");
1403 CString lastError
= gitLastErr
;
1405 return msg
+ _T("\n") + lastError
;
1409 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1411 if (UsingLibGit2(cmd
))
1412 return GetLibGit2LastErr(msg
);
1413 else if (gitLastErr
.IsEmpty())
1414 return msg
+ _T("\nUnknown git.exe error.");
1417 CString lastError
= gitLastErr
;
1419 return msg
+ _T("\n") + lastError
;
1423 CString
CGit::GetLibGit2LastErr()
1425 const git_error
*libgit2err
= giterr_last();
1428 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1430 return _T("libgit2 returned: ") + lastError
;
1433 return _T("An error occoured in libgit2, but no message is available.");
1436 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1439 return msg
+ _T("\n") + GetLibGit2LastErr();
1440 return GetLibGit2LastErr();
1443 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1445 if(branchName
== "FETCH_HEAD")
1446 branchName
= DerefFetchHead();
1450 CString
CGit::FixBranchName(const CString
& branchName
)
1452 CString tempBranchName
= branchName
;
1453 FixBranchName_Mod(tempBranchName
);
1454 return tempBranchName
;
1457 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1461 CAutoRepository
repo(GetGitRepository());
1463 return true; // TODO: optimize error reporting
1465 CAutoReference tagRef
;
1466 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1469 CAutoReference branchRef
;
1470 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1479 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1480 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1486 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1496 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1500 CAutoRepository
repo(GetGitRepository());
1502 return false; // TODO: optimize error reporting
1506 prefix
= _T("refs/heads/");
1508 prefix
= _T("refs/tags/");
1511 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1517 CString cmd
, output
;
1519 cmd
= _T("git.exe show-ref ");
1521 cmd
+= _T("--heads ");
1523 cmd
+= _T("--tags ");
1525 cmd
+= _T("refs/heads/") + name
;
1526 cmd
+= _T(" refs/tags/") + name
;
1528 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1531 if (!output
.IsEmpty())
1538 CString
CGit::DerefFetchHead()
1541 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1542 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1543 int forMergeLineCount
= 0;
1545 std::string hashToReturn
;
1546 while(getline(fetchHeadFile
, line
))
1548 //Tokenize this line
1549 std::string::size_type prevPos
= 0;
1550 std::string::size_type pos
= line
.find('\t');
1551 if(pos
== std::string::npos
) continue; //invalid line
1553 std::string hash
= line
.substr(0, pos
);
1554 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1556 bool forMerge
= pos
== prevPos
;
1557 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1559 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1564 hashToReturn
= hash
;
1565 ++forMergeLineCount
;
1566 if(forMergeLineCount
> 1)
1567 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1571 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1574 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1580 CAutoRepository
repo(GetGitRepository());
1584 if (git_repository_head_detached(repo
) == 1)
1585 cur
= _T("(detached from ");
1587 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1589 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1590 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1591 flags
= GIT_BRANCH_ALL
;
1592 else if (type
& BRANCH_REMOTE
)
1593 flags
= GIT_BRANCH_REMOTE
;
1595 CAutoBranchIterator it
;
1596 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1599 git_reference
* ref
= nullptr;
1600 git_branch_t branchType
;
1601 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1603 CAutoReference
autoRef(ref
);
1604 const char * name
= nullptr;
1605 if (git_branch_name(&name
, ref
))
1608 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1609 if (branchType
& GIT_BRANCH_REMOTE
)
1610 list
.push_back(_T("remotes/") + branchname
);
1613 if (git_branch_is_head(ref
))
1615 list
.push_back(branchname
);
1622 CString cmd
, output
;
1623 cmd
= _T("git.exe branch --no-color");
1625 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1627 else if (type
& BRANCH_REMOTE
)
1630 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1637 one
= output
.Tokenize(_T("\n"), pos
);
1638 one
.Trim(L
" \r\n\t");
1639 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1640 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1641 if (one
[0] == _T('*'))
1646 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1648 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1649 one
= _T("remotes/") + one
;
1650 list
.push_back(one
);
1654 else if (ret
== 1 && IsInitRepos())
1658 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1659 list
.push_back(L
"FETCH_HEAD");
1661 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1663 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1665 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1678 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1680 if (this->m_IsUseLibGit2
)
1682 CAutoRepository
repo(GetGitRepository());
1686 CAutoStrArray remotes
;
1687 if (git_remote_list(remotes
, repo
))
1690 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1692 CStringA
remote(remotes
->strings
[i
]);
1693 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1696 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1703 CString cmd
, output
;
1704 cmd
=_T("git.exe remote");
1705 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1712 one
=output
.Tokenize(_T("\n"),pos
);
1714 list
.push_back(one
);
1721 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1723 if (UsingLibGit2(GIT_CMD_FETCH
))
1725 CAutoRepository
repo(GetGitRepository());
1729 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1730 CAutoRemote gitremote
;
1731 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1734 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1735 callbacks
.credentials
= g_Git2CredCallback
;
1736 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1737 git_remote_set_callbacks(gitremote
, &callbacks
);
1738 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
) < 0)
1741 const git_remote_head
** heads
= nullptr;
1743 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1746 for (size_t i
= 0; i
< size
; i
++)
1748 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1750 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1752 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1753 if (shortname
.Find(_T("^{}")) >= 1)
1755 list
.push_back(shortname
);
1757 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1761 CString cmd
, out
, err
;
1762 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1763 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1765 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1772 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1773 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1774 if (one
.Find(_T("^{}")) >= 1)
1777 list
.push_back(one
);
1779 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1783 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1785 if (UsingLibGit2(GIT_CMD_PUSH
))
1787 CAutoRepository
repo(GetGitRepository());
1791 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1793 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1796 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1797 callbacks
.credentials
= g_Git2CredCallback
;
1798 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1799 git_remote_set_callbacks(remote
, &callbacks
);
1800 if (git_remote_connect(remote
, GIT_DIRECTION_PUSH
) < 0)
1803 std::vector
<CStringA
> refspecs
;
1804 for (auto ref
: list
)
1805 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1807 std::vector
<char*> vc
;
1808 vc
.reserve(refspecs
.size());
1809 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1810 git_strarray specs
= { &vc
[0], vc
.size() };
1812 if (git_remote_push(remote
, &specs
, nullptr) < 0)
1817 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1818 for (auto ref
: list
)
1820 CString refspec
= _T(":") + ref
;
1821 mgtPush
.AddFile(refspec
);
1824 BOOL cancel
= FALSE
;
1825 mgtPush
.Execute(cancel
);
1831 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1833 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1834 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1838 int CGit::GetRefList(STRING_VECTOR
&list
)
1840 if (this->m_IsUseLibGit2
)
1842 CAutoRepository
repo(GetGitRepository());
1846 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1849 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1855 CString cmd
, output
;
1856 cmd
=_T("git.exe show-ref -d");
1857 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1864 one
=output
.Tokenize(_T("\n"),pos
);
1865 int start
=one
.Find(_T(" "),0);
1869 name
=one
.Right(one
.GetLength()-start
-1);
1870 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1871 list
.push_back(name
);
1874 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1876 else if (ret
== 1 && IsInitRepos())
1882 typedef struct map_each_ref_payload
{
1883 git_repository
* repo
;
1884 MAP_HASH_NAME
* map
;
1885 } map_each_ref_payload
;
1887 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1889 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1891 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1893 CAutoObject gitObject
;
1894 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1897 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1899 str
+= _T("^{}"); // deref tag
1900 CAutoObject derefedTag
;
1901 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1903 gitObject
.Swap(derefedTag
);
1906 const git_oid
* oid
= git_object_id(gitObject
);
1910 CGitHash
hash((char *)oid
->id
);
1911 (*payloadContent
->map
)[hash
].push_back(str
);
1915 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1919 map_each_ref_payload payloadContent
= { repo
, &map
};
1921 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1924 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1926 std::sort(it
->second
.begin(), it
->second
.end());
1932 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1934 if (this->m_IsUseLibGit2
)
1936 CAutoRepository
repo(GetGitRepository());
1940 return GetMapHashToFriendName(repo
, map
);
1944 CString cmd
, output
;
1945 cmd
=_T("git.exe show-ref -d");
1946 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1953 one
=output
.Tokenize(_T("\n"),pos
);
1954 int start
=one
.Find(_T(" "),0);
1958 name
=one
.Right(one
.GetLength()-start
-1);
1961 hash
=one
.Left(start
);
1963 map
[CGitHash(hash
)].push_back(name
);
1967 else if (ret
== 1 && IsInitRepos())
1973 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1975 CAutoConfig
config(true);
1976 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1978 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1980 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1981 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1982 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1983 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1988 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1990 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1991 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1994 static void SetLibGit2TemplatePath(const CString
&value
)
1996 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1997 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
2000 int CGit::FindAndSetGitExePath(BOOL bFallback
)
2002 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
2003 CString str
= msysdir
;
2004 if (!str
.IsEmpty() && FileExists(str
+ _T("\\git.exe")))
2006 CGit::ms_LastMsysGitDir
= str
;
2010 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2014 // first, search PATH if git/bin directory is already present
2017 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
2018 msysdir
= CGit::ms_LastMsysGitDir
;
2023 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2024 str
= msyslocalinstalldir
;
2025 str
.TrimRight(_T("\\"));
2029 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2030 str
= msysinstalldir
;
2031 str
.TrimRight(_T("\\"));
2036 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2037 str
= msysinstalldir
;
2038 str
.TrimRight(_T("\\"));
2042 if (FileExists(str
+ _T("\\bin\\git.exe")))
2044 else if (FileExists(str
+ _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2048 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), str
);
2052 CGit::ms_LastMsysGitDir
= str
;
2057 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": Found no git.exe\n"));
2061 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2068 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2069 this->m_Environment
.clear();
2070 m_Environment
.CopyProcessEnvironment();
2071 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2073 // set HOME if not set already
2075 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
2077 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2080 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2081 if (sshclient
.IsEmpty())
2082 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2084 if(!sshclient
.IsEmpty())
2086 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2087 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2091 TCHAR sPlink
[MAX_PATH
] = {0};
2092 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
2093 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2095 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
2096 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2097 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2102 TCHAR sAskPass
[MAX_PATH
] = {0};
2103 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
2104 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2107 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2108 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2109 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2110 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2114 if (!FindAndSetGitExePath(bFallback
))
2118 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\"));
2119 msysGitDir
.ReleaseBuffer();
2120 static CString prefixes
[] = { L
"mingw64\\etc", L
"mingw32\\etc", L
"etc" };
2121 static int prefixes_len
[] = { 8, 8, 0 };
2122 for (int i
= 0; i
< _countof(prefixes
); ++i
)
2128 if (PathIsDirectory(msysGitDir
+ prefixes
[i
])) {
2129 msysGitDir
+= prefixes
[i
].Left(prefixes_len
[i
]);
2133 CGit::ms_MsysGitRootDir
= msysGitDir
;
2135 if ((CString
)CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) != g_Git
.GetGitSystemConfig())
2136 CRegString(REG_SYSTEM_GITCONFIGPATH
, _T(""), FALSE
) = g_Git
.GetGitSystemConfig();
2138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
2139 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_MsysGitRootDir = %s\n"), CGit::ms_MsysGitRootDir
);
2140 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": System config = %s\n"), g_Git
.GetGitSystemConfig());
2142 // Configure libgit2 search paths
2143 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, CTGitPath(g_Git
.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2144 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2145 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2146 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 };
2147 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2149 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("share\\git-core\\templates"));
2151 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir
+ _T("usr\\share\\git-core\\templates"));
2153 m_Environment
.AddToPath(CGit::ms_LastMsysGitDir
);
2154 m_Environment
.AddToPath((CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
, _T(""), FALSE
));
2156 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2157 // register filter only once
2158 if (!git_filter_lookup("filter"))
2160 static CString binDirPrefixes
[] = { L
"", L
"\\..\\bin", L
"\\..\\usr\\bin" };
2162 for (const CString
& binDirPrefix
: binDirPrefixes
)
2164 CString possibleShExe
= CGit::ms_LastMsysGitDir
+ binDirPrefix
+ L
"\\sh.exe";
2165 if (PathFileExists(possibleShExe
))
2168 PathCanonicalize(temp
.GetBufferSetLength(MAX_PATH
), possibleShExe
);
2169 temp
.ReleaseBuffer();
2170 sh
.Format(L
"\"%s\"", temp
);
2171 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2172 m_Environment
.AddToPath(temp
.Left(temp
.GetLength() - 7)); // 7 = len("\\sh.exe")
2176 if (git_filter_register("filter", git_filter_filter_new(sh
, m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2181 m_bInitialized
= TRUE
;
2185 CString
CGit::GetHomeDirectory() const
2187 const wchar_t * homeDir
= wget_windows_home_directory();
2188 return CString(homeDir
, (int)wcslen(homeDir
));
2191 CString
CGit::GetGitLocalConfig() const
2194 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2195 path
+= _T("config");
2199 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2201 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2204 CString
CGit::GetGitGlobalConfig() const
2206 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2209 CString
CGit::GetGitGlobalXDGConfigPath() const
2211 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2214 CString
CGit::GetGitGlobalXDGConfig() const
2216 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2219 CString
CGit::GetGitSystemConfig() const
2221 const wchar_t * systemConfig
= wget_msysgit_etc();
2222 return CString(systemConfig
, (int)wcslen(systemConfig
));
2225 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2227 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2229 CAutoRepository repo
= GetGitRepository();
2233 if (git_repository_head_unborn(repo
))
2236 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2237 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2238 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2240 CAutoStatusList status
;
2241 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2244 return (0 == git_status_list_entrycount(status
));
2249 cmd
=_T("git.exe rev-parse --verify HEAD");
2251 if(Run(cmd
,&out
,CP_UTF8
))
2254 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2255 if(Run(cmd
,&out
,CP_UTF8
))
2258 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2259 if(Run(cmd
,&out
,CP_UTF8
))
2262 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2263 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2268 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2271 for (int i
= 0; i
< list
.GetCount(); ++i
)
2273 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2279 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2283 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2285 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2287 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2291 // if the filenames only differ in case, we have to pass "-f"
2292 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2294 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2295 if (Run(cmd
, &err
, CP_UTF8
))
2298 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2299 if (Run(cmd
, &err
, CP_UTF8
))
2302 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2303 { //To init git repository, there are not HEAD, so we can use git reset command
2304 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2306 if (Run(cmd
, &err
, CP_UTF8
))
2311 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2312 if (Run(cmd
, &err
, CP_UTF8
))
2316 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2318 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2319 if (Run(cmd
, &err
, CP_UTF8
))
2326 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2331 if (git_repository_index(index
.GetPointer(), repo
))
2334 return git_index_has_conflicts(index
);
2337 int CGit::HasWorkingTreeConflicts()
2339 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2341 CAutoRepository
repo(GetGitRepository());
2345 return HasWorkingTreeConflicts(repo
);
2348 CString cmd
= _T("git.exe ls-files -u -t -z");
2351 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2354 return output
.IsEmpty() ? 0 : 1;
2357 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2359 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2361 CAutoRepository
repo(GetGitRepository());
2365 CGitHash fromHash
, toHash
, baseHash
;
2366 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2369 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2373 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2376 baseHash
= baseOid
.id
;
2379 *commonAncestor
= baseHash
;
2381 return fromHash
== baseHash
;
2385 CGitHash basehash
,hash
;
2387 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2389 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2393 basehash
= base
.Trim();
2395 GetHash(hash
, from
);
2398 *commonAncestor
= basehash
;
2400 return hash
== basehash
;
2403 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2406 for (int i
= 0; i
< 4; ++i
)
2409 ret
|= hash
.m_hash
[i
];
2414 int CGit::RefreshGitIndex()
2416 if(g_Git
.m_IsUseGitDLL
)
2418 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2421 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2432 cmd
=_T("git.exe update-index --refresh");
2433 return Run(cmd
, &output
, CP_UTF8
);
2437 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2439 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2441 CAutoRepository
repo(GetGitRepository());
2446 if (GetHash(repo
, hash
, Refname
))
2450 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2454 if (git_commit_tree(tree
.GetPointer(), commit
))
2457 CAutoTreeEntry entry
;
2458 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2462 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2465 FILE *file
= nullptr;
2466 _tfopen_s(&file
, outputfile
, _T("wb"));
2467 if (file
== nullptr)
2469 giterr_set_str(GITERR_NONE
, "Could not create file.");
2473 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2478 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2480 giterr_set_str(GITERR_OS
, "Could not write to file.");
2489 else if (g_Git
.m_IsUseGitDLL
)
2491 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2494 g_Git
.CheckAndInitDll();
2495 CStringA ref
, patha
, outa
;
2496 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2497 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2498 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2499 ::DeleteFile(outputfile
);
2500 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2501 outa
.ReleaseBuffer();
2505 catch (const char * msg
)
2507 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2512 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2519 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2520 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2524 void CEnvironment::clear()
2529 bool CEnvironment::empty()
2531 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2534 CEnvironment::operator LPTSTR()
2538 return &__super::at(0);
2541 void CEnvironment::CopyProcessEnvironment()
2545 TCHAR
*porig
= GetEnvironmentStrings();
2547 while(*p
!=0 || *(p
+1) !=0)
2548 this->push_back(*p
++);
2550 push_back(_T('\0'));
2551 push_back(_T('\0'));
2553 FreeEnvironmentStrings(porig
);
2556 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2559 for (size_t i
= 0; i
< size(); ++i
)
2563 CString sname
= str
.Tokenize(_T("="),start
);
2564 if(sname
.CompareNoCase(name
) == 0)
2566 return &(*this)[i
+start
];
2573 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2576 for (i
= 0; i
< size(); ++i
)
2578 CString str
= &(*this)[i
];
2580 CString sname
= str
.Tokenize(_T("="),start
);
2581 if(sname
.CompareNoCase(name
) == 0)
2590 if (!value
) // as we haven't found the variable we want to remove, just return
2592 if (i
== 0) // make inserting into an empty environment work
2594 this->push_back(_T('\0'));
2597 i
-= 1; // roll back terminate \0\0
2598 this->push_back(_T('\0'));
2601 CEnvironment::iterator it
;
2605 while(*it
&& i
<size())
2612 if (value
== nullptr) // remove the variable
2620 this->insert(it
,*name
++);
2625 this->insert(it
, _T('='));
2631 this->insert(it
,*value
++);
2638 void CEnvironment::AddToPath(CString value
)
2640 value
.TrimRight(L
"\\");
2641 if (value
.IsEmpty())
2644 CString path
= GetEnv(L
"PATH").TrimRight(L
";") + L
";";
2646 // do not double add paths to %PATH%
2647 if (path
.Find(value
+ L
";") >= 0 || path
.Find(value
+ L
"\\;") >= 0)
2652 SetEnv(L
"PATH", path
);
2655 int CGit::GetGitEncode(TCHAR
* configkey
)
2657 CString str
=GetConfigValue(configkey
);
2662 return CUnicodeUtils::GetCPCode(str
);
2666 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2672 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2677 diff
= GetGitDiff();
2679 git_open_diff(&diff
, arg
);
2683 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2694 isStat
= !!strstr(arg
, "stat");
2699 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2701 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2710 for (int j
= 0; j
< count
; ++j
)
2719 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2720 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2721 &mode
,&IsBin
,&inc
,&dec
);
2723 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2724 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2726 path
.SetFromGit(strnewname
,&stroldname
);
2727 path
.ParserAction((BYTE
)mode
);
2731 path
.m_StatAdd
=_T("-");
2732 path
.m_StatDel
=_T("-");
2736 path
.m_StatAdd
.Format(_T("%d"),inc
);
2737 path
.m_StatDel
.Format(_T("%d"),dec
);
2739 PathList
->AddPath(path
);
2741 git_diff_flush(diff
);
2744 git_close_diff(diff
);
2749 int CGit::GetShortHASHLength() const
2754 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2758 REF_TYPE type
= CGit::UNKNOWN
;
2760 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2762 type
= CGit::LOCAL_BRANCH
;
2765 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2767 type
= CGit::REMOTE_BRANCH
;
2769 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2773 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2776 shortname
=_T("stash");
2778 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2780 if (shortname
.Find(_T("good")) == 0)
2782 type
= CGit::BISECT_GOOD
;
2783 shortname
= _T("good");
2786 if (shortname
.Find(_T("bad")) == 0)
2788 type
= CGit::BISECT_BAD
;
2789 shortname
= _T("bad");
2792 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2796 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2798 type
= CGit::UNKNOWN
;
2802 type
= CGit::UNKNOWN
;
2812 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2814 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2817 void CGit::SetGit2CredentialCallback(void* callback
)
2819 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2822 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2824 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2827 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2830 if (rev2
== GitRev::GetWorkingCopy())
2831 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2832 else if (rev1
== GitRev::GetWorkingCopy())
2833 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2844 if (diffContext
>= 0)
2845 unified
.Format(_T(" --unified=%d"), diffContext
);
2846 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2849 if (!path
.IsEmpty())
2852 cmd
+= path
.GetGitPathString();
2859 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2861 ATLASSERT(payload
&& text
);
2862 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2863 fwrite("\n", 1, 1, (FILE *)payload
);
2866 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2868 ATLASSERT(payload
&& line
);
2869 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2870 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2871 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2875 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2877 ATLASSERT(repo
&& identifier
&& tree
);
2879 /* try to resolve identifier */
2881 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2885 return GIT_ENOTFOUND
;
2888 switch (git_object_type(obj
))
2891 *tree
= (git_tree
*)obj
.Detach();
2893 case GIT_OBJ_COMMIT
:
2894 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2897 err
= GIT_ENOTFOUND
;
2903 /* use libgit2 get unified diff */
2904 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 */)
2906 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2907 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2909 CAutoRepository
repo(g_Git
.GetGitRepository());
2913 int isHeadOrphan
= git_repository_head_unborn(repo
);
2914 if (isHeadOrphan
== 1)
2916 else if (isHeadOrphan
!= 0)
2919 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2920 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2921 char *buf
= pathA
.GetBuffer();
2922 if (!pathA
.IsEmpty())
2924 opts
.pathspec
.strings
= &buf
;
2925 opts
.pathspec
.count
= 1;
2929 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2934 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2937 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2940 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2943 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2946 if (git_diff_merge(diff
, diff2
))
2951 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2954 if (tree1
.IsEmpty())
2962 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2965 if (tree2
.IsEmpty())
2967 /* don't check return value, there are not parent commit at first commit*/
2968 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2970 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2972 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2976 CAutoDiffStats stats
;
2977 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2980 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2982 statCallback(statBuf
, data
);
2984 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2987 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2990 if (git_patch_print(patch
, callback
, data
))
2994 pathA
.ReleaseBuffer();
2999 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
3001 if (UsingLibGit2(GIT_CMD_DIFF
))
3003 FILE *file
= nullptr;
3004 _tfopen_s(&file
, patchfile
, _T("w"));
3005 if (file
== nullptr)
3007 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
);
3014 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3015 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
3019 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
3021 ATLASSERT(payload
&& text
);
3022 CStringA
*str
= (CStringA
*) payload
;
3023 str
->Append(text
->ptr
, (int)text
->size
);
3024 str
->AppendChar('\n');
3027 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
3029 ATLASSERT(payload
&& line
);
3030 CStringA
*str
= (CStringA
*) payload
;
3031 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
3032 str
->Append(&line
->origin
, 1);
3033 str
->Append(line
->content
, (int)line
->content_len
);
3037 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
3039 if (UsingLibGit2(GIT_CMD_DIFF
))
3040 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
);
3044 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
3046 int ret
= Run(cmd
, &vector
);
3047 if (!vector
.empty())
3049 vector
.push_back(0); // vector is not NUL terminated
3050 buffer
->Append((char *)&vector
[0]);
3056 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3058 if (UsingLibGit2(GIT_CMD_REVERT
))
3060 CAutoRepository
repo(GetGitRepository());
3065 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3068 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3069 revert_opts
.mainline
= parent
;
3070 int result
= git_revert(repo
, commit
, &revert_opts
);
3072 return !result
? 0 : -1;
3078 merge
.Format(_T("-m %d "), parent
);
3079 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
3080 gitLastErr
= cmd
+ _T("\n");
3081 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3093 int CGit::DeleteRef(const CString
& reference
)
3095 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3097 CAutoRepository
repo(GetGitRepository());
3102 if (reference
.Right(3) == _T("^{}"))
3103 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3105 refA
= CUnicodeUtils::GetUTF8(reference
);
3108 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3112 if (git_reference_is_tag(ref
))
3113 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3114 else if (git_reference_is_branch(ref
))
3115 result
= git_branch_delete(ref
);
3116 else if (git_reference_is_remote(ref
))
3117 result
= git_branch_delete(ref
);
3119 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3125 CString cmd
, shortname
;
3126 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3127 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
3128 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3129 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
3130 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3131 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
3134 gitLastErr
= L
"unsupported reference type: " + reference
;
3138 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3146 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3148 if (PathFileExists(filename
))
3150 FILE *pFile
= nullptr;
3151 _tfopen_s(&pFile
, filename
, _T("r"));
3157 char s
[8196] = { 0 };
3158 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3161 str
+= CStringA(s
, read
);
3164 msg
= CUnicodeUtils::GetUnicode(str
);
3165 msg
.Replace(_T("\r\n"), _T("\n"));
3166 msg
.TrimRight(_T("\n"));
3170 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3171 return true; // load no further files
3176 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3179 return GetInitAddList(result
);
3185 count
= filterlist
->GetCount();
3187 CString head
= _T("HEAD");
3189 head
= _T("HEAD~1");
3191 for (int i
= 0; i
< count
; ++i
)
3197 // Prevent showing all files as modified when using cygwin's git
3199 cmd
= _T("git.exe status --");
3201 cmd
.Format(_T("git.exe status -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3206 // also list staged files which will be in the commit
3207 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3210 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3212 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3215 if (Run(cmd
, &cmdout
, &cmdErr
))
3217 int last
= cmdErr
.RevertFind(0, -1);
3219 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3220 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3223 out
.append(cmdout
, 0);
3225 result
.ParserFromLog(out
);
3227 // handle delete conflict case, when remote : modified, local : deleted.
3228 for (int i
= 0; i
< count
; ++i
)
3234 cmd
= _T("git.exe ls-files -u -t -z");
3236 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3240 CTGitPathList conflictlist
;
3241 conflictlist
.ParserFromLog(cmdout
);
3242 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3244 CTGitPath
* p
= result
.LookForGitPath(conflictlist
[j
].GetGitPathString());
3246 p
->m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3248 result
.AddPath(conflictlist
[j
]);
3252 // handle source files of file renames/moves (issue #860)
3253 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3254 for (int i
= 0; i
< count
; ++i
)
3260 cmd
= _T("git.exe ls-files -d -z");
3262 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3266 CTGitPathList deletelist
;
3267 deletelist
.ParserFromLog(cmdout
, true);
3268 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3270 CTGitPath
* p
= result
.LookForGitPath(deletelist
[j
].GetGitPathString());
3272 result
.AddPath(deletelist
[j
]);