1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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.
24 #include "GitConfig.h"
26 #include "UnicodeUtils.h"
29 #include "FormatMessageWrapper.h"
31 int CGit::m_LogEncode
=CP_UTF8
;
32 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
34 static LPTSTR
nextpath(wchar_t *path
, wchar_t *buf
, size_t buflen
)
36 wchar_t term
, *base
= path
;
38 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
41 term
= (*path
== L
'"') ? *path
++ : L
';';
43 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
46 *buf
= L
'\0'; /* reserved a byte via initial subtract */
48 while (*path
== term
|| *path
== L
';')
51 return (path
!= base
) ? path
: NULL
;
54 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
57 return _tstat(lpszFileName
, &st
) == 0;
60 static BOOL
FindGitPath()
63 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
70 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
71 _tgetenv_s(&size
, env
, size
, _T("PATH"));
73 TCHAR buf
[MAX_PATH
] = {0};
75 // search in all paths defined in PATH
76 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
78 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
80 // ensure trailing slash
81 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
82 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len
= _tcslen(buf
);
86 if ((len
+ 7) < MAX_PATH
)
87 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, _T("git.exe"));
91 if ( FileExists(buf
) )
95 CGit::ms_LastMsysGitDir
= buf
;
96 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir
))
103 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
112 static bool g_bSortLogical
;
113 static bool g_bSortLocalBranchesFirst
;
115 static void GetSortOptions()
117 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
119 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
120 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
121 if (g_bSortLocalBranchesFirst
)
122 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
125 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
128 return StrCmpLogicalW(left
, right
) < 0;
129 return StrCmpI(left
, right
) < 0;
132 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
134 if (g_bSortLocalBranchesFirst
)
136 int leftIsRemote
= left
.Find(_T("remotes/"));
137 int rightIsRemote
= right
.Find(_T("remotes/"));
139 if (leftIsRemote
== 0 && rightIsRemote
< 0)
141 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
145 return StrCmpLogicalW(left
, right
) < 0;
146 return StrCmpI(left
, right
) < 0;
149 #define MAX_DIRBUFFER 1000
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString
CGit::ms_LastMsysGitDir
;
153 int CGit::ms_LastMsysGitVersion
= 0;
159 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
160 m_CurrentDir
.ReleaseBuffer();
161 m_IsGitDllInited
= false;
163 m_GitSimpleListDiff
=0;
164 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
165 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
166 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), (1 << GIT_CMD_MERGE_BASE
) | (1 << GIT_CMD_DELETETAGBRANCH
) | (1 << GIT_CMD_GETONEFILE
));
168 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
171 this->m_bInitialized
=false;
173 m_critGitDllSec
.Init();
180 git_close_diff(m_GitDiff
);
183 if(this->m_GitSimpleListDiff
)
185 git_close_diff(m_GitSimpleListDiff
);
186 m_GitSimpleListDiff
=0;
190 bool CGit::IsBranchNameValid(const CString
& branchname
)
192 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
194 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
196 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
197 return !!git_reference_is_valid_name(branchA
);
200 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
202 SECURITY_ATTRIBUTES sa
;
203 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
204 HANDLE hStdioFile
= NULL
;
206 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
207 sa
.lpSecurityDescriptor
=NULL
;
208 sa
.bInheritHandle
=TRUE
;
209 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
211 CString err
= CFormatMessageWrapper();
212 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
213 return TGIT_GIT_ERROR_OPEN_PIP
;
215 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
217 CString err
= CFormatMessageWrapper();
218 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
221 return TGIT_GIT_ERROR_OPEN_PIP
;
226 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
227 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
231 PROCESS_INFORMATION pi
;
232 si
.cb
=sizeof(STARTUPINFO
);
236 si
.hStdError
= hWriteErr
;
238 si
.hStdError
= hWrite
;
240 si
.hStdOutput
=hStdioFile
;
242 si
.hStdOutput
=hWrite
;
244 si
.wShowWindow
=SW_HIDE
;
245 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
247 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
248 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
250 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
251 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
253 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
254 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
256 if(cmd
.Find(_T("git")) == 0)
258 int firstSpace
= cmd
.Find(_T(" "));
260 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
262 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
265 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
266 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
268 CString err
= CFormatMessageWrapper();
269 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
274 CloseHandle(hReadErr
);
275 CloseHandle(hWriteErr
);
277 return TGIT_GIT_ERROR_CREATE_PROCESS
;
284 CloseHandle(hWriteErr
);
292 *hErrReadOut
= hReadErr
;
296 //Must use sperate function to convert ANSI str to union code string
297 //Becuase A2W use stack as internal convert buffer.
298 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
305 len
= (int)strlen((const char*)p
);
310 int currentContentLen
= str
->GetLength();
311 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
312 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
313 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
316 // This method was originally used to check for orphaned branches
317 BOOL
CGit::CanParseRev(CString ref
)
323 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
333 // Checks if we have an orphaned HEAD
334 BOOL
CGit::IsInitRepos()
337 // handle error on reading HEAD hash as init repo
338 if (GetHash(hash
, _T("HEAD")) != 0)
340 return hash
.IsEmpty() ? TRUE
: FALSE
;
343 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
345 PASYNCREADSTDERRTHREADARGS pDataArray
;
346 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
349 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
350 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
352 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
359 int CGit::Run(CGitCall
* pcall
)
361 PROCESS_INFORMATION pi
;
362 HANDLE hRead
, hReadErr
;
363 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
364 return TGIT_GIT_ERROR_CREATE_PROCESS
;
367 ASYNCREADSTDERRTHREADARGS threadArguments
;
368 threadArguments
.fileHandle
= hReadErr
;
369 threadArguments
.pcall
= pcall
;
370 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
373 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
375 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
377 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
378 if(!bAborted
)//For now, flush output when command aborted.
379 if(pcall
->OnOutputData(data
,readnumber
))
386 WaitForSingleObject(thread
, INFINITE
);
388 CloseHandle(pi
.hThread
);
390 WaitForSingleObject(pi
.hProcess
, INFINITE
);
393 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
395 CString err
= CFormatMessageWrapper();
396 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
397 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
400 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
402 CloseHandle(pi
.hProcess
);
405 CloseHandle(hReadErr
);
408 class CGitCall_ByteVector
: public CGitCall
411 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
412 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
414 if (!m_pvector
|| size
== 0)
416 size_t oldsize
=m_pvector
->size();
417 m_pvector
->resize(m_pvector
->size()+size
);
418 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
421 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
423 if (!m_pvectorErr
|| size
== 0)
425 size_t oldsize
= m_pvectorErr
->size();
426 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
427 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
430 BYTE_VECTOR
* m_pvector
;
431 BYTE_VECTOR
* m_pvectorErr
;
434 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
436 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
439 int CGit::Run(CString cmd
, CString
* output
, int code
)
443 ret
= Run(cmd
, output
, &err
, code
);
445 if (output
&& !err
.IsEmpty())
447 if (!output
->IsEmpty())
454 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
456 BYTE_VECTOR vector
, vectorErr
;
459 ret
= Run(cmd
, &vector
, &vectorErr
);
461 ret
= Run(cmd
, &vector
);
464 StringAppend(output
, &(vector
[0]), code
);
468 vectorErr
.push_back(0);
469 StringAppend(outputErr
, &(vectorErr
[0]), code
);
475 class CGitCallCb
: public CGitCall
478 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
480 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
485 int oldEndPos
= m_buffer
.GetLength();
486 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
487 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
489 // Break into lines and feed to m_recv
491 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
493 m_recv(m_buffer
.Left(eolPos
));
494 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
499 virtual bool OnOutputErrData(const BYTE
*, size_t) override
501 return false; // Ignore error output for now
504 virtual void OnEnd() override
506 if (!m_buffer
.IsEmpty())
508 m_buffer
.Empty(); // Just for sure
512 GitReceiverFunc m_recv
;
516 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
518 CGitCallCb
call(cmd
, recv
);
522 CString
CGit::GetUserName(void)
525 env
.CopyProcessEnvironment();
526 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
527 if (!envname
.IsEmpty())
529 return GetConfigValue(L
"user.name");
531 CString
CGit::GetUserEmail(void)
534 env
.CopyProcessEnvironment();
535 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
536 if (!envmail
.IsEmpty())
539 return GetConfigValue(L
"user.email");
542 CString
CGit::GetConfigValue(const CString
& name
, int encoding
, BOOL RemoveCR
)
546 if(this->m_IsUseGitDLL
)
548 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
557 key
= CUnicodeUtils::GetMulti(name
, encoding
);
561 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
564 catch (const char *msg
)
566 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
570 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
, encoding
);
572 return configValue
.Tokenize(_T("\n"),start
);
578 cmd
.Format(L
"git.exe config %s", name
);
579 Run(cmd
, &configValue
, NULL
, encoding
);
581 return configValue
.Tokenize(_T("\n"),start
);
586 bool CGit::GetConfigValueBool(const CString
& name
)
588 CString configValue
= GetConfigValue(name
);
589 configValue
.MakeLower();
591 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
597 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
, int encoding
)
599 if(this->m_IsUseGitDLL
)
601 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
610 CStringA keya
, valuea
;
611 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
612 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
616 return [=]() { return get_set_config(keya
, valuea
, type
); }();
618 catch (const char *msg
)
620 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
631 option
= _T("--global");
634 option
= _T("--system");
639 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
641 if (Run(cmd
, &out
, NULL
, encoding
))
649 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
, int encoding
)
651 if(this->m_IsUseGitDLL
)
653 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
662 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
666 return [=]() { return get_set_config(keya
, nullptr, type
); }();
668 catch (const char *msg
)
670 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
681 option
= _T("--global");
684 option
= _T("--system");
689 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
691 if (Run(cmd
, &out
, NULL
, encoding
))
699 CString
CGit::GetCurrentBranch(bool fallback
)
702 //Run(_T("git.exe branch"),&branch);
704 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
705 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
707 return _T("(no branch)");
714 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
717 if(this->m_IsUseGitDLL
)
719 unsigned char sha1
[20] = { 0 };
722 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
723 const char *refs_heads_master
= nullptr;
726 refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
728 catch (const char *err
)
730 ::MessageBox(NULL
, _T("Could not resolve ref ") + CString(symbolicRefName
) + _T(".\nlibgit reports:\n") + CString(err
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
732 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
734 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
736 refName
= StripRefName(refName
);
743 cmd
.Format(L
"git.exe symbolic-ref %s", symbolicRefName
);
744 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
745 return CString();//Error
747 refName
= refName
.Tokenize(L
"\n", iStart
);
749 refName
= StripRefName(refName
);
754 CString
CGit::GetFullRefName(const CString
& shortRefName
)
758 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
759 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
760 return CString();//Error
762 return refName
.Tokenize(L
"\n", iStart
);
765 CString
CGit::StripRefName(CString refName
)
767 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
768 refName
= refName
.Mid(11);
769 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
770 refName
= refName
.Mid(5);
772 return refName
.Tokenize(_T("\n"),start
);
775 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
777 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
779 if ( sProjectRoot
.IsEmpty() )
783 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
786 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
789 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
797 fgets(s
, sizeof(s
), pFile
);
801 const char *pfx
= "ref: refs/heads/";
802 const int len
= 16;//strlen(pfx)
804 if ( !strncmp(s
, pfx
, len
) )
806 //# We're on a branch. It might not exist. But
807 //# HEAD looks good enough to be a branch.
808 CStringA
utf8Branch(s
+ len
);
809 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
810 sBranchOut
.TrimRight(_T(" \r\n\t"));
812 if ( sBranchOut
.IsEmpty() )
817 CStringA
utf8Hash(s
);
818 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
819 unicodeHash
.TrimRight(_T(" \r\n\t"));
820 if (CGitHash::IsValidSHA1(unicodeHash
))
821 sBranchOut
= unicodeHash
;
823 //# Assume this is a detached head.
824 sBranchOut
= _T("HEAD");
829 //# Assume this is a detached head.
838 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
841 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
845 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
847 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
849 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
851 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
853 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
855 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
857 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
861 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
863 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
865 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
870 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
876 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
883 CString file
= _T(" --");
886 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
889 num
.Format(_T("-n%d"),count
);
893 if(mask
& LOG_INFO_STAT
)
894 param
+= _T(" --numstat ");
895 if(mask
& LOG_INFO_FILESTATE
)
896 param
+= _T(" --raw ");
898 if(mask
& LOG_INFO_FULLHISTORY
)
899 param
+= _T(" --full-history ");
901 if(mask
& LOG_INFO_BOUNDARY
)
902 param
+= _T(" --left-right --boundary ");
904 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
905 param
+= _T(" --all ");
907 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
908 param
+= _T(" --branches ");
910 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
913 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
916 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
917 param
+= _T(" --first-parent ");
919 if(mask
& CGit::LOG_INFO_NO_MERGE
)
920 param
+= _T(" --no-merges ");
922 if(mask
& CGit::LOG_INFO_FOLLOW
)
923 param
+= _T(" --follow ");
925 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
928 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
929 param
+= _T(" --full-diff ");
931 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
932 param
+= _T(" --simplify-by-decoration ");
938 if( Filter
&& (Filter
->m_From
!= -1))
940 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
944 if( Filter
&& (Filter
->m_To
!= -1))
946 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
951 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
953 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
958 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
960 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
965 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
967 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
974 if(!Filter
->m_IsRegex
)
975 param
+= _T(" --fixed-strings ");
977 param
+= _T(" --regexp-ignore-case --extended-regexp ");
980 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
981 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
982 param
+= _T(" --topo-order");
983 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
984 param
+= _T(" --date-order");
986 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
987 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
991 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
992 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1001 void GetTempPath(CString
&path
)
1003 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1005 DWORD dwBufSize
=BUFSIZE
;
1006 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1007 lpPathBuffer
); // buffer for path
1008 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1012 path
.Format(_T("%s"),lpPathBuffer
);
1014 CString
GetTempFile()
1016 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1018 DWORD dwBufSize
=BUFSIZE
;
1019 TCHAR szTempName
[BUFSIZE
] = { 0 };
1022 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1023 lpPathBuffer
); // buffer for path
1024 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1028 // Create a temporary file.
1029 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1030 TEXT("Patch"), // temp file name prefix
1031 0, // create unique name
1032 szTempName
); // buffer for name
1040 return CString(szTempName
);
1044 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1046 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1047 if (result
== 0) return 0;
1048 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1055 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1056 CreateDirectory(lpBuffer
, NULL
);
1061 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1064 PROCESS_INFORMATION pi
;
1065 si
.cb
=sizeof(STARTUPINFO
);
1066 GetStartupInfo(&si
);
1068 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1069 psa
.bInheritHandle
=TRUE
;
1071 HANDLE hReadErr
, hWriteErr
;
1072 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1074 CString err
= CFormatMessageWrapper();
1075 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1076 return TGIT_GIT_ERROR_OPEN_PIP
;
1079 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1080 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1082 if (houtfile
== INVALID_HANDLE_VALUE
)
1084 CString err
= CFormatMessageWrapper();
1085 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1086 CloseHandle(hReadErr
);
1087 CloseHandle(hWriteErr
);
1088 return TGIT_GIT_ERROR_OPEN_PIP
;
1091 si
.wShowWindow
= SW_HIDE
;
1092 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1093 si
.hStdOutput
= houtfile
;
1094 si
.hStdError
= hWriteErr
;
1096 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1097 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1099 if(cmd
.Find(_T("git")) == 0)
1100 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1102 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1103 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1105 CString err
= CFormatMessageWrapper();
1106 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1108 CloseHandle(hReadErr
);
1109 CloseHandle(hWriteErr
);
1110 CloseHandle(houtfile
);
1111 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1114 BYTE_VECTOR stderrVector
;
1115 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1117 ASYNCREADSTDERRTHREADARGS threadArguments
;
1118 threadArguments
.fileHandle
= hReadErr
;
1119 threadArguments
.pcall
= &pcall
;
1120 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1122 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1124 CloseHandle(hWriteErr
);
1125 CloseHandle(hReadErr
);
1128 WaitForSingleObject(thread
, INFINITE
);
1130 stderrVector
.push_back(0);
1131 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1134 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1136 CString err
= CFormatMessageWrapper();
1137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1138 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1141 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1143 CloseHandle(pi
.hThread
);
1144 CloseHandle(pi
.hProcess
);
1145 CloseHandle(houtfile
);
1149 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1151 // no need to parse a ref if it's already a 40-byte hash
1152 if (CGitHash::IsValidSHA1(friendname
))
1154 hash
= CGitHash(friendname
);
1160 git_repository
*repo
= NULL
;
1161 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1162 if (git_repository_open(&repo
, gitdirA
))
1165 int isHeadOrphan
= git_repository_head_unborn(repo
);
1166 if (isHeadOrphan
!= 0)
1168 git_repository_free(repo
);
1170 if (isHeadOrphan
== 1)
1176 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1178 git_object
* gitObject
= NULL
;
1179 if (git_revparse_single(&gitObject
, repo
, refnameA
))
1181 git_repository_free(repo
);
1185 const git_oid
* oid
= git_object_id(gitObject
);
1188 git_object_free(gitObject
);
1189 git_repository_free(repo
);
1193 hash
= CGitHash((char *)oid
->id
);
1195 git_object_free(gitObject
); // also frees oid
1196 git_repository_free(repo
);
1203 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1205 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1206 hash
= CGitHash(gitLastErr
.Trim());
1213 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1218 cmd
=_T("git.exe ls-files -s -t -z");
1220 if (Run(cmd
, &cmdout
))
1223 if (outputlist
.ParserFromLsFile(cmdout
))
1225 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1226 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1230 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1234 if (ignoreSpaceAtEol
)
1235 ignore
+= _T(" --ignore-space-at-eol");
1236 if (ignoreSpaceChange
)
1237 ignore
+= _T(" --ignore-space-change");
1239 ignore
+= _T(" --ignore-all-space");
1240 if (ignoreBlankLines
)
1241 ignore
+= _T(" --ignore-blank-lines");
1243 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1246 if(rev1
== GIT_REV_ZERO
)
1247 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1249 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), ignore
, rev1
);
1253 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1260 outputlist
.ParserFromLog(out
);
1265 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1267 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1269 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1270 list
->push_back(str
);
1274 int CGit::GetTagList(STRING_VECTOR
&list
)
1276 if (this->m_IsUseLibGit2
)
1278 git_repository
*repo
= NULL
;
1280 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1281 if (git_repository_open(&repo
, gitdir
))
1284 git_strarray tag_names
;
1286 if (git_tag_list(&tag_names
, repo
))
1288 git_repository_free(repo
);
1292 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1294 CStringA
tagName(tag_names
.strings
[i
]);
1295 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1298 git_strarray_free(&tag_names
);
1300 git_repository_free(repo
);
1302 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1308 CString cmd
, output
;
1309 cmd
=_T("git.exe tag -l");
1310 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1317 one
=output
.Tokenize(_T("\n"),pos
);
1319 list
.push_back(one
);
1321 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1328 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1329 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1331 CString
CGit::GetGitLastErr(const CString
& msg
)
1333 if (this->m_IsUseLibGit2
)
1334 return GetLibGit2LastErr(msg
);
1335 else if (gitLastErr
.IsEmpty())
1336 return msg
+ _T("\nUnknown git.exe error.");
1339 CString lastError
= gitLastErr
;
1341 return msg
+ _T("\n") + lastError
;
1345 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1347 if (UsingLibGit2(cmd
))
1348 return GetLibGit2LastErr(msg
);
1349 else if (gitLastErr
.IsEmpty())
1350 return msg
+ _T("\nUnknown git.exe error.");
1353 CString lastError
= gitLastErr
;
1355 return msg
+ _T("\n") + lastError
;
1359 CString
CGit::GetLibGit2LastErr()
1361 const git_error
*libgit2err
= giterr_last();
1364 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1366 return _T("libgit2 returned: ") + lastError
;
1369 return _T("An error occoured in libgit2, but no message is available.");
1372 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1375 return msg
+ _T("\n") + GetLibGit2LastErr();
1376 return GetLibGit2LastErr();
1379 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1381 if(branchName
== "FETCH_HEAD")
1382 branchName
= DerefFetchHead();
1386 CString
CGit::FixBranchName(const CString
& branchName
)
1388 CString tempBranchName
= branchName
;
1389 FixBranchName_Mod(tempBranchName
);
1390 return tempBranchName
;
1393 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1397 git_repository
*repo
= nullptr;
1399 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1400 return true; // TODO: optimize error reporting
1402 git_reference
* tagRef
= nullptr;
1403 if (git_reference_lookup(&tagRef
, repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1405 git_repository_free(repo
);
1408 git_reference_free(tagRef
);
1410 git_reference
* branchRef
= nullptr;
1411 if (git_reference_lookup(&branchRef
, repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1413 git_repository_free(repo
);
1417 git_reference_free(branchRef
);
1418 git_repository_free(repo
);
1426 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1427 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1433 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1444 Checks if a branch or tag with the given name exists
1445 isBranch is true -> branch, tag otherwise
1447 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1451 git_repository
*repo
= nullptr;
1453 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1454 return false; // TODO: optimize error reporting
1458 prefix
= _T("refs/heads/");
1460 prefix
= _T("refs/tags/");
1462 git_reference
* ref
= nullptr;
1463 if (git_reference_lookup(&ref
, repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1465 git_repository_free(repo
);
1469 git_reference_free(ref
);
1470 git_repository_free(repo
);
1475 CString cmd
, output
;
1477 cmd
= _T("git.exe show-ref ");
1479 cmd
+= _T("--heads ");
1481 cmd
+= _T("--tags ");
1483 cmd
+= _T("refs/heads/") + name
;
1484 cmd
+= _T(" refs/tags/") + name
;
1486 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1489 if (!output
.IsEmpty())
1496 CString
CGit::DerefFetchHead()
1499 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1500 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1501 int forMergeLineCount
= 0;
1503 std::string hashToReturn
;
1504 while(getline(fetchHeadFile
, line
))
1506 //Tokenize this line
1507 std::string::size_type prevPos
= 0;
1508 std::string::size_type pos
= line
.find('\t');
1509 if(pos
== std::string::npos
) continue; //invalid line
1511 std::string hash
= line
.substr(0, pos
);
1512 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1514 bool forMerge
= pos
== prevPos
;
1515 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1517 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1522 hashToReturn
= hash
;
1523 ++forMergeLineCount
;
1524 if(forMergeLineCount
> 1)
1525 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1529 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1532 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1538 git_repository
*repo
= nullptr;
1540 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1543 if (git_repository_head_detached(repo
) == 1)
1544 cur
= _T("(detached from ");
1546 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1548 git_branch_iterator
* it
= nullptr;
1550 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1551 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1552 flags
= GIT_BRANCH_ALL
;
1553 else if (type
& BRANCH_REMOTE
)
1554 flags
= GIT_BRANCH_REMOTE
;
1556 if (git_branch_iterator_new(&it
, repo
, flags
))
1558 git_repository_free(repo
);
1562 git_reference
* ref
= nullptr;
1563 git_branch_t branchType
;
1564 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1566 const char * name
= nullptr;
1567 if (git_branch_name(&name
, ref
))
1569 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1570 if (branchType
& GIT_BRANCH_REMOTE
)
1571 list
.push_back(_T("remotes/") + branchname
);
1574 if (git_branch_is_head(ref
))
1576 list
.push_back(branchname
);
1578 git_reference_free(ref
);
1581 git_branch_iterator_free(it
);
1583 git_repository_free(repo
);
1587 CString cmd
, output
;
1588 cmd
= _T("git.exe branch --no-color");
1590 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1592 else if (type
& BRANCH_REMOTE
)
1595 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1602 one
= output
.Tokenize(_T("\n"), pos
);
1603 one
.Trim(L
" \r\n\t");
1604 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1605 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1606 if (one
[0] == _T('*'))
1611 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1612 list
.push_back(one
);
1617 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1618 list
.push_back(L
"FETCH_HEAD");
1620 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1622 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1624 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1637 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1639 if (this->m_IsUseLibGit2
)
1641 git_repository
*repo
= NULL
;
1643 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1644 if (git_repository_open(&repo
, gitdir
))
1647 git_strarray remotes
;
1649 if (git_remote_list(&remotes
, repo
))
1651 git_repository_free(repo
);
1655 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1657 CStringA
remote(remotes
.strings
[i
]);
1658 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1661 git_strarray_free(&remotes
);
1663 git_repository_free(repo
);
1665 std::sort(list
.begin(), list
.end());
1672 CString cmd
, output
;
1673 cmd
=_T("git.exe remote");
1674 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1681 one
=output
.Tokenize(_T("\n"),pos
);
1683 list
.push_back(one
);
1690 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1692 CString cmd
, out
, err
;
1693 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1694 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1696 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1703 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1704 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1705 if (one
.Find(_T("^{}")) >= 1)
1708 list
.push_back(one
);
1710 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1714 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1716 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1718 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1719 list
->push_back(str
);
1723 int CGit::GetRefList(STRING_VECTOR
&list
)
1725 if (this->m_IsUseLibGit2
)
1727 git_repository
*repo
= NULL
;
1729 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1730 if (git_repository_open(&repo
, gitdir
))
1733 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1735 git_repository_free(repo
);
1739 git_repository_free(repo
);
1741 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1747 CString cmd
, output
;
1748 cmd
=_T("git.exe show-ref -d");
1749 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1756 one
=output
.Tokenize(_T("\n"),pos
);
1757 int start
=one
.Find(_T(" "),0);
1761 name
=one
.Right(one
.GetLength()-start
-1);
1762 list
.push_back(name
);
1765 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1771 typedef struct map_each_ref_payload
{
1772 git_repository
* repo
;
1773 MAP_HASH_NAME
* map
;
1774 } map_each_ref_payload
;
1776 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1778 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1781 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1783 git_object
* gitObject
= NULL
;
1787 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1792 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1794 str
+= _T("^{}"); // deref tag
1795 git_object
* derefedTag
= NULL
;
1796 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1800 git_object_free(gitObject
);
1801 gitObject
= derefedTag
;
1804 const git_oid
* oid
= git_object_id(gitObject
);
1810 CGitHash
hash((char *)oid
->id
);
1811 (*payloadContent
->map
)[hash
].push_back(str
);
1816 git_object_free(gitObject
);
1823 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1825 if (this->m_IsUseLibGit2
)
1827 git_repository
*repo
= NULL
;
1829 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1830 if (git_repository_open(&repo
, gitdir
))
1833 map_each_ref_payload payloadContent
= { repo
, &map
};
1835 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1837 git_repository_free(repo
);
1841 git_repository_free(repo
);
1843 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1845 std::sort(it
->second
.begin(), it
->second
.end());
1852 CString cmd
, output
;
1853 cmd
=_T("git.exe show-ref -d");
1854 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1861 one
=output
.Tokenize(_T("\n"),pos
);
1862 int start
=one
.Find(_T(" "),0);
1866 name
=one
.Right(one
.GetLength()-start
-1);
1869 hash
=one
.Left(start
);
1871 map
[CGitHash(hash
)].push_back(name
);
1879 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1881 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1882 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1885 static void SetLibGit2TemplatePath(const CString
&value
)
1887 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1888 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1891 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1898 this->m_Environment
.clear();
1899 m_Environment
.CopyProcessEnvironment();
1902 size_t homesize
,size
;
1904 // set HOME if not set already
1905 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1907 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1910 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1911 if (sshclient
.IsEmpty())
1912 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1914 if(!sshclient
.IsEmpty())
1916 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1917 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1921 TCHAR sPlink
[MAX_PATH
] = {0};
1922 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1923 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1925 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1926 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1927 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1932 TCHAR sAskPass
[MAX_PATH
] = {0};
1933 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1934 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1937 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1938 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1939 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1940 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1944 // add git/bin path to PATH
1946 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1947 CString str
= msysdir
;
1948 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1953 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1954 str
= msyslocalinstalldir
;
1955 str
.TrimRight(_T("\\"));
1958 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1959 str
= msysinstalldir
;
1960 str
.TrimRight(_T("\\"));
1962 if ( !str
.IsEmpty() )
1966 CGit::ms_LastMsysGitDir
= str
;
1971 // search PATH if git/bin directory is already present
1972 if ( FindGitPath() )
1974 m_bInitialized
= TRUE
;
1975 msysdir
= CGit::ms_LastMsysGitDir
;
1985 CGit::ms_LastMsysGitDir
= str
;
1988 // check for git.exe existance (maybe it was deinstalled in the meantime)
1989 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1992 // Configure libgit2 search paths
1994 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1995 msysGitDir
.ReleaseBuffer();
1996 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1997 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1998 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1999 CString msysGitTemplateDir
;
2000 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
2001 msysGitTemplateDir
.ReleaseBuffer();
2002 SetLibGit2TemplatePath(msysGitTemplateDir
);
2005 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
2008 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
2010 m_Environment
.SetEnv(_T("PATH"), path
);
2012 CString str1
= m_Environment
.GetEnv(_T("PATH"));
2014 CString sOldPath
= oldpath
;
2017 m_bInitialized
= TRUE
;
2021 CString
CGit::GetHomeDirectory()
2023 const wchar_t * homeDir
= wget_windows_home_directory();
2024 return CString(homeDir
, (int)wcslen(homeDir
));
2027 CString
CGit::GetGitLocalConfig()
2030 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
2031 path
+= _T("config");
2035 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2037 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2040 CString
CGit::GetGitGlobalConfig()
2042 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2045 CString
CGit::GetGitGlobalXDGConfigPath()
2047 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2050 CString
CGit::GetGitGlobalXDGConfig()
2052 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2055 CString
CGit::GetGitSystemConfig()
2057 const wchar_t * systemConfig
= wget_msysgit_etc();
2058 return CString(systemConfig
, (int)wcslen(systemConfig
));
2061 BOOL
CGit::CheckCleanWorkTree()
2065 cmd
=_T("git.exe rev-parse --verify HEAD");
2067 if(Run(cmd
,&out
,CP_UTF8
))
2070 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2071 if(Run(cmd
,&out
,CP_UTF8
))
2074 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2075 if(Run(cmd
,&out
,CP_UTF8
))
2078 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2079 if(Run(cmd
,&out
,CP_UTF8
))
2084 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
2087 for (int i
= 0; i
< list
.GetCount(); ++i
)
2089 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
2095 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
2099 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2101 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2104 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2105 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2109 // if the filenames only differ in case, we have to pass "-f"
2110 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2112 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2113 if (Run(cmd
, &out
, CP_UTF8
))
2115 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2119 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2120 if (Run(cmd
, &out
, CP_UTF8
))
2122 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2127 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2128 { //To init git repository, there are not HEAD, so we can use git reset command
2129 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2131 if (Run(cmd
, &out
, CP_UTF8
))
2133 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2139 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2140 if (Run(cmd
, &out
, CP_UTF8
))
2142 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2147 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2149 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2150 if (Run(cmd
, &out
, CP_UTF8
))
2152 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2160 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2166 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2168 cmd
=_T("git.exe ls-files -u -t -z");
2170 if (Run(cmd
, &vector
))
2175 if (list
.ParserFromLsFile(vector
))
2181 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2183 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2185 CGitHash fromHash
, toHash
, baseHash
;
2186 if (GetHash(toHash
, FixBranchName(to
)))
2189 if (GetHash(fromHash
, FixBranchName(from
)))
2192 git_repository
*repo
= nullptr;
2193 if (git_repository_open(&repo
, CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
)))
2197 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2199 git_repository_free(repo
);
2203 baseHash
= baseOid
.id
;
2206 *commonAncestor
= baseHash
;
2208 git_repository_free(repo
);
2210 return fromHash
== baseHash
;
2214 CGitHash basehash
,hash
;
2216 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2218 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2222 basehash
= base
.Trim();
2224 GetHash(hash
, from
);
2227 *commonAncestor
= basehash
;
2229 return hash
== basehash
;
2232 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2235 for (int i
= 0; i
< 4; ++i
)
2238 ret
|= hash
.m_hash
[i
];
2243 int CGit::RefreshGitIndex()
2245 if(g_Git
.m_IsUseGitDLL
)
2247 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2250 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2261 cmd
=_T("git.exe update-index --refresh");
2262 return Run(cmd
, &output
, CP_UTF8
);
2266 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2268 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2271 if (GetHash(hash
, Refname
))
2274 git_repository
*repo
= nullptr;
2275 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
2278 git_commit
* commit
= nullptr;
2279 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2281 git_repository_free(repo
);
2285 git_tree
* tree
= nullptr;
2286 if (git_commit_tree(&tree
, commit
))
2288 git_commit_free(commit
);
2289 git_repository_free(repo
);
2293 git_tree_entry
* entry
= nullptr;
2294 if (git_tree_entry_bypath(&entry
, tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2296 git_tree_free(tree
);
2297 git_commit_free(commit
);
2298 git_repository_free(repo
);
2302 git_blob
* blob
= nullptr;
2303 if (git_tree_entry_to_object((git_object
**)&blob
, repo
, entry
))
2305 git_tree_entry_free(entry
);
2306 git_tree_free(tree
);
2307 git_commit_free(commit
);
2308 git_repository_free(repo
);
2312 FILE *file
= nullptr;
2313 _tfopen_s(&file
, outputfile
, _T("w"));
2314 if (file
== nullptr)
2316 giterr_set_str(GITERR_NONE
, "Could not create file.");
2317 git_blob_free(blob
);
2318 git_tree_entry_free(entry
);
2319 git_tree_free(tree
);
2320 git_commit_free(commit
);
2321 git_repository_free(repo
);
2324 git_buf buf
= { 0 };
2325 if (git_blob_filtered_content(&buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2327 git_blob_free(blob
);
2328 git_tree_entry_free(entry
);
2329 git_tree_free(tree
);
2330 git_commit_free(commit
);
2331 git_repository_free(repo
);
2334 if (fwrite(buf
.ptr
, sizeof(char), buf
.size
, file
) != buf
.size
)
2336 giterr_set_str(GITERR_OS
, "Could not write to file.");
2340 git_blob_free(blob
);
2341 git_tree_entry_free(entry
);
2342 git_tree_free(tree
);
2343 git_commit_free(commit
);
2344 git_repository_free(repo
);
2350 git_blob_free(blob
);
2351 git_tree_entry_free(entry
);
2352 git_tree_free(tree
);
2353 git_commit_free(commit
);
2354 git_repository_free(repo
);
2358 else if (g_Git
.m_IsUseGitDLL
)
2360 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2363 g_Git
.CheckAndInitDll();
2364 CStringA ref
, patha
, outa
;
2365 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2366 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2367 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2368 ::DeleteFile(outputfile
);
2369 return git_checkout_file(ref
, patha
, outa
);
2372 catch (const char * msg
)
2374 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2379 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2386 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2387 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2390 void CEnvironment::CopyProcessEnvironment()
2392 TCHAR
*porig
= GetEnvironmentStrings();
2394 while(*p
!=0 || *(p
+1) !=0)
2395 this->push_back(*p
++);
2397 push_back(_T('\0'));
2398 push_back(_T('\0'));
2400 FreeEnvironmentStrings(porig
);
2403 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2406 for (size_t i
= 0; i
< size(); ++i
)
2410 CString sname
= str
.Tokenize(_T("="),start
);
2411 if(sname
.CompareNoCase(name
) == 0)
2413 return &(*this)[i
+start
];
2420 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2423 for (i
= 0; i
< size(); ++i
)
2425 CString str
= &(*this)[i
];
2427 CString sname
= str
.Tokenize(_T("="),start
);
2428 if(sname
.CompareNoCase(name
) == 0)
2437 i
-= 1; // roll back terminate \0\0
2438 this->push_back(_T('\0'));
2441 CEnvironment::iterator it
;
2445 while(*it
&& i
<size())
2454 this->insert(it
,*name
++);
2459 this->insert(it
, _T('='));
2465 this->insert(it
,*value
++);
2472 int CGit::GetGitEncode(TCHAR
* configkey
)
2474 CString str
=GetConfigValue(configkey
);
2479 return CUnicodeUtils::GetCPCode(str
);
2483 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2489 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2492 diff
= GetGitDiff();
2494 git_open_diff(&diff
, arg
);
2503 isStat
= !!strstr(arg
, "stat");
2508 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2510 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2519 for (int j
= 0; j
< count
; ++j
)
2528 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2529 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2530 &mode
,&IsBin
,&inc
,&dec
);
2532 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2533 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2535 path
.SetFromGit(strnewname
,&stroldname
);
2536 path
.ParserAction((BYTE
)mode
);
2540 path
.m_StatAdd
=_T("-");
2541 path
.m_StatDel
=_T("-");
2545 path
.m_StatAdd
.Format(_T("%d"),inc
);
2546 path
.m_StatDel
.Format(_T("%d"),dec
);
2548 PathList
->AddPath(path
);
2550 git_diff_flush(diff
);
2553 git_close_diff(diff
);
2558 int CGit::GetShortHASHLength()
2563 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2567 REF_TYPE type
= CGit::UNKNOWN
;
2569 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2571 type
= CGit::LOCAL_BRANCH
;
2574 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2576 type
= CGit::REMOTE_BRANCH
;
2578 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2582 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2585 shortname
=_T("stash");
2587 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2589 if (shortname
.Find(_T("good")) == 0)
2591 type
= CGit::BISECT_GOOD
;
2592 shortname
= _T("good");
2595 if (shortname
.Find(_T("bad")) == 0)
2597 type
= CGit::BISECT_BAD
;
2598 shortname
= _T("bad");
2601 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2605 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2607 type
= CGit::UNKNOWN
;
2611 type
= CGit::UNKNOWN
;
2621 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
)
2623 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2626 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2629 if (rev2
== GitRev::GetWorkingCopy())
2630 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2631 else if (rev1
== GitRev::GetWorkingCopy())
2632 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2643 if (diffContext
> 0)
2644 unified
.Format(_T(" --unified=%d"), diffContext
);
2645 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2648 if (!path
.IsEmpty())
2651 cmd
+= path
.GetGitPathString();
2658 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2660 ATLASSERT(payload
&& line
);
2661 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2662 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2663 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2667 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2669 ATLASSERT(repo
&& identifier
&& tree
);
2671 /* try to resolve identifier */
2672 git_object
*obj
= nullptr;
2673 if (git_revparse_single(&obj
, repo
, identifier
))
2677 return GIT_ENOTFOUND
;
2680 switch (git_object_type(obj
))
2683 *tree
= (git_tree
*)obj
;
2685 case GIT_OBJ_COMMIT
:
2686 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2687 git_object_free(obj
);
2690 err
= GIT_ENOTFOUND
;
2696 /* use libgit2 get unified diff */
2697 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const git_revnum_t
& revOld
, const git_revnum_t
& revNew
, git_diff_line_cb callback
, void *data
, bool /* bMerge */)
2699 git_repository
*repo
= nullptr;
2700 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2701 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2702 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2705 if (git_repository_open(&repo
, gitdirA
))
2708 int isHeadOrphan
= git_repository_head_unborn(repo
);
2709 if (isHeadOrphan
!= 0)
2711 git_repository_free(repo
);
2712 if (isHeadOrphan
== 1)
2718 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2719 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2720 char *buf
= pathA
.GetBuffer();
2721 if (!pathA
.IsEmpty())
2723 opts
.pathspec
.strings
= &buf
;
2724 opts
.pathspec
.count
= 1;
2726 git_diff
*diff
= nullptr;
2728 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2730 git_tree
*t1
= nullptr;
2731 git_diff
*diff2
= nullptr;
2735 if (revNew
!= GitRev::GetWorkingCopy())
2737 if (resolve_to_tree(repo
, tree1
, &t1
))
2743 if (revOld
!= GitRev::GetWorkingCopy())
2745 if (resolve_to_tree(repo
, tree2
, &t1
))
2752 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2756 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2760 ret
= git_diff_merge(diff
, diff2
);
2764 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2767 if (git_patch_from_diff(&patch
, diff
, i
))
2773 if (git_patch_print(patch
, callback
, data
))
2775 git_patch_free(patch
);
2780 git_patch_free(patch
);
2784 git_diff_free(diff
);
2786 git_diff_free(diff2
);
2792 git_tree
*t1
= nullptr, *t2
= nullptr;
2795 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2801 if (tree1
.IsEmpty())
2807 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2813 if (tree2
.IsEmpty())
2815 /* don't check return value, there are not parent commit at first commit*/
2816 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2818 else if (resolve_to_tree(repo
, tree2
, &t2
))
2823 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2829 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2832 if (git_patch_from_diff(&patch
, diff
, i
))
2838 if (git_patch_print(patch
, callback
, data
))
2840 git_patch_free(patch
);
2845 git_patch_free(patch
);
2850 git_diff_free(diff
);
2856 git_repository_free(repo
);
2857 pathA
.ReleaseBuffer();
2862 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2864 if (UsingLibGit2(GIT_CMD_DIFF
))
2866 FILE *file
= nullptr;
2867 _tfopen_s(&file
, patchfile
, _T("w"));
2868 if (file
== nullptr)
2870 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2877 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2878 return g_Git
.RunLogFile(cmd
, patchfile
, &gitLastErr
);
2882 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2884 ATLASSERT(payload
&& line
);
2885 CStringA
*str
= (CStringA
*) payload
;
2886 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2887 str
->Append(&line
->origin
, 1);
2888 str
->Append(line
->content
, (int)line
->content_len
);
2892 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2894 if (UsingLibGit2(GIT_CMD_DIFF
))
2895 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2899 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2901 int ret
= Run(cmd
, &vector
);
2902 if (!vector
.empty())
2904 vector
.push_back(0); // vector is not NUL terminated
2905 buffer
->Append((char *)&vector
[0]);
2911 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2913 if (UsingLibGit2(GIT_CMD_REVERT
))
2915 git_repository
*repo
= nullptr;
2916 CStringA gitdirA
= CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString());
2917 if (git_repository_open(&repo
, gitdirA
))
2920 git_commit
*commit
= nullptr;
2921 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2923 git_repository_free(repo
);
2927 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2928 revert_opts
.mainline
= parent
;
2929 int result
= git_revert(repo
, commit
, &revert_opts
);
2931 git_commit_free(commit
);
2932 git_repository_free(repo
);
2933 return !result
? 0 : -1;
2939 merge
.Format(_T("-m %d "), parent
);
2940 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2941 gitLastErr
= cmd
+ _T("\n");
2942 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))
2954 int CGit::DeleteRef(const CString
& reference
)
2956 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2958 git_repository
*repo
= nullptr;
2959 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
2962 git_reference
*ref
= nullptr;
2963 if (git_reference_lookup(&ref
, repo
, CUnicodeUtils::GetUTF8(reference
)))
2965 git_repository_free(repo
);
2970 if (git_reference_is_tag(ref
))
2971 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2972 else if (git_reference_is_branch(ref
))
2973 result
= git_branch_delete(ref
);
2974 else if (git_reference_is_remote(ref
))
2975 result
= git_branch_delete(ref
);
2977 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2979 git_reference_free(ref
);
2980 git_repository_free(repo
);
2985 CString cmd
, shortname
;
2986 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2987 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2988 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2989 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2990 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2991 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2994 gitLastErr
= L
"unsupported reference type: " + reference
;
2998 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))
3006 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3008 if (PathFileExists(filename
))
3010 FILE *pFile
= nullptr;
3011 _tfopen_s(&pFile
, filename
, _T("r"));
3017 char s
[8196] = { 0 };
3018 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3021 str
+= CStringA(s
, read
);
3024 msg
= CUnicodeUtils::GetUnicode(str
);
3025 msg
.Replace(_T("\r\n"), _T("\n"));
3026 msg
.TrimRight(_T("\n"));
3030 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3031 return true; // load no further files