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)) && *buf
)
110 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
112 // ensure trailing slash
113 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
114 _tcscpy(++pfin
, _T("\\"));
116 const int len
= _tcslen(buf
);
118 if ((len
+ 7) < _MAX_PATH
)
119 _tcscpy(pfin
+1, _T("git.exe"));
123 if ( FileExists(buf
) )
127 CGit::ms_LastMsysGitDir
= buf
;
136 #define MAX_DIRBUFFER 1000
137 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
139 CString
CGit::ms_LastMsysGitDir
;
145 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
146 m_CurrentDir
.ReleaseBuffer();
147 m_IsGitDllInited
= false;
149 m_GitSimpleListDiff
=0;
150 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
151 this->m_bInitialized
=false;
153 m_critGitDllSec
.Init();
160 git_close_diff(m_GitDiff
);
163 if(this->m_GitSimpleListDiff
)
165 git_close_diff(m_GitSimpleListDiff
);
166 m_GitSimpleListDiff
=0;
170 bool CGit::IsBranchNameValid(CString branchname
)
172 if (branchname
.IsEmpty())
175 for(int i
=0; i
< branchname
.GetLength(); i
++)
177 TCHAR c
= branchname
.GetAt(i
);
178 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
182 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
185 CString reverseBranchname
= branchname
.MakeReverse();
186 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
192 static char g_Buffer
[4096];
194 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
196 SECURITY_ATTRIBUTES sa
;
197 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
198 HANDLE hStdioFile
= NULL
;
200 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
201 sa
.lpSecurityDescriptor
=NULL
;
202 sa
.bInheritHandle
=TRUE
;
203 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
205 return TGIT_GIT_ERROR_OPEN_PIP
;
207 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
208 return TGIT_GIT_ERROR_OPEN_PIP
;
212 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
213 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
217 PROCESS_INFORMATION pi
;
218 si
.cb
=sizeof(STARTUPINFO
);
222 si
.hStdError
= hWriteErr
;
224 si
.hStdError
= hWrite
;
226 si
.hStdOutput
=hStdioFile
;
228 si
.hStdOutput
=hWrite
;
230 si
.wShowWindow
=SW_HIDE
;
231 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
233 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
234 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
236 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
237 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
239 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
240 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
242 if(cmd
.Find(_T("git")) == 0)
244 int firstSpace
= cmd
.Find(_T(" "));
246 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
248 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
251 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
254 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
255 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
258 return TGIT_GIT_ERROR_CREATE_PROCESS
;
265 CloseHandle(hWriteErr
);
271 *hErrReadOut
= hReadErr
;
275 //Must use sperate function to convert ANSI str to union code string
276 //Becuase A2W use stack as internal convert buffer.
277 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
280 //str->Append(A2W_CP((LPCSTR)p,code));
288 len
= strlen((const char*)p
);
293 //buf = new WCHAR[len*4 + 1];
294 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
295 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
296 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
297 str
->ReleaseBuffer();
301 BOOL
CGit::IsInitRepos()
305 if(g_Git
.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout
,CP_UTF8
))
307 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
316 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
318 PASYNCREADSTDERRTHREADARGS pDataArray
;
319 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
322 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
323 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
325 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
332 int CGit::Run(CGitCall
* pcall
)
334 PROCESS_INFORMATION pi
;
335 HANDLE hRead
, hReadErr
;
336 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
337 return TGIT_GIT_ERROR_CREATE_PROCESS
;
340 ASYNCREADSTDERRTHREADARGS threadArguments
;
341 threadArguments
.fileHandle
= hReadErr
;
342 threadArguments
.pcall
= pcall
;
343 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
346 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
348 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
350 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
351 if(!bAborted
)//For now, flush output when command aborted.
352 if(pcall
->OnOutputData(data
,readnumber
))
359 WaitForSingleObject(thread
, INFINITE
);
361 CloseHandle(pi
.hThread
);
363 WaitForSingleObject(pi
.hProcess
, INFINITE
);
366 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
368 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
371 CloseHandle(pi
.hProcess
);
374 CloseHandle(hReadErr
);
377 class CGitCall_ByteVector
: public CGitCall
380 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
381 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
385 size_t oldsize
=m_pvector
->size();
386 m_pvector
->resize(m_pvector
->size()+size
);
387 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
390 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
392 if (!m_pvectorErr
|| size
== 0)
394 size_t oldsize
= m_pvectorErr
->size();
395 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
396 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
399 BYTE_VECTOR
* m_pvector
;
400 BYTE_VECTOR
* m_pvectorErr
;
403 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
405 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
408 int CGit::Run(CString cmd
, CString
* output
, int code
)
412 ret
= Run(cmd
, output
, &err
, code
);
414 if (output
&& !err
.IsEmpty())
416 if (!output
->IsEmpty())
423 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
425 BYTE_VECTOR vector
, vectorErr
;
428 ret
= Run(cmd
, &vector
, &vectorErr
);
430 ret
= Run(cmd
, &vector
);
433 StringAppend(output
, &(vector
[0]), code
);
437 vectorErr
.push_back(0);
438 StringAppend(outputErr
, &(vectorErr
[0]), code
);
444 CString
CGit::GetUserName(void)
447 env
.CopyProcessEnvironment();
448 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
449 if (!envname
.IsEmpty())
451 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
453 CString
CGit::GetUserEmail(void)
456 env
.CopyProcessEnvironment();
457 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
458 if (!envmail
.IsEmpty())
461 return GetConfigValue(L
"user.email");
464 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
468 if(this->m_IsUseGitDLL
)
470 CString
*git_path
=NULL
;
472 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
485 key
= CUnicodeUtils::GetMulti(name
, encoding
);
488 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
490 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
494 g_Git
.StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
496 return configValue
.Tokenize(_T("\n"),start
);
504 cmd
.Format(L
"git.exe config %s", name
);
505 Run(cmd
, &configValue
, NULL
, encoding
);
507 return configValue
.Tokenize(_T("\n"),start
);
512 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
514 if(this->m_IsUseGitDLL
)
516 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
525 CStringA keya
, valuea
;
526 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
527 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
530 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
532 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
542 option
= _T("--global");
545 option
= _T("--system");
550 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
552 if (Run(cmd
, &out
, NULL
, encoding
))
560 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
562 if(this->m_IsUseGitDLL
)
564 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
573 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
576 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
578 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
587 option
= _T("--global");
590 option
= _T("--system");
595 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
597 if (Run(cmd
, &out
, NULL
, encoding
))
605 CString
CGit::GetCurrentBranch(void)
608 //Run(_T("git.exe branch"),&branch);
610 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
612 return _T("(no branch)");
619 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
622 if(this->m_IsUseGitDLL
)
624 unsigned char sha1
[20];
627 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
628 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
629 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
631 g_Git
.StringAppend(&refName
,(BYTE
*)refs_heads_master
);
633 refName
= StripRefName(refName
);
640 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
641 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
642 return CString();//Error
644 refName
= refName
.Tokenize(L
"\n", iStart
);
646 refName
= StripRefName(refName
);
651 CString
CGit::GetFullRefName(CString shortRefName
)
655 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
656 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
657 return CString();//Error
659 return refName
.Tokenize(L
"\n", iStart
);
662 CString
CGit::StripRefName(CString refName
)
664 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
665 refName
= refName
.Mid(11);
666 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
667 refName
= refName
.Mid(5);
669 return refName
.Tokenize(_T("\n"),start
);
672 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
674 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
676 if ( sProjectRoot
.IsEmpty() )
680 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
683 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
686 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
694 fgets(s
, sizeof(s
), pFile
);
698 const char *pfx
= "ref: refs/heads/";
699 const int len
= 16;//strlen(pfx)
701 if ( !strncmp(s
, pfx
, len
) )
703 //# We're on a branch. It might not exist. But
704 //# HEAD looks good enough to be a branch.
705 CStringA
utf8Branch(s
+ len
);
706 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
707 sBranchOut
.TrimRight(_T(" \r\n\t"));
709 if ( sBranchOut
.IsEmpty() )
714 //# Assume this is a detached head.
723 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
726 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
730 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
732 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
734 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
736 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
738 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
740 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
742 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
746 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
748 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
750 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
755 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
761 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
763 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
764 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
767 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
777 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
780 num
.Format(_T("-n%d"),count
);
784 if(mask
& LOG_INFO_STAT
)
785 param
+= _T(" --numstat ");
786 if(mask
& LOG_INFO_FILESTATE
)
787 param
+= _T(" --raw ");
789 if(mask
& LOG_INFO_FULLHISTORY
)
790 param
+= _T(" --full-history ");
792 if(mask
& LOG_INFO_BOUNDARY
)
793 param
+= _T(" --left-right --boundary ");
795 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
796 param
+= _T(" --all ");
798 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
801 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
804 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
805 param
+= _T(" --first-parent ");
807 if(mask
& CGit::LOG_INFO_NO_MERGE
)
808 param
+= _T(" --no-merges ");
810 if(mask
& CGit::LOG_INFO_FOLLOW
)
811 param
+= _T(" --follow ");
813 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
816 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
817 param
+= _T(" --full-diff ");
819 if(from
!= NULL
&& to
!= NULL
)
822 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
825 else if(to
!= NULL
&& hash
.IsEmpty())
828 range
.Format(_T(" %s "), FixBranchName(*to
));
835 if( Filter
&& (Filter
->m_From
!= -1))
837 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
841 if( Filter
&& (Filter
->m_To
!= -1))
843 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
848 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
850 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
855 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
857 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
862 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
864 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
871 if(!Filter
->m_IsRegex
)
872 param
+= _T(" --fixed-strings ");
874 param
+= _T(" --regexp-ignore-case --extended-regexp ");
877 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
878 param
+= _T(" --topo-order");
880 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
881 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
885 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
886 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
894 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
895 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
897 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
899 return Run(pgitCall
);
900 // return Run(cmd,&logOut);
904 void GetTempPath(CString
&path
)
906 TCHAR lpPathBuffer
[BUFSIZE
];
908 DWORD dwBufSize
=BUFSIZE
;
909 dwRetVal
= GetTempPath(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
= GetTempPath(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 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
950 PROCESS_INFORMATION pi
;
951 si
.cb
=sizeof(STARTUPINFO
);
954 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
955 psa
.bInheritHandle
=TRUE
;
957 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
958 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
960 si
.wShowWindow
= SW_HIDE
;
961 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
962 si
.hStdOutput
= houtfile
;
964 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
965 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
967 if(cmd
.Find(_T("git")) == 0)
968 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
970 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
973 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
974 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
977 return TGIT_GIT_ERROR_CREATE_PROCESS
;
980 WaitForSingleObject(pi
.hProcess
,INFINITE
);
982 CloseHandle(pi
.hThread
);
983 CloseHandle(pi
.hProcess
);
984 CloseHandle(houtfile
);
985 return TGIT_GIT_SUCCESS
;
989 CGitHash
CGit::GetHash(TCHAR
* friendname
)
991 if(this->m_IsUseGitDLL
)
993 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
995 this->CheckAndInitDll();
999 ref
= CUnicodeUtils::GetMulti(FixBranchName(friendname
), CP_UTF8
);
1002 git_get_sha1(ref
, hash
.m_hash
);
1014 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1015 Run(cmd
, &out
, NULL
, CP_UTF8
);
1016 // int pos=out.ReverseFind(_T('\n'));
1017 out
.FindOneOf(_T("\r\n"));
1018 return CGitHash(out
);
1022 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1027 cmd
=_T("git.exe ls-files -s -t -z");
1029 if (g_Git
.Run(cmd
, &cmdout
))
1032 outputlist
.ParserFromLsFile(cmdout
);
1033 for(int i
=0;i
<outputlist
.GetCount();i
++)
1034 ((unsigned int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
1038 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1042 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1045 if(rev1
== GIT_REV_ZERO
)
1046 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1048 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1052 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1056 if (g_Git
.Run(cmd
, &out
))
1059 outputlist
.ParserFromLog(out
);
1064 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1066 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1068 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1069 list
->push_back(str
);
1073 int CGit::GetTagList(STRING_VECTOR
&list
)
1077 if(this->m_IsUseGitDLL
)
1079 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1080 return git_for_each_ref_in("refs/tags/",addto_list_each_ref_fn
, &list
);
1085 CString cmd
, output
;
1086 cmd
=_T("git.exe tag -l");
1088 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1096 one
=output
.Tokenize(_T("\n"),pos
);
1097 list
.push_back(one
);
1104 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1106 if(branchName
== "FETCH_HEAD")
1107 branchName
= DerefFetchHead();
1111 CString
CGit::FixBranchName(const CString
& branchName
)
1113 CString tempBranchName
= branchName
;
1114 FixBranchName_Mod(tempBranchName
);
1115 return tempBranchName
;
1118 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1122 int ret
= g_Git
.Run(_T("git show-ref --tags --heads ") + name
, &output
, NULL
, CP_UTF8
);
1128 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1139 Checks if a branch or tag with the given name exists
1140 isBranch is true -> branch, tag otherwise
1142 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1144 CString cmd
, output
;
1146 cmd
= _T("git show-ref ");
1148 cmd
+= _T("--heads ");
1150 cmd
+= _T("--tags ");
1152 int ret
= g_Git
.Run(cmd
+ name
, &output
, NULL
, CP_UTF8
);
1155 if (!output
.IsEmpty())
1162 CString
CGit::DerefFetchHead()
1164 using namespace std
;
1166 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1167 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1168 int forMergeLineCount
= 0;
1170 string hashToReturn
;
1171 while(getline(fetchHeadFile
, line
))
1173 //Tokenize this line
1174 string::size_type prevPos
= 0;
1175 string::size_type pos
= line
.find('\t');
1176 if(pos
== string::npos
) continue; //invalid line
1178 string hash
= line
.substr(0, pos
);
1179 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1181 bool forMerge
= pos
== prevPos
;
1182 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1184 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1189 hashToReturn
= hash
;
1190 ++forMergeLineCount
;
1191 if(forMergeLineCount
> 1)
1192 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1196 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1199 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1202 CString cmd
, output
;
1203 cmd
= _T("git.exe branch --no-color");
1205 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1207 else if(type
&BRANCH_REMOTE
)
1211 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1218 one
=output
.Tokenize(_T("\n"),pos
);
1219 one
.Trim(L
" \r\n\t");
1220 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1221 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1222 if(one
[0] == _T('*'))
1228 if (one
!= _T("(no branch)"))
1229 list
.push_back(one
);
1234 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1235 list
.push_back(L
"FETCH_HEAD");
1240 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1243 CString cmd
, output
;
1244 cmd
=_T("git.exe remote");
1245 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1252 one
=output
.Tokenize(_T("\n"),pos
);
1254 list
.push_back(one
);
1260 int CGit::GetRefList(STRING_VECTOR
&list
)
1263 if(this->m_IsUseGitDLL
)
1265 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1266 return git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
1271 CString cmd
, output
;
1272 cmd
=_T("git.exe show-ref -d");
1273 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1280 one
=output
.Tokenize(_T("\n"),pos
);
1281 int start
=one
.Find(_T(" "),0);
1285 name
=one
.Right(one
.GetLength()-start
-1);
1286 list
.push_back(name
);
1294 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int /*flags*/, void *cb_data
)
1296 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
1298 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1299 CGitHash
hash((char*)sha1
);
1301 (*map
)[hash
].push_back(str
);
1303 if(strncmp(refname
, "refs/tags", 9) == 0)
1308 if(!git_deref_tag(sha1
, refhash
))
1310 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
1316 ::MessageBox(NULL
, _T("Could not get (readable) reference for hash ") + hash
.ToString() + _T(".\nlibgit reports:\n") + err
, _T("TortoiseGit"), MB_ICONERROR
);
1322 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1325 if(this->m_IsUseGitDLL
)
1327 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1328 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1333 CString cmd
, output
;
1334 cmd
=_T("git.exe show-ref -d");
1335 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1342 one
=output
.Tokenize(_T("\n"),pos
);
1343 int start
=one
.Find(_T(" "),0);
1347 name
=one
.Right(one
.GetLength()-start
-1);
1350 hash
=one
.Left(start
);
1352 map
[CGitHash(hash
)].push_back(name
);
1360 BOOL
CGit::CheckMsysGitDir()
1367 this->m_Environment
.clear();
1368 m_Environment
.CopyProcessEnvironment();
1371 size_t homesize
,size
;
1373 // set HOME if not set already
1374 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1377 CString home
= g_Git
.GetHomeDirectory();
1378 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1379 home
.ReleaseBuffer();
1384 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1386 if(!sshclient
.IsEmpty())
1388 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1389 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1393 TCHAR sPlink
[MAX_PATH
];
1394 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1395 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1397 _tcscpy(ptr
+ 1, _T("TortoisePlink.exe"));
1398 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1399 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1404 TCHAR sAskPass
[MAX_PATH
];
1405 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1406 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1409 _tcscpy(ptr
+ 1, _T("SshAskPass.exe"));
1410 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1411 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1412 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1416 // add git/bin path to PATH
1418 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1420 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1422 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1424 if ( !str
.IsEmpty() )
1426 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
1428 CGit::ms_LastMsysGitDir
= str
;
1433 // search PATH if git/bin directory is already present
1434 if ( FindGitPath() )
1436 m_bInitialized
= TRUE
;
1437 msysdir
= CGit::ms_LastMsysGitDir
;
1447 CGit::ms_LastMsysGitDir
= str
;
1450 // check for git.exe existance (maybe it was deinstalled in the meantime)
1451 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1455 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1458 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1460 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1462 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1464 CString sOldPath
= oldpath
;
1467 m_bInitialized
= TRUE
;
1471 CString
CGit::GetHomeDirectory()
1473 const wchar_t * homeDir
= wget_windows_home_directory();
1474 return CString(homeDir
, wcslen(homeDir
));
1477 CString
CGit::GetGitSystemConfig()
1479 const wchar_t * systemConfig
= wget_msysgit_etc();
1480 return CString(systemConfig
, wcslen(systemConfig
));
1483 BOOL
CGit::CheckCleanWorkTree()
1487 cmd
=_T("git.exe rev-parse --verify HEAD");
1489 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1492 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1493 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1496 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1497 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1500 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1501 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1506 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1509 for(int i
=0;i
<list
.GetCount();i
++)
1511 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1517 int CGit::Revert(CString commit
, CTGitPath
&path
)
1521 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1523 cmd
.Format(_T("git.exe mv -- \"%s\" \"%s\""),path
.GetGitPathString(),path
.GetGitOldPathString());
1524 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1526 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1530 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1531 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1533 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1538 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1539 { //To init git repository, there are not HEAD, so we can use git reset command
1540 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1542 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1544 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1550 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1551 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1553 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1558 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1560 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1561 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1563 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1571 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1577 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1579 cmd
=_T("git.exe ls-files -u -t -z");
1581 if (g_Git
.Run(cmd
, &vector
))
1586 list
.ParserFromLsFile(vector
);
1591 bool CGit::IsFastForward(const CString
&from
, const CString
&to
)
1594 CGitHash basehash
,hash
;
1596 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1598 if (g_Git
.Run(cmd
, &base
, &err
, CP_UTF8
))
1600 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1605 hash
=g_Git
.GetHash(from
);
1607 return hash
== basehash
;
1610 unsigned int CGit::Hash2int(CGitHash
&hash
)
1613 for(int i
=0;i
<4;i
++)
1616 ret
|= hash
.m_hash
[i
];
1621 int CGit::RefreshGitIndex()
1623 if(g_Git
.m_IsUseGitDLL
)
1625 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1628 return git_run_cmd("update-index","update-index -q --refresh");
1639 cmd
=_T("git.exe update-index --refresh");
1640 return Run(cmd
, &output
, CP_UTF8
);
1644 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1646 if(g_Git
.m_IsUseGitDLL
)
1648 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1651 g_Git
.CheckAndInitDll();
1652 CStringA ref
, patha
, outa
;
1653 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1654 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1655 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1656 ::DeleteFile(outputfile
);
1657 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1667 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1668 return g_Git
.RunLogFile(cmd
,outputfile
);
1671 void CEnvironment::CopyProcessEnvironment()
1673 TCHAR
*p
= GetEnvironmentStrings();
1674 while(*p
!=0 || *(p
+1) !=0)
1675 this->push_back(*p
++);
1677 push_back(_T('\0'));
1678 push_back(_T('\0'));
1681 CString
CEnvironment::GetEnv(TCHAR
*name
)
1684 for(int i
=0;i
<size();i
++)
1688 CString sname
= str
.Tokenize(_T("="),start
);
1689 if(sname
.CompareNoCase(name
) == 0)
1691 return &(*this)[i
+start
];
1698 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1701 for( i
=0;i
<size();i
++)
1703 CString str
= &(*this)[i
];
1705 CString sname
= str
.Tokenize(_T("="),start
);
1706 if(sname
.CompareNoCase(name
) == 0)
1715 i
-= 1; // roll back terminate \0\0
1716 this->push_back(_T('\0'));
1719 CEnvironment::iterator it
;
1723 while(*it
&& i
<size())
1732 this->insert(it
,*name
++);
1737 this->insert(it
, _T('='));
1743 this->insert(it
,*value
++);
1750 int CGit::GetGitEncode(TCHAR
* configkey
)
1752 CString str
=GetConfigValue(configkey
);
1757 return CUnicodeUtils::GetCPCode(str
);
1761 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
1767 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1770 diff
= GetGitDiff();
1772 git_open_diff(&diff
, arg
);
1781 isStat
= !!strstr(arg
, "stat");
1786 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
1788 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
1797 for(int j
=0;j
<count
;j
++)
1806 int mode
=0,IsBin
=0,inc
=0,dec
=0;
1807 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
1808 &mode
,&IsBin
,&inc
,&dec
);
1810 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
1811 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
1813 path
.SetFromGit(strnewname
,&stroldname
);
1814 path
.ParserAction((BYTE
)mode
);
1818 path
.m_StatAdd
=_T("-");
1819 path
.m_StatDel
=_T("-");
1823 path
.m_StatAdd
.Format(_T("%d"),inc
);
1824 path
.m_StatDel
.Format(_T("%d"),dec
);
1826 PathList
->AddPath(path
);
1828 git_diff_flush(diff
);
1831 git_close_diff(diff
);
1836 int CGit::GetShortHASHLength()