1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - 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"
32 int CGit::m_LogEncode
=CP_UTF8
;
33 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
35 static LPTSTR
nextpath(LPCTSTR src
, LPTSTR dst
, UINT maxlen
)
39 while (*src
== _T(';'))
47 while (*src
&& *src
!= _T(';'))
61 while (*src
&& *src
!= _T('"'))
76 while (*src
== _T(';'))
83 return (orgsrc
!= src
) ? (LPTSTR
)src
: NULL
;
86 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
89 return _tstat(lpszFileName
, &st
) == 0;
92 static BOOL
FindGitPath()
95 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
102 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
103 _tgetenv_s(&size
, env
, size
, _T("PATH"));
105 TCHAR buf
[_MAX_PATH
];
107 // search in all paths defined in PATH
108 while ((env
= nextpath(env
, buf
, _MAX_PATH
-1)) != NULL
&& *buf
)
110 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
112 // ensure trailing slash
113 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
114 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, _MAX_PATH-1 is used in nextpath above
116 const size_t len
= _tcslen(buf
);
118 if ((len
+ 7) < _MAX_PATH
)
119 _tcscpy_s(pfin
+ 1, _MAX_PATH
- len
, _T("git.exe"));
123 if ( FileExists(buf
) )
127 CGit::ms_LastMsysGitDir
= buf
;
135 static bool g_bSortLogical
;
137 static void GetSortLogicalEnabled()
139 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
141 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
144 static int LogicalComparePredicate(CString
&left
, CString
&right
)
147 return StrCmpLogicalW(left
, right
) < 0;
148 return StrCmpI(left
, right
) < 0;
151 #define MAX_DIRBUFFER 1000
152 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
154 CString
CGit::ms_LastMsysGitDir
;
160 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
161 m_CurrentDir
.ReleaseBuffer();
162 m_IsGitDllInited
= false;
164 m_GitSimpleListDiff
=0;
165 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
166 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
167 GetSortLogicalEnabled();
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();
318 BOOL
CGit::IsInitRepos()
322 if(g_Git
.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout
,CP_UTF8
))
324 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
333 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
335 PASYNCREADSTDERRTHREADARGS pDataArray
;
336 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
339 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
340 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
342 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
349 int CGit::Run(CGitCall
* pcall
)
351 PROCESS_INFORMATION pi
;
352 HANDLE hRead
, hReadErr
;
353 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
354 return TGIT_GIT_ERROR_CREATE_PROCESS
;
357 ASYNCREADSTDERRTHREADARGS threadArguments
;
358 threadArguments
.fileHandle
= hReadErr
;
359 threadArguments
.pcall
= pcall
;
360 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
363 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
365 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
367 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
368 if(!bAborted
)//For now, flush output when command aborted.
369 if(pcall
->OnOutputData(data
,readnumber
))
376 WaitForSingleObject(thread
, INFINITE
);
378 CloseHandle(pi
.hThread
);
380 WaitForSingleObject(pi
.hProcess
, INFINITE
);
383 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
385 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
388 CloseHandle(pi
.hProcess
);
391 CloseHandle(hReadErr
);
394 class CGitCall_ByteVector
: public CGitCall
397 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
398 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
402 size_t oldsize
=m_pvector
->size();
403 m_pvector
->resize(m_pvector
->size()+size
);
404 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
407 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
409 if (!m_pvectorErr
|| size
== 0)
411 size_t oldsize
= m_pvectorErr
->size();
412 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
413 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
416 BYTE_VECTOR
* m_pvector
;
417 BYTE_VECTOR
* m_pvectorErr
;
420 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
422 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
425 int CGit::Run(CString cmd
, CString
* output
, int code
)
429 ret
= Run(cmd
, output
, &err
, code
);
431 if (output
&& !err
.IsEmpty())
433 if (!output
->IsEmpty())
440 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
442 BYTE_VECTOR vector
, vectorErr
;
445 ret
= Run(cmd
, &vector
, &vectorErr
);
447 ret
= Run(cmd
, &vector
);
450 StringAppend(output
, &(vector
[0]), code
);
454 vectorErr
.push_back(0);
455 StringAppend(outputErr
, &(vectorErr
[0]), code
);
461 CString
CGit::GetUserName(void)
464 env
.CopyProcessEnvironment();
465 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
466 if (!envname
.IsEmpty())
468 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
470 CString
CGit::GetUserEmail(void)
473 env
.CopyProcessEnvironment();
474 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
475 if (!envmail
.IsEmpty())
478 return GetConfigValue(L
"user.email");
481 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
485 if(this->m_IsUseGitDLL
)
487 CString
*git_path
=NULL
;
489 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
502 key
= CUnicodeUtils::GetMulti(name
, encoding
);
505 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
507 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
511 g_Git
.StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
513 return configValue
.Tokenize(_T("\n"),start
);
521 cmd
.Format(L
"git.exe config %s", name
);
522 Run(cmd
, &configValue
, NULL
, encoding
);
524 return configValue
.Tokenize(_T("\n"),start
);
529 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
531 if(this->m_IsUseGitDLL
)
533 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
542 CStringA keya
, valuea
;
543 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
544 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
547 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
549 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
559 option
= _T("--global");
562 option
= _T("--system");
567 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
569 if (Run(cmd
, &out
, NULL
, encoding
))
577 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
579 if(this->m_IsUseGitDLL
)
581 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
590 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
593 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
595 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
604 option
= _T("--global");
607 option
= _T("--system");
612 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
614 if (Run(cmd
, &out
, NULL
, encoding
))
622 CString
CGit::GetCurrentBranch(void)
625 //Run(_T("git.exe branch"),&branch);
627 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
629 return _T("(no branch)");
636 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
639 if(this->m_IsUseGitDLL
)
641 unsigned char sha1
[20];
644 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
645 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
646 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
648 g_Git
.StringAppend(&refName
,(BYTE
*)refs_heads_master
);
650 refName
= StripRefName(refName
);
657 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
658 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
659 return CString();//Error
661 refName
= refName
.Tokenize(L
"\n", iStart
);
663 refName
= StripRefName(refName
);
668 CString
CGit::GetFullRefName(CString shortRefName
)
672 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
673 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
674 return CString();//Error
676 return refName
.Tokenize(L
"\n", iStart
);
679 CString
CGit::StripRefName(CString refName
)
681 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
682 refName
= refName
.Mid(11);
683 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
684 refName
= refName
.Mid(5);
686 return refName
.Tokenize(_T("\n"),start
);
689 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
691 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
693 if ( sProjectRoot
.IsEmpty() )
697 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
700 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
703 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
711 fgets(s
, sizeof(s
), pFile
);
715 const char *pfx
= "ref: refs/heads/";
716 const int len
= 16;//strlen(pfx)
718 if ( !strncmp(s
, pfx
, len
) )
720 //# We're on a branch. It might not exist. But
721 //# HEAD looks good enough to be a branch.
722 CStringA
utf8Branch(s
+ len
);
723 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
724 sBranchOut
.TrimRight(_T(" \r\n\t"));
726 if ( sBranchOut
.IsEmpty() )
731 //# Assume this is a detached head.
740 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
743 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
747 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
749 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
751 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
753 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
755 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
757 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
759 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
763 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
765 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
767 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
772 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
778 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
780 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
781 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
784 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
794 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
797 num
.Format(_T("-n%d"),count
);
801 if(mask
& LOG_INFO_STAT
)
802 param
+= _T(" --numstat ");
803 if(mask
& LOG_INFO_FILESTATE
)
804 param
+= _T(" --raw ");
806 if(mask
& LOG_INFO_FULLHISTORY
)
807 param
+= _T(" --full-history ");
809 if(mask
& LOG_INFO_BOUNDARY
)
810 param
+= _T(" --left-right --boundary ");
812 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
813 param
+= _T(" --all ");
815 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
818 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
821 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
822 param
+= _T(" --first-parent ");
824 if(mask
& CGit::LOG_INFO_NO_MERGE
)
825 param
+= _T(" --no-merges ");
827 if(mask
& CGit::LOG_INFO_FOLLOW
)
828 param
+= _T(" --follow ");
830 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
833 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
834 param
+= _T(" --full-diff ");
836 if(from
!= NULL
&& to
!= NULL
)
839 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
842 else if(to
!= NULL
&& hash
.IsEmpty())
845 range
.Format(_T(" %s "), FixBranchName(*to
));
852 if( Filter
&& (Filter
->m_From
!= -1))
854 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
858 if( Filter
&& (Filter
->m_To
!= -1))
860 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
865 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
867 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
872 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
874 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
879 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
881 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
888 if(!Filter
->m_IsRegex
)
889 param
+= _T(" --fixed-strings ");
891 param
+= _T(" --regexp-ignore-case --extended-regexp ");
894 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
895 param
+= _T(" --topo-order");
897 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
898 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
902 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
903 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
911 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
912 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
914 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
916 return Run(pgitCall
);
917 // return Run(cmd,&logOut);
921 void GetTempPath(CString
&path
)
923 TCHAR lpPathBuffer
[BUFSIZE
];
925 DWORD dwBufSize
=BUFSIZE
;
926 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
927 lpPathBuffer
); // buffer for path
928 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
932 path
.Format(_T("%s"),lpPathBuffer
);
934 CString
GetTempFile()
936 TCHAR lpPathBuffer
[BUFSIZE
];
938 DWORD dwBufSize
=BUFSIZE
;
939 TCHAR szTempName
[BUFSIZE
];
942 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
943 lpPathBuffer
); // buffer for path
944 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
948 // Create a temporary file.
949 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
950 TEXT("Patch"), // temp file name prefix
951 0, // create unique name
952 szTempName
); // buffer for name
960 return CString(szTempName
);
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 CGitHash
CGit::GetHash(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 return CGitHash(sHash
);
1015 if(this->m_IsUseGitDLL
)
1017 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1019 this->CheckAndInitDll();
1023 ref
= CUnicodeUtils::GetMulti(FixBranchName(friendname
), CP_UTF8
);
1026 git_get_sha1(ref
, hash
.m_hash
);
1038 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1039 Run(cmd
, &out
, NULL
, CP_UTF8
);
1040 // int pos=out.ReverseFind(_T('\n'));
1041 out
.FindOneOf(_T("\r\n"));
1042 return CGitHash(out
);
1046 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1051 cmd
=_T("git.exe ls-files -s -t -z");
1053 if (g_Git
.Run(cmd
, &cmdout
))
1056 outputlist
.ParserFromLsFile(cmdout
);
1057 for(int i
=0;i
<outputlist
.GetCount();i
++)
1058 ((unsigned int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
1062 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1066 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1069 if(rev1
== GIT_REV_ZERO
)
1070 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1072 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1076 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1080 if (g_Git
.Run(cmd
, &out
))
1083 outputlist
.ParserFromLog(out
);
1088 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1090 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1092 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1093 list
->push_back(str
);
1097 int CGit::GetTagList(STRING_VECTOR
&list
)
1099 if (this->m_IsUseLibGit2
)
1101 git_repository
*repo
= NULL
;
1103 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1104 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1106 gitdir
.ReleaseBuffer();
1109 gitdir
.ReleaseBuffer();
1111 git_strarray tag_names
;
1113 if (git_tag_list(&tag_names
, repo
))
1115 git_repository_free(repo
);
1119 for (size_t i
= 0; i
< tag_names
.count
; i
++)
1121 CStringA
tagName(tag_names
.strings
[i
]);
1122 list
.push_back(CUnicodeUtils::GetUnicode(tagName
).Mid(10)); // strip "refs/tags/"
1125 git_strarray_free(&tag_names
);
1127 git_repository_free(repo
);
1129 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1135 CString cmd
, output
;
1136 cmd
=_T("git.exe tag -l");
1138 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1146 one
=output
.Tokenize(_T("\n"),pos
);
1147 list
.push_back(one
);
1149 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1155 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1157 if(branchName
== "FETCH_HEAD")
1158 branchName
= DerefFetchHead();
1162 CString
CGit::FixBranchName(const CString
& branchName
)
1164 CString tempBranchName
= branchName
;
1165 FixBranchName_Mod(tempBranchName
);
1166 return tempBranchName
;
1169 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1174 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1175 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1181 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1192 Checks if a branch or tag with the given name exists
1193 isBranch is true -> branch, tag otherwise
1195 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1197 CString cmd
, output
;
1199 cmd
= _T("git show-ref ");
1201 cmd
+= _T("--heads ");
1203 cmd
+= _T("--tags ");
1205 cmd
+= _T("refs/heads/") + name
;
1206 cmd
+= _T(" refs/tags/") + name
;
1208 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1211 if (!output
.IsEmpty())
1218 CString
CGit::DerefFetchHead()
1220 using namespace std
;
1222 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1223 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1224 int forMergeLineCount
= 0;
1226 string hashToReturn
;
1227 while(getline(fetchHeadFile
, line
))
1229 //Tokenize this line
1230 string::size_type prevPos
= 0;
1231 string::size_type pos
= line
.find('\t');
1232 if(pos
== string::npos
) continue; //invalid line
1234 string hash
= line
.substr(0, pos
);
1235 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1237 bool forMerge
= pos
== prevPos
;
1238 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1240 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1245 hashToReturn
= hash
;
1246 ++forMergeLineCount
;
1247 if(forMergeLineCount
> 1)
1248 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1252 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1255 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1258 CString cmd
, output
, cur
;
1259 cmd
= _T("git.exe branch --no-color");
1261 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1263 else if(type
&BRANCH_REMOTE
)
1266 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1273 one
=output
.Tokenize(_T("\n"),pos
);
1274 one
.Trim(L
" \r\n\t");
1275 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1276 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1277 if(one
[0] == _T('*'))
1282 if (one
!= _T("(no branch)"))
1283 list
.push_back(one
);
1287 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1288 list
.push_back(L
"FETCH_HEAD");
1290 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1292 if (current
&& cur
!= _T("(no branch)"))
1294 for (unsigned int i
= 0; i
< list
.size(); i
++)
1307 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1309 if (this->m_IsUseLibGit2
)
1311 git_repository
*repo
= NULL
;
1313 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1314 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1316 gitdir
.ReleaseBuffer();
1319 gitdir
.ReleaseBuffer();
1321 git_strarray remotes
;
1323 if (git_remote_list(&remotes
, repo
))
1325 git_repository_free(repo
);
1329 for (size_t i
= 0; i
< remotes
.count
; i
++)
1331 CStringA
remote(remotes
.strings
[i
]);
1332 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1335 git_strarray_free(&remotes
);
1337 git_repository_free(repo
);
1339 std::sort(list
.begin(), list
.end());
1346 CString cmd
, output
;
1347 cmd
=_T("git.exe remote");
1348 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1355 one
=output
.Tokenize(_T("\n"),pos
);
1357 list
.push_back(one
);
1364 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1366 CString cmd
, out
, err
;
1367 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1368 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
1370 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1377 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1378 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1379 if (one
.Find(_T("^{}")) >= 1)
1382 list
.push_back(one
);
1384 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1388 int CGit::GetRefList(STRING_VECTOR
&list
)
1391 if(this->m_IsUseGitDLL
)
1393 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1394 ret
= git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
1395 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1399 CString cmd
, output
;
1400 cmd
=_T("git.exe show-ref -d");
1401 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1408 one
=output
.Tokenize(_T("\n"),pos
);
1409 int start
=one
.Find(_T(" "),0);
1413 name
=one
.Right(one
.GetLength()-start
-1);
1414 list
.push_back(name
);
1422 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int /*flags*/, void *cb_data
)
1424 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
1426 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1427 CGitHash
hash((char*)sha1
);
1429 (*map
)[hash
].push_back(str
);
1431 if(strncmp(refname
, "refs/tags", 9) == 0)
1436 if(!git_deref_tag(sha1
, refhash
))
1438 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
1444 ::MessageBox(NULL
, _T("Could not get (readable) reference for hash ") + hash
.ToString() + _T(".\nlibgit reports:\n") + err
, _T("TortoiseGit"), MB_ICONERROR
);
1450 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1453 if(this->m_IsUseGitDLL
)
1455 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1456 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1461 CString cmd
, output
;
1462 cmd
=_T("git.exe show-ref -d");
1463 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1470 one
=output
.Tokenize(_T("\n"),pos
);
1471 int start
=one
.Find(_T(" "),0);
1475 name
=one
.Right(one
.GetLength()-start
-1);
1478 hash
=one
.Left(start
);
1480 map
[CGitHash(hash
)].push_back(name
);
1488 BOOL
CGit::CheckMsysGitDir()
1495 this->m_Environment
.clear();
1496 m_Environment
.CopyProcessEnvironment();
1499 size_t homesize
,size
;
1501 // set HOME if not set already
1502 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1505 CString home
= g_Git
.GetHomeDirectory();
1506 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1507 home
.ReleaseBuffer();
1512 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1514 if(!sshclient
.IsEmpty())
1516 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1517 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1521 TCHAR sPlink
[MAX_PATH
];
1522 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1523 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1525 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoisePlink.exe"));
1526 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1527 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1532 TCHAR sAskPass
[MAX_PATH
];
1533 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1534 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1537 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1538 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1539 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1540 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1544 // add git/bin path to PATH
1546 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1548 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1550 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1552 if ( !str
.IsEmpty() )
1554 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
1556 CGit::ms_LastMsysGitDir
= str
;
1561 // search PATH if git/bin directory is already present
1562 if ( FindGitPath() )
1564 m_bInitialized
= TRUE
;
1565 msysdir
= CGit::ms_LastMsysGitDir
;
1575 CGit::ms_LastMsysGitDir
= str
;
1578 // check for git.exe existance (maybe it was deinstalled in the meantime)
1579 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1583 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1586 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1588 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1590 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1592 CString sOldPath
= oldpath
;
1595 m_bInitialized
= TRUE
;
1599 CString
CGit::GetHomeDirectory()
1601 const wchar_t * homeDir
= wget_windows_home_directory();
1602 return CString(homeDir
, (int)wcslen(homeDir
));
1605 CString
CGit::GetGitSystemConfig()
1607 const wchar_t * systemConfig
= wget_msysgit_etc();
1608 return CString(systemConfig
, (int)wcslen(systemConfig
));
1611 BOOL
CGit::CheckCleanWorkTree()
1615 cmd
=_T("git.exe rev-parse --verify HEAD");
1617 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1620 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1621 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1624 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1625 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1628 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1629 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1634 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1637 for(int i
=0;i
<list
.GetCount();i
++)
1639 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1645 int CGit::Revert(CString commit
, CTGitPath
&path
)
1649 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1651 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1654 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1655 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1659 // if the filenames only differ in case, we have to pass "-f"
1660 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1662 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1663 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1665 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1669 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1670 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1672 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1677 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1678 { //To init git repository, there are not HEAD, so we can use git reset command
1679 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1681 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1683 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1689 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1690 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1692 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1697 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1699 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1700 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1702 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1710 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1716 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1718 cmd
=_T("git.exe ls-files -u -t -z");
1720 if (g_Git
.Run(cmd
, &vector
))
1725 list
.ParserFromLsFile(vector
);
1730 bool CGit::IsFastForward(const CString
&from
, const CString
&to
)
1733 CGitHash basehash
,hash
;
1735 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1737 if (g_Git
.Run(cmd
, &base
, &err
, CP_UTF8
))
1739 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1744 hash
=g_Git
.GetHash(from
);
1746 return hash
== basehash
;
1749 unsigned int CGit::Hash2int(CGitHash
&hash
)
1752 for(int i
=0;i
<4;i
++)
1755 ret
|= hash
.m_hash
[i
];
1760 int CGit::RefreshGitIndex()
1762 if(g_Git
.m_IsUseGitDLL
)
1764 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1767 return git_run_cmd("update-index","update-index -q --refresh");
1778 cmd
=_T("git.exe update-index --refresh");
1779 return Run(cmd
, &output
, CP_UTF8
);
1783 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1785 if(g_Git
.m_IsUseGitDLL
)
1787 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1790 g_Git
.CheckAndInitDll();
1791 CStringA ref
, patha
, outa
;
1792 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1793 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1794 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1795 ::DeleteFile(outputfile
);
1796 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1806 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1807 return g_Git
.RunLogFile(cmd
,outputfile
);
1810 void CEnvironment::CopyProcessEnvironment()
1812 TCHAR
*p
= GetEnvironmentStrings();
1813 while(*p
!=0 || *(p
+1) !=0)
1814 this->push_back(*p
++);
1816 push_back(_T('\0'));
1817 push_back(_T('\0'));
1820 CString
CEnvironment::GetEnv(TCHAR
*name
)
1823 for (size_t i
= 0; i
< size(); i
++)
1827 CString sname
= str
.Tokenize(_T("="),start
);
1828 if(sname
.CompareNoCase(name
) == 0)
1830 return &(*this)[i
+start
];
1837 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1840 for( i
=0;i
<size();i
++)
1842 CString str
= &(*this)[i
];
1844 CString sname
= str
.Tokenize(_T("="),start
);
1845 if(sname
.CompareNoCase(name
) == 0)
1854 i
-= 1; // roll back terminate \0\0
1855 this->push_back(_T('\0'));
1858 CEnvironment::iterator it
;
1862 while(*it
&& i
<size())
1871 this->insert(it
,*name
++);
1876 this->insert(it
, _T('='));
1882 this->insert(it
,*value
++);
1889 int CGit::GetGitEncode(TCHAR
* configkey
)
1891 CString str
=GetConfigValue(configkey
);
1896 return CUnicodeUtils::GetCPCode(str
);
1900 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
1906 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1909 diff
= GetGitDiff();
1911 git_open_diff(&diff
, arg
);
1920 isStat
= !!strstr(arg
, "stat");
1925 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
1927 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
1936 for(int j
=0;j
<count
;j
++)
1945 int mode
=0,IsBin
=0,inc
=0,dec
=0;
1946 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
1947 &mode
,&IsBin
,&inc
,&dec
);
1949 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
1950 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
1952 path
.SetFromGit(strnewname
,&stroldname
);
1953 path
.ParserAction((BYTE
)mode
);
1957 path
.m_StatAdd
=_T("-");
1958 path
.m_StatDel
=_T("-");
1962 path
.m_StatAdd
.Format(_T("%d"),inc
);
1963 path
.m_StatDel
.Format(_T("%d"),dec
);
1965 PathList
->AddPath(path
);
1967 git_diff_flush(diff
);
1970 git_close_diff(diff
);
1975 int CGit::GetShortHASHLength()