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 CString
CGit::GetLogCmd(CString
&range
, CTGitPath
*path
, int count
, int mask
, bool paramonly
,
795 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
798 num
.Format(_T("-n%d"),count
);
802 if(mask
& LOG_INFO_STAT
)
803 param
+= _T(" --numstat ");
804 if(mask
& LOG_INFO_FILESTATE
)
805 param
+= _T(" --raw ");
807 if(mask
& LOG_INFO_FULLHISTORY
)
808 param
+= _T(" --full-history ");
810 if(mask
& LOG_INFO_BOUNDARY
)
811 param
+= _T(" --left-right --boundary ");
813 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
814 param
+= _T(" --all ");
816 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
819 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
822 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
823 param
+= _T(" --first-parent ");
825 if(mask
& CGit::LOG_INFO_NO_MERGE
)
826 param
+= _T(" --no-merges ");
828 if(mask
& CGit::LOG_INFO_FOLLOW
)
829 param
+= _T(" --follow ");
831 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
834 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
835 param
+= _T(" --full-diff ");
837 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
838 param
+= _T(" --simplify-by-decoration ");
844 if( Filter
&& (Filter
->m_From
!= -1))
846 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
850 if( Filter
&& (Filter
->m_To
!= -1))
852 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
857 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
859 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
864 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
866 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
871 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
873 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
880 if(!Filter
->m_IsRegex
)
881 param
+= _T(" --fixed-strings ");
883 param
+= _T(" --regexp-ignore-case --extended-regexp ");
886 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
887 param
+= _T(" --topo-order");
889 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
890 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
894 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
895 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
904 void GetTempPath(CString
&path
)
906 TCHAR lpPathBuffer
[BUFSIZE
];
908 DWORD dwBufSize
=BUFSIZE
;
909 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
910 lpPathBuffer
); // buffer for path
911 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
915 path
.Format(_T("%s"),lpPathBuffer
);
917 CString
GetTempFile()
919 TCHAR lpPathBuffer
[BUFSIZE
];
921 DWORD dwBufSize
=BUFSIZE
;
922 TCHAR szTempName
[BUFSIZE
];
925 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
926 lpPathBuffer
); // buffer for path
927 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
931 // Create a temporary file.
932 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
933 TEXT("Patch"), // temp file name prefix
934 0, // create unique name
935 szTempName
); // buffer for name
943 return CString(szTempName
);
947 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
949 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
950 if (result
== 0) return 0;
951 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
958 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
959 CreateDirectory(lpBuffer
, NULL
);
964 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
967 PROCESS_INFORMATION pi
;
968 si
.cb
=sizeof(STARTUPINFO
);
971 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
972 psa
.bInheritHandle
=TRUE
;
974 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
975 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
977 si
.wShowWindow
= SW_HIDE
;
978 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
979 si
.hStdOutput
= houtfile
;
981 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
982 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
984 if(cmd
.Find(_T("git")) == 0)
985 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
987 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
990 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
991 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
994 return TGIT_GIT_ERROR_CREATE_PROCESS
;
997 WaitForSingleObject(pi
.hProcess
,INFINITE
);
999 CloseHandle(pi
.hThread
);
1000 CloseHandle(pi
.hProcess
);
1001 CloseHandle(houtfile
);
1002 return TGIT_GIT_SUCCESS
;
1006 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1008 // no need to parse a ref if it's already a 40-byte hash
1009 if (CGitHash::IsValidSHA1(friendname
))
1011 CString
sHash(friendname
);
1012 hash
= CGitHash(sHash
);
1018 git_repository
*repo
= NULL
;
1019 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1020 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1022 gitdirA
.ReleaseBuffer();
1025 gitdirA
.ReleaseBuffer();
1027 int isHeadOrphan
= git_repository_head_orphan(repo
);
1028 if (isHeadOrphan
!= 0)
1030 git_repository_free(repo
);
1032 if (isHeadOrphan
== 1)
1038 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1040 git_object
* gitObject
= NULL
;
1041 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1043 refnameA
.ReleaseBuffer();
1044 git_repository_free(repo
);
1047 refnameA
.ReleaseBuffer();
1049 const git_oid
* oid
= git_object_id(gitObject
);
1052 git_object_free(gitObject
);
1053 git_repository_free(repo
);
1057 hash
= CGitHash((char *)oid
->id
);
1059 git_object_free(gitObject
); // also frees oid
1060 git_repository_free(repo
);
1067 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1068 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1069 hash
= CGitHash(gitLastErr
.Trim());
1074 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1079 cmd
=_T("git.exe ls-files -s -t -z");
1081 if (Run(cmd
, &cmdout
))
1084 outputlist
.ParserFromLsFile(cmdout
);
1085 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1086 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1090 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1094 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1097 if(rev1
== GIT_REV_ZERO
)
1098 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1100 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1104 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1111 outputlist
.ParserFromLog(out
);
1116 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1118 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1120 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1121 list
->push_back(str
);
1125 int CGit::GetTagList(STRING_VECTOR
&list
)
1127 if (this->m_IsUseLibGit2
)
1129 git_repository
*repo
= NULL
;
1131 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1132 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1134 gitdir
.ReleaseBuffer();
1137 gitdir
.ReleaseBuffer();
1139 git_strarray tag_names
;
1141 if (git_tag_list(&tag_names
, repo
))
1143 git_repository_free(repo
);
1147 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1149 CStringA
tagName(tag_names
.strings
[i
]);
1150 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1153 git_strarray_free(&tag_names
);
1155 git_repository_free(repo
);
1157 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1163 CString cmd
, output
;
1164 cmd
=_T("git.exe tag -l");
1165 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1172 one
=output
.Tokenize(_T("\n"),pos
);
1174 list
.push_back(one
);
1176 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1183 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1184 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1186 CString
CGit::GetGitLastErr(CString msg
)
1188 if (this->m_IsUseLibGit2
)
1189 return GetLibGit2LastErr(msg
);
1190 else if (gitLastErr
.IsEmpty())
1191 return msg
+ _T("\nUnknown git.exe error.");
1194 CString lastError
= gitLastErr
;
1196 return msg
+ _T("\n") + lastError
;
1200 CString
CGit::GetLibGit2LastErr()
1202 const git_error
*libgit2err
= giterr_last();
1205 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1207 return _T("libgit2 returned: ") + lastError
;
1210 return _T("An error occoured in libgit2, but no message is available.");
1213 CString
CGit::GetLibGit2LastErr(CString msg
)
1216 return msg
+ _T("\n") + GetLibGit2LastErr();
1217 return GetLibGit2LastErr();
1220 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1222 if(branchName
== "FETCH_HEAD")
1223 branchName
= DerefFetchHead();
1227 CString
CGit::FixBranchName(const CString
& branchName
)
1229 CString tempBranchName
= branchName
;
1230 FixBranchName_Mod(tempBranchName
);
1231 return tempBranchName
;
1234 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1239 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1240 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1246 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1257 Checks if a branch or tag with the given name exists
1258 isBranch is true -> branch, tag otherwise
1260 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1262 CString cmd
, output
;
1264 cmd
= _T("git show-ref ");
1266 cmd
+= _T("--heads ");
1268 cmd
+= _T("--tags ");
1270 cmd
+= _T("refs/heads/") + name
;
1271 cmd
+= _T(" refs/tags/") + name
;
1273 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1276 if (!output
.IsEmpty())
1283 CString
CGit::DerefFetchHead()
1285 using namespace std
;
1287 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1288 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1289 int forMergeLineCount
= 0;
1291 string hashToReturn
;
1292 while(getline(fetchHeadFile
, line
))
1294 //Tokenize this line
1295 string::size_type prevPos
= 0;
1296 string::size_type pos
= line
.find('\t');
1297 if(pos
== string::npos
) continue; //invalid line
1299 string hash
= line
.substr(0, pos
);
1300 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1302 bool forMerge
= pos
== prevPos
;
1303 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1305 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1310 hashToReturn
= hash
;
1311 ++forMergeLineCount
;
1312 if(forMergeLineCount
> 1)
1313 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1317 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1320 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1323 CString cmd
, output
, cur
;
1324 cmd
= _T("git.exe branch --no-color");
1326 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1328 else if(type
&BRANCH_REMOTE
)
1331 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1338 one
=output
.Tokenize(_T("\n"),pos
);
1339 one
.Trim(L
" \r\n\t");
1340 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1341 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1342 if(one
[0] == _T('*'))
1347 if (one
!= _T("(no branch)"))
1348 list
.push_back(one
);
1352 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1353 list
.push_back(L
"FETCH_HEAD");
1355 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1357 if (current
&& cur
!= _T("(no branch)"))
1359 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1372 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1374 if (this->m_IsUseLibGit2
)
1376 git_repository
*repo
= NULL
;
1378 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1379 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1381 gitdir
.ReleaseBuffer();
1384 gitdir
.ReleaseBuffer();
1386 git_strarray remotes
;
1388 if (git_remote_list(&remotes
, repo
))
1390 git_repository_free(repo
);
1394 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1396 CStringA
remote(remotes
.strings
[i
]);
1397 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1400 git_strarray_free(&remotes
);
1402 git_repository_free(repo
);
1404 std::sort(list
.begin(), list
.end());
1411 CString cmd
, output
;
1412 cmd
=_T("git.exe remote");
1413 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1420 one
=output
.Tokenize(_T("\n"),pos
);
1422 list
.push_back(one
);
1429 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1431 CString cmd
, out
, err
;
1432 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1433 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1435 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1442 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1443 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1444 if (one
.Find(_T("^{}")) >= 1)
1447 list
.push_back(one
);
1449 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1453 int libgit2_addto_list_each_ref_fn(const char *refname
, void *payload
)
1455 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1457 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1458 list
->push_back(str
);
1462 int CGit::GetRefList(STRING_VECTOR
&list
)
1464 if (this->m_IsUseLibGit2
)
1466 git_repository
*repo
= NULL
;
1468 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1469 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1471 gitdir
.ReleaseBuffer();
1474 gitdir
.ReleaseBuffer();
1476 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_list_each_ref_fn
, &list
))
1478 git_repository_free(repo
);
1482 git_repository_free(repo
);
1484 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1490 CString cmd
, output
;
1491 cmd
=_T("git.exe show-ref -d");
1492 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1499 one
=output
.Tokenize(_T("\n"),pos
);
1500 int start
=one
.Find(_T(" "),0);
1504 name
=one
.Right(one
.GetLength()-start
-1);
1505 list
.push_back(name
);
1508 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1514 typedef struct map_each_ref_payload
{
1515 git_repository
* repo
;
1516 MAP_HASH_NAME
* map
;
1517 } map_each_ref_payload
;
1519 int libgit2_addto_map_each_ref_fn(const char *refname
, void *payload
)
1521 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1524 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1526 git_object
* gitObject
= NULL
;
1530 if (git_revparse_single(&gitObject
, payloadContent
->repo
, refname
))
1535 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1537 str
+= _T("^{}"); // deref tag
1538 git_object
* derefedTag
= NULL
;
1539 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1543 git_object_free(gitObject
);
1544 gitObject
= derefedTag
;
1547 const git_oid
* oid
= git_object_id(gitObject
);
1553 CGitHash
hash((char *)oid
->id
);
1554 (*payloadContent
->map
)[hash
].push_back(str
);
1559 git_object_free(gitObject
);
1566 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1568 if (this->m_IsUseLibGit2
)
1570 git_repository
*repo
= NULL
;
1572 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1573 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1575 gitdir
.ReleaseBuffer();
1578 gitdir
.ReleaseBuffer();
1580 map_each_ref_payload payloadContent
= { repo
, &map
};
1582 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1584 git_repository_free(repo
);
1588 git_repository_free(repo
);
1590 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1592 std::sort(it
->second
.begin(), it
->second
.end());
1599 CString cmd
, output
;
1600 cmd
=_T("git.exe show-ref -d");
1601 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1608 one
=output
.Tokenize(_T("\n"),pos
);
1609 int start
=one
.Find(_T(" "),0);
1613 name
=one
.Right(one
.GetLength()-start
-1);
1616 hash
=one
.Left(start
);
1618 map
[CGitHash(hash
)].push_back(name
);
1626 BOOL
CGit::CheckMsysGitDir()
1633 this->m_Environment
.clear();
1634 m_Environment
.CopyProcessEnvironment();
1637 size_t homesize
,size
;
1639 // set HOME if not set already
1640 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1643 CString home
= GetHomeDirectory();
1644 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1645 home
.ReleaseBuffer();
1650 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1652 if(!sshclient
.IsEmpty())
1654 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1655 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1659 TCHAR sPlink
[MAX_PATH
];
1660 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1661 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1663 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1664 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1665 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1670 TCHAR sAskPass
[MAX_PATH
];
1671 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1672 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1675 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1676 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1677 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1678 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1682 // add git/bin path to PATH
1684 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1686 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1688 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1689 str
= msyslocalinstalldir
;
1690 str
.TrimRight(_T("\\"));
1693 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1694 str
= msysinstalldir
;
1695 str
.TrimRight(_T("\\"));
1697 if ( !str
.IsEmpty() )
1701 CGit::ms_LastMsysGitDir
= str
;
1706 // search PATH if git/bin directory is already present
1707 if ( FindGitPath() )
1709 m_bInitialized
= TRUE
;
1710 msysdir
= CGit::ms_LastMsysGitDir
;
1720 CGit::ms_LastMsysGitDir
= str
;
1723 // check for git.exe existance (maybe it was deinstalled in the meantime)
1724 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1728 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1731 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1733 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1735 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1737 CString sOldPath
= oldpath
;
1740 m_bInitialized
= TRUE
;
1744 CString
CGit::GetHomeDirectory()
1746 const wchar_t * homeDir
= wget_windows_home_directory();
1747 return CString(homeDir
, (int)wcslen(homeDir
));
1750 CString
CGit::GetGitLocalConfig()
1753 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1754 path
+= _T("config");
1758 CString
CGit::GetGitGlobalConfig()
1760 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1763 CString
CGit::GetGitGlobalXDGConfigPath()
1765 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1768 CString
CGit::GetGitGlobalXDGConfig()
1770 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1773 CString
CGit::GetGitSystemConfig()
1775 const wchar_t * systemConfig
= wget_msysgit_etc();
1776 return CString(systemConfig
, (int)wcslen(systemConfig
));
1779 BOOL
CGit::CheckCleanWorkTree()
1783 cmd
=_T("git.exe rev-parse --verify HEAD");
1785 if(Run(cmd
,&out
,CP_UTF8
))
1788 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1789 if(Run(cmd
,&out
,CP_UTF8
))
1792 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1793 if(Run(cmd
,&out
,CP_UTF8
))
1796 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1797 if(Run(cmd
,&out
,CP_UTF8
))
1802 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1805 for (int i
= 0; i
< list
.GetCount(); ++i
)
1807 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1813 int CGit::Revert(CString commit
, CTGitPath
&path
)
1817 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1819 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1822 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1823 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1827 // if the filenames only differ in case, we have to pass "-f"
1828 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1830 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1831 if (Run(cmd
, &out
, CP_UTF8
))
1833 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1837 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1838 if (Run(cmd
, &out
, CP_UTF8
))
1840 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1845 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1846 { //To init git repository, there are not HEAD, so we can use git reset command
1847 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1849 if (Run(cmd
, &out
, CP_UTF8
))
1851 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1857 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1858 if (Run(cmd
, &out
, CP_UTF8
))
1860 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1865 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1867 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1868 if (Run(cmd
, &out
, CP_UTF8
))
1870 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1878 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1884 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1886 cmd
=_T("git.exe ls-files -u -t -z");
1888 if (Run(cmd
, &vector
))
1893 list
.ParserFromLsFile(vector
);
1898 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1901 CGitHash basehash
,hash
;
1903 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1905 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1909 basehash
= base
.Trim();
1911 GetHash(hash
, from
);
1914 *commonAncestor
= basehash
;
1916 return hash
== basehash
;
1919 unsigned int CGit::Hash2int(CGitHash
&hash
)
1922 for (int i
= 0; i
< 4; ++i
)
1925 ret
|= hash
.m_hash
[i
];
1930 int CGit::RefreshGitIndex()
1932 if(g_Git
.m_IsUseGitDLL
)
1934 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1937 return git_run_cmd("update-index","update-index -q --refresh");
1948 cmd
=_T("git.exe update-index --refresh");
1949 return Run(cmd
, &output
, CP_UTF8
);
1953 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1955 if(g_Git
.m_IsUseGitDLL
)
1957 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1960 g_Git
.CheckAndInitDll();
1961 CStringA ref
, patha
, outa
;
1962 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1963 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1964 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1965 ::DeleteFile(outputfile
);
1966 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1976 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1977 return RunLogFile(cmd
,outputfile
);
1980 void CEnvironment::CopyProcessEnvironment()
1982 TCHAR
*p
= GetEnvironmentStrings();
1983 while(*p
!=0 || *(p
+1) !=0)
1984 this->push_back(*p
++);
1986 push_back(_T('\0'));
1987 push_back(_T('\0'));
1990 CString
CEnvironment::GetEnv(TCHAR
*name
)
1993 for (size_t i
= 0; i
< size(); ++i
)
1997 CString sname
= str
.Tokenize(_T("="),start
);
1998 if(sname
.CompareNoCase(name
) == 0)
2000 return &(*this)[i
+start
];
2007 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2010 for (i
= 0; i
< size(); ++i
)
2012 CString str
= &(*this)[i
];
2014 CString sname
= str
.Tokenize(_T("="),start
);
2015 if(sname
.CompareNoCase(name
) == 0)
2024 i
-= 1; // roll back terminate \0\0
2025 this->push_back(_T('\0'));
2028 CEnvironment::iterator it
;
2032 while(*it
&& i
<size())
2041 this->insert(it
,*name
++);
2046 this->insert(it
, _T('='));
2052 this->insert(it
,*value
++);
2059 int CGit::GetGitEncode(TCHAR
* configkey
)
2061 CString str
=GetConfigValue(configkey
);
2066 return CUnicodeUtils::GetCPCode(str
);
2070 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2076 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2079 diff
= GetGitDiff();
2081 git_open_diff(&diff
, arg
);
2090 isStat
= !!strstr(arg
, "stat");
2095 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2097 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2106 for (int j
= 0; j
< count
; ++j
)
2115 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2116 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2117 &mode
,&IsBin
,&inc
,&dec
);
2119 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2120 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2122 path
.SetFromGit(strnewname
,&stroldname
);
2123 path
.ParserAction((BYTE
)mode
);
2127 path
.m_StatAdd
=_T("-");
2128 path
.m_StatDel
=_T("-");
2132 path
.m_StatAdd
.Format(_T("%d"),inc
);
2133 path
.m_StatDel
.Format(_T("%d"),dec
);
2135 PathList
->AddPath(path
);
2137 git_diff_flush(diff
);
2140 git_close_diff(diff
);
2145 int CGit::GetShortHASHLength()
2150 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2154 REF_TYPE type
= CGit::UNKNOWN
;
2156 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2158 type
= CGit::LOCAL_BRANCH
;
2161 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2163 type
= CGit::REMOTE_BRANCH
;
2165 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2169 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2172 shortname
=_T("stash");
2174 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2176 if (shortname
.Find(_T("good")) == 0)
2178 type
= CGit::BISECT_GOOD
;
2179 shortname
= _T("good");
2182 if (shortname
.Find(_T("bad")) == 0)
2184 type
= CGit::BISECT_BAD
;
2185 shortname
= _T("bad");
2188 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2194 type
= CGit::UNKNOWN
;
2195 shortname
= _T("Unknown");
2204 bool CGit::UsingLibGit2(int cmd
)
2206 if (cmd
>= 0 && cmd
< 32)
2207 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;