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\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
121 if (g_bSortLocalBranchesFirst
)
122 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\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"), 0);
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(CString branchname
)
192 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
193 return !!git_reference_is_valid_name(branchA
);
196 static char g_Buffer
[4096];
198 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
200 SECURITY_ATTRIBUTES sa
;
201 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
202 HANDLE hStdioFile
= NULL
;
204 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
205 sa
.lpSecurityDescriptor
=NULL
;
206 sa
.bInheritHandle
=TRUE
;
207 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
209 CString err
= CFormatMessageWrapper();
210 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
211 return TGIT_GIT_ERROR_OPEN_PIP
;
213 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
215 CString err
= CFormatMessageWrapper();
216 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
217 return TGIT_GIT_ERROR_OPEN_PIP
;
222 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
223 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
227 PROCESS_INFORMATION pi
;
228 si
.cb
=sizeof(STARTUPINFO
);
232 si
.hStdError
= hWriteErr
;
234 si
.hStdError
= hWrite
;
236 si
.hStdOutput
=hStdioFile
;
238 si
.hStdOutput
=hWrite
;
240 si
.wShowWindow
=SW_HIDE
;
241 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
243 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
244 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
246 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
247 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
249 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
250 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
252 if(cmd
.Find(_T("git")) == 0)
254 int firstSpace
= cmd
.Find(_T(" "));
256 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
258 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
261 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
262 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
264 CString err
= CFormatMessageWrapper();
265 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
266 return TGIT_GIT_ERROR_CREATE_PROCESS
;
273 CloseHandle(hWriteErr
);
279 *hErrReadOut
= hReadErr
;
283 //Must use sperate function to convert ANSI str to union code string
284 //Becuase A2W use stack as internal convert buffer.
285 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
288 //str->Append(A2W_CP((LPCSTR)p,code));
296 len
= (int)strlen((const char*)p
);
301 //buf = new WCHAR[len*4 + 1];
302 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
303 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
304 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
305 str
->ReleaseBuffer();
310 // This method was originally used to check for orphaned branches
311 BOOL
CGit::CanParseRev(CString ref
)
317 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
327 // Checks if we have an orphaned HEAD
328 BOOL
CGit::IsInitRepos()
331 // handle error on reading HEAD hash as init repo
332 if (GetHash(hash
, _T("HEAD")) != 0)
334 return hash
.IsEmpty() ? TRUE
: FALSE
;
337 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
339 PASYNCREADSTDERRTHREADARGS pDataArray
;
340 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
343 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
344 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
346 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
353 int CGit::Run(CGitCall
* pcall
)
355 PROCESS_INFORMATION pi
;
356 HANDLE hRead
, hReadErr
;
357 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
358 return TGIT_GIT_ERROR_CREATE_PROCESS
;
361 ASYNCREADSTDERRTHREADARGS threadArguments
;
362 threadArguments
.fileHandle
= hReadErr
;
363 threadArguments
.pcall
= pcall
;
364 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
367 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
369 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
371 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
372 if(!bAborted
)//For now, flush output when command aborted.
373 if(pcall
->OnOutputData(data
,readnumber
))
380 WaitForSingleObject(thread
, INFINITE
);
382 CloseHandle(pi
.hThread
);
384 WaitForSingleObject(pi
.hProcess
, INFINITE
);
387 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
389 CString err
= CFormatMessageWrapper();
390 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
391 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
394 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
396 CloseHandle(pi
.hProcess
);
399 CloseHandle(hReadErr
);
402 class CGitCall_ByteVector
: public CGitCall
405 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
406 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
408 if (!m_pvector
|| size
== 0)
410 size_t oldsize
=m_pvector
->size();
411 m_pvector
->resize(m_pvector
->size()+size
);
412 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
415 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
417 if (!m_pvectorErr
|| size
== 0)
419 size_t oldsize
= m_pvectorErr
->size();
420 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
421 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
424 BYTE_VECTOR
* m_pvector
;
425 BYTE_VECTOR
* m_pvectorErr
;
428 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
430 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
433 int CGit::Run(CString cmd
, CString
* output
, int code
)
437 ret
= Run(cmd
, output
, &err
, code
);
439 if (output
&& !err
.IsEmpty())
441 if (!output
->IsEmpty())
448 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
450 BYTE_VECTOR vector
, vectorErr
;
453 ret
= Run(cmd
, &vector
, &vectorErr
);
455 ret
= Run(cmd
, &vector
);
458 StringAppend(output
, &(vector
[0]), code
);
462 vectorErr
.push_back(0);
463 StringAppend(outputErr
, &(vectorErr
[0]), code
);
469 CString
CGit::GetUserName(void)
472 env
.CopyProcessEnvironment();
473 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
474 if (!envname
.IsEmpty())
476 return GetConfigValue(L
"user.name");
478 CString
CGit::GetUserEmail(void)
481 env
.CopyProcessEnvironment();
482 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
483 if (!envmail
.IsEmpty())
486 return GetConfigValue(L
"user.email");
489 CString
CGit::GetConfigValue(CString name
,int encoding
, BOOL RemoveCR
)
493 if(this->m_IsUseGitDLL
)
495 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
504 key
= CUnicodeUtils::GetMulti(name
, encoding
);
508 if (git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096))
511 catch (const char *msg
)
513 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
517 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
519 return configValue
.Tokenize(_T("\n"),start
);
525 cmd
.Format(L
"git.exe config %s", name
);
526 Run(cmd
, &configValue
, NULL
, encoding
);
528 return configValue
.Tokenize(_T("\n"),start
);
533 bool CGit::GetConfigValueBool(CString name
)
535 CString configValue
= GetConfigValue(name
);
536 configValue
.MakeLower();
538 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
544 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
)
546 if(this->m_IsUseGitDLL
)
548 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
557 CStringA keya
, valuea
;
558 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
559 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
563 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
);
565 catch (const char *msg
)
567 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
578 option
= _T("--global");
581 option
= _T("--system");
586 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
588 if (Run(cmd
, &out
, NULL
, encoding
))
596 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
)
598 if(this->m_IsUseGitDLL
)
600 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
609 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
613 return get_set_config(keya
.GetBuffer(), nullptr, type
);
615 catch (const char *msg
)
617 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
628 option
= _T("--global");
631 option
= _T("--system");
636 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
638 if (Run(cmd
, &out
, NULL
, encoding
))
646 CString
CGit::GetCurrentBranch(bool fallback
)
649 //Run(_T("git.exe branch"),&branch);
651 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
652 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
654 return _T("(no branch)");
661 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
664 if(this->m_IsUseGitDLL
)
666 unsigned char sha1
[20] = { 0 };
669 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
670 const char *refs_heads_master
= nullptr;
673 refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
675 catch (const char *err
)
677 ::MessageBox(NULL
, _T("Could not resolve ref ") + CString(symbolicRefName
) + _T(".\nlibgit reports:\n") + CString(err
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
679 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
681 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
683 refName
= StripRefName(refName
);
690 cmd
.Format(L
"git.exe symbolic-ref %s", symbolicRefName
);
691 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
692 return CString();//Error
694 refName
= refName
.Tokenize(L
"\n", iStart
);
696 refName
= StripRefName(refName
);
701 CString
CGit::GetFullRefName(const CString
& shortRefName
)
705 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
706 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
707 return CString();//Error
709 return refName
.Tokenize(L
"\n", iStart
);
712 CString
CGit::StripRefName(CString refName
)
714 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
715 refName
= refName
.Mid(11);
716 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
717 refName
= refName
.Mid(5);
719 return refName
.Tokenize(_T("\n"),start
);
722 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
724 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
726 if ( sProjectRoot
.IsEmpty() )
730 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
733 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
736 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
744 fgets(s
, sizeof(s
), pFile
);
748 const char *pfx
= "ref: refs/heads/";
749 const int len
= 16;//strlen(pfx)
751 if ( !strncmp(s
, pfx
, len
) )
753 //# We're on a branch. It might not exist. But
754 //# HEAD looks good enough to be a branch.
755 CStringA
utf8Branch(s
+ len
);
756 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
757 sBranchOut
.TrimRight(_T(" \r\n\t"));
759 if ( sBranchOut
.IsEmpty() )
764 CStringA
utf8Hash(s
);
765 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
766 unicodeHash
.TrimRight(_T(" \r\n\t"));
767 if (CGitHash::IsValidSHA1(unicodeHash
))
768 sBranchOut
= unicodeHash
;
770 //# Assume this is a detached head.
771 sBranchOut
= _T("HEAD");
776 //# Assume this is a detached head.
785 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
788 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
792 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
794 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
796 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
798 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
800 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
802 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
804 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
808 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
810 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
812 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
817 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
823 CString
CGit::GetLogCmd(const CString
&range
, CTGitPath
*path
, int count
, int mask
, bool paramonly
,
830 CString file
= _T(" --");
833 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
836 num
.Format(_T("-n%d"),count
);
840 if(mask
& LOG_INFO_STAT
)
841 param
+= _T(" --numstat ");
842 if(mask
& LOG_INFO_FILESTATE
)
843 param
+= _T(" --raw ");
845 if(mask
& LOG_INFO_FULLHISTORY
)
846 param
+= _T(" --full-history ");
848 if(mask
& LOG_INFO_BOUNDARY
)
849 param
+= _T(" --left-right --boundary ");
851 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
852 param
+= _T(" --all ");
854 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
855 param
+= _T(" --branches ");
857 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
860 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
863 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
864 param
+= _T(" --first-parent ");
866 if(mask
& CGit::LOG_INFO_NO_MERGE
)
867 param
+= _T(" --no-merges ");
869 if(mask
& CGit::LOG_INFO_FOLLOW
)
870 param
+= _T(" --follow ");
872 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
875 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
876 param
+= _T(" --full-diff ");
878 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
879 param
+= _T(" --simplify-by-decoration ");
885 if( Filter
&& (Filter
->m_From
!= -1))
887 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
891 if( Filter
&& (Filter
->m_To
!= -1))
893 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
898 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
900 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
905 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
907 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
912 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
914 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
921 if(!Filter
->m_IsRegex
)
922 param
+= _T(" --fixed-strings ");
924 param
+= _T(" --regexp-ignore-case --extended-regexp ");
927 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
928 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
929 param
+= _T(" --topo-order");
930 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
931 param
+= _T(" --date-order");
933 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
934 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
938 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
939 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
948 void GetTempPath(CString
&path
)
950 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
952 DWORD dwBufSize
=BUFSIZE
;
953 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
954 lpPathBuffer
); // buffer for path
955 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
959 path
.Format(_T("%s"),lpPathBuffer
);
961 CString
GetTempFile()
963 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
965 DWORD dwBufSize
=BUFSIZE
;
966 TCHAR szTempName
[BUFSIZE
] = { 0 };
969 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
970 lpPathBuffer
); // buffer for path
971 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
975 // Create a temporary file.
976 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
977 TEXT("Patch"), // temp file name prefix
978 0, // create unique name
979 szTempName
); // buffer for name
987 return CString(szTempName
);
991 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
993 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
994 if (result
== 0) return 0;
995 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1002 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1003 CreateDirectory(lpBuffer
, NULL
);
1008 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1011 PROCESS_INFORMATION pi
;
1012 si
.cb
=sizeof(STARTUPINFO
);
1013 GetStartupInfo(&si
);
1015 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1016 psa
.bInheritHandle
=TRUE
;
1018 HANDLE hReadErr
, hWriteErr
;
1019 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1021 CString err
= CFormatMessageWrapper();
1022 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1023 return TGIT_GIT_ERROR_OPEN_PIP
;
1026 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1027 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1029 if (houtfile
== INVALID_HANDLE_VALUE
)
1031 CString err
= CFormatMessageWrapper();
1032 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1033 return TGIT_GIT_ERROR_OPEN_PIP
;
1036 si
.wShowWindow
= SW_HIDE
;
1037 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1038 si
.hStdOutput
= houtfile
;
1039 si
.hStdError
= hWriteErr
;
1041 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1042 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1044 if(cmd
.Find(_T("git")) == 0)
1045 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1047 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1048 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1050 CString err
= CFormatMessageWrapper();
1051 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1053 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1056 BYTE_VECTOR stderrVector
;
1057 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1059 ASYNCREADSTDERRTHREADARGS threadArguments
;
1060 threadArguments
.fileHandle
= hReadErr
;
1061 threadArguments
.pcall
= &pcall
;
1062 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1064 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1066 CloseHandle(hWriteErr
);
1067 CloseHandle(hReadErr
);
1070 WaitForSingleObject(thread
, INFINITE
);
1072 stderrVector
.push_back(0);
1073 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1076 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1078 CString err
= CFormatMessageWrapper();
1079 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1080 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1083 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1085 CloseHandle(pi
.hThread
);
1086 CloseHandle(pi
.hProcess
);
1087 CloseHandle(houtfile
);
1091 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1093 // no need to parse a ref if it's already a 40-byte hash
1094 if (CGitHash::IsValidSHA1(friendname
))
1096 CString
sHash(friendname
);
1097 hash
= CGitHash(sHash
);
1103 git_repository
*repo
= NULL
;
1104 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1105 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1107 gitdirA
.ReleaseBuffer();
1110 gitdirA
.ReleaseBuffer();
1112 int isHeadOrphan
= git_repository_head_unborn(repo
);
1113 if (isHeadOrphan
!= 0)
1115 git_repository_free(repo
);
1117 if (isHeadOrphan
== 1)
1123 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1125 git_object
* gitObject
= NULL
;
1126 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1128 refnameA
.ReleaseBuffer();
1129 git_repository_free(repo
);
1132 refnameA
.ReleaseBuffer();
1134 const git_oid
* oid
= git_object_id(gitObject
);
1137 git_object_free(gitObject
);
1138 git_repository_free(repo
);
1142 hash
= CGitHash((char *)oid
->id
);
1144 git_object_free(gitObject
); // also frees oid
1145 git_repository_free(repo
);
1152 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1154 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1155 hash
= CGitHash(gitLastErr
.Trim());
1162 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1167 cmd
=_T("git.exe ls-files -s -t -z");
1169 if (Run(cmd
, &cmdout
))
1172 if (outputlist
.ParserFromLsFile(cmdout
))
1174 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1175 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1179 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1183 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1186 if(rev1
== GIT_REV_ZERO
)
1187 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s --"), rev2
);
1189 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), rev1
);
1193 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s --"), rev2
, rev1
);
1200 outputlist
.ParserFromLog(out
);
1205 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1207 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1209 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1210 list
->push_back(str
);
1214 int CGit::GetTagList(STRING_VECTOR
&list
)
1216 if (this->m_IsUseLibGit2
)
1218 git_repository
*repo
= NULL
;
1220 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1221 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1223 gitdir
.ReleaseBuffer();
1226 gitdir
.ReleaseBuffer();
1228 git_strarray tag_names
;
1230 if (git_tag_list(&tag_names
, repo
))
1232 git_repository_free(repo
);
1236 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1238 CStringA
tagName(tag_names
.strings
[i
]);
1239 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1242 git_strarray_free(&tag_names
);
1244 git_repository_free(repo
);
1246 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1252 CString cmd
, output
;
1253 cmd
=_T("git.exe tag -l");
1254 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1261 one
=output
.Tokenize(_T("\n"),pos
);
1263 list
.push_back(one
);
1265 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1272 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1273 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1275 CString
CGit::GetGitLastErr(CString msg
)
1277 if (this->m_IsUseLibGit2
)
1278 return GetLibGit2LastErr(msg
);
1279 else if (gitLastErr
.IsEmpty())
1280 return msg
+ _T("\nUnknown git.exe error.");
1283 CString lastError
= gitLastErr
;
1285 return msg
+ _T("\n") + lastError
;
1289 CString
CGit::GetGitLastErr(CString msg
, int cmd
)
1291 if (UsingLibGit2(cmd
))
1292 return GetLibGit2LastErr(msg
);
1293 else if (gitLastErr
.IsEmpty())
1294 return msg
+ _T("\nUnknown git.exe error.");
1297 CString lastError
= gitLastErr
;
1299 return msg
+ _T("\n") + lastError
;
1303 CString
CGit::GetLibGit2LastErr()
1305 const git_error
*libgit2err
= giterr_last();
1308 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1310 return _T("libgit2 returned: ") + lastError
;
1313 return _T("An error occoured in libgit2, but no message is available.");
1316 CString
CGit::GetLibGit2LastErr(CString msg
)
1319 return msg
+ _T("\n") + GetLibGit2LastErr();
1320 return GetLibGit2LastErr();
1323 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1325 if(branchName
== "FETCH_HEAD")
1326 branchName
= DerefFetchHead();
1330 CString
CGit::FixBranchName(const CString
& branchName
)
1332 CString tempBranchName
= branchName
;
1333 FixBranchName_Mod(tempBranchName
);
1334 return tempBranchName
;
1337 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1342 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1343 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1349 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1360 Checks if a branch or tag with the given name exists
1361 isBranch is true -> branch, tag otherwise
1363 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1365 CString cmd
, output
;
1367 cmd
= _T("git.exe show-ref ");
1369 cmd
+= _T("--heads ");
1371 cmd
+= _T("--tags ");
1373 cmd
+= _T("refs/heads/") + name
;
1374 cmd
+= _T(" refs/tags/") + name
;
1376 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1379 if (!output
.IsEmpty())
1386 CString
CGit::DerefFetchHead()
1389 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1390 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1391 int forMergeLineCount
= 0;
1393 std::string hashToReturn
;
1394 while(getline(fetchHeadFile
, line
))
1396 //Tokenize this line
1397 std::string::size_type prevPos
= 0;
1398 std::string::size_type pos
= line
.find('\t');
1399 if(pos
== std::string::npos
) continue; //invalid line
1401 std::string hash
= line
.substr(0, pos
);
1402 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1404 bool forMerge
= pos
== prevPos
;
1405 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1407 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1412 hashToReturn
= hash
;
1413 ++forMergeLineCount
;
1414 if(forMergeLineCount
> 1)
1415 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1419 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1422 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1425 CString cmd
, output
, cur
;
1426 cmd
= _T("git.exe branch --no-color");
1428 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1430 else if(type
&BRANCH_REMOTE
)
1433 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1440 one
=output
.Tokenize(_T("\n"),pos
);
1441 one
.Trim(L
" \r\n\t");
1442 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1443 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1444 if(one
[0] == _T('*'))
1449 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1450 list
.push_back(one
);
1454 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1455 list
.push_back(L
"FETCH_HEAD");
1457 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1459 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1461 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1474 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1476 if (this->m_IsUseLibGit2
)
1478 git_repository
*repo
= NULL
;
1480 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1481 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1483 gitdir
.ReleaseBuffer();
1486 gitdir
.ReleaseBuffer();
1488 git_strarray remotes
;
1490 if (git_remote_list(&remotes
, repo
))
1492 git_repository_free(repo
);
1496 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1498 CStringA
remote(remotes
.strings
[i
]);
1499 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1502 git_strarray_free(&remotes
);
1504 git_repository_free(repo
);
1506 std::sort(list
.begin(), list
.end());
1513 CString cmd
, output
;
1514 cmd
=_T("git.exe remote");
1515 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1522 one
=output
.Tokenize(_T("\n"),pos
);
1524 list
.push_back(one
);
1531 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1533 CString cmd
, out
, err
;
1534 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1535 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1537 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1544 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1545 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1546 if (one
.Find(_T("^{}")) >= 1)
1549 list
.push_back(one
);
1551 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1555 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1557 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1559 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1560 list
->push_back(str
);
1564 int CGit::GetRefList(STRING_VECTOR
&list
)
1566 if (this->m_IsUseLibGit2
)
1568 git_repository
*repo
= NULL
;
1570 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1571 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1573 gitdir
.ReleaseBuffer();
1576 gitdir
.ReleaseBuffer();
1578 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1580 git_repository_free(repo
);
1584 git_repository_free(repo
);
1586 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1592 CString cmd
, output
;
1593 cmd
=_T("git.exe show-ref -d");
1594 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1601 one
=output
.Tokenize(_T("\n"),pos
);
1602 int start
=one
.Find(_T(" "),0);
1606 name
=one
.Right(one
.GetLength()-start
-1);
1607 list
.push_back(name
);
1610 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1616 typedef struct map_each_ref_payload
{
1617 git_repository
* repo
;
1618 MAP_HASH_NAME
* map
;
1619 } map_each_ref_payload
;
1621 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1623 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1626 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1628 git_object
* gitObject
= NULL
;
1632 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1637 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1639 str
+= _T("^{}"); // deref tag
1640 git_object
* derefedTag
= NULL
;
1641 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1645 git_object_free(gitObject
);
1646 gitObject
= derefedTag
;
1649 const git_oid
* oid
= git_object_id(gitObject
);
1655 CGitHash
hash((char *)oid
->id
);
1656 (*payloadContent
->map
)[hash
].push_back(str
);
1661 git_object_free(gitObject
);
1668 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1670 if (this->m_IsUseLibGit2
)
1672 git_repository
*repo
= NULL
;
1674 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1675 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1677 gitdir
.ReleaseBuffer();
1680 gitdir
.ReleaseBuffer();
1682 map_each_ref_payload payloadContent
= { repo
, &map
};
1684 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1686 git_repository_free(repo
);
1690 git_repository_free(repo
);
1692 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1694 std::sort(it
->second
.begin(), it
->second
.end());
1701 CString cmd
, output
;
1702 cmd
=_T("git.exe show-ref -d");
1703 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1710 one
=output
.Tokenize(_T("\n"),pos
);
1711 int start
=one
.Find(_T(" "),0);
1715 name
=one
.Right(one
.GetLength()-start
-1);
1718 hash
=one
.Left(start
);
1720 map
[CGitHash(hash
)].push_back(name
);
1728 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1730 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1731 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
.GetBuffer());
1732 valueA
.ReleaseBuffer();
1735 static void SetLibGit2TemplatePath(const CString
&value
)
1737 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1738 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
.GetBuffer());
1739 valueA
.ReleaseBuffer();
1742 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1749 this->m_Environment
.clear();
1750 m_Environment
.CopyProcessEnvironment();
1753 size_t homesize
,size
;
1755 // set HOME if not set already
1756 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1759 CString home
= GetHomeDirectory();
1760 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1761 home
.ReleaseBuffer();
1766 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1767 if (sshclient
.IsEmpty())
1768 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1770 if(!sshclient
.IsEmpty())
1772 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1773 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1777 TCHAR sPlink
[MAX_PATH
] = {0};
1778 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1779 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1781 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1782 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1783 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1788 TCHAR sAskPass
[MAX_PATH
] = {0};
1789 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1790 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1793 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1794 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1795 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1796 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1800 // add git/bin path to PATH
1802 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1804 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1809 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1810 str
= msyslocalinstalldir
;
1811 str
.TrimRight(_T("\\"));
1814 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1815 str
= msysinstalldir
;
1816 str
.TrimRight(_T("\\"));
1818 if ( !str
.IsEmpty() )
1822 CGit::ms_LastMsysGitDir
= str
;
1827 // search PATH if git/bin directory is already present
1828 if ( FindGitPath() )
1830 m_bInitialized
= TRUE
;
1831 msysdir
= CGit::ms_LastMsysGitDir
;
1841 CGit::ms_LastMsysGitDir
= str
;
1844 // check for git.exe existance (maybe it was deinstalled in the meantime)
1845 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1848 // Configure libgit2 search paths
1850 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1851 msysGitDir
.ReleaseBuffer();
1852 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1853 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1854 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1855 CString msysGitTemplateDir
;
1856 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1857 msysGitTemplateDir
.ReleaseBuffer();
1858 SetLibGit2TemplatePath(msysGitTemplateDir
);
1861 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1864 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1866 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1868 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1870 CString sOldPath
= oldpath
;
1873 m_bInitialized
= TRUE
;
1877 CString
CGit::GetHomeDirectory()
1879 const wchar_t * homeDir
= wget_windows_home_directory();
1880 return CString(homeDir
, (int)wcslen(homeDir
));
1883 CString
CGit::GetGitLocalConfig()
1886 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1887 path
+= _T("config");
1891 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1893 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1896 CString
CGit::GetGitGlobalConfig()
1898 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1901 CString
CGit::GetGitGlobalXDGConfigPath()
1903 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1906 CString
CGit::GetGitGlobalXDGConfig()
1908 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1911 CString
CGit::GetGitSystemConfig()
1913 const wchar_t * systemConfig
= wget_msysgit_etc();
1914 return CString(systemConfig
, (int)wcslen(systemConfig
));
1917 BOOL
CGit::CheckCleanWorkTree()
1921 cmd
=_T("git.exe rev-parse --verify HEAD");
1923 if(Run(cmd
,&out
,CP_UTF8
))
1926 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1927 if(Run(cmd
,&out
,CP_UTF8
))
1930 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1931 if(Run(cmd
,&out
,CP_UTF8
))
1934 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1935 if(Run(cmd
,&out
,CP_UTF8
))
1940 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1943 for (int i
= 0; i
< list
.GetCount(); ++i
)
1945 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1951 int CGit::Revert(CString commit
, CTGitPath
&path
)
1955 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1957 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1960 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1961 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1965 // if the filenames only differ in case, we have to pass "-f"
1966 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1968 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1969 if (Run(cmd
, &out
, CP_UTF8
))
1971 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1975 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1976 if (Run(cmd
, &out
, CP_UTF8
))
1978 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1983 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1984 { //To init git repository, there are not HEAD, so we can use git reset command
1985 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1987 if (Run(cmd
, &out
, CP_UTF8
))
1989 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1995 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1996 if (Run(cmd
, &out
, CP_UTF8
))
1998 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2003 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2005 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2006 if (Run(cmd
, &out
, CP_UTF8
))
2008 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2016 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
2022 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2024 cmd
=_T("git.exe ls-files -u -t -z");
2026 if (Run(cmd
, &vector
))
2031 if (list
.ParserFromLsFile(vector
))
2037 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2040 CGitHash basehash
,hash
;
2042 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2044 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2048 basehash
= base
.Trim();
2050 GetHash(hash
, from
);
2053 *commonAncestor
= basehash
;
2055 return hash
== basehash
;
2058 unsigned int CGit::Hash2int(CGitHash
&hash
)
2061 for (int i
= 0; i
< 4; ++i
)
2064 ret
|= hash
.m_hash
[i
];
2069 int CGit::RefreshGitIndex()
2071 if(g_Git
.m_IsUseGitDLL
)
2073 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2076 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2087 cmd
=_T("git.exe update-index --refresh");
2088 return Run(cmd
, &output
, CP_UTF8
);
2092 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2094 if(g_Git
.m_IsUseGitDLL
)
2096 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2099 g_Git
.CheckAndInitDll();
2100 CStringA ref
, patha
, outa
;
2101 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2102 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2103 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2104 ::DeleteFile(outputfile
);
2105 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
2115 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2116 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2119 void CEnvironment::CopyProcessEnvironment()
2121 TCHAR
*porig
= GetEnvironmentStrings();
2123 while(*p
!=0 || *(p
+1) !=0)
2124 this->push_back(*p
++);
2126 push_back(_T('\0'));
2127 push_back(_T('\0'));
2129 FreeEnvironmentStrings(porig
);
2132 CString
CEnvironment::GetEnv(TCHAR
*name
)
2135 for (size_t i
= 0; i
< size(); ++i
)
2139 CString sname
= str
.Tokenize(_T("="),start
);
2140 if(sname
.CompareNoCase(name
) == 0)
2142 return &(*this)[i
+start
];
2149 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2152 for (i
= 0; i
< size(); ++i
)
2154 CString str
= &(*this)[i
];
2156 CString sname
= str
.Tokenize(_T("="),start
);
2157 if(sname
.CompareNoCase(name
) == 0)
2166 i
-= 1; // roll back terminate \0\0
2167 this->push_back(_T('\0'));
2170 CEnvironment::iterator it
;
2174 while(*it
&& i
<size())
2183 this->insert(it
,*name
++);
2188 this->insert(it
, _T('='));
2194 this->insert(it
,*value
++);
2201 int CGit::GetGitEncode(TCHAR
* configkey
)
2203 CString str
=GetConfigValue(configkey
);
2208 return CUnicodeUtils::GetCPCode(str
);
2212 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2218 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2221 diff
= GetGitDiff();
2223 git_open_diff(&diff
, arg
);
2232 isStat
= !!strstr(arg
, "stat");
2237 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2239 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2248 for (int j
= 0; j
< count
; ++j
)
2257 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2258 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2259 &mode
,&IsBin
,&inc
,&dec
);
2261 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2262 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2264 path
.SetFromGit(strnewname
,&stroldname
);
2265 path
.ParserAction((BYTE
)mode
);
2269 path
.m_StatAdd
=_T("-");
2270 path
.m_StatDel
=_T("-");
2274 path
.m_StatAdd
.Format(_T("%d"),inc
);
2275 path
.m_StatDel
.Format(_T("%d"),dec
);
2277 PathList
->AddPath(path
);
2279 git_diff_flush(diff
);
2282 git_close_diff(diff
);
2287 int CGit::GetShortHASHLength()
2292 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2296 REF_TYPE type
= CGit::UNKNOWN
;
2298 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2300 type
= CGit::LOCAL_BRANCH
;
2303 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2305 type
= CGit::REMOTE_BRANCH
;
2307 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2311 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2314 shortname
=_T("stash");
2316 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2318 if (shortname
.Find(_T("good")) == 0)
2320 type
= CGit::BISECT_GOOD
;
2321 shortname
= _T("good");
2324 if (shortname
.Find(_T("bad")) == 0)
2326 type
= CGit::BISECT_BAD
;
2327 shortname
= _T("bad");
2330 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2334 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2336 type
= CGit::UNKNOWN
;
2340 type
= CGit::UNKNOWN
;
2350 bool CGit::UsingLibGit2(int cmd
)
2352 if (cmd
>= 0 && cmd
< 32)
2353 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2357 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2360 if (rev2
== GitRev::GetWorkingCopy())
2361 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2362 else if (rev1
== GitRev::GetWorkingCopy())
2363 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2374 if (diffContext
> 0)
2375 unified
.Format(_T(" --unified=%d"), diffContext
);
2376 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2379 if (!path
.IsEmpty())
2382 cmd
+= path
.GetGitPathString();
2389 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2391 ATLASSERT(payload
&& line
);
2392 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2393 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2394 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2398 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2400 ATLASSERT(repo
&& identifier
&& tree
);
2402 /* try to resolve identifier */
2403 git_object
*obj
= nullptr;
2404 if (git_revparse_single(&obj
, repo
, identifier
))
2408 return GIT_ENOTFOUND
;
2411 switch (git_object_type(obj
))
2414 *tree
= (git_tree
*)obj
;
2416 case GIT_OBJ_COMMIT
:
2417 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2418 git_object_free(obj
);
2421 err
= GIT_ENOTFOUND
;
2427 /* use libgit2 get unified diff */
2428 static int GetUnifiedDiffLibGit2(const CTGitPath
& /*path*/, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, git_diff_line_cb callback
, void *data
, bool /* bMerge */)
2430 git_repository
*repo
= nullptr;
2431 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2432 CStringA tree1
= CUnicodeUtils::GetMulti(rev1
, CP_UTF8
);
2433 CStringA tree2
= CUnicodeUtils::GetMulti(rev2
, CP_UTF8
);
2436 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
2438 gitdirA
.ReleaseBuffer();
2441 gitdirA
.ReleaseBuffer();
2443 int isHeadOrphan
= git_repository_head_unborn(repo
);
2444 if (isHeadOrphan
!= 0)
2446 git_repository_free(repo
);
2447 if (isHeadOrphan
== 1)
2453 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2454 git_diff
*diff
= nullptr;
2456 if (rev1
== GitRev::GetWorkingCopy() || rev2
== GitRev::GetWorkingCopy())
2458 git_tree
*t1
= nullptr;
2459 git_diff
*diff2
= nullptr;
2463 if (rev1
!= GitRev::GetWorkingCopy())
2465 if (resolve_to_tree(repo
, tree1
, &t1
))
2471 if (rev2
!= GitRev::GetWorkingCopy())
2473 if (resolve_to_tree(repo
, tree2
, &t1
))
2480 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2484 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2488 ret
= git_diff_merge(diff
, diff2
);
2492 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2495 if (git_patch_from_diff(&patch
, diff
, i
))
2501 if (git_patch_print(patch
, callback
, data
))
2503 git_patch_free(patch
);
2508 git_patch_free(patch
);
2512 git_diff_free(diff
);
2514 git_diff_free(diff2
);
2520 git_tree
*t1
= nullptr, *t2
= nullptr;
2523 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2529 if (tree1
.IsEmpty())
2535 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2541 if (tree2
.IsEmpty())
2543 /* don't check return value, there are not parent commit at first commit*/
2544 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2546 else if (resolve_to_tree(repo
, tree2
, &t2
))
2551 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2557 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2560 if (git_patch_from_diff(&patch
, diff
, i
))
2566 if (git_patch_print(patch
, callback
, data
))
2568 git_patch_free(patch
);
2573 git_patch_free(patch
);
2578 git_diff_free(diff
);
2584 git_repository_free(repo
);
2589 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2591 if (UsingLibGit2(GIT_CMD_DIFF
))
2593 FILE *file
= nullptr;
2594 _tfopen_s(&file
, patchfile
, _T("w"));
2595 if (file
== nullptr)
2597 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2604 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2605 return g_Git
.RunLogFile(cmd
, patchfile
, &gitLastErr
);
2609 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2611 ATLASSERT(payload
&& line
);
2612 CStringA
*str
= (CStringA
*) payload
;
2613 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2614 str
->Append(&line
->origin
, 1);
2615 str
->Append(line
->content
, (int)line
->content_len
);
2619 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2621 if (UsingLibGit2(GIT_CMD_DIFF
))
2622 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2626 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2628 int ret
= Run(cmd
, &vector
);
2629 if (!vector
.empty())
2630 buffer
->Append((char *)&vector
[0]);