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.
25 #include "GitConfig.h"
27 #include "UnicodeUtils.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
;
158 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
159 m_CurrentDir
.ReleaseBuffer();
160 m_IsGitDllInited
= false;
162 m_GitSimpleListDiff
=0;
163 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
164 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
165 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), 0);
168 this->m_bInitialized
=false;
170 m_critGitDllSec
.Init();
177 git_close_diff(m_GitDiff
);
180 if(this->m_GitSimpleListDiff
)
182 git_close_diff(m_GitSimpleListDiff
);
183 m_GitSimpleListDiff
=0;
187 bool CGit::IsBranchNameValid(CString branchname
)
189 if (branchname
.IsEmpty())
192 for (int i
= 0; i
< branchname
.GetLength(); ++i
)
194 TCHAR c
= branchname
.GetAt(i
);
195 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
199 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
202 CString reverseBranchname
= branchname
.MakeReverse();
203 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
209 static char g_Buffer
[4096];
211 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
213 SECURITY_ATTRIBUTES sa
;
214 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
215 HANDLE hStdioFile
= NULL
;
217 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
218 sa
.lpSecurityDescriptor
=NULL
;
219 sa
.bInheritHandle
=TRUE
;
220 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
222 return TGIT_GIT_ERROR_OPEN_PIP
;
224 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
225 return TGIT_GIT_ERROR_OPEN_PIP
;
229 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
230 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
234 PROCESS_INFORMATION pi
;
235 si
.cb
=sizeof(STARTUPINFO
);
239 si
.hStdError
= hWriteErr
;
241 si
.hStdError
= hWrite
;
243 si
.hStdOutput
=hStdioFile
;
245 si
.hStdOutput
=hWrite
;
247 si
.wShowWindow
=SW_HIDE
;
248 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
250 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
251 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
253 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
254 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
256 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
257 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
259 if(cmd
.Find(_T("git")) == 0)
261 int firstSpace
= cmd
.Find(_T(" "));
263 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
265 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
268 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
271 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
272 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
275 return TGIT_GIT_ERROR_CREATE_PROCESS
;
282 CloseHandle(hWriteErr
);
288 *hErrReadOut
= hReadErr
;
292 //Must use sperate function to convert ANSI str to union code string
293 //Becuase A2W use stack as internal convert buffer.
294 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
297 //str->Append(A2W_CP((LPCSTR)p,code));
305 len
= (int)strlen((const char*)p
);
310 //buf = new WCHAR[len*4 + 1];
311 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
312 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
313 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
314 str
->ReleaseBuffer();
319 BOOL
CGit::IsOrphanBranch(CString ref
)
325 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
335 BOOL
CGit::IsInitRepos()
337 return IsOrphanBranch(_T("HEAD"));
340 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
342 PASYNCREADSTDERRTHREADARGS pDataArray
;
343 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
346 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
347 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
349 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
356 int CGit::Run(CGitCall
* pcall
)
358 PROCESS_INFORMATION pi
;
359 HANDLE hRead
, hReadErr
;
360 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
361 return TGIT_GIT_ERROR_CREATE_PROCESS
;
364 ASYNCREADSTDERRTHREADARGS threadArguments
;
365 threadArguments
.fileHandle
= hReadErr
;
366 threadArguments
.pcall
= pcall
;
367 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
370 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
372 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
374 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
375 if(!bAborted
)//For now, flush output when command aborted.
376 if(pcall
->OnOutputData(data
,readnumber
))
383 WaitForSingleObject(thread
, INFINITE
);
385 CloseHandle(pi
.hThread
);
387 WaitForSingleObject(pi
.hProcess
, INFINITE
);
390 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
392 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
395 CloseHandle(pi
.hProcess
);
398 CloseHandle(hReadErr
);
401 class CGitCall_ByteVector
: public CGitCall
404 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
405 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
409 size_t oldsize
=m_pvector
->size();
410 m_pvector
->resize(m_pvector
->size()+size
);
411 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
414 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
416 if (!m_pvectorErr
|| size
== 0)
418 size_t oldsize
= m_pvectorErr
->size();
419 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
420 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
423 BYTE_VECTOR
* m_pvector
;
424 BYTE_VECTOR
* m_pvectorErr
;
427 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
429 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
432 int CGit::Run(CString cmd
, CString
* output
, int code
)
436 ret
= Run(cmd
, output
, &err
, code
);
438 if (output
&& !err
.IsEmpty())
440 if (!output
->IsEmpty())
447 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
449 BYTE_VECTOR vector
, vectorErr
;
452 ret
= Run(cmd
, &vector
, &vectorErr
);
454 ret
= Run(cmd
, &vector
);
457 StringAppend(output
, &(vector
[0]), code
);
461 vectorErr
.push_back(0);
462 StringAppend(outputErr
, &(vectorErr
[0]), code
);
468 CString
CGit::GetUserName(void)
471 env
.CopyProcessEnvironment();
472 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
473 if (!envname
.IsEmpty())
475 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
477 CString
CGit::GetUserEmail(void)
480 env
.CopyProcessEnvironment();
481 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
482 if (!envmail
.IsEmpty())
485 return GetConfigValue(L
"user.email");
488 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
492 if(this->m_IsUseGitDLL
)
494 CString
*git_path
=NULL
;
496 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
509 key
= CUnicodeUtils::GetMulti(name
, encoding
);
512 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
514 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
518 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
520 return configValue
.Tokenize(_T("\n"),start
);
528 cmd
.Format(L
"git.exe config %s", name
);
529 Run(cmd
, &configValue
, NULL
, encoding
);
531 return configValue
.Tokenize(_T("\n"),start
);
536 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
538 if(this->m_IsUseGitDLL
)
540 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
549 CStringA keya
, valuea
;
550 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
551 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
554 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
556 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
566 option
= _T("--global");
569 option
= _T("--system");
574 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
576 if (Run(cmd
, &out
, NULL
, encoding
))
584 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
586 if(this->m_IsUseGitDLL
)
588 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
597 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
600 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
602 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
611 option
= _T("--global");
614 option
= _T("--system");
619 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
621 if (Run(cmd
, &out
, NULL
, encoding
))
629 CString
CGit::GetCurrentBranch(void)
632 //Run(_T("git.exe branch"),&branch);
634 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
636 return _T("(no branch)");
643 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
646 if(this->m_IsUseGitDLL
)
648 unsigned char sha1
[20];
651 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
652 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
653 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
655 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
657 refName
= StripRefName(refName
);
664 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
665 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
666 return CString();//Error
668 refName
= refName
.Tokenize(L
"\n", iStart
);
670 refName
= StripRefName(refName
);
675 CString
CGit::GetFullRefName(CString shortRefName
)
679 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
680 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
681 return CString();//Error
683 return refName
.Tokenize(L
"\n", iStart
);
686 CString
CGit::StripRefName(CString refName
)
688 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
689 refName
= refName
.Mid(11);
690 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
691 refName
= refName
.Mid(5);
693 return refName
.Tokenize(_T("\n"),start
);
696 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
698 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
700 if ( sProjectRoot
.IsEmpty() )
704 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
707 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
710 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
718 fgets(s
, sizeof(s
), pFile
);
722 const char *pfx
= "ref: refs/heads/";
723 const int len
= 16;//strlen(pfx)
725 if ( !strncmp(s
, pfx
, len
) )
727 //# We're on a branch. It might not exist. But
728 //# HEAD looks good enough to be a branch.
729 CStringA
utf8Branch(s
+ len
);
730 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
731 sBranchOut
.TrimRight(_T(" \r\n\t"));
733 if ( sBranchOut
.IsEmpty() )
738 //# Assume this is a detached head.
747 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
750 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
754 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
756 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
758 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
760 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
762 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
764 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
766 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
770 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
772 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
774 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
779 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
785 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
787 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
788 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
791 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
801 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
804 num
.Format(_T("-n%d"),count
);
808 if(mask
& LOG_INFO_STAT
)
809 param
+= _T(" --numstat ");
810 if(mask
& LOG_INFO_FILESTATE
)
811 param
+= _T(" --raw ");
813 if(mask
& LOG_INFO_FULLHISTORY
)
814 param
+= _T(" --full-history ");
816 if(mask
& LOG_INFO_BOUNDARY
)
817 param
+= _T(" --left-right --boundary ");
819 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
820 param
+= _T(" --all ");
822 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
825 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
828 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
829 param
+= _T(" --first-parent ");
831 if(mask
& CGit::LOG_INFO_NO_MERGE
)
832 param
+= _T(" --no-merges ");
834 if(mask
& CGit::LOG_INFO_FOLLOW
)
835 param
+= _T(" --follow ");
837 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
840 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
841 param
+= _T(" --full-diff ");
843 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
844 param
+= _T(" --simplify-by-decoration ");
846 if(from
!= NULL
&& to
!= NULL
)
849 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
852 else if(to
!= NULL
&& hash
.IsEmpty())
855 range
.Format(_T(" %s "), FixBranchName(*to
));
862 if( Filter
&& (Filter
->m_From
!= -1))
864 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
868 if( Filter
&& (Filter
->m_To
!= -1))
870 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
875 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
877 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
882 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
884 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
889 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
891 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
898 if(!Filter
->m_IsRegex
)
899 param
+= _T(" --fixed-strings ");
901 param
+= _T(" --regexp-ignore-case --extended-regexp ");
904 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
905 param
+= _T(" --topo-order");
907 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
908 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
912 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
913 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
921 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
922 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
924 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
926 return Run(pgitCall
);
927 // return Run(cmd,&logOut);
931 void GetTempPath(CString
&path
)
933 TCHAR lpPathBuffer
[BUFSIZE
];
935 DWORD dwBufSize
=BUFSIZE
;
936 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
937 lpPathBuffer
); // buffer for path
938 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
942 path
.Format(_T("%s"),lpPathBuffer
);
944 CString
GetTempFile()
946 TCHAR lpPathBuffer
[BUFSIZE
];
948 DWORD dwBufSize
=BUFSIZE
;
949 TCHAR szTempName
[BUFSIZE
];
952 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
953 lpPathBuffer
); // buffer for path
954 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
958 // Create a temporary file.
959 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
960 TEXT("Patch"), // temp file name prefix
961 0, // create unique name
962 szTempName
); // buffer for name
970 return CString(szTempName
);
974 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
976 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
977 if (result
== 0) return 0;
978 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
985 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
986 CreateDirectory(lpBuffer
, NULL
);
991 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
994 PROCESS_INFORMATION pi
;
995 si
.cb
=sizeof(STARTUPINFO
);
998 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
999 psa
.bInheritHandle
=TRUE
;
1001 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1002 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1004 si
.wShowWindow
= SW_HIDE
;
1005 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1006 si
.hStdOutput
= houtfile
;
1008 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1009 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1011 if(cmd
.Find(_T("git")) == 0)
1012 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1014 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1017 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
1018 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1021 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1024 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1026 CloseHandle(pi
.hThread
);
1027 CloseHandle(pi
.hProcess
);
1028 CloseHandle(houtfile
);
1029 return TGIT_GIT_SUCCESS
;
1033 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1035 // no need to parse a ref if it's already a 40-byte hash
1036 if (CGitHash::IsValidSHA1(friendname
))
1038 CString
sHash(friendname
);
1039 hash
= CGitHash(sHash
);
1045 git_repository
*repo
= NULL
;
1046 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1047 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1049 gitdirA
.ReleaseBuffer();
1052 gitdirA
.ReleaseBuffer();
1054 int isHeadOrphan
= git_repository_head_orphan(repo
);
1055 if (isHeadOrphan
!= 0)
1057 git_repository_free(repo
);
1059 if (isHeadOrphan
== 1)
1065 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1067 git_object
* gitObject
= NULL
;
1068 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1070 refnameA
.ReleaseBuffer();
1071 git_repository_free(repo
);
1074 refnameA
.ReleaseBuffer();
1076 const git_oid
* oid
= git_object_id(gitObject
);
1079 git_object_free(gitObject
);
1080 git_repository_free(repo
);
1084 hash
= CGitHash((char *)oid
->id
);
1086 git_object_free(gitObject
); // also frees oid
1087 git_repository_free(repo
);
1094 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1095 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1096 hash
= CGitHash(gitLastErr
.Trim());
1101 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1106 cmd
=_T("git.exe ls-files -s -t -z");
1108 if (Run(cmd
, &cmdout
))
1111 outputlist
.ParserFromLsFile(cmdout
);
1112 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1113 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1117 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1121 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1124 if(rev1
== GIT_REV_ZERO
)
1125 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1127 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1131 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1138 outputlist
.ParserFromLog(out
);
1143 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1145 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1147 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1148 list
->push_back(str
);
1152 int CGit::GetTagList(STRING_VECTOR
&list
)
1154 if (this->m_IsUseLibGit2
)
1156 git_repository
*repo
= NULL
;
1158 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1159 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1161 gitdir
.ReleaseBuffer();
1164 gitdir
.ReleaseBuffer();
1166 git_strarray tag_names
;
1168 if (git_tag_list(&tag_names
, repo
))
1170 git_repository_free(repo
);
1174 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1176 CStringA
tagName(tag_names
.strings
[i
]);
1177 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1180 git_strarray_free(&tag_names
);
1182 git_repository_free(repo
);
1184 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1190 CString cmd
, output
;
1191 cmd
=_T("git.exe tag -l");
1192 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1199 one
=output
.Tokenize(_T("\n"),pos
);
1201 list
.push_back(one
);
1203 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1210 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1211 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1213 CString
CGit::GetGitLastErr(CString msg
)
1215 if (this->m_IsUseLibGit2
)
1216 return GetLibGit2LastErr(msg
);
1217 else if (gitLastErr
.IsEmpty())
1218 return msg
+ _T("\nUnknown git.exe error.");
1221 CString lastError
= gitLastErr
;
1223 return msg
+ _T("\n") + lastError
;
1227 CString
CGit::GetLibGit2LastErr()
1229 const git_error
*libgit2err
= giterr_last();
1232 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1234 return _T("libgit2 returned: ") + lastError
;
1237 return _T("An error occoured in libgit2, but no message is available.");
1240 CString
CGit::GetLibGit2LastErr(CString msg
)
1243 return msg
+ _T("\n") + GetLibGit2LastErr();
1244 return GetLibGit2LastErr();
1247 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1249 if(branchName
== "FETCH_HEAD")
1250 branchName
= DerefFetchHead();
1254 CString
CGit::FixBranchName(const CString
& branchName
)
1256 CString tempBranchName
= branchName
;
1257 FixBranchName_Mod(tempBranchName
);
1258 return tempBranchName
;
1261 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1266 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1267 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1273 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1284 Checks if a branch or tag with the given name exists
1285 isBranch is true -> branch, tag otherwise
1287 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1289 CString cmd
, output
;
1291 cmd
= _T("git show-ref ");
1293 cmd
+= _T("--heads ");
1295 cmd
+= _T("--tags ");
1297 cmd
+= _T("refs/heads/") + name
;
1298 cmd
+= _T(" refs/tags/") + name
;
1300 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1303 if (!output
.IsEmpty())
1310 CString
CGit::DerefFetchHead()
1312 using namespace std
;
1314 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1315 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1316 int forMergeLineCount
= 0;
1318 string hashToReturn
;
1319 while(getline(fetchHeadFile
, line
))
1321 //Tokenize this line
1322 string::size_type prevPos
= 0;
1323 string::size_type pos
= line
.find('\t');
1324 if(pos
== string::npos
) continue; //invalid line
1326 string hash
= line
.substr(0, pos
);
1327 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1329 bool forMerge
= pos
== prevPos
;
1330 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1332 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1337 hashToReturn
= hash
;
1338 ++forMergeLineCount
;
1339 if(forMergeLineCount
> 1)
1340 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1344 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1347 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1350 CString cmd
, output
, cur
;
1351 cmd
= _T("git.exe branch --no-color");
1353 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1355 else if(type
&BRANCH_REMOTE
)
1358 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1365 one
=output
.Tokenize(_T("\n"),pos
);
1366 one
.Trim(L
" \r\n\t");
1367 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1368 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1369 if(one
[0] == _T('*'))
1374 if (one
!= _T("(no branch)"))
1375 list
.push_back(one
);
1379 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1380 list
.push_back(L
"FETCH_HEAD");
1382 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1384 if (current
&& cur
!= _T("(no branch)"))
1386 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1399 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1401 if (this->m_IsUseLibGit2
)
1403 git_repository
*repo
= NULL
;
1405 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1406 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1408 gitdir
.ReleaseBuffer();
1411 gitdir
.ReleaseBuffer();
1413 git_strarray remotes
;
1415 if (git_remote_list(&remotes
, repo
))
1417 git_repository_free(repo
);
1421 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1423 CStringA
remote(remotes
.strings
[i
]);
1424 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1427 git_strarray_free(&remotes
);
1429 git_repository_free(repo
);
1431 std::sort(list
.begin(), list
.end());
1438 CString cmd
, output
;
1439 cmd
=_T("git.exe remote");
1440 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1447 one
=output
.Tokenize(_T("\n"),pos
);
1449 list
.push_back(one
);
1456 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1458 CString cmd
, out
, err
;
1459 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1460 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1462 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1469 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1470 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1471 if (one
.Find(_T("^{}")) >= 1)
1474 list
.push_back(one
);
1476 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1480 int libgit2_addto_list_each_ref_fn(const char *refname
, void *payload
)
1482 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1484 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1485 list
->push_back(str
);
1489 int CGit::GetRefList(STRING_VECTOR
&list
)
1491 if (this->m_IsUseLibGit2
)
1493 git_repository
*repo
= NULL
;
1495 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1496 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1498 gitdir
.ReleaseBuffer();
1501 gitdir
.ReleaseBuffer();
1503 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_list_each_ref_fn
, &list
))
1505 git_repository_free(repo
);
1509 git_repository_free(repo
);
1511 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1517 CString cmd
, output
;
1518 cmd
=_T("git.exe show-ref -d");
1519 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1526 one
=output
.Tokenize(_T("\n"),pos
);
1527 int start
=one
.Find(_T(" "),0);
1531 name
=one
.Right(one
.GetLength()-start
-1);
1532 list
.push_back(name
);
1535 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1541 typedef struct map_each_ref_payload
{
1542 git_repository
* repo
;
1543 MAP_HASH_NAME
* map
;
1544 } map_each_ref_payload
;
1546 int libgit2_addto_map_each_ref_fn(const char *refname
, void *payload
)
1548 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1551 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1553 git_object
* gitObject
= NULL
;
1557 if (git_revparse_single(&gitObject
, payloadContent
->repo
, refname
))
1562 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1564 str
+= _T("^{}"); // deref tag
1565 git_object
* derefedTag
= NULL
;
1566 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1570 git_object_free(gitObject
);
1571 gitObject
= derefedTag
;
1574 const git_oid
* oid
= git_object_id(gitObject
);
1580 CGitHash
hash((char *)oid
->id
);
1581 (*payloadContent
->map
)[hash
].push_back(str
);
1586 git_object_free(gitObject
);
1593 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1595 if (this->m_IsUseLibGit2
)
1597 git_repository
*repo
= NULL
;
1599 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1600 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1602 gitdir
.ReleaseBuffer();
1605 gitdir
.ReleaseBuffer();
1607 map_each_ref_payload payloadContent
= { repo
, &map
};
1609 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1611 git_repository_free(repo
);
1615 git_repository_free(repo
);
1617 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1619 std::sort(it
->second
.begin(), it
->second
.end());
1626 CString cmd
, output
;
1627 cmd
=_T("git.exe show-ref -d");
1628 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1635 one
=output
.Tokenize(_T("\n"),pos
);
1636 int start
=one
.Find(_T(" "),0);
1640 name
=one
.Right(one
.GetLength()-start
-1);
1643 hash
=one
.Left(start
);
1645 map
[CGitHash(hash
)].push_back(name
);
1653 BOOL
CGit::CheckMsysGitDir()
1660 this->m_Environment
.clear();
1661 m_Environment
.CopyProcessEnvironment();
1664 size_t homesize
,size
;
1666 // set HOME if not set already
1667 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1670 CString home
= GetHomeDirectory();
1671 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1672 home
.ReleaseBuffer();
1677 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1679 if(!sshclient
.IsEmpty())
1681 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1682 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1686 TCHAR sPlink
[MAX_PATH
];
1687 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1688 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1690 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1691 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1692 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1697 TCHAR sAskPass
[MAX_PATH
];
1698 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1699 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1702 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1703 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1704 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1705 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1709 // add git/bin path to PATH
1711 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1713 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1715 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1716 str
= msyslocalinstalldir
;
1717 str
.TrimRight(_T("\\"));
1720 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1721 str
= msysinstalldir
;
1722 str
.TrimRight(_T("\\"));
1724 if ( !str
.IsEmpty() )
1728 CGit::ms_LastMsysGitDir
= str
;
1733 // search PATH if git/bin directory is already present
1734 if ( FindGitPath() )
1736 m_bInitialized
= TRUE
;
1737 msysdir
= CGit::ms_LastMsysGitDir
;
1747 CGit::ms_LastMsysGitDir
= str
;
1750 // check for git.exe existance (maybe it was deinstalled in the meantime)
1751 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1755 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1758 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1760 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1762 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1764 CString sOldPath
= oldpath
;
1767 m_bInitialized
= TRUE
;
1771 CString
CGit::GetHomeDirectory()
1773 const wchar_t * homeDir
= wget_windows_home_directory();
1774 return CString(homeDir
, (int)wcslen(homeDir
));
1777 CString
CGit::GetGitLocalConfig()
1780 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1781 path
+= _T("config");
1785 CString
CGit::GetGitGlobalConfig()
1787 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1790 CString
CGit::GetGitGlobalXDGConfigPath()
1792 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1795 CString
CGit::GetGitGlobalXDGConfig()
1797 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1800 CString
CGit::GetGitSystemConfig()
1802 const wchar_t * systemConfig
= wget_msysgit_etc();
1803 return CString(systemConfig
, (int)wcslen(systemConfig
));
1806 BOOL
CGit::CheckCleanWorkTree()
1810 cmd
=_T("git.exe rev-parse --verify HEAD");
1812 if(Run(cmd
,&out
,CP_UTF8
))
1815 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1816 if(Run(cmd
,&out
,CP_UTF8
))
1819 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1820 if(Run(cmd
,&out
,CP_UTF8
))
1823 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1824 if(Run(cmd
,&out
,CP_UTF8
))
1829 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1832 for (int i
= 0; i
< list
.GetCount(); ++i
)
1834 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1840 int CGit::Revert(CString commit
, CTGitPath
&path
)
1844 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1846 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1849 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1850 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1854 // if the filenames only differ in case, we have to pass "-f"
1855 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1857 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1858 if (Run(cmd
, &out
, CP_UTF8
))
1860 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1864 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1865 if (Run(cmd
, &out
, CP_UTF8
))
1867 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1872 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1873 { //To init git repository, there are not HEAD, so we can use git reset command
1874 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1876 if (Run(cmd
, &out
, CP_UTF8
))
1878 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1884 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1885 if (Run(cmd
, &out
, CP_UTF8
))
1887 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1892 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1894 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1895 if (Run(cmd
, &out
, CP_UTF8
))
1897 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1905 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1911 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1913 cmd
=_T("git.exe ls-files -u -t -z");
1915 if (Run(cmd
, &vector
))
1920 list
.ParserFromLsFile(vector
);
1925 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1928 CGitHash basehash
,hash
;
1930 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1932 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1936 basehash
= base
.Trim();
1938 GetHash(hash
, from
);
1941 *commonAncestor
= basehash
;
1943 return hash
== basehash
;
1946 unsigned int CGit::Hash2int(CGitHash
&hash
)
1949 for (int i
= 0; i
< 4; ++i
)
1952 ret
|= hash
.m_hash
[i
];
1957 int CGit::RefreshGitIndex()
1959 if(g_Git
.m_IsUseGitDLL
)
1961 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1964 return git_run_cmd("update-index","update-index -q --refresh");
1975 cmd
=_T("git.exe update-index --refresh");
1976 return Run(cmd
, &output
, CP_UTF8
);
1980 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1982 if(g_Git
.m_IsUseGitDLL
)
1984 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1987 g_Git
.CheckAndInitDll();
1988 CStringA ref
, patha
, outa
;
1989 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1990 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1991 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1992 ::DeleteFile(outputfile
);
1993 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
2003 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2004 return RunLogFile(cmd
,outputfile
);
2007 void CEnvironment::CopyProcessEnvironment()
2009 TCHAR
*p
= GetEnvironmentStrings();
2010 while(*p
!=0 || *(p
+1) !=0)
2011 this->push_back(*p
++);
2013 push_back(_T('\0'));
2014 push_back(_T('\0'));
2017 CString
CEnvironment::GetEnv(TCHAR
*name
)
2020 for (size_t i
= 0; i
< size(); ++i
)
2024 CString sname
= str
.Tokenize(_T("="),start
);
2025 if(sname
.CompareNoCase(name
) == 0)
2027 return &(*this)[i
+start
];
2034 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2037 for (i
= 0; i
< size(); ++i
)
2039 CString str
= &(*this)[i
];
2041 CString sname
= str
.Tokenize(_T("="),start
);
2042 if(sname
.CompareNoCase(name
) == 0)
2051 i
-= 1; // roll back terminate \0\0
2052 this->push_back(_T('\0'));
2055 CEnvironment::iterator it
;
2059 while(*it
&& i
<size())
2068 this->insert(it
,*name
++);
2073 this->insert(it
, _T('='));
2079 this->insert(it
,*value
++);
2086 int CGit::GetGitEncode(TCHAR
* configkey
)
2088 CString str
=GetConfigValue(configkey
);
2093 return CUnicodeUtils::GetCPCode(str
);
2097 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2103 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2106 diff
= GetGitDiff();
2108 git_open_diff(&diff
, arg
);
2117 isStat
= !!strstr(arg
, "stat");
2122 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2124 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2133 for (int j
= 0; j
< count
; ++j
)
2142 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2143 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2144 &mode
,&IsBin
,&inc
,&dec
);
2146 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2147 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2149 path
.SetFromGit(strnewname
,&stroldname
);
2150 path
.ParserAction((BYTE
)mode
);
2154 path
.m_StatAdd
=_T("-");
2155 path
.m_StatDel
=_T("-");
2159 path
.m_StatAdd
.Format(_T("%d"),inc
);
2160 path
.m_StatDel
.Format(_T("%d"),dec
);
2162 PathList
->AddPath(path
);
2164 git_diff_flush(diff
);
2167 git_close_diff(diff
);
2172 int CGit::GetShortHASHLength()
2177 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2181 REF_TYPE type
= CGit::UNKNOWN
;
2183 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2185 type
= CGit::LOCAL_BRANCH
;
2188 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2190 type
= CGit::REMOTE_BRANCH
;
2192 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2196 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2199 shortname
=_T("stash");
2201 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2203 if (shortname
.Find(_T("good")) == 0)
2205 type
= CGit::BISECT_GOOD
;
2206 shortname
= _T("good");
2209 if (shortname
.Find(_T("bad")) == 0)
2211 type
= CGit::BISECT_BAD
;
2212 shortname
= _T("bad");
2215 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2221 type
= CGit::UNKNOWN
;
2222 shortname
= _T("Unknown");
2231 bool CGit::UsingLibGit2(int cmd
)
2233 if (cmd
>= 0 && cmd
< 32)
2234 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;