1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2013 - 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"));
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(CString
&left
, CString
&right
)
128 return StrCmpLogicalW(left
, right
) < 0;
129 return StrCmpI(left
, right
) < 0;
132 static int LogicalCompareBranchesPredicate(CString
&left
, 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", this->GetGitEncode(L
"i18n.commitencoding"));
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
= g_Git
.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(void)
649 //Run(_T("git.exe branch"),&branch);
651 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
653 return _T("(no branch)");
660 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
663 if(this->m_IsUseGitDLL
)
665 unsigned char sha1
[20];
668 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
669 const char *refs_heads_master
= nullptr;
672 refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
674 catch (const char *err
)
676 ::MessageBox(NULL
, _T("Could not resolve ref ") + CString(symbolicRefName
) + _T(".\nlibgit reports:\n") + CString(err
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
678 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
680 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
682 refName
= StripRefName(refName
);
689 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
690 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
691 return CString();//Error
693 refName
= refName
.Tokenize(L
"\n", iStart
);
695 refName
= StripRefName(refName
);
700 CString
CGit::GetFullRefName(CString shortRefName
)
704 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
705 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
706 return CString();//Error
708 return refName
.Tokenize(L
"\n", iStart
);
711 CString
CGit::StripRefName(CString refName
)
713 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
714 refName
= refName
.Mid(11);
715 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
716 refName
= refName
.Mid(5);
718 return refName
.Tokenize(_T("\n"),start
);
721 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
723 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
725 if ( sProjectRoot
.IsEmpty() )
729 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
732 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
735 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
743 fgets(s
, sizeof(s
), pFile
);
747 const char *pfx
= "ref: refs/heads/";
748 const int len
= 16;//strlen(pfx)
750 if ( !strncmp(s
, pfx
, len
) )
752 //# We're on a branch. It might not exist. But
753 //# HEAD looks good enough to be a branch.
754 CStringA
utf8Branch(s
+ len
);
755 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
756 sBranchOut
.TrimRight(_T(" \r\n\t"));
758 if ( sBranchOut
.IsEmpty() )
763 //# Assume this is a detached head.
772 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
775 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
779 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
781 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
783 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
785 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
787 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
789 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
791 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
795 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
797 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
799 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
804 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
810 CString
CGit::GetLogCmd(CString
&range
, CTGitPath
*path
, int count
, int mask
, bool paramonly
,
820 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
823 num
.Format(_T("-n%d"),count
);
827 if(mask
& LOG_INFO_STAT
)
828 param
+= _T(" --numstat ");
829 if(mask
& LOG_INFO_FILESTATE
)
830 param
+= _T(" --raw ");
832 if(mask
& LOG_INFO_FULLHISTORY
)
833 param
+= _T(" --full-history ");
835 if(mask
& LOG_INFO_BOUNDARY
)
836 param
+= _T(" --left-right --boundary ");
838 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
839 param
+= _T(" --all ");
841 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
844 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
847 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
848 param
+= _T(" --first-parent ");
850 if(mask
& CGit::LOG_INFO_NO_MERGE
)
851 param
+= _T(" --no-merges ");
853 if(mask
& CGit::LOG_INFO_FOLLOW
)
854 param
+= _T(" --follow ");
856 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
859 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
860 param
+= _T(" --full-diff ");
862 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
863 param
+= _T(" --simplify-by-decoration ");
869 if( Filter
&& (Filter
->m_From
!= -1))
871 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
875 if( Filter
&& (Filter
->m_To
!= -1))
877 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
882 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
884 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
889 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
891 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
896 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
898 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
905 if(!Filter
->m_IsRegex
)
906 param
+= _T(" --fixed-strings ");
908 param
+= _T(" --regexp-ignore-case --extended-regexp ");
911 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
912 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
913 param
+= _T(" --topo-order");
914 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
915 param
+= _T(" --date-order");
917 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
918 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
922 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
923 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
932 void GetTempPath(CString
&path
)
934 TCHAR lpPathBuffer
[BUFSIZE
];
936 DWORD dwBufSize
=BUFSIZE
;
937 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
938 lpPathBuffer
); // buffer for path
939 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
943 path
.Format(_T("%s"),lpPathBuffer
);
945 CString
GetTempFile()
947 TCHAR lpPathBuffer
[BUFSIZE
];
949 DWORD dwBufSize
=BUFSIZE
;
950 TCHAR szTempName
[BUFSIZE
];
953 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
954 lpPathBuffer
); // buffer for path
955 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
959 // Create a temporary file.
960 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
961 TEXT("Patch"), // temp file name prefix
962 0, // create unique name
963 szTempName
); // buffer for name
971 return CString(szTempName
);
975 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
977 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
978 if (result
== 0) return 0;
979 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
986 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
987 CreateDirectory(lpBuffer
, NULL
);
992 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
995 PROCESS_INFORMATION pi
;
996 si
.cb
=sizeof(STARTUPINFO
);
999 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1000 psa
.bInheritHandle
=TRUE
;
1002 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1003 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1005 si
.wShowWindow
= SW_HIDE
;
1006 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1007 si
.hStdOutput
= houtfile
;
1009 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1010 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1012 if(cmd
.Find(_T("git")) == 0)
1013 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1015 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1016 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1019 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
1020 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1023 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1026 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1028 CloseHandle(pi
.hThread
);
1029 CloseHandle(pi
.hProcess
);
1030 CloseHandle(houtfile
);
1031 return TGIT_GIT_SUCCESS
;
1035 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1037 // no need to parse a ref if it's already a 40-byte hash
1038 if (CGitHash::IsValidSHA1(friendname
))
1040 CString
sHash(friendname
);
1041 hash
= CGitHash(sHash
);
1047 git_repository
*repo
= NULL
;
1048 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1049 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1051 gitdirA
.ReleaseBuffer();
1054 gitdirA
.ReleaseBuffer();
1056 int isHeadOrphan
= git_repository_head_orphan(repo
);
1057 if (isHeadOrphan
!= 0)
1059 git_repository_free(repo
);
1061 if (isHeadOrphan
== 1)
1067 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1069 git_object
* gitObject
= NULL
;
1070 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1072 refnameA
.ReleaseBuffer();
1073 git_repository_free(repo
);
1076 refnameA
.ReleaseBuffer();
1078 const git_oid
* oid
= git_object_id(gitObject
);
1081 git_object_free(gitObject
);
1082 git_repository_free(repo
);
1086 hash
= CGitHash((char *)oid
->id
);
1088 git_object_free(gitObject
); // also frees oid
1089 git_repository_free(repo
);
1096 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1098 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1099 hash
= CGitHash(gitLastErr
.Trim());
1106 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1111 cmd
=_T("git.exe ls-files -s -t -z");
1113 if (Run(cmd
, &cmdout
))
1116 if (outputlist
.ParserFromLsFile(cmdout
))
1118 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1119 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1123 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1127 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1130 if(rev1
== GIT_REV_ZERO
)
1131 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1133 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1137 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1144 outputlist
.ParserFromLog(out
);
1149 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1151 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1153 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1154 list
->push_back(str
);
1158 int CGit::GetTagList(STRING_VECTOR
&list
)
1160 if (this->m_IsUseLibGit2
)
1162 git_repository
*repo
= NULL
;
1164 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1165 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1167 gitdir
.ReleaseBuffer();
1170 gitdir
.ReleaseBuffer();
1172 git_strarray tag_names
;
1174 if (git_tag_list(&tag_names
, repo
))
1176 git_repository_free(repo
);
1180 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1182 CStringA
tagName(tag_names
.strings
[i
]);
1183 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1186 git_strarray_free(&tag_names
);
1188 git_repository_free(repo
);
1190 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1196 CString cmd
, output
;
1197 cmd
=_T("git.exe tag -l");
1198 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1205 one
=output
.Tokenize(_T("\n"),pos
);
1207 list
.push_back(one
);
1209 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1216 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1217 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1219 CString
CGit::GetGitLastErr(CString msg
)
1221 if (this->m_IsUseLibGit2
)
1222 return GetLibGit2LastErr(msg
);
1223 else if (gitLastErr
.IsEmpty())
1224 return msg
+ _T("\nUnknown git.exe error.");
1227 CString lastError
= gitLastErr
;
1229 return msg
+ _T("\n") + lastError
;
1233 CString
CGit::GetLibGit2LastErr()
1235 const git_error
*libgit2err
= giterr_last();
1238 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1240 return _T("libgit2 returned: ") + lastError
;
1243 return _T("An error occoured in libgit2, but no message is available.");
1246 CString
CGit::GetLibGit2LastErr(CString msg
)
1249 return msg
+ _T("\n") + GetLibGit2LastErr();
1250 return GetLibGit2LastErr();
1253 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1255 if(branchName
== "FETCH_HEAD")
1256 branchName
= DerefFetchHead();
1260 CString
CGit::FixBranchName(const CString
& branchName
)
1262 CString tempBranchName
= branchName
;
1263 FixBranchName_Mod(tempBranchName
);
1264 return tempBranchName
;
1267 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1272 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1273 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1279 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1290 Checks if a branch or tag with the given name exists
1291 isBranch is true -> branch, tag otherwise
1293 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1295 CString cmd
, output
;
1297 cmd
= _T("git show-ref ");
1299 cmd
+= _T("--heads ");
1301 cmd
+= _T("--tags ");
1303 cmd
+= _T("refs/heads/") + name
;
1304 cmd
+= _T(" refs/tags/") + name
;
1306 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1309 if (!output
.IsEmpty())
1316 CString
CGit::DerefFetchHead()
1319 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1320 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1321 int forMergeLineCount
= 0;
1323 std::string hashToReturn
;
1324 while(getline(fetchHeadFile
, line
))
1326 //Tokenize this line
1327 std::string::size_type prevPos
= 0;
1328 std::string::size_type pos
= line
.find('\t');
1329 if(pos
== std::string::npos
) continue; //invalid line
1331 std::string hash
= line
.substr(0, pos
);
1332 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1334 bool forMerge
= pos
== prevPos
;
1335 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1337 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1342 hashToReturn
= hash
;
1343 ++forMergeLineCount
;
1344 if(forMergeLineCount
> 1)
1345 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1349 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1352 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1355 CString cmd
, output
, cur
;
1356 cmd
= _T("git.exe branch --no-color");
1358 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1360 else if(type
&BRANCH_REMOTE
)
1363 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1370 one
=output
.Tokenize(_T("\n"),pos
);
1371 one
.Trim(L
" \r\n\t");
1372 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1373 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1374 if(one
[0] == _T('*'))
1379 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1380 list
.push_back(one
);
1384 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1385 list
.push_back(L
"FETCH_HEAD");
1387 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1389 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1391 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1404 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1406 if (this->m_IsUseLibGit2
)
1408 git_repository
*repo
= NULL
;
1410 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1411 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1413 gitdir
.ReleaseBuffer();
1416 gitdir
.ReleaseBuffer();
1418 git_strarray remotes
;
1420 if (git_remote_list(&remotes
, repo
))
1422 git_repository_free(repo
);
1426 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1428 CStringA
remote(remotes
.strings
[i
]);
1429 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1432 git_strarray_free(&remotes
);
1434 git_repository_free(repo
);
1436 std::sort(list
.begin(), list
.end());
1443 CString cmd
, output
;
1444 cmd
=_T("git.exe remote");
1445 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1452 one
=output
.Tokenize(_T("\n"),pos
);
1454 list
.push_back(one
);
1461 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1463 CString cmd
, out
, err
;
1464 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1465 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1467 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1474 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1475 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1476 if (one
.Find(_T("^{}")) >= 1)
1479 list
.push_back(one
);
1481 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1485 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1487 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1489 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1490 list
->push_back(str
);
1494 int CGit::GetRefList(STRING_VECTOR
&list
)
1496 if (this->m_IsUseLibGit2
)
1498 git_repository
*repo
= NULL
;
1500 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1501 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1503 gitdir
.ReleaseBuffer();
1506 gitdir
.ReleaseBuffer();
1508 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1510 git_repository_free(repo
);
1514 git_repository_free(repo
);
1516 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1522 CString cmd
, output
;
1523 cmd
=_T("git.exe show-ref -d");
1524 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1531 one
=output
.Tokenize(_T("\n"),pos
);
1532 int start
=one
.Find(_T(" "),0);
1536 name
=one
.Right(one
.GetLength()-start
-1);
1537 list
.push_back(name
);
1540 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1546 typedef struct map_each_ref_payload
{
1547 git_repository
* repo
;
1548 MAP_HASH_NAME
* map
;
1549 } map_each_ref_payload
;
1551 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1553 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1556 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1558 git_object
* gitObject
= NULL
;
1562 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1567 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1569 str
+= _T("^{}"); // deref tag
1570 git_object
* derefedTag
= NULL
;
1571 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1575 git_object_free(gitObject
);
1576 gitObject
= derefedTag
;
1579 const git_oid
* oid
= git_object_id(gitObject
);
1585 CGitHash
hash((char *)oid
->id
);
1586 (*payloadContent
->map
)[hash
].push_back(str
);
1591 git_object_free(gitObject
);
1598 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1600 if (this->m_IsUseLibGit2
)
1602 git_repository
*repo
= NULL
;
1604 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1605 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1607 gitdir
.ReleaseBuffer();
1610 gitdir
.ReleaseBuffer();
1612 map_each_ref_payload payloadContent
= { repo
, &map
};
1614 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1616 git_repository_free(repo
);
1620 git_repository_free(repo
);
1622 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1624 std::sort(it
->second
.begin(), it
->second
.end());
1631 CString cmd
, output
;
1632 cmd
=_T("git.exe show-ref -d");
1633 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1640 one
=output
.Tokenize(_T("\n"),pos
);
1641 int start
=one
.Find(_T(" "),0);
1645 name
=one
.Right(one
.GetLength()-start
-1);
1648 hash
=one
.Left(start
);
1650 map
[CGitHash(hash
)].push_back(name
);
1658 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1660 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1661 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
.GetBuffer());
1662 valueA
.ReleaseBuffer();
1665 BOOL
CGit::CheckMsysGitDir()
1672 this->m_Environment
.clear();
1673 m_Environment
.CopyProcessEnvironment();
1676 size_t homesize
,size
;
1678 // set HOME if not set already
1679 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1682 CString home
= GetHomeDirectory();
1683 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1684 home
.ReleaseBuffer();
1689 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1690 if (sshclient
.IsEmpty())
1691 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1693 if(!sshclient
.IsEmpty())
1695 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1696 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1700 TCHAR sPlink
[MAX_PATH
];
1701 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1702 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1704 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1705 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1706 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1711 TCHAR sAskPass
[MAX_PATH
];
1712 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1713 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1716 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1717 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1718 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1719 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1723 // add git/bin path to PATH
1725 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1727 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1729 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1730 str
= msyslocalinstalldir
;
1731 str
.TrimRight(_T("\\"));
1734 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1735 str
= msysinstalldir
;
1736 str
.TrimRight(_T("\\"));
1738 if ( !str
.IsEmpty() )
1742 CGit::ms_LastMsysGitDir
= str
;
1747 // search PATH if git/bin directory is already present
1748 if ( FindGitPath() )
1750 m_bInitialized
= TRUE
;
1751 msysdir
= CGit::ms_LastMsysGitDir
;
1761 CGit::ms_LastMsysGitDir
= str
;
1764 // check for git.exe existance (maybe it was deinstalled in the meantime)
1765 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1768 // Configure libgit2 search paths
1770 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1771 msysGitDir
.ReleaseBuffer();
1772 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1773 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1774 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1777 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1780 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1782 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1784 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1786 CString sOldPath
= oldpath
;
1789 m_bInitialized
= TRUE
;
1793 CString
CGit::GetHomeDirectory()
1795 const wchar_t * homeDir
= wget_windows_home_directory();
1796 return CString(homeDir
, (int)wcslen(homeDir
));
1799 CString
CGit::GetGitLocalConfig()
1802 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1803 path
+= _T("config");
1807 CString
CGit::GetGitGlobalConfig()
1809 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1812 CString
CGit::GetGitGlobalXDGConfigPath()
1814 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1817 CString
CGit::GetGitGlobalXDGConfig()
1819 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1822 CString
CGit::GetGitSystemConfig()
1824 const wchar_t * systemConfig
= wget_msysgit_etc();
1825 return CString(systemConfig
, (int)wcslen(systemConfig
));
1828 BOOL
CGit::CheckCleanWorkTree()
1832 cmd
=_T("git.exe rev-parse --verify HEAD");
1834 if(Run(cmd
,&out
,CP_UTF8
))
1837 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1838 if(Run(cmd
,&out
,CP_UTF8
))
1841 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1842 if(Run(cmd
,&out
,CP_UTF8
))
1845 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1846 if(Run(cmd
,&out
,CP_UTF8
))
1851 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1854 for (int i
= 0; i
< list
.GetCount(); ++i
)
1856 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1862 int CGit::Revert(CString commit
, CTGitPath
&path
)
1866 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1868 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1871 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1872 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1876 // if the filenames only differ in case, we have to pass "-f"
1877 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1879 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1880 if (Run(cmd
, &out
, CP_UTF8
))
1882 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1886 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1887 if (Run(cmd
, &out
, CP_UTF8
))
1889 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1894 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1895 { //To init git repository, there are not HEAD, so we can use git reset command
1896 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1898 if (Run(cmd
, &out
, CP_UTF8
))
1900 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1906 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1907 if (Run(cmd
, &out
, CP_UTF8
))
1909 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1914 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1916 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1917 if (Run(cmd
, &out
, CP_UTF8
))
1919 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1927 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1933 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1935 cmd
=_T("git.exe ls-files -u -t -z");
1937 if (Run(cmd
, &vector
))
1942 if (list
.ParserFromLsFile(vector
))
1948 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1951 CGitHash basehash
,hash
;
1953 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1955 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1959 basehash
= base
.Trim();
1961 GetHash(hash
, from
);
1964 *commonAncestor
= basehash
;
1966 return hash
== basehash
;
1969 unsigned int CGit::Hash2int(CGitHash
&hash
)
1972 for (int i
= 0; i
< 4; ++i
)
1975 ret
|= hash
.m_hash
[i
];
1980 int CGit::RefreshGitIndex()
1982 if(g_Git
.m_IsUseGitDLL
)
1984 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1987 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
1998 cmd
=_T("git.exe update-index --refresh");
1999 return Run(cmd
, &output
, CP_UTF8
);
2003 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
2005 if(g_Git
.m_IsUseGitDLL
)
2007 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2010 g_Git
.CheckAndInitDll();
2011 CStringA ref
, patha
, outa
;
2012 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2013 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2014 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2015 ::DeleteFile(outputfile
);
2016 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
2026 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2027 return RunLogFile(cmd
,outputfile
);
2030 void CEnvironment::CopyProcessEnvironment()
2032 TCHAR
*porig
= GetEnvironmentStrings();
2034 while(*p
!=0 || *(p
+1) !=0)
2035 this->push_back(*p
++);
2037 push_back(_T('\0'));
2038 push_back(_T('\0'));
2040 FreeEnvironmentStrings(porig
);
2043 CString
CEnvironment::GetEnv(TCHAR
*name
)
2046 for (size_t i
= 0; i
< size(); ++i
)
2050 CString sname
= str
.Tokenize(_T("="),start
);
2051 if(sname
.CompareNoCase(name
) == 0)
2053 return &(*this)[i
+start
];
2060 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2063 for (i
= 0; i
< size(); ++i
)
2065 CString str
= &(*this)[i
];
2067 CString sname
= str
.Tokenize(_T("="),start
);
2068 if(sname
.CompareNoCase(name
) == 0)
2077 i
-= 1; // roll back terminate \0\0
2078 this->push_back(_T('\0'));
2081 CEnvironment::iterator it
;
2085 while(*it
&& i
<size())
2094 this->insert(it
,*name
++);
2099 this->insert(it
, _T('='));
2105 this->insert(it
,*value
++);
2112 int CGit::GetGitEncode(TCHAR
* configkey
)
2114 CString str
=GetConfigValue(configkey
);
2119 return CUnicodeUtils::GetCPCode(str
);
2123 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2129 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2132 diff
= GetGitDiff();
2134 git_open_diff(&diff
, arg
);
2143 isStat
= !!strstr(arg
, "stat");
2148 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2150 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2159 for (int j
= 0; j
< count
; ++j
)
2168 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2169 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2170 &mode
,&IsBin
,&inc
,&dec
);
2172 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2173 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2175 path
.SetFromGit(strnewname
,&stroldname
);
2176 path
.ParserAction((BYTE
)mode
);
2180 path
.m_StatAdd
=_T("-");
2181 path
.m_StatDel
=_T("-");
2185 path
.m_StatAdd
.Format(_T("%d"),inc
);
2186 path
.m_StatDel
.Format(_T("%d"),dec
);
2188 PathList
->AddPath(path
);
2190 git_diff_flush(diff
);
2193 git_close_diff(diff
);
2198 int CGit::GetShortHASHLength()
2203 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2207 REF_TYPE type
= CGit::UNKNOWN
;
2209 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2211 type
= CGit::LOCAL_BRANCH
;
2214 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2216 type
= CGit::REMOTE_BRANCH
;
2218 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2222 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2225 shortname
=_T("stash");
2227 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2229 if (shortname
.Find(_T("good")) == 0)
2231 type
= CGit::BISECT_GOOD
;
2232 shortname
= _T("good");
2235 if (shortname
.Find(_T("bad")) == 0)
2237 type
= CGit::BISECT_BAD
;
2238 shortname
= _T("bad");
2241 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2245 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2247 type
= CGit::UNKNOWN
;
2251 type
= CGit::UNKNOWN
;
2261 bool CGit::UsingLibGit2(int cmd
)
2263 if (cmd
>= 0 && cmd
< 32)
2264 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2268 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2271 if (rev2
== GitRev::GetWorkingCopy())
2272 cmd
.Format(_T("git.exe diff --stat -p %s"), rev1
);
2273 else if (rev1
== GitRev::GetWorkingCopy())
2274 cmd
.Format(_T("git.exe diff -R --stat -p %s"), rev2
);
2285 if (diffContext
> 0)
2286 unified
.Format(_T(" --unified=%d"), diffContext
);
2287 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s"), merge
, unified
, rev1
, rev2
);
2290 if (!path
.IsEmpty())
2292 cmd
+= _T(" -- \"");
2293 cmd
+= path
.GetGitPathString();
2300 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_range
* /* range */, char /* line_origin */, const char *content
, size_t content_len
, void *payload
)
2302 ATLASSERT(payload
&& content
);
2303 fwrite(content
, 1, content_len
, (FILE *)payload
);
2307 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2309 ATLASSERT(repo
&& identifier
&& tree
);
2311 /* try to resolve identifier */
2312 git_object
*obj
= nullptr;
2313 if (git_revparse_single(&obj
, repo
, identifier
))
2317 return GIT_ENOTFOUND
;
2320 switch (git_object_type(obj
))
2323 *tree
= (git_tree
*)obj
;
2325 case GIT_OBJ_COMMIT
:
2326 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2327 git_object_free(obj
);
2330 err
= GIT_ENOTFOUND
;
2336 /* use libgit2 get unified diff */
2337 static int GetUnifiedDiffLibGit2(const CTGitPath
& /*path*/, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, git_diff_data_cb callback
, void *data
, bool /* bMerge */)
2339 git_repository
*repo
= nullptr;
2340 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2341 CStringA tree1
= CUnicodeUtils::GetMulti(rev1
, CP_UTF8
);
2342 CStringA tree2
= CUnicodeUtils::GetMulti(rev2
, CP_UTF8
);
2345 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
2347 gitdirA
.ReleaseBuffer();
2350 gitdirA
.ReleaseBuffer();
2352 int isHeadOrphan
= git_repository_head_orphan(repo
);
2353 if (isHeadOrphan
!= 0)
2355 git_repository_free(repo
);
2356 if (isHeadOrphan
== 1)
2362 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2363 git_diff_list
*diff
= nullptr;
2365 if (rev1
== GitRev::GetWorkingCopy() || rev2
== GitRev::GetWorkingCopy())
2367 git_tree
*t1
= nullptr;
2368 git_diff_list
*diff2
= nullptr;
2372 if (rev1
!= GitRev::GetWorkingCopy())
2374 if (resolve_to_tree(repo
, tree1
, &t1
))
2380 if (rev2
!= GitRev::GetWorkingCopy())
2382 if (resolve_to_tree(repo
, tree2
, &t1
))
2389 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2393 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2397 ret
= git_diff_merge(diff
, diff2
);
2401 ret
= git_diff_print_patch(diff
, callback
, data
);
2406 git_diff_list_free(diff
);
2408 git_diff_list_free(diff2
);
2414 git_tree
*t1
= nullptr, *t2
= nullptr;
2417 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2423 if (tree1
.IsEmpty())
2429 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2435 if (tree2
.IsEmpty())
2437 /* don't check return value, there are not parent commit at first commit*/
2438 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2440 else if (resolve_to_tree(repo
, tree2
, &t2
))
2445 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2450 if(git_diff_print_patch(diff
, callback
, data
))
2458 git_diff_list_free(diff
);
2464 git_repository_free(repo
);
2469 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2471 if (UsingLibGit2(GIT_CMD_DIFF
))
2473 FILE *file
= nullptr;
2474 _tfopen_s(&file
, patchfile
, _T("w"));
2475 if (file
== nullptr)
2477 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2484 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2485 return g_Git
.RunLogFile(cmd
, patchfile
);
2489 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_range
* /*range*/, char /*line_origin*/, const char *content
, size_t content_len
, void *payload
)
2491 ATLASSERT(payload
&& content
);
2492 CStringA
*str
= (CStringA
*) payload
;
2493 str
->Append(content
, content_len
);
2497 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2499 if (UsingLibGit2(GIT_CMD_DIFF
))
2500 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2504 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2506 int ret
= Run(cmd
, &vector
);
2507 if (!vector
.empty())
2508 buffer
->Append((char *)&vector
[0]);