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()
716 // return symbolic name of HEAD or empty string (e.g. on detached head)
717 // must also return the symbolic name of HEAD in unborn state
718 // NOTE: cannot use libgit2 git_repository_head since it fails for unborn state
720 if (GetCurrentBranchFromFile(g_Git
.m_CurrentDir
, refName
))
725 CString
CGit::GetFullRefName(const CString
& shortRefName
)
729 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
730 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
731 return CString();//Error
733 return refName
.Tokenize(L
"\n", iStart
);
736 CString
CGit::StripRefName(CString refName
)
738 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
739 refName
= refName
.Mid(11);
740 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
741 refName
= refName
.Mid(5);
743 return refName
.Tokenize(_T("\n"),start
);
746 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
748 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
750 if ( sProjectRoot
.IsEmpty() )
754 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
757 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
760 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
768 fgets(s
, sizeof(s
), pFile
);
772 const char *pfx
= "ref: refs/heads/";
773 const int len
= 16;//strlen(pfx)
775 if ( !strncmp(s
, pfx
, len
) )
777 //# We're on a branch. It might not exist. But
778 //# HEAD looks good enough to be a branch.
779 CStringA
utf8Branch(s
+ len
);
780 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
781 sBranchOut
.TrimRight(_T(" \r\n\t"));
783 if ( sBranchOut
.IsEmpty() )
788 CStringA
utf8Hash(s
);
789 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
790 unicodeHash
.TrimRight(_T(" \r\n\t"));
791 if (CGitHash::IsValidSHA1(unicodeHash
))
792 sBranchOut
= unicodeHash
;
794 //# Assume this is a detached head.
795 sBranchOut
= _T("HEAD");
800 //# Assume this is a detached head.
809 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
812 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
816 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
818 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
820 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
822 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
824 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
826 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
828 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
832 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
834 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
836 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
841 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
847 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
854 CString file
= _T(" --");
857 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
860 num
.Format(_T("-n%d"),count
);
864 if(mask
& LOG_INFO_STAT
)
865 param
+= _T(" --numstat ");
866 if(mask
& LOG_INFO_FILESTATE
)
867 param
+= _T(" --raw ");
869 if(mask
& LOG_INFO_FULLHISTORY
)
870 param
+= _T(" --full-history ");
872 if(mask
& LOG_INFO_BOUNDARY
)
873 param
+= _T(" --left-right --boundary ");
875 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
876 param
+= _T(" --all ");
878 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
879 param
+= _T(" --branches ");
881 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
884 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
887 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
888 param
+= _T(" --first-parent ");
890 if(mask
& CGit::LOG_INFO_NO_MERGE
)
891 param
+= _T(" --no-merges ");
893 if(mask
& CGit::LOG_INFO_FOLLOW
)
894 param
+= _T(" --follow ");
896 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
899 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
900 param
+= _T(" --full-diff ");
902 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
903 param
+= _T(" --simplify-by-decoration ");
909 if( Filter
&& (Filter
->m_From
!= -1))
911 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
915 if( Filter
&& (Filter
->m_To
!= -1))
917 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
922 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
924 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
929 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
931 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
936 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
938 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
945 if(!Filter
->m_IsRegex
)
946 param
+= _T(" --fixed-strings ");
948 param
+= _T(" --regexp-ignore-case --extended-regexp ");
951 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
952 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
953 param
+= _T(" --topo-order");
954 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
955 param
+= _T(" --date-order");
957 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
958 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
962 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
963 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
972 void GetTempPath(CString
&path
)
974 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
976 DWORD dwBufSize
=BUFSIZE
;
977 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
978 lpPathBuffer
); // buffer for path
979 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
983 path
.Format(_T("%s"),lpPathBuffer
);
985 CString
GetTempFile()
987 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
989 DWORD dwBufSize
=BUFSIZE
;
990 TCHAR szTempName
[BUFSIZE
] = { 0 };
993 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
994 lpPathBuffer
); // buffer for path
995 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
999 // Create a temporary file.
1000 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1001 TEXT("Patch"), // temp file name prefix
1002 0, // create unique name
1003 szTempName
); // buffer for name
1011 return CString(szTempName
);
1015 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1017 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1018 if (result
== 0) return 0;
1019 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1026 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1027 CreateDirectory(lpBuffer
, NULL
);
1032 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1035 PROCESS_INFORMATION pi
;
1036 si
.cb
=sizeof(STARTUPINFO
);
1037 GetStartupInfo(&si
);
1039 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1040 psa
.bInheritHandle
=TRUE
;
1042 HANDLE hReadErr
, hWriteErr
;
1043 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1045 CString err
= CFormatMessageWrapper();
1046 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1047 return TGIT_GIT_ERROR_OPEN_PIP
;
1050 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1051 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1053 if (houtfile
== INVALID_HANDLE_VALUE
)
1055 CString err
= CFormatMessageWrapper();
1056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1057 CloseHandle(hReadErr
);
1058 CloseHandle(hWriteErr
);
1059 return TGIT_GIT_ERROR_OPEN_PIP
;
1062 si
.wShowWindow
= SW_HIDE
;
1063 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1064 si
.hStdOutput
= houtfile
;
1065 si
.hStdError
= hWriteErr
;
1067 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1068 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1070 if(cmd
.Find(_T("git")) == 0)
1071 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1073 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1074 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1076 CString err
= CFormatMessageWrapper();
1077 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1079 CloseHandle(hReadErr
);
1080 CloseHandle(hWriteErr
);
1081 CloseHandle(houtfile
);
1082 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1085 BYTE_VECTOR stderrVector
;
1086 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1088 ASYNCREADSTDERRTHREADARGS threadArguments
;
1089 threadArguments
.fileHandle
= hReadErr
;
1090 threadArguments
.pcall
= &pcall
;
1091 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1093 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1095 CloseHandle(hWriteErr
);
1096 CloseHandle(hReadErr
);
1099 WaitForSingleObject(thread
, INFINITE
);
1101 stderrVector
.push_back(0);
1102 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1105 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1107 CString err
= CFormatMessageWrapper();
1108 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1109 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1112 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1114 CloseHandle(pi
.hThread
);
1115 CloseHandle(pi
.hProcess
);
1116 CloseHandle(houtfile
);
1120 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1122 // no need to parse a ref if it's already a 40-byte hash
1123 if (CGitHash::IsValidSHA1(friendname
))
1125 hash
= CGitHash(friendname
);
1131 git_repository
*repo
= NULL
;
1132 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1133 if (git_repository_open(&repo
, gitdirA
))
1136 int isHeadOrphan
= git_repository_head_unborn(repo
);
1137 if (isHeadOrphan
!= 0)
1139 git_repository_free(repo
);
1141 if (isHeadOrphan
== 1)
1147 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1149 git_object
* gitObject
= NULL
;
1150 if (git_revparse_single(&gitObject
, repo
, refnameA
))
1152 git_repository_free(repo
);
1156 const git_oid
* oid
= git_object_id(gitObject
);
1159 git_object_free(gitObject
);
1160 git_repository_free(repo
);
1164 hash
= CGitHash((char *)oid
->id
);
1166 git_object_free(gitObject
); // also frees oid
1167 git_repository_free(repo
);
1174 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1176 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1177 hash
= CGitHash(gitLastErr
.Trim());
1184 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1189 cmd
=_T("git.exe ls-files -s -t -z");
1191 if (Run(cmd
, &cmdout
))
1194 if (outputlist
.ParserFromLsFile(cmdout
))
1196 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1197 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1201 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1205 if (ignoreSpaceAtEol
)
1206 ignore
+= _T(" --ignore-space-at-eol");
1207 if (ignoreSpaceChange
)
1208 ignore
+= _T(" --ignore-space-change");
1210 ignore
+= _T(" --ignore-all-space");
1211 if (ignoreBlankLines
)
1212 ignore
+= _T(" --ignore-blank-lines");
1214 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1217 if(rev1
== GIT_REV_ZERO
)
1218 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1220 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), ignore
, rev1
);
1224 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1231 outputlist
.ParserFromLog(out
);
1236 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1238 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1240 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1241 list
->push_back(str
);
1245 int CGit::GetTagList(STRING_VECTOR
&list
)
1247 if (this->m_IsUseLibGit2
)
1249 git_repository
*repo
= NULL
;
1251 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1252 if (git_repository_open(&repo
, gitdir
))
1255 git_strarray tag_names
;
1257 if (git_tag_list(&tag_names
, repo
))
1259 git_repository_free(repo
);
1263 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1265 CStringA
tagName(tag_names
.strings
[i
]);
1266 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1269 git_strarray_free(&tag_names
);
1271 git_repository_free(repo
);
1273 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1279 CString cmd
, output
;
1280 cmd
=_T("git.exe tag -l");
1281 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1288 one
=output
.Tokenize(_T("\n"),pos
);
1290 list
.push_back(one
);
1292 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1299 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1300 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1302 CString
CGit::GetGitLastErr(const CString
& msg
)
1304 if (this->m_IsUseLibGit2
)
1305 return GetLibGit2LastErr(msg
);
1306 else if (gitLastErr
.IsEmpty())
1307 return msg
+ _T("\nUnknown git.exe error.");
1310 CString lastError
= gitLastErr
;
1312 return msg
+ _T("\n") + lastError
;
1316 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1318 if (UsingLibGit2(cmd
))
1319 return GetLibGit2LastErr(msg
);
1320 else if (gitLastErr
.IsEmpty())
1321 return msg
+ _T("\nUnknown git.exe error.");
1324 CString lastError
= gitLastErr
;
1326 return msg
+ _T("\n") + lastError
;
1330 CString
CGit::GetLibGit2LastErr()
1332 const git_error
*libgit2err
= giterr_last();
1335 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1337 return _T("libgit2 returned: ") + lastError
;
1340 return _T("An error occoured in libgit2, but no message is available.");
1343 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1346 return msg
+ _T("\n") + GetLibGit2LastErr();
1347 return GetLibGit2LastErr();
1350 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1352 if(branchName
== "FETCH_HEAD")
1353 branchName
= DerefFetchHead();
1357 CString
CGit::FixBranchName(const CString
& branchName
)
1359 CString tempBranchName
= branchName
;
1360 FixBranchName_Mod(tempBranchName
);
1361 return tempBranchName
;
1364 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1368 git_repository
*repo
= nullptr;
1370 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1371 return true; // TODO: optimize error reporting
1373 git_reference
* tagRef
= nullptr;
1374 if (git_reference_lookup(&tagRef
, repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1376 git_repository_free(repo
);
1379 git_reference_free(tagRef
);
1381 git_reference
* branchRef
= nullptr;
1382 if (git_reference_lookup(&branchRef
, repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1384 git_repository_free(repo
);
1388 git_reference_free(branchRef
);
1389 git_repository_free(repo
);
1397 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1398 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1404 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1415 Checks if a branch or tag with the given name exists
1416 isBranch is true -> branch, tag otherwise
1418 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1422 git_repository
*repo
= nullptr;
1424 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1425 return false; // TODO: optimize error reporting
1429 prefix
= _T("refs/heads/");
1431 prefix
= _T("refs/tags/");
1433 git_reference
* ref
= nullptr;
1434 if (git_reference_lookup(&ref
, repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1436 git_repository_free(repo
);
1440 git_reference_free(ref
);
1441 git_repository_free(repo
);
1446 CString cmd
, output
;
1448 cmd
= _T("git.exe show-ref ");
1450 cmd
+= _T("--heads ");
1452 cmd
+= _T("--tags ");
1454 cmd
+= _T("refs/heads/") + name
;
1455 cmd
+= _T(" refs/tags/") + name
;
1457 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1460 if (!output
.IsEmpty())
1467 CString
CGit::DerefFetchHead()
1470 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1471 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1472 int forMergeLineCount
= 0;
1474 std::string hashToReturn
;
1475 while(getline(fetchHeadFile
, line
))
1477 //Tokenize this line
1478 std::string::size_type prevPos
= 0;
1479 std::string::size_type pos
= line
.find('\t');
1480 if(pos
== std::string::npos
) continue; //invalid line
1482 std::string hash
= line
.substr(0, pos
);
1483 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1485 bool forMerge
= pos
== prevPos
;
1486 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1488 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1493 hashToReturn
= hash
;
1494 ++forMergeLineCount
;
1495 if(forMergeLineCount
> 1)
1496 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1500 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1503 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1509 git_repository
*repo
= nullptr;
1511 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
1514 if (git_repository_head_detached(repo
) == 1)
1515 cur
= _T("(detached from ");
1517 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1519 git_branch_iterator
* it
= nullptr;
1521 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1522 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1523 flags
= GIT_BRANCH_ALL
;
1524 else if (type
& BRANCH_REMOTE
)
1525 flags
= GIT_BRANCH_REMOTE
;
1527 if (git_branch_iterator_new(&it
, repo
, flags
))
1529 git_repository_free(repo
);
1533 git_reference
* ref
= nullptr;
1534 git_branch_t branchType
;
1535 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1537 const char * name
= nullptr;
1538 if (git_branch_name(&name
, ref
))
1540 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1541 if (branchType
& GIT_BRANCH_REMOTE
)
1542 list
.push_back(_T("remotes/") + branchname
);
1545 if (git_branch_is_head(ref
))
1547 list
.push_back(branchname
);
1549 git_reference_free(ref
);
1552 git_branch_iterator_free(it
);
1554 git_repository_free(repo
);
1558 CString cmd
, output
;
1559 cmd
= _T("git.exe branch --no-color");
1561 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1563 else if (type
& BRANCH_REMOTE
)
1566 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1573 one
= output
.Tokenize(_T("\n"), pos
);
1574 one
.Trim(L
" \r\n\t");
1575 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1576 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1577 if (one
[0] == _T('*'))
1582 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1583 list
.push_back(one
);
1588 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1589 list
.push_back(L
"FETCH_HEAD");
1591 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1593 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1595 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1608 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1610 if (this->m_IsUseLibGit2
)
1612 git_repository
*repo
= NULL
;
1614 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1615 if (git_repository_open(&repo
, gitdir
))
1618 git_strarray remotes
;
1620 if (git_remote_list(&remotes
, repo
))
1622 git_repository_free(repo
);
1626 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1628 CStringA
remote(remotes
.strings
[i
]);
1629 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1632 git_strarray_free(&remotes
);
1634 git_repository_free(repo
);
1636 std::sort(list
.begin(), list
.end());
1643 CString cmd
, output
;
1644 cmd
=_T("git.exe remote");
1645 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1652 one
=output
.Tokenize(_T("\n"),pos
);
1654 list
.push_back(one
);
1661 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1663 CString cmd
, out
, err
;
1664 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1665 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1667 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1674 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1675 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1676 if (one
.Find(_T("^{}")) >= 1)
1679 list
.push_back(one
);
1681 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1685 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1687 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1689 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1690 list
->push_back(str
);
1694 int CGit::GetRefList(STRING_VECTOR
&list
)
1696 if (this->m_IsUseLibGit2
)
1698 git_repository
*repo
= NULL
;
1700 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1701 if (git_repository_open(&repo
, gitdir
))
1704 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1706 git_repository_free(repo
);
1710 git_repository_free(repo
);
1712 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1718 CString cmd
, output
;
1719 cmd
=_T("git.exe show-ref -d");
1720 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1727 one
=output
.Tokenize(_T("\n"),pos
);
1728 int start
=one
.Find(_T(" "),0);
1732 name
=one
.Right(one
.GetLength()-start
-1);
1733 list
.push_back(name
);
1736 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1742 typedef struct map_each_ref_payload
{
1743 git_repository
* repo
;
1744 MAP_HASH_NAME
* map
;
1745 } map_each_ref_payload
;
1747 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1749 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1752 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1754 git_object
* gitObject
= NULL
;
1758 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1763 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1765 str
+= _T("^{}"); // deref tag
1766 git_object
* derefedTag
= NULL
;
1767 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1771 git_object_free(gitObject
);
1772 gitObject
= derefedTag
;
1775 const git_oid
* oid
= git_object_id(gitObject
);
1781 CGitHash
hash((char *)oid
->id
);
1782 (*payloadContent
->map
)[hash
].push_back(str
);
1787 git_object_free(gitObject
);
1794 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1796 if (this->m_IsUseLibGit2
)
1798 git_repository
*repo
= NULL
;
1800 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1801 if (git_repository_open(&repo
, gitdir
))
1804 map_each_ref_payload payloadContent
= { repo
, &map
};
1806 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1808 git_repository_free(repo
);
1812 git_repository_free(repo
);
1814 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1816 std::sort(it
->second
.begin(), it
->second
.end());
1823 CString cmd
, output
;
1824 cmd
=_T("git.exe show-ref -d");
1825 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1832 one
=output
.Tokenize(_T("\n"),pos
);
1833 int start
=one
.Find(_T(" "),0);
1837 name
=one
.Right(one
.GetLength()-start
-1);
1840 hash
=one
.Left(start
);
1842 map
[CGitHash(hash
)].push_back(name
);
1850 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1852 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1853 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1856 static void SetLibGit2TemplatePath(const CString
&value
)
1858 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1859 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1862 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1869 this->m_Environment
.clear();
1870 m_Environment
.CopyProcessEnvironment();
1873 size_t homesize
,size
;
1875 // set HOME if not set already
1876 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1878 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1881 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1882 if (sshclient
.IsEmpty())
1883 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1885 if(!sshclient
.IsEmpty())
1887 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1888 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1892 TCHAR sPlink
[MAX_PATH
] = {0};
1893 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1894 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1896 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1897 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1898 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1903 TCHAR sAskPass
[MAX_PATH
] = {0};
1904 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1905 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1908 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1909 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1910 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1911 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1915 // add git/bin path to PATH
1917 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1918 CString str
= msysdir
;
1919 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1924 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1925 str
= msyslocalinstalldir
;
1926 str
.TrimRight(_T("\\"));
1929 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1930 str
= msysinstalldir
;
1931 str
.TrimRight(_T("\\"));
1933 if ( !str
.IsEmpty() )
1937 CGit::ms_LastMsysGitDir
= str
;
1942 // search PATH if git/bin directory is already present
1943 if ( FindGitPath() )
1945 m_bInitialized
= TRUE
;
1946 msysdir
= CGit::ms_LastMsysGitDir
;
1956 CGit::ms_LastMsysGitDir
= str
;
1959 // check for git.exe existance (maybe it was deinstalled in the meantime)
1960 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1963 // Configure libgit2 search paths
1965 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1966 msysGitDir
.ReleaseBuffer();
1967 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1968 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1969 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1970 CString msysGitTemplateDir
;
1971 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1972 msysGitTemplateDir
.ReleaseBuffer();
1973 SetLibGit2TemplatePath(msysGitTemplateDir
);
1976 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1979 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1981 m_Environment
.SetEnv(_T("PATH"), path
);
1983 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1985 CString sOldPath
= oldpath
;
1988 m_bInitialized
= TRUE
;
1992 CString
CGit::GetHomeDirectory()
1994 const wchar_t * homeDir
= wget_windows_home_directory();
1995 return CString(homeDir
, (int)wcslen(homeDir
));
1998 CString
CGit::GetGitLocalConfig()
2001 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
2002 path
+= _T("config");
2006 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2008 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2011 CString
CGit::GetGitGlobalConfig()
2013 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2016 CString
CGit::GetGitGlobalXDGConfigPath()
2018 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2021 CString
CGit::GetGitGlobalXDGConfig()
2023 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2026 CString
CGit::GetGitSystemConfig()
2028 const wchar_t * systemConfig
= wget_msysgit_etc();
2029 return CString(systemConfig
, (int)wcslen(systemConfig
));
2032 BOOL
CGit::CheckCleanWorkTree()
2036 cmd
=_T("git.exe rev-parse --verify HEAD");
2038 if(Run(cmd
,&out
,CP_UTF8
))
2041 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2042 if(Run(cmd
,&out
,CP_UTF8
))
2045 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2046 if(Run(cmd
,&out
,CP_UTF8
))
2049 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2050 if(Run(cmd
,&out
,CP_UTF8
))
2055 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
2058 for (int i
= 0; i
< list
.GetCount(); ++i
)
2060 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
2066 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
2070 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2072 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2075 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2076 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2080 // if the filenames only differ in case, we have to pass "-f"
2081 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2083 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2084 if (Run(cmd
, &out
, CP_UTF8
))
2086 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2090 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2091 if (Run(cmd
, &out
, CP_UTF8
))
2093 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2098 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2099 { //To init git repository, there are not HEAD, so we can use git reset command
2100 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2102 if (Run(cmd
, &out
, CP_UTF8
))
2104 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2110 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2111 if (Run(cmd
, &out
, CP_UTF8
))
2113 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2118 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2120 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2121 if (Run(cmd
, &out
, CP_UTF8
))
2123 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2131 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2137 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2139 cmd
=_T("git.exe ls-files -u -t -z");
2141 if (Run(cmd
, &vector
))
2146 if (list
.ParserFromLsFile(vector
))
2152 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2154 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2156 CGitHash fromHash
, toHash
, baseHash
;
2157 if (GetHash(toHash
, FixBranchName(to
)))
2160 if (GetHash(fromHash
, FixBranchName(from
)))
2163 git_repository
*repo
= nullptr;
2164 if (git_repository_open(&repo
, CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
)))
2168 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2170 git_repository_free(repo
);
2174 baseHash
= baseOid
.id
;
2177 *commonAncestor
= baseHash
;
2179 git_repository_free(repo
);
2181 return fromHash
== baseHash
;
2185 CGitHash basehash
,hash
;
2187 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2189 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2193 basehash
= base
.Trim();
2195 GetHash(hash
, from
);
2198 *commonAncestor
= basehash
;
2200 return hash
== basehash
;
2203 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2206 for (int i
= 0; i
< 4; ++i
)
2209 ret
|= hash
.m_hash
[i
];
2214 int CGit::RefreshGitIndex()
2216 if(g_Git
.m_IsUseGitDLL
)
2218 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2221 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2232 cmd
=_T("git.exe update-index --refresh");
2233 return Run(cmd
, &output
, CP_UTF8
);
2237 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2239 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2242 if (GetHash(hash
, Refname
))
2245 git_repository
*repo
= nullptr;
2246 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
2249 git_commit
* commit
= nullptr;
2250 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2252 git_repository_free(repo
);
2256 git_tree
* tree
= nullptr;
2257 if (git_commit_tree(&tree
, commit
))
2259 git_commit_free(commit
);
2260 git_repository_free(repo
);
2264 git_tree_entry
* entry
= nullptr;
2265 if (git_tree_entry_bypath(&entry
, tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2267 git_tree_free(tree
);
2268 git_commit_free(commit
);
2269 git_repository_free(repo
);
2273 git_blob
* blob
= nullptr;
2274 if (git_tree_entry_to_object((git_object
**)&blob
, repo
, entry
))
2276 git_tree_entry_free(entry
);
2277 git_tree_free(tree
);
2278 git_commit_free(commit
);
2279 git_repository_free(repo
);
2283 FILE *file
= nullptr;
2284 _tfopen_s(&file
, outputfile
, _T("w"));
2285 if (file
== nullptr)
2287 giterr_set_str(GITERR_NONE
, "Could not create file.");
2288 git_blob_free(blob
);
2289 git_tree_entry_free(entry
);
2290 git_tree_free(tree
);
2291 git_commit_free(commit
);
2292 git_repository_free(repo
);
2295 git_buf buf
= { 0 };
2296 if (git_blob_filtered_content(&buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2298 git_blob_free(blob
);
2299 git_tree_entry_free(entry
);
2300 git_tree_free(tree
);
2301 git_commit_free(commit
);
2302 git_repository_free(repo
);
2305 if (fwrite(buf
.ptr
, sizeof(char), buf
.size
, file
) != buf
.size
)
2307 giterr_set_str(GITERR_OS
, "Could not write to file.");
2311 git_blob_free(blob
);
2312 git_tree_entry_free(entry
);
2313 git_tree_free(tree
);
2314 git_commit_free(commit
);
2315 git_repository_free(repo
);
2321 git_blob_free(blob
);
2322 git_tree_entry_free(entry
);
2323 git_tree_free(tree
);
2324 git_commit_free(commit
);
2325 git_repository_free(repo
);
2329 else if (g_Git
.m_IsUseGitDLL
)
2331 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2334 g_Git
.CheckAndInitDll();
2335 CStringA ref
, patha
, outa
;
2336 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2337 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2338 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2339 ::DeleteFile(outputfile
);
2340 return git_checkout_file(ref
, patha
, outa
);
2343 catch (const char * msg
)
2345 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2350 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2357 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2358 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2361 void CEnvironment::CopyProcessEnvironment()
2363 TCHAR
*porig
= GetEnvironmentStrings();
2365 while(*p
!=0 || *(p
+1) !=0)
2366 this->push_back(*p
++);
2368 push_back(_T('\0'));
2369 push_back(_T('\0'));
2371 FreeEnvironmentStrings(porig
);
2374 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2377 for (size_t i
= 0; i
< size(); ++i
)
2381 CString sname
= str
.Tokenize(_T("="),start
);
2382 if(sname
.CompareNoCase(name
) == 0)
2384 return &(*this)[i
+start
];
2391 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2394 for (i
= 0; i
< size(); ++i
)
2396 CString str
= &(*this)[i
];
2398 CString sname
= str
.Tokenize(_T("="),start
);
2399 if(sname
.CompareNoCase(name
) == 0)
2408 i
-= 1; // roll back terminate \0\0
2409 this->push_back(_T('\0'));
2412 CEnvironment::iterator it
;
2416 while(*it
&& i
<size())
2425 this->insert(it
,*name
++);
2430 this->insert(it
, _T('='));
2436 this->insert(it
,*value
++);
2443 int CGit::GetGitEncode(TCHAR
* configkey
)
2445 CString str
=GetConfigValue(configkey
);
2450 return CUnicodeUtils::GetCPCode(str
);
2454 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2460 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2463 diff
= GetGitDiff();
2465 git_open_diff(&diff
, arg
);
2474 isStat
= !!strstr(arg
, "stat");
2479 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2481 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2490 for (int j
= 0; j
< count
; ++j
)
2499 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2500 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2501 &mode
,&IsBin
,&inc
,&dec
);
2503 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2504 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2506 path
.SetFromGit(strnewname
,&stroldname
);
2507 path
.ParserAction((BYTE
)mode
);
2511 path
.m_StatAdd
=_T("-");
2512 path
.m_StatDel
=_T("-");
2516 path
.m_StatAdd
.Format(_T("%d"),inc
);
2517 path
.m_StatDel
.Format(_T("%d"),dec
);
2519 PathList
->AddPath(path
);
2521 git_diff_flush(diff
);
2524 git_close_diff(diff
);
2529 int CGit::GetShortHASHLength()
2534 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2538 REF_TYPE type
= CGit::UNKNOWN
;
2540 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2542 type
= CGit::LOCAL_BRANCH
;
2545 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2547 type
= CGit::REMOTE_BRANCH
;
2549 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2553 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2556 shortname
=_T("stash");
2558 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2560 if (shortname
.Find(_T("good")) == 0)
2562 type
= CGit::BISECT_GOOD
;
2563 shortname
= _T("good");
2566 if (shortname
.Find(_T("bad")) == 0)
2568 type
= CGit::BISECT_BAD
;
2569 shortname
= _T("bad");
2572 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2576 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2578 type
= CGit::UNKNOWN
;
2582 type
= CGit::UNKNOWN
;
2592 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
)
2594 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2597 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2600 if (rev2
== GitRev::GetWorkingCopy())
2601 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2602 else if (rev1
== GitRev::GetWorkingCopy())
2603 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2614 if (diffContext
> 0)
2615 unified
.Format(_T(" --unified=%d"), diffContext
);
2616 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2619 if (!path
.IsEmpty())
2622 cmd
+= path
.GetGitPathString();
2629 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2631 ATLASSERT(payload
&& line
);
2632 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2633 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2634 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2638 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2640 ATLASSERT(repo
&& identifier
&& tree
);
2642 /* try to resolve identifier */
2643 git_object
*obj
= nullptr;
2644 if (git_revparse_single(&obj
, repo
, identifier
))
2648 return GIT_ENOTFOUND
;
2651 switch (git_object_type(obj
))
2654 *tree
= (git_tree
*)obj
;
2656 case GIT_OBJ_COMMIT
:
2657 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2658 git_object_free(obj
);
2661 err
= GIT_ENOTFOUND
;
2667 /* use libgit2 get unified diff */
2668 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 */)
2670 git_repository
*repo
= nullptr;
2671 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2672 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2673 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2676 if (git_repository_open(&repo
, gitdirA
))
2679 int isHeadOrphan
= git_repository_head_unborn(repo
);
2680 if (isHeadOrphan
!= 0)
2682 git_repository_free(repo
);
2683 if (isHeadOrphan
== 1)
2689 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2690 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2691 char *buf
= pathA
.GetBuffer();
2692 if (!pathA
.IsEmpty())
2694 opts
.pathspec
.strings
= &buf
;
2695 opts
.pathspec
.count
= 1;
2697 git_diff
*diff
= nullptr;
2699 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2701 git_tree
*t1
= nullptr;
2702 git_diff
*diff2
= nullptr;
2706 if (revNew
!= GitRev::GetWorkingCopy())
2708 if (resolve_to_tree(repo
, tree1
, &t1
))
2714 if (revOld
!= GitRev::GetWorkingCopy())
2716 if (resolve_to_tree(repo
, tree2
, &t1
))
2723 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2727 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2731 ret
= git_diff_merge(diff
, diff2
);
2735 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2738 if (git_patch_from_diff(&patch
, diff
, i
))
2744 if (git_patch_print(patch
, callback
, data
))
2746 git_patch_free(patch
);
2751 git_patch_free(patch
);
2755 git_diff_free(diff
);
2757 git_diff_free(diff2
);
2763 git_tree
*t1
= nullptr, *t2
= nullptr;
2766 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2772 if (tree1
.IsEmpty())
2778 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2784 if (tree2
.IsEmpty())
2786 /* don't check return value, there are not parent commit at first commit*/
2787 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2789 else if (resolve_to_tree(repo
, tree2
, &t2
))
2794 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2800 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2803 if (git_patch_from_diff(&patch
, diff
, i
))
2809 if (git_patch_print(patch
, callback
, data
))
2811 git_patch_free(patch
);
2816 git_patch_free(patch
);
2821 git_diff_free(diff
);
2827 git_repository_free(repo
);
2828 pathA
.ReleaseBuffer();
2833 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2835 if (UsingLibGit2(GIT_CMD_DIFF
))
2837 FILE *file
= nullptr;
2838 _tfopen_s(&file
, patchfile
, _T("w"));
2839 if (file
== nullptr)
2841 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2848 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2849 return g_Git
.RunLogFile(cmd
, patchfile
, &gitLastErr
);
2853 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2855 ATLASSERT(payload
&& line
);
2856 CStringA
*str
= (CStringA
*) payload
;
2857 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2858 str
->Append(&line
->origin
, 1);
2859 str
->Append(line
->content
, (int)line
->content_len
);
2863 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2865 if (UsingLibGit2(GIT_CMD_DIFF
))
2866 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2870 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2872 int ret
= Run(cmd
, &vector
);
2873 if (!vector
.empty())
2875 vector
.push_back(0); // vector is not NUL terminated
2876 buffer
->Append((char *)&vector
[0]);
2882 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2884 if (UsingLibGit2(GIT_CMD_REVERT
))
2886 git_repository
*repo
= nullptr;
2887 CStringA gitdirA
= CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString());
2888 if (git_repository_open(&repo
, gitdirA
))
2891 git_commit
*commit
= nullptr;
2892 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2894 git_repository_free(repo
);
2898 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2899 revert_opts
.mainline
= parent
;
2900 int result
= git_revert(repo
, commit
, &revert_opts
);
2902 git_commit_free(commit
);
2903 git_repository_free(repo
);
2904 return !result
? 0 : -1;
2910 merge
.Format(_T("-m %d "), parent
);
2911 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2912 gitLastErr
= cmd
+ _T("\n");
2913 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))
2925 int CGit::DeleteRef(const CString
& reference
)
2927 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2929 git_repository
*repo
= nullptr;
2930 if (git_repository_open(&repo
, CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString())))
2934 if (reference
.Right(3) == _T("^{}"))
2935 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2937 refA
= CUnicodeUtils::GetUTF8(reference
);
2939 git_reference
*ref
= nullptr;
2940 if (git_reference_lookup(&ref
, repo
, refA
))
2942 git_repository_free(repo
);
2947 if (git_reference_is_tag(ref
))
2948 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2949 else if (git_reference_is_branch(ref
))
2950 result
= git_branch_delete(ref
);
2951 else if (git_reference_is_remote(ref
))
2952 result
= git_branch_delete(ref
);
2954 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2956 git_reference_free(ref
);
2957 git_repository_free(repo
);
2962 CString cmd
, shortname
;
2963 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2964 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2965 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2966 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2967 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2968 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2971 gitLastErr
= L
"unsupported reference type: " + reference
;
2975 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))
2983 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2985 if (PathFileExists(filename
))
2987 FILE *pFile
= nullptr;
2988 _tfopen_s(&pFile
, filename
, _T("r"));
2994 char s
[8196] = { 0 };
2995 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2998 str
+= CStringA(s
, read
);
3001 msg
= CUnicodeUtils::GetUnicode(str
);
3002 msg
.Replace(_T("\r\n"), _T("\n"));
3003 msg
.TrimRight(_T("\n"));
3007 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3008 return true; // load no further files