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
);
1017 git_repository
*repo
= NULL
;
1018 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1019 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1021 gitdirA
.ReleaseBuffer();
1024 gitdirA
.ReleaseBuffer();
1026 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1028 git_object
* gitObject
= NULL
;
1029 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1031 refnameA
.ReleaseBuffer();
1032 git_repository_free(repo
);
1035 refnameA
.ReleaseBuffer();
1037 const git_oid
* oid
= git_object_id(gitObject
);
1040 git_object_free(gitObject
);
1041 git_repository_free(repo
);
1045 CGitHash
hash((char *)oid
->id
);
1047 git_object_free(gitObject
); // also frees oid
1048 git_repository_free(repo
);
1052 else if (this->m_IsUseGitDLL
)
1054 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1056 this->CheckAndInitDll();
1060 ref
= CUnicodeUtils::GetMulti(FixBranchName(friendname
), CP_UTF8
);
1063 git_get_sha1(ref
, hash
.m_hash
);
1075 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1076 Run(cmd
, &out
, NULL
, CP_UTF8
);
1077 // int pos=out.ReverseFind(_T('\n'));
1078 out
.FindOneOf(_T("\r\n"));
1079 return CGitHash(out
);
1083 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1088 cmd
=_T("git.exe ls-files -s -t -z");
1090 if (g_Git
.Run(cmd
, &cmdout
))
1093 outputlist
.ParserFromLsFile(cmdout
);
1094 for(int i
=0;i
<outputlist
.GetCount();i
++)
1095 ((unsigned int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
1099 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1103 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1106 if(rev1
== GIT_REV_ZERO
)
1107 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1109 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1113 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1117 if (g_Git
.Run(cmd
, &out
))
1120 outputlist
.ParserFromLog(out
);
1125 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1127 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1129 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1130 list
->push_back(str
);
1134 int CGit::GetTagList(STRING_VECTOR
&list
)
1136 if (this->m_IsUseLibGit2
)
1138 git_repository
*repo
= NULL
;
1140 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1141 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1143 gitdir
.ReleaseBuffer();
1146 gitdir
.ReleaseBuffer();
1148 git_strarray tag_names
;
1150 if (git_tag_list(&tag_names
, repo
))
1152 git_repository_free(repo
);
1156 for (size_t i
= 0; i
< tag_names
.count
; i
++)
1158 CStringA
tagName(tag_names
.strings
[i
]);
1159 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1162 git_strarray_free(&tag_names
);
1164 git_repository_free(repo
);
1166 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1172 CString cmd
, output
;
1173 cmd
=_T("git.exe tag -l");
1174 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1181 one
=output
.Tokenize(_T("\n"),pos
);
1183 list
.push_back(one
);
1185 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1191 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1193 if(branchName
== "FETCH_HEAD")
1194 branchName
= DerefFetchHead();
1198 CString
CGit::FixBranchName(const CString
& branchName
)
1200 CString tempBranchName
= branchName
;
1201 FixBranchName_Mod(tempBranchName
);
1202 return tempBranchName
;
1205 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1210 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1211 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1217 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1228 Checks if a branch or tag with the given name exists
1229 isBranch is true -> branch, tag otherwise
1231 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1233 CString cmd
, output
;
1235 cmd
= _T("git show-ref ");
1237 cmd
+= _T("--heads ");
1239 cmd
+= _T("--tags ");
1241 cmd
+= _T("refs/heads/") + name
;
1242 cmd
+= _T(" refs/tags/") + name
;
1244 int ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1247 if (!output
.IsEmpty())
1254 CString
CGit::DerefFetchHead()
1256 using namespace std
;
1258 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1259 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1260 int forMergeLineCount
= 0;
1262 string hashToReturn
;
1263 while(getline(fetchHeadFile
, line
))
1265 //Tokenize this line
1266 string::size_type prevPos
= 0;
1267 string::size_type pos
= line
.find('\t');
1268 if(pos
== string::npos
) continue; //invalid line
1270 string hash
= line
.substr(0, pos
);
1271 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1273 bool forMerge
= pos
== prevPos
;
1274 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1276 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1281 hashToReturn
= hash
;
1282 ++forMergeLineCount
;
1283 if(forMergeLineCount
> 1)
1284 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1288 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1291 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1294 CString cmd
, output
, cur
;
1295 cmd
= _T("git.exe branch --no-color");
1297 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1299 else if(type
&BRANCH_REMOTE
)
1302 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1309 one
=output
.Tokenize(_T("\n"),pos
);
1310 one
.Trim(L
" \r\n\t");
1311 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1312 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1313 if(one
[0] == _T('*'))
1318 if (one
!= _T("(no branch)"))
1319 list
.push_back(one
);
1323 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1324 list
.push_back(L
"FETCH_HEAD");
1326 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1328 if (current
&& cur
!= _T("(no branch)"))
1330 for (unsigned int i
= 0; i
< list
.size(); i
++)
1343 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1345 if (this->m_IsUseLibGit2
)
1347 git_repository
*repo
= NULL
;
1349 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1350 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1352 gitdir
.ReleaseBuffer();
1355 gitdir
.ReleaseBuffer();
1357 git_strarray remotes
;
1359 if (git_remote_list(&remotes
, repo
))
1361 git_repository_free(repo
);
1365 for (size_t i
= 0; i
< remotes
.count
; i
++)
1367 CStringA
remote(remotes
.strings
[i
]);
1368 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1371 git_strarray_free(&remotes
);
1373 git_repository_free(repo
);
1375 std::sort(list
.begin(), list
.end());
1382 CString cmd
, output
;
1383 cmd
=_T("git.exe remote");
1384 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1391 one
=output
.Tokenize(_T("\n"),pos
);
1393 list
.push_back(one
);
1400 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1402 CString cmd
, out
, err
;
1403 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1404 if (g_Git
.Run(cmd
, &out
, &err
, CP_UTF8
))
1406 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1413 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1414 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1415 if (one
.Find(_T("^{}")) >= 1)
1418 list
.push_back(one
);
1420 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1424 int CGit::GetRefList(STRING_VECTOR
&list
)
1427 if(this->m_IsUseGitDLL
)
1429 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1430 ret
= git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
1431 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1435 CString cmd
, output
;
1436 cmd
=_T("git.exe show-ref -d");
1437 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1444 one
=output
.Tokenize(_T("\n"),pos
);
1445 int start
=one
.Find(_T(" "),0);
1449 name
=one
.Right(one
.GetLength()-start
-1);
1450 list
.push_back(name
);
1453 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1459 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int /*flags*/, void *cb_data
)
1461 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
1463 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1464 CGitHash
hash((char*)sha1
);
1466 (*map
)[hash
].push_back(str
);
1468 if(strncmp(refname
, "refs/tags", 9) == 0)
1473 if(!git_deref_tag(sha1
, refhash
))
1475 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
1481 ::MessageBox(NULL
, _T("Could not get (readable) reference for hash ") + hash
.ToString() + _T(".\nlibgit reports:\n") + err
, _T("TortoiseGit"), MB_ICONERROR
);
1487 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1490 if(this->m_IsUseGitDLL
)
1492 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1493 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1498 CString cmd
, output
;
1499 cmd
=_T("git.exe show-ref -d");
1500 ret
= g_Git
.Run(cmd
, &output
, NULL
, CP_UTF8
);
1507 one
=output
.Tokenize(_T("\n"),pos
);
1508 int start
=one
.Find(_T(" "),0);
1512 name
=one
.Right(one
.GetLength()-start
-1);
1515 hash
=one
.Left(start
);
1517 map
[CGitHash(hash
)].push_back(name
);
1525 BOOL
CGit::CheckMsysGitDir()
1532 this->m_Environment
.clear();
1533 m_Environment
.CopyProcessEnvironment();
1536 size_t homesize
,size
;
1538 // set HOME if not set already
1539 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1542 CString home
= g_Git
.GetHomeDirectory();
1543 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1544 home
.ReleaseBuffer();
1549 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1551 if(!sshclient
.IsEmpty())
1553 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1554 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1558 TCHAR sPlink
[MAX_PATH
];
1559 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1560 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1562 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoisePlink.exe"));
1563 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1564 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1569 TCHAR sAskPass
[MAX_PATH
];
1570 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1571 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1574 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1575 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1576 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1577 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1581 // add git/bin path to PATH
1583 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1585 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1587 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1589 if ( !str
.IsEmpty() )
1591 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
1593 CGit::ms_LastMsysGitDir
= str
;
1598 // search PATH if git/bin directory is already present
1599 if ( FindGitPath() )
1601 m_bInitialized
= TRUE
;
1602 msysdir
= CGit::ms_LastMsysGitDir
;
1612 CGit::ms_LastMsysGitDir
= str
;
1615 // check for git.exe existance (maybe it was deinstalled in the meantime)
1616 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1620 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1623 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1625 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1627 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1629 CString sOldPath
= oldpath
;
1632 m_bInitialized
= TRUE
;
1636 CString
CGit::GetHomeDirectory()
1638 const wchar_t * homeDir
= wget_windows_home_directory();
1639 return CString(homeDir
, (int)wcslen(homeDir
));
1642 CString
CGit::GetGitSystemConfig()
1644 const wchar_t * systemConfig
= wget_msysgit_etc();
1645 return CString(systemConfig
, (int)wcslen(systemConfig
));
1648 BOOL
CGit::CheckCleanWorkTree()
1652 cmd
=_T("git.exe rev-parse --verify HEAD");
1654 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1657 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1658 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1661 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1662 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1665 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1666 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1671 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1674 for(int i
=0;i
<list
.GetCount();i
++)
1676 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1682 int CGit::Revert(CString commit
, CTGitPath
&path
)
1686 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1688 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1691 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1692 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1696 // if the filenames only differ in case, we have to pass "-f"
1697 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1699 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1700 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1702 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1706 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1707 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1709 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1714 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1715 { //To init git repository, there are not HEAD, so we can use git reset command
1716 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1718 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1720 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1726 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1727 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1729 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1734 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1736 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1737 if (g_Git
.Run(cmd
, &out
, CP_UTF8
))
1739 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1747 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1753 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1755 cmd
=_T("git.exe ls-files -u -t -z");
1757 if (g_Git
.Run(cmd
, &vector
))
1762 list
.ParserFromLsFile(vector
);
1767 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1770 CGitHash basehash
,hash
;
1772 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1774 if (g_Git
.Run(cmd
, &base
, &err
, CP_UTF8
))
1776 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1779 basehash
= base
.Trim();
1781 hash
=g_Git
.GetHash(from
);
1784 *commonAncestor
= basehash
;
1786 return hash
== basehash
;
1789 unsigned int CGit::Hash2int(CGitHash
&hash
)
1792 for(int i
=0;i
<4;i
++)
1795 ret
|= hash
.m_hash
[i
];
1800 int CGit::RefreshGitIndex()
1802 if(g_Git
.m_IsUseGitDLL
)
1804 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1807 return git_run_cmd("update-index","update-index -q --refresh");
1818 cmd
=_T("git.exe update-index --refresh");
1819 return Run(cmd
, &output
, CP_UTF8
);
1823 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1825 if(g_Git
.m_IsUseGitDLL
)
1827 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1830 g_Git
.CheckAndInitDll();
1831 CStringA ref
, patha
, outa
;
1832 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1833 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1834 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1835 ::DeleteFile(outputfile
);
1836 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1846 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1847 return g_Git
.RunLogFile(cmd
,outputfile
);
1850 void CEnvironment::CopyProcessEnvironment()
1852 TCHAR
*p
= GetEnvironmentStrings();
1853 while(*p
!=0 || *(p
+1) !=0)
1854 this->push_back(*p
++);
1856 push_back(_T('\0'));
1857 push_back(_T('\0'));
1860 CString
CEnvironment::GetEnv(TCHAR
*name
)
1863 for (size_t i
= 0; i
< size(); i
++)
1867 CString sname
= str
.Tokenize(_T("="),start
);
1868 if(sname
.CompareNoCase(name
) == 0)
1870 return &(*this)[i
+start
];
1877 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1880 for( i
=0;i
<size();i
++)
1882 CString str
= &(*this)[i
];
1884 CString sname
= str
.Tokenize(_T("="),start
);
1885 if(sname
.CompareNoCase(name
) == 0)
1894 i
-= 1; // roll back terminate \0\0
1895 this->push_back(_T('\0'));
1898 CEnvironment::iterator it
;
1902 while(*it
&& i
<size())
1911 this->insert(it
,*name
++);
1916 this->insert(it
, _T('='));
1922 this->insert(it
,*value
++);
1929 int CGit::GetGitEncode(TCHAR
* configkey
)
1931 CString str
=GetConfigValue(configkey
);
1936 return CUnicodeUtils::GetCPCode(str
);
1940 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
1946 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1949 diff
= GetGitDiff();
1951 git_open_diff(&diff
, arg
);
1960 isStat
= !!strstr(arg
, "stat");
1965 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
1967 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
1976 for(int j
=0;j
<count
;j
++)
1985 int mode
=0,IsBin
=0,inc
=0,dec
=0;
1986 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
1987 &mode
,&IsBin
,&inc
,&dec
);
1989 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
1990 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
1992 path
.SetFromGit(strnewname
,&stroldname
);
1993 path
.ParserAction((BYTE
)mode
);
1997 path
.m_StatAdd
=_T("-");
1998 path
.m_StatDel
=_T("-");
2002 path
.m_StatAdd
.Format(_T("%d"),inc
);
2003 path
.m_StatDel
.Format(_T("%d"),dec
);
2005 PathList
->AddPath(path
);
2007 git_diff_flush(diff
);
2010 git_close_diff(diff
);
2015 int CGit::GetShortHASHLength()