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"
31 int CGit::m_LogEncode
=CP_UTF8
;
32 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
34 static LPTSTR
nextpath(LPCTSTR src
, LPTSTR dst
, UINT maxlen
)
38 while (*src
== _T(';'))
46 while (*src
&& *src
!= _T(';'))
60 while (*src
&& *src
!= _T('"'))
75 while (*src
== _T(';'))
82 return (orgsrc
!= src
) ? (LPTSTR
)src
: NULL
;
85 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
88 return _tstat(lpszFileName
, &st
) == 0;
91 static BOOL
FindGitPath()
94 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
101 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
102 _tgetenv_s(&size
, env
, size
, _T("PATH"));
104 TCHAR buf
[_MAX_PATH
];
106 // search in all paths defined in PATH
107 while ((env
= nextpath(env
, buf
, _MAX_PATH
-1)) && *buf
)
109 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
111 // ensure trailing slash
112 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
113 _tcscpy(++pfin
, _T("\\"));
115 const int len
= _tcslen(buf
);
117 if ((len
+ 7) < _MAX_PATH
)
118 _tcscpy(pfin
+1, _T("git.exe"));
122 if ( FileExists(buf
) )
126 CGit::ms_LastMsysGitDir
= buf
;
135 #define MAX_DIRBUFFER 1000
136 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
138 CString
CGit::ms_LastMsysGitDir
;
144 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
145 m_CurrentDir
.ReleaseBuffer();
146 m_IsGitDllInited
= false;
148 m_GitSimpleListDiff
=0;
149 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
150 this->m_bInitialized
=false;
152 m_critGitDllSec
.Init();
159 git_close_diff(m_GitDiff
);
162 if(this->m_GitSimpleListDiff
)
164 git_close_diff(m_GitSimpleListDiff
);
165 m_GitSimpleListDiff
=0;
169 bool CGit::IsBranchNameValid(CString branchname
)
171 if (branchname
.IsEmpty())
174 for(int i
=0; i
< branchname
.GetLength(); i
++)
176 TCHAR c
= branchname
.GetAt(i
);
177 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
181 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
184 CString reverseBranchname
= branchname
.MakeReverse();
185 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
191 static char g_Buffer
[4096];
193 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
195 SECURITY_ATTRIBUTES sa
;
196 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
197 HANDLE hStdioFile
= NULL
;
199 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
200 sa
.lpSecurityDescriptor
=NULL
;
201 sa
.bInheritHandle
=TRUE
;
202 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
204 return TGIT_GIT_ERROR_OPEN_PIP
;
206 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
207 return TGIT_GIT_ERROR_OPEN_PIP
;
211 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
212 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
216 PROCESS_INFORMATION pi
;
217 si
.cb
=sizeof(STARTUPINFO
);
221 si
.hStdError
= hWriteErr
;
223 si
.hStdError
= hWrite
;
225 si
.hStdOutput
=hStdioFile
;
227 si
.hStdOutput
=hWrite
;
229 si
.wShowWindow
=SW_HIDE
;
230 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
232 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
233 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
235 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
236 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
238 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
239 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
241 if(cmd
.Find(_T("git")) == 0)
243 int firstSpace
= cmd
.Find(_T(" "));
245 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
247 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
250 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
253 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
254 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
257 return TGIT_GIT_ERROR_CREATE_PROCESS
;
264 CloseHandle(hWriteErr
);
270 *hErrReadOut
= hReadErr
;
274 //Must use sperate function to convert ANSI str to union code string
275 //Becuase A2W use stack as internal convert buffer.
276 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
279 //str->Append(A2W_CP((LPCSTR)p,code));
287 len
= strlen((const char*)p
);
292 //buf = new WCHAR[len*4 + 1];
293 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
294 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
295 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
296 str
->ReleaseBuffer();
300 BOOL
CGit::IsInitRepos()
304 if(g_Git
.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout
,CP_UTF8
))
306 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
315 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
317 PASYNCREADSTDERRTHREADARGS pDataArray
;
318 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
321 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
322 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
324 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
331 int CGit::Run(CGitCall
* pcall
)
333 PROCESS_INFORMATION pi
;
334 HANDLE hRead
, hReadErr
;
335 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
336 return TGIT_GIT_ERROR_CREATE_PROCESS
;
339 ASYNCREADSTDERRTHREADARGS threadArguments
;
340 threadArguments
.fileHandle
= hReadErr
;
341 threadArguments
.pcall
= pcall
;
342 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
345 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
347 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
349 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
350 if(!bAborted
)//For now, flush output when command aborted.
351 if(pcall
->OnOutputData(data
,readnumber
))
358 WaitForSingleObject(thread
, INFINITE
);
360 CloseHandle(pi
.hThread
);
362 WaitForSingleObject(pi
.hProcess
, INFINITE
);
365 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
367 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
370 CloseHandle(pi
.hProcess
);
373 CloseHandle(hReadErr
);
376 class CGitCall_ByteVector
: public CGitCall
379 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
380 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
384 size_t oldsize
=m_pvector
->size();
385 m_pvector
->resize(m_pvector
->size()+size
);
386 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
389 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
391 if (!m_pvectorErr
|| size
== 0)
393 size_t oldsize
= m_pvectorErr
->size();
394 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
395 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
398 BYTE_VECTOR
* m_pvector
;
399 BYTE_VECTOR
* m_pvectorErr
;
402 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
404 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
407 int CGit::Run(CString cmd
, CString
* output
, int code
)
411 ret
= Run(cmd
, output
, &err
, code
);
413 if (output
&& !err
.IsEmpty())
415 if (!output
->IsEmpty())
422 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
424 BYTE_VECTOR vector
, vectorErr
;
427 ret
= Run(cmd
, &vector
, &vectorErr
);
429 ret
= Run(cmd
, &vector
);
432 StringAppend(output
, &(vector
[0]), code
);
436 vectorErr
.push_back(0);
437 StringAppend(outputErr
, &(vectorErr
[0]), code
);
443 CString
CGit::GetUserName(void)
446 env
.CopyProcessEnvironment();
447 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
448 if (!envname
.IsEmpty())
450 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
452 CString
CGit::GetUserEmail(void)
455 env
.CopyProcessEnvironment();
456 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
457 if (!envmail
.IsEmpty())
460 return GetConfigValue(L
"user.email");
463 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
467 if(this->m_IsUseGitDLL
)
469 CString
*git_path
=NULL
;
471 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
484 key
= CUnicodeUtils::GetMulti(name
, encoding
);
487 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
489 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
493 g_Git
.StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
495 return configValue
.Tokenize(_T("\n"),start
);
503 cmd
.Format(L
"git.exe config %s", name
);
504 Run(cmd
, &configValue
, NULL
, encoding
);
506 return configValue
.Tokenize(_T("\n"),start
);
511 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
513 if(this->m_IsUseGitDLL
)
515 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
524 CStringA keya
, valuea
;
525 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
526 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
529 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
531 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
541 option
= _T("--global");
544 option
= _T("--system");
549 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
551 if (Run(cmd
, &out
, NULL
, encoding
))
559 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
561 if(this->m_IsUseGitDLL
)
563 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
572 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
575 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
577 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
586 option
= _T("--global");
589 option
= _T("--system");
594 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
596 if (Run(cmd
, &out
, NULL
, encoding
))
604 CString
CGit::GetCurrentBranch(void)
607 //Run(_T("git.exe branch"),&branch);
609 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
611 return _T("(no branch)");
618 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
621 if(this->m_IsUseGitDLL
)
623 unsigned char sha1
[20];
626 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
627 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
628 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
630 g_Git
.StringAppend(&refName
,(BYTE
*)refs_heads_master
);
632 refName
= StripRefName(refName
);
639 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
640 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
641 return CString();//Error
643 refName
= refName
.Tokenize(L
"\n", iStart
);
645 refName
= StripRefName(refName
);
650 CString
CGit::GetFullRefName(CString shortRefName
)
654 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
655 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
656 return CString();//Error
658 return refName
.Tokenize(L
"\n", iStart
);
661 CString
CGit::StripRefName(CString refName
)
663 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
664 refName
= refName
.Mid(11);
665 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
666 refName
= refName
.Mid(5);
668 return refName
.Tokenize(_T("\n"),start
);
671 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
673 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
675 if ( sProjectRoot
.IsEmpty() )
679 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
682 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
685 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
693 fgets(s
, sizeof(s
), pFile
);
697 const char *pfx
= "ref: refs/heads/";
698 const int len
= 16;//strlen(pfx)
700 if ( !strncmp(s
, pfx
, len
) )
702 //# We're on a branch. It might not exist. But
703 //# HEAD looks good enough to be a branch.
704 CStringA
utf8Branch(s
+ len
);
705 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
706 sBranchOut
.TrimRight(_T(" \r\n\t"));
708 if ( sBranchOut
.IsEmpty() )
713 //# Assume this is a detached head.
722 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
725 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
729 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
731 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
733 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
735 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
737 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
739 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
741 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
745 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
747 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
749 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
754 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
760 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
762 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
763 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
766 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
776 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
779 num
.Format(_T("-n%d"),count
);
783 if(mask
& LOG_INFO_STAT
)
784 param
+= _T(" --numstat ");
785 if(mask
& LOG_INFO_FILESTATE
)
786 param
+= _T(" --raw ");
788 if(mask
& LOG_INFO_FULLHISTORY
)
789 param
+= _T(" --full-history ");
791 if(mask
& LOG_INFO_BOUNDARY
)
792 param
+= _T(" --left-right --boundary ");
794 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
795 param
+= _T(" --all ");
797 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
800 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
803 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
804 param
+= _T(" --first-parent ");
806 if(mask
& CGit::LOG_INFO_NO_MERGE
)
807 param
+= _T(" --no-merges ");
809 if(mask
& CGit::LOG_INFO_FOLLOW
)
810 param
+= _T(" --follow ");
812 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
815 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
816 param
+= _T(" --full-diff ");
818 if(from
!= NULL
&& to
!= NULL
)
821 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
824 else if(to
!= NULL
&& hash
.IsEmpty())
827 range
.Format(_T(" %s "), FixBranchName(*to
));
834 if( Filter
&& (Filter
->m_From
!= -1))
836 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
840 if( Filter
&& (Filter
->m_To
!= -1))
842 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
847 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
849 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
854 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
856 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
861 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
863 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
870 if(!Filter
->m_IsRegex
)
871 param
+= _T(" --fixed-strings ");
873 param
+= _T(" --regexp-ignore-case --extended-regexp ");
876 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
877 param
+= _T(" --topo-order");
879 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
880 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
884 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
885 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
893 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
894 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
896 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
898 return Run(pgitCall
);
899 // return Run(cmd,&logOut);
903 void GetTempPath(CString
&path
)
905 TCHAR lpPathBuffer
[BUFSIZE
];
907 DWORD dwBufSize
=BUFSIZE
;
908 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
909 lpPathBuffer
); // buffer for path
910 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
914 path
.Format(_T("%s"),lpPathBuffer
);
916 CString
GetTempFile()
918 TCHAR lpPathBuffer
[BUFSIZE
];
920 DWORD dwBufSize
=BUFSIZE
;
921 TCHAR szTempName
[BUFSIZE
];
924 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
925 lpPathBuffer
); // buffer for path
926 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
930 // Create a temporary file.
931 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
932 TEXT("Patch"), // temp file name prefix
933 0, // create unique name
934 szTempName
); // buffer for name
942 return CString(szTempName
);
946 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
949 PROCESS_INFORMATION pi
;
950 si
.cb
=sizeof(STARTUPINFO
);
953 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
954 psa
.bInheritHandle
=TRUE
;
956 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
957 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
959 si
.wShowWindow
= SW_HIDE
;
960 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
961 si
.hStdOutput
= houtfile
;
963 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
964 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
966 if(cmd
.Find(_T("git")) == 0)
967 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
969 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
972 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
973 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
976 return TGIT_GIT_ERROR_CREATE_PROCESS
;
979 WaitForSingleObject(pi
.hProcess
,INFINITE
);
981 CloseHandle(pi
.hThread
);
982 CloseHandle(pi
.hProcess
);
983 CloseHandle(houtfile
);
984 return TGIT_GIT_SUCCESS
;
988 CGitHash
CGit::GetHash(TCHAR
* friendname
)
990 if(this->m_IsUseGitDLL
)
992 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
994 this->CheckAndInitDll();
998 ref
= CUnicodeUtils::GetMulti(FixBranchName(friendname
), CP_UTF8
);
1001 git_get_sha1(ref
, hash
.m_hash
);
1013 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1014 Run(cmd
, &out
, NULL
, CP_UTF8
);
1015 // int pos=out.ReverseFind(_T('\n'));
1016 out
.FindOneOf(_T("\r\n"));
1017 return CGitHash(out
);
1021 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1026 cmd
=_T("git.exe ls-files -s -t -z");
1028 if (g_Git
.Run(cmd
, &cmdout
))
1031 outputlist
.ParserFromLsFile(cmdout
);
1032 for(int i
=0;i
<outputlist
.GetCount();i
++)
1033 ((unsigned int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
1037 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1041 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1044 if(rev1
== GIT_REV_ZERO
)
1045 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1047 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1051 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1055 if (g_Git
.Run(cmd
, &out
))
1058 outputlist
.ParserFromLog(out
);
1063 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1065 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1067 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1068 list
->push_back(str
);
1072 int CGit::GetTagList(STRING_VECTOR
&list
)
1076 if(this->m_IsUseGitDLL
)
1078 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1079 return git_for_each_ref_in("refs/tags/",addto_list_each_ref_fn
, &list
);
1084 CString cmd
, output
;
1085 cmd
=_T("git.exe tag -l");
1087 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1095 one
=output
.Tokenize(_T("\n"),pos
);
1096 list
.push_back(one
);
1103 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1105 if(branchName
== "FETCH_HEAD")
1106 branchName
= DerefFetchHead();
1110 CString
CGit::FixBranchName(const CString
& branchName
)
1112 CString tempBranchName
= branchName
;
1113 FixBranchName_Mod(tempBranchName
);
1114 return tempBranchName
;
1118 CString
CGit::DerefFetchHead()
1120 using namespace std
;
1122 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1123 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1124 int forMergeLineCount
= 0;
1126 string hashToReturn
;
1127 while(getline(fetchHeadFile
, line
))
1129 //Tokenize this line
1130 string::size_type prevPos
= 0;
1131 string::size_type pos
= line
.find('\t');
1132 if(pos
== string::npos
) continue; //invalid line
1134 string hash
= line
.substr(0, pos
);
1135 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1137 bool forMerge
= pos
== prevPos
;
1138 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1140 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1145 hashToReturn
= hash
;
1146 ++forMergeLineCount
;
1147 if(forMergeLineCount
> 1)
1148 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1152 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1155 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1158 CString cmd
, output
;
1159 cmd
= _T("git.exe branch --no-color");
1161 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1163 else if(type
&BRANCH_REMOTE
)
1167 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1174 one
=output
.Tokenize(_T("\n"),pos
);
1175 one
.Trim(L
" \r\n\t");
1176 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1177 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1178 if(one
[0] == _T('*'))
1184 if (one
!= _T("(no branch)"))
1185 list
.push_back(one
);
1190 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1191 list
.push_back(L
"FETCH_HEAD");
1196 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1199 CString cmd
, output
;
1200 cmd
=_T("git.exe remote");
1201 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1208 one
=output
.Tokenize(_T("\n"),pos
);
1209 list
.push_back(one
);
1215 int CGit::GetRefList(STRING_VECTOR
&list
)
1218 if(this->m_IsUseGitDLL
)
1220 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1221 return git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
1226 CString cmd
, output
;
1227 cmd
=_T("git.exe show-ref -d");
1228 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1235 one
=output
.Tokenize(_T("\n"),pos
);
1236 int start
=one
.Find(_T(" "),0);
1240 name
=one
.Right(one
.GetLength()-start
-1);
1241 list
.push_back(name
);
1249 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int /*flags*/, void *cb_data
)
1251 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
1253 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1254 CGitHash
hash((char*)sha1
);
1256 (*map
)[hash
].push_back(str
);
1258 if(strncmp(refname
, "refs/tags", 9) == 0)
1261 if(!git_deref_tag(sha1
, refhash
))
1263 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
1269 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1272 if(this->m_IsUseGitDLL
)
1274 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1275 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1280 CString cmd
, output
;
1281 cmd
=_T("git.exe show-ref -d");
1282 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1289 one
=output
.Tokenize(_T("\n"),pos
);
1290 int start
=one
.Find(_T(" "),0);
1294 name
=one
.Right(one
.GetLength()-start
-1);
1297 hash
=one
.Left(start
);
1299 map
[CGitHash(hash
)].push_back(name
);
1307 BOOL
CGit::CheckMsysGitDir()
1314 this->m_Environment
.clear();
1315 m_Environment
.CopyProcessEnvironment();
1318 size_t homesize
,size
;
1320 // set HOME if not set already
1321 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1324 CString home
= g_Git
.GetHomeDirectory();
1325 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1326 home
.ReleaseBuffer();
1331 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1333 if(!sshclient
.IsEmpty())
1335 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1336 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1340 TCHAR sPlink
[MAX_PATH
];
1341 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1342 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1344 _tcscpy(ptr
+ 1, _T("TortoisePlink.exe"));
1345 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1346 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1351 TCHAR sAskPass
[MAX_PATH
];
1352 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1353 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1356 _tcscpy(ptr
+ 1, _T("SshAskPass.exe"));
1357 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1358 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1359 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1363 // add git/bin path to PATH
1365 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1367 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1369 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1371 if ( !str
.IsEmpty() )
1373 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
1375 CGit::ms_LastMsysGitDir
= str
;
1380 // search PATH if git/bin directory is already present
1381 if ( FindGitPath() )
1383 m_bInitialized
= TRUE
;
1384 msysdir
= CGit::ms_LastMsysGitDir
;
1394 CGit::ms_LastMsysGitDir
= str
;
1397 // check for git.exe existance (maybe it was deinstalled in the meantime)
1398 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1402 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1405 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1407 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1409 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1411 CString sOldPath
= oldpath
;
1414 m_bInitialized
= TRUE
;
1418 CString
CGit::GetHomeDirectory()
1420 return CString(get_windows_home_directory());
1423 BOOL
CGit::CheckCleanWorkTree()
1427 cmd
=_T("git.exe rev-parse --verify HEAD");
1429 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1432 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1433 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1436 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1437 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1440 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1441 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1446 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1449 for(int i
=0;i
<list
.GetCount();i
++)
1451 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1457 int CGit::Revert(CString commit
, CTGitPath
&path
)
1461 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1463 cmd
.Format(_T("git.exe mv -- \"%s\" \"%s\""),path
.GetGitPathString(),path
.GetGitOldPathString());
1464 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1466 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1470 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1471 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1473 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1478 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1479 { //To init git repository, there are not HEAD, so we can use git reset command
1480 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1482 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1484 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1490 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1491 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1493 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1498 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1500 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1501 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1503 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1511 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1517 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1519 cmd
=_T("git.exe ls-files -u -t -z");
1521 if (g_Git
.Run(cmd
, &vector
))
1526 list
.ParserFromLsFile(vector
);
1531 bool CGit::IsFastForward(const CString
&from
, const CString
&to
)
1534 CGitHash basehash
,hash
;
1536 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1538 if (g_Git
.Run(cmd
, &base
, &err
, CP_UTF8
))
1540 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1545 hash
=g_Git
.GetHash(from
);
1547 return hash
== basehash
;
1550 unsigned int CGit::Hash2int(CGitHash
&hash
)
1553 for(int i
=0;i
<4;i
++)
1556 ret
|= hash
.m_hash
[i
];
1561 int CGit::RefreshGitIndex()
1563 if(g_Git
.m_IsUseGitDLL
)
1567 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1568 return git_run_cmd("update-index","update-index -q --refresh");
1579 cmd
=_T("git.exe update-index --refresh");
1580 return Run(cmd
, &output
, CP_UTF8
);
1584 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1586 if(g_Git
.m_IsUseGitDLL
)
1590 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1591 g_Git
.CheckAndInitDll();
1592 CStringA ref
, patha
, outa
;
1593 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1594 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1595 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1596 ::DeleteFile(outputfile
);
1597 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1607 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1608 return g_Git
.RunLogFile(cmd
,outputfile
);
1611 void CEnvironment::CopyProcessEnvironment()
1613 TCHAR
*p
= GetEnvironmentStrings();
1614 while(*p
!=0 || *(p
+1) !=0)
1615 this->push_back(*p
++);
1617 push_back(_T('\0'));
1618 push_back(_T('\0'));
1621 CString
CEnvironment::GetEnv(TCHAR
*name
)
1624 for(int i
=0;i
<size();i
++)
1628 CString sname
= str
.Tokenize(_T("="),start
);
1629 if(sname
.CompareNoCase(name
) == 0)
1631 return &(*this)[i
+start
];
1638 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1641 for( i
=0;i
<size();i
++)
1643 CString str
= &(*this)[i
];
1645 CString sname
= str
.Tokenize(_T("="),start
);
1646 if(sname
.CompareNoCase(name
) == 0)
1655 i
-= 1; // roll back terminate \0\0
1656 this->push_back(_T('\0'));
1659 CEnvironment::iterator it
;
1663 while(*it
&& i
<size())
1672 this->insert(it
,*name
++);
1677 this->insert(it
, _T('='));
1683 this->insert(it
,*value
++);
1690 int CGit::GetGitEncode(TCHAR
* configkey
)
1692 CString str
=GetConfigValue(configkey
);
1697 return CUnicodeUtils::GetCPCode(str
);
1701 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
1707 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1710 diff
= GetGitDiff();
1712 git_open_diff(&diff
, arg
);
1721 isStat
= !!strstr(arg
, "stat");
1726 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
1728 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
1737 for(int j
=0;j
<count
;j
++)
1746 int mode
=0,IsBin
=0,inc
=0,dec
=0;
1747 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
1748 &mode
,&IsBin
,&inc
,&dec
);
1750 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
1751 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
1753 path
.SetFromGit(strnewname
,&stroldname
);
1754 path
.ParserAction((BYTE
)mode
);
1758 path
.m_StatAdd
=_T("-");
1759 path
.m_StatDel
=_T("-");
1763 path
.m_StatAdd
.Format(_T("%d"),inc
);
1764 path
.m_StatDel
.Format(_T("%d"),dec
);
1766 PathList
->AddPath(path
);
1768 git_diff_flush(diff
);
1771 git_close_diff(diff
);
1776 int CGit::GetShortHASHLength()