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
));
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 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 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
)
1398 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1399 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1405 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1416 Checks if a branch or tag with the given name exists
1417 isBranch is true -> branch, tag otherwise
1419 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1421 CString cmd
, output
;
1423 cmd
= _T("git.exe show-ref ");
1425 cmd
+= _T("--heads ");
1427 cmd
+= _T("--tags ");
1429 cmd
+= _T("refs/heads/") + name
;
1430 cmd
+= _T(" refs/tags/") + name
;
1432 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1435 if (!output
.IsEmpty())
1442 CString
CGit::DerefFetchHead()
1445 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1446 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1447 int forMergeLineCount
= 0;
1449 std::string hashToReturn
;
1450 while(getline(fetchHeadFile
, line
))
1452 //Tokenize this line
1453 std::string::size_type prevPos
= 0;
1454 std::string::size_type pos
= line
.find('\t');
1455 if(pos
== std::string::npos
) continue; //invalid line
1457 std::string hash
= line
.substr(0, pos
);
1458 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1460 bool forMerge
= pos
== prevPos
;
1461 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1463 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1468 hashToReturn
= hash
;
1469 ++forMergeLineCount
;
1470 if(forMergeLineCount
> 1)
1471 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1475 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1478 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1481 CString cmd
, output
, cur
;
1482 cmd
= _T("git.exe branch --no-color");
1484 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1486 else if(type
&BRANCH_REMOTE
)
1489 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1496 one
=output
.Tokenize(_T("\n"),pos
);
1497 one
.Trim(L
" \r\n\t");
1498 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1499 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1500 if(one
[0] == _T('*'))
1505 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1506 list
.push_back(one
);
1510 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1511 list
.push_back(L
"FETCH_HEAD");
1513 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1515 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1517 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1530 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1532 if (this->m_IsUseLibGit2
)
1534 git_repository
*repo
= NULL
;
1536 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1537 if (git_repository_open(&repo
, gitdir
))
1540 git_strarray remotes
;
1542 if (git_remote_list(&remotes
, repo
))
1544 git_repository_free(repo
);
1548 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1550 CStringA
remote(remotes
.strings
[i
]);
1551 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1554 git_strarray_free(&remotes
);
1556 git_repository_free(repo
);
1558 std::sort(list
.begin(), list
.end());
1565 CString cmd
, output
;
1566 cmd
=_T("git.exe remote");
1567 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1574 one
=output
.Tokenize(_T("\n"),pos
);
1576 list
.push_back(one
);
1583 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1585 CString cmd
, out
, err
;
1586 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1587 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1589 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1596 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1597 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1598 if (one
.Find(_T("^{}")) >= 1)
1601 list
.push_back(one
);
1603 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1607 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1609 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1611 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1612 list
->push_back(str
);
1616 int CGit::GetRefList(STRING_VECTOR
&list
)
1618 if (this->m_IsUseLibGit2
)
1620 git_repository
*repo
= NULL
;
1622 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1623 if (git_repository_open(&repo
, gitdir
))
1626 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1628 git_repository_free(repo
);
1632 git_repository_free(repo
);
1634 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1640 CString cmd
, output
;
1641 cmd
=_T("git.exe show-ref -d");
1642 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1649 one
=output
.Tokenize(_T("\n"),pos
);
1650 int start
=one
.Find(_T(" "),0);
1654 name
=one
.Right(one
.GetLength()-start
-1);
1655 list
.push_back(name
);
1658 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1664 typedef struct map_each_ref_payload
{
1665 git_repository
* repo
;
1666 MAP_HASH_NAME
* map
;
1667 } map_each_ref_payload
;
1669 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1671 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1674 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1676 git_object
* gitObject
= NULL
;
1680 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1685 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1687 str
+= _T("^{}"); // deref tag
1688 git_object
* derefedTag
= NULL
;
1689 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1693 git_object_free(gitObject
);
1694 gitObject
= derefedTag
;
1697 const git_oid
* oid
= git_object_id(gitObject
);
1703 CGitHash
hash((char *)oid
->id
);
1704 (*payloadContent
->map
)[hash
].push_back(str
);
1709 git_object_free(gitObject
);
1716 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1718 if (this->m_IsUseLibGit2
)
1720 git_repository
*repo
= NULL
;
1722 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1723 if (git_repository_open(&repo
, gitdir
))
1726 map_each_ref_payload payloadContent
= { repo
, &map
};
1728 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1730 git_repository_free(repo
);
1734 git_repository_free(repo
);
1736 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1738 std::sort(it
->second
.begin(), it
->second
.end());
1745 CString cmd
, output
;
1746 cmd
=_T("git.exe show-ref -d");
1747 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1754 one
=output
.Tokenize(_T("\n"),pos
);
1755 int start
=one
.Find(_T(" "),0);
1759 name
=one
.Right(one
.GetLength()-start
-1);
1762 hash
=one
.Left(start
);
1764 map
[CGitHash(hash
)].push_back(name
);
1772 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1774 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1775 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1778 static void SetLibGit2TemplatePath(const CString
&value
)
1780 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1781 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1784 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1791 this->m_Environment
.clear();
1792 m_Environment
.CopyProcessEnvironment();
1795 size_t homesize
,size
;
1797 // set HOME if not set already
1798 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1800 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1803 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1804 if (sshclient
.IsEmpty())
1805 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1807 if(!sshclient
.IsEmpty())
1809 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1810 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1814 TCHAR sPlink
[MAX_PATH
] = {0};
1815 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1816 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1818 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1819 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1820 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1825 TCHAR sAskPass
[MAX_PATH
] = {0};
1826 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1827 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1830 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1831 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1832 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1833 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1837 // add git/bin path to PATH
1839 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1840 CString str
= msysdir
;
1841 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1846 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1847 str
= msyslocalinstalldir
;
1848 str
.TrimRight(_T("\\"));
1851 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1852 str
= msysinstalldir
;
1853 str
.TrimRight(_T("\\"));
1855 if ( !str
.IsEmpty() )
1859 CGit::ms_LastMsysGitDir
= str
;
1864 // search PATH if git/bin directory is already present
1865 if ( FindGitPath() )
1867 m_bInitialized
= TRUE
;
1868 msysdir
= CGit::ms_LastMsysGitDir
;
1878 CGit::ms_LastMsysGitDir
= str
;
1881 // check for git.exe existance (maybe it was deinstalled in the meantime)
1882 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1885 // Configure libgit2 search paths
1887 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1888 msysGitDir
.ReleaseBuffer();
1889 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1890 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1891 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1892 CString msysGitTemplateDir
;
1893 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1894 msysGitTemplateDir
.ReleaseBuffer();
1895 SetLibGit2TemplatePath(msysGitTemplateDir
);
1898 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1901 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1903 m_Environment
.SetEnv(_T("PATH"), path
);
1905 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1907 CString sOldPath
= oldpath
;
1910 m_bInitialized
= TRUE
;
1914 CString
CGit::GetHomeDirectory()
1916 const wchar_t * homeDir
= wget_windows_home_directory();
1917 return CString(homeDir
, (int)wcslen(homeDir
));
1920 CString
CGit::GetGitLocalConfig()
1923 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1924 path
+= _T("config");
1928 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1930 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1933 CString
CGit::GetGitGlobalConfig()
1935 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1938 CString
CGit::GetGitGlobalXDGConfigPath()
1940 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1943 CString
CGit::GetGitGlobalXDGConfig()
1945 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1948 CString
CGit::GetGitSystemConfig()
1950 const wchar_t * systemConfig
= wget_msysgit_etc();
1951 return CString(systemConfig
, (int)wcslen(systemConfig
));
1954 BOOL
CGit::CheckCleanWorkTree()
1958 cmd
=_T("git.exe rev-parse --verify HEAD");
1960 if(Run(cmd
,&out
,CP_UTF8
))
1963 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1964 if(Run(cmd
,&out
,CP_UTF8
))
1967 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1968 if(Run(cmd
,&out
,CP_UTF8
))
1971 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1972 if(Run(cmd
,&out
,CP_UTF8
))
1977 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
1980 for (int i
= 0; i
< list
.GetCount(); ++i
)
1982 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1988 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
1992 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1994 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1997 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1998 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2002 // if the filenames only differ in case, we have to pass "-f"
2003 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2005 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2006 if (Run(cmd
, &out
, CP_UTF8
))
2008 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2012 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2013 if (Run(cmd
, &out
, CP_UTF8
))
2015 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2020 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2021 { //To init git repository, there are not HEAD, so we can use git reset command
2022 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2024 if (Run(cmd
, &out
, CP_UTF8
))
2026 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2032 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2033 if (Run(cmd
, &out
, CP_UTF8
))
2035 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2040 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2042 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2043 if (Run(cmd
, &out
, CP_UTF8
))
2045 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2053 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2059 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2061 cmd
=_T("git.exe ls-files -u -t -z");
2063 if (Run(cmd
, &vector
))
2068 if (list
.ParserFromLsFile(vector
))
2074 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2076 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2078 CGitHash fromHash
, toHash
, baseHash
;
2079 if (GetHash(toHash
, FixBranchName(to
)))
2082 if (GetHash(fromHash
, FixBranchName(from
)))
2085 git_repository
*repo
= nullptr;
2086 if (git_repository_open(&repo
, CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
)))
2090 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2092 git_repository_free(repo
);
2096 baseHash
= baseOid
.id
;
2099 *commonAncestor
= baseHash
;
2101 git_repository_free(repo
);
2103 return fromHash
== baseHash
;
2107 CGitHash basehash
,hash
;
2109 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2111 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2115 basehash
= base
.Trim();
2117 GetHash(hash
, from
);
2120 *commonAncestor
= basehash
;
2122 return hash
== basehash
;
2125 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2128 for (int i
= 0; i
< 4; ++i
)
2131 ret
|= hash
.m_hash
[i
];
2136 int CGit::RefreshGitIndex()
2138 if(g_Git
.m_IsUseGitDLL
)
2140 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2143 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2154 cmd
=_T("git.exe update-index --refresh");
2155 return Run(cmd
, &output
, CP_UTF8
);
2159 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2161 if(g_Git
.m_IsUseGitDLL
)
2163 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2166 g_Git
.CheckAndInitDll();
2167 CStringA ref
, patha
, outa
;
2168 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2169 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2170 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2171 ::DeleteFile(outputfile
);
2172 return git_checkout_file(ref
, patha
, outa
);
2182 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2183 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2186 void CEnvironment::CopyProcessEnvironment()
2188 TCHAR
*porig
= GetEnvironmentStrings();
2190 while(*p
!=0 || *(p
+1) !=0)
2191 this->push_back(*p
++);
2193 push_back(_T('\0'));
2194 push_back(_T('\0'));
2196 FreeEnvironmentStrings(porig
);
2199 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2202 for (size_t i
= 0; i
< size(); ++i
)
2206 CString sname
= str
.Tokenize(_T("="),start
);
2207 if(sname
.CompareNoCase(name
) == 0)
2209 return &(*this)[i
+start
];
2216 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2219 for (i
= 0; i
< size(); ++i
)
2221 CString str
= &(*this)[i
];
2223 CString sname
= str
.Tokenize(_T("="),start
);
2224 if(sname
.CompareNoCase(name
) == 0)
2233 i
-= 1; // roll back terminate \0\0
2234 this->push_back(_T('\0'));
2237 CEnvironment::iterator it
;
2241 while(*it
&& i
<size())
2250 this->insert(it
,*name
++);
2255 this->insert(it
, _T('='));
2261 this->insert(it
,*value
++);
2268 int CGit::GetGitEncode(TCHAR
* configkey
)
2270 CString str
=GetConfigValue(configkey
);
2275 return CUnicodeUtils::GetCPCode(str
);
2279 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2285 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2288 diff
= GetGitDiff();
2290 git_open_diff(&diff
, arg
);
2299 isStat
= !!strstr(arg
, "stat");
2304 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2306 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2315 for (int j
= 0; j
< count
; ++j
)
2324 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2325 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2326 &mode
,&IsBin
,&inc
,&dec
);
2328 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2329 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2331 path
.SetFromGit(strnewname
,&stroldname
);
2332 path
.ParserAction((BYTE
)mode
);
2336 path
.m_StatAdd
=_T("-");
2337 path
.m_StatDel
=_T("-");
2341 path
.m_StatAdd
.Format(_T("%d"),inc
);
2342 path
.m_StatDel
.Format(_T("%d"),dec
);
2344 PathList
->AddPath(path
);
2346 git_diff_flush(diff
);
2349 git_close_diff(diff
);
2354 int CGit::GetShortHASHLength()
2359 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2363 REF_TYPE type
= CGit::UNKNOWN
;
2365 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2367 type
= CGit::LOCAL_BRANCH
;
2370 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2372 type
= CGit::REMOTE_BRANCH
;
2374 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2378 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2381 shortname
=_T("stash");
2383 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2385 if (shortname
.Find(_T("good")) == 0)
2387 type
= CGit::BISECT_GOOD
;
2388 shortname
= _T("good");
2391 if (shortname
.Find(_T("bad")) == 0)
2393 type
= CGit::BISECT_BAD
;
2394 shortname
= _T("bad");
2397 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2401 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2403 type
= CGit::UNKNOWN
;
2407 type
= CGit::UNKNOWN
;
2417 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
)
2419 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2422 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2425 if (rev2
== GitRev::GetWorkingCopy())
2426 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2427 else if (rev1
== GitRev::GetWorkingCopy())
2428 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2439 if (diffContext
> 0)
2440 unified
.Format(_T(" --unified=%d"), diffContext
);
2441 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2444 if (!path
.IsEmpty())
2447 cmd
+= path
.GetGitPathString();
2454 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2456 ATLASSERT(payload
&& line
);
2457 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2458 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2459 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2463 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2465 ATLASSERT(repo
&& identifier
&& tree
);
2467 /* try to resolve identifier */
2468 git_object
*obj
= nullptr;
2469 if (git_revparse_single(&obj
, repo
, identifier
))
2473 return GIT_ENOTFOUND
;
2476 switch (git_object_type(obj
))
2479 *tree
= (git_tree
*)obj
;
2481 case GIT_OBJ_COMMIT
:
2482 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2483 git_object_free(obj
);
2486 err
= GIT_ENOTFOUND
;
2492 /* use libgit2 get unified diff */
2493 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 */)
2495 git_repository
*repo
= nullptr;
2496 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2497 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2498 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2501 if (git_repository_open(&repo
, gitdirA
))
2504 int isHeadOrphan
= git_repository_head_unborn(repo
);
2505 if (isHeadOrphan
!= 0)
2507 git_repository_free(repo
);
2508 if (isHeadOrphan
== 1)
2514 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2515 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2516 char *buf
= pathA
.GetBuffer();
2517 if (!pathA
.IsEmpty())
2519 opts
.pathspec
.strings
= &buf
;
2520 opts
.pathspec
.count
= 1;
2522 git_diff
*diff
= nullptr;
2524 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2526 git_tree
*t1
= nullptr;
2527 git_diff
*diff2
= nullptr;
2531 if (revNew
!= GitRev::GetWorkingCopy())
2533 if (resolve_to_tree(repo
, tree1
, &t1
))
2539 if (revOld
!= GitRev::GetWorkingCopy())
2541 if (resolve_to_tree(repo
, tree2
, &t1
))
2548 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2552 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2556 ret
= git_diff_merge(diff
, diff2
);
2560 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2563 if (git_patch_from_diff(&patch
, diff
, i
))
2569 if (git_patch_print(patch
, callback
, data
))
2571 git_patch_free(patch
);
2576 git_patch_free(patch
);
2580 git_diff_free(diff
);
2582 git_diff_free(diff2
);
2588 git_tree
*t1
= nullptr, *t2
= nullptr;
2591 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2597 if (tree1
.IsEmpty())
2603 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2609 if (tree2
.IsEmpty())
2611 /* don't check return value, there are not parent commit at first commit*/
2612 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2614 else if (resolve_to_tree(repo
, tree2
, &t2
))
2619 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2625 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2628 if (git_patch_from_diff(&patch
, diff
, i
))
2634 if (git_patch_print(patch
, callback
, data
))
2636 git_patch_free(patch
);
2641 git_patch_free(patch
);
2646 git_diff_free(diff
);
2652 git_repository_free(repo
);
2653 pathA
.ReleaseBuffer();
2658 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2660 if (UsingLibGit2(GIT_CMD_DIFF
))
2662 FILE *file
= nullptr;
2663 _tfopen_s(&file
, patchfile
, _T("w"));
2664 if (file
== nullptr)
2666 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2673 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2674 return g_Git
.RunLogFile(cmd
, patchfile
, &gitLastErr
);
2678 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2680 ATLASSERT(payload
&& line
);
2681 CStringA
*str
= (CStringA
*) payload
;
2682 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2683 str
->Append(&line
->origin
, 1);
2684 str
->Append(line
->content
, (int)line
->content_len
);
2688 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2690 if (UsingLibGit2(GIT_CMD_DIFF
))
2691 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2695 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2697 int ret
= Run(cmd
, &vector
);
2698 if (!vector
.empty())
2700 vector
.push_back(0); // vector is not NUL terminated
2701 buffer
->Append((char *)&vector
[0]);
2707 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2709 if (UsingLibGit2(GIT_CMD_REVERT
))
2711 git_repository
*repo
= nullptr;
2712 CStringA gitdirA
= CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString());
2713 if (git_repository_open(&repo
, gitdirA
))
2716 git_commit
*commit
= nullptr;
2717 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2719 git_repository_free(repo
);
2723 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2724 revert_opts
.mainline
= parent
;
2725 int result
= git_revert(repo
, commit
, &revert_opts
);
2727 git_commit_free(commit
);
2728 git_repository_free(repo
);
2729 return !result
? 0 : -1;
2735 merge
.Format(_T("-m %d "), parent
);
2736 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2737 gitLastErr
= cmd
+ _T("\n");
2738 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))