8 #include "UnicodeUtils.h"
11 int CGit::m_LogEncode
=CP_UTF8
;
14 static LPTSTR
nextpath(LPCTSTR src
, LPTSTR dst
, UINT maxlen
)
18 while (*src
== _T(';'))
26 while (*src
&& *src
!= _T(';'))
40 while (*src
&& *src
!= _T('"'))
55 while (*src
== _T(';'))
62 return (orgsrc
!= src
) ? (LPTSTR
)src
: NULL
;
65 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
68 return _tstat(lpszFileName
, &st
) == 0;
71 static BOOL
FindGitPath()
74 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
81 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
82 _tgetenv_s(&size
, env
, size
, _T("PATH"));
86 // search in all paths defined in PATH
87 while ((env
= nextpath(env
, buf
, _MAX_PATH
-1)) && *buf
)
89 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
91 // ensure trailing slash
92 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
93 _tcscpy(++pfin
, _T("\\"));
95 const int len
= _tcslen(buf
);
97 if ((len
+ 7) < _MAX_PATH
)
98 _tcscpy(pfin
+1, _T("git.exe"));
102 if ( FileExists(buf
) )
106 CGit::ms_LastMsysGitDir
= buf
;
115 #define MAX_DIRBUFFER 1000
116 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
118 CString
CGit::ms_LastMsysGitDir
;
124 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
125 m_CurrentDir
.ReleaseBuffer();
126 m_IsGitDllInited
= false;
128 m_IsUseGitDLL
= CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
129 this->m_bInitialized
=false;
131 m_critGitDllSec
.Init();
138 git_close_diff(m_GitDiff
);
143 static char g_Buffer
[4096];
145 int CGit::RunAsync(CString cmd
,PROCESS_INFORMATION
*piOut
,HANDLE
*hReadOut
,CString
*StdioFile
)
147 SECURITY_ATTRIBUTES sa
;
148 HANDLE hRead
, hWrite
;
149 HANDLE hStdioFile
= NULL
;
151 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
152 sa
.lpSecurityDescriptor
=NULL
;
153 sa
.bInheritHandle
=TRUE
;
154 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
156 return GIT_ERROR_OPEN_PIP
;
161 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
162 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
166 PROCESS_INFORMATION pi
;
167 si
.cb
=sizeof(STARTUPINFO
);
172 si
.hStdOutput
=hStdioFile
;
174 si
.hStdOutput
=hWrite
;
176 si
.wShowWindow
=SW_HIDE
;
177 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
179 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
180 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
182 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
183 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
185 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
186 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
188 if(cmd
.Find(_T("git")) == 0)
189 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
191 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
194 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
195 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
198 return GIT_ERROR_CREATE_PROCESS
;
212 //Must use sperate function to convert ANSI str to union code string
213 //Becuase A2W use stack as internal convert buffer.
214 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
217 //str->Append(A2W_CP((LPCSTR)p,code));
225 len
= strlen((const char*)p
);
230 //buf = new WCHAR[len*4 + 1];
231 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
232 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
233 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
234 str
->ReleaseBuffer();
238 BOOL
CGit::IsInitRepos()
242 if(g_Git
.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout
,CP_UTF8
))
244 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
252 int CGit::Run(CGitCall
* pcall
)
254 PROCESS_INFORMATION pi
;
256 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
))
257 return GIT_ERROR_CREATE_PROCESS
;
260 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
262 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
264 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
265 if(!bAborted
)//For now, flush output when command aborted.
266 if(pcall
->OnOutputData(data
,readnumber
))
272 CloseHandle(pi
.hThread
);
274 WaitForSingleObject(pi
.hProcess
, INFINITE
);
277 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
279 return GIT_ERROR_GET_EXIT_CODE
;
282 CloseHandle(pi
.hProcess
);
287 class CGitCall_ByteVector
: public CGitCall
290 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
):CGitCall(cmd
),m_pvector(pvector
){}
291 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
293 size_t oldsize
=m_pvector
->size();
294 m_pvector
->resize(m_pvector
->size()+size
);
295 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
298 BYTE_VECTOR
* m_pvector
;
301 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
)
303 CGitCall_ByteVector
call(cmd
,vector
);
306 int CGit::Run(CString cmd
, CString
* output
,int code
)
310 ret
=Run(cmd
,&vector
);
314 StringAppend(output
,&(vector
[0]),code
);
318 CString
CGit::GetUserName(void)
320 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
322 CString
CGit::GetUserEmail(void)
324 return GetConfigValue(L
"user.email");
327 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
331 if(this->m_IsUseGitDLL
)
333 CString
*git_path
=NULL
;
346 key
= CUnicodeUtils::GetMulti(name
, encoding
);
349 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
351 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
355 g_Git
.StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
357 return configValue
.Tokenize(_T("\n"),start
);
364 cmd
.Format(L
"git.exe config %s", name
);
365 Run(cmd
,&configValue
,encoding
);
367 return configValue
.Tokenize(_T("\n"),start
);
372 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
374 if(this->m_IsUseGitDLL
)
383 CStringA keya
, valuea
;
384 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
385 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
388 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
390 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
399 option
= _T("--global");
402 option
= _T("--system");
407 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
409 if(Run(cmd
,&out
,encoding
))
418 CString
CGit::GetCurrentBranch(void)
421 //Run(_T("git.exe branch"),&branch);
423 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
425 return _T("(no branch)");
431 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
434 if(this->m_IsUseGitDLL
)
436 unsigned char sha1
[20];
439 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
440 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
442 g_Git
.StringAppend(&refName
,(BYTE
*)refs_heads_master
);
444 refName
= StripRefName(refName
);
450 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
451 if(Run(cmd
, &refName
, CP_UTF8
) != 0)
452 return CString();//Error
454 refName
= refName
.Tokenize(L
"\n", iStart
);
456 refName
= StripRefName(refName
);
461 CString
CGit::GetFullRefName(CString shortRefName
)
465 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
466 if(Run(cmd
, &refName
, CP_UTF8
) != 0)
467 return CString();//Error
469 return refName
.Tokenize(L
"\n", iStart
);
472 CString
CGit::StripRefName(CString refName
)
474 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
475 refName
= refName
.Mid(11);
476 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
477 refName
= refName
.Mid(5);
479 return refName
.Tokenize(_T("\n"),start
);
482 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
484 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
486 if ( sProjectRoot
.IsEmpty() )
489 CString sHeadFile
= sProjectRoot
+ _T("\\") + g_GitAdminDir
.GetAdminDirName() + _T("\\HEAD");
492 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
500 fgets(s
, sizeof(s
), pFile
);
504 const char *pfx
= "ref: refs/heads/";
505 const int len
= 16;//strlen(pfx)
507 if ( !strncmp(s
, pfx
, len
) )
509 //# We're on a branch. It might not exist. But
510 //# HEAD looks good enough to be a branch.
511 sBranchOut
= s
+ len
;
512 sBranchOut
.TrimRight(_T(" \r\n\t"));
514 if ( sBranchOut
.IsEmpty() )
519 //# Assume this is a detached head.
528 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
531 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
535 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
537 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
539 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
541 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
543 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
545 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
547 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
551 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
553 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
555 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
560 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
566 int CGit::GetLog(BYTE_VECTOR
& logOut
, CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
568 CGitCall_ByteVector
gitCall(CString(),&logOut
);
569 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
572 CString
CGit::GetLogCmd( CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
583 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
586 num
.Format(_T("-n%d"),count
);
590 if(mask
& LOG_INFO_STAT
)
591 param
+= _T(" --numstat ");
592 if(mask
& LOG_INFO_FILESTATE
)
593 param
+= _T(" --raw ");
595 if(mask
& LOG_INFO_FULLHISTORY
)
596 param
+= _T(" --full-history ");
598 if(mask
& LOG_INFO_BOUNDARY
)
599 param
+= _T(" --left-right --boundary ");
601 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
602 param
+= _T(" --all ");
604 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
607 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
610 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
611 param
+= _T(" --first-parent ");
613 if(mask
& CGit::LOG_INFO_NO_MERGE
)
614 param
+= _T(" --no-merges ");
616 if(mask
& CGit::LOG_INFO_FOLLOW
)
617 param
+= _T(" --follow ");
619 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
622 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
623 param
+= _T(" --full-diff ");
625 if(from
!= NULL
&& to
!= NULL
)
628 range
.Format(_T(" %s..%s "),*from
,*to
);
635 if( Filter
&& (Filter
->m_From
!= -1))
637 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
641 if( Filter
&& (Filter
->m_To
!= -1))
643 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
648 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
650 st1
.Format(_T(" --author=%s" ),Filter
->m_Author
);
655 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
657 st1
.Format(_T(" --committer=%s" ),Filter
->m_Author
);
662 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
664 st1
.Format(_T(" --grep=%s" ),Filter
->m_MessageFilter
);
671 if(!Filter
->m_IsRegex
)
672 param
+=_T(" --fixed-strings ");
674 param
+= _T(" --regexp-ignore-case --extended-regexp ");
678 cmd
.Format(_T("%s -z %s --parents "),
681 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\""),
684 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
688 cmd
+= _T("-- ")+file
;
692 cmd
+= CString(_T("\" -- "))+file
;
697 //int CGit::GetLog(CGitCall* pgitCall, CString &hash, CTGitPath *path ,int count,int mask)
698 int CGit::GetLog(CGitCall
* pgitCall
, CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
700 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
702 return Run(pgitCall
);
703 // return Run(cmd,&logOut);
707 void GetTempPath(CString
&path
)
709 TCHAR lpPathBuffer
[BUFSIZE
];
711 DWORD dwBufSize
=BUFSIZE
;
712 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
713 lpPathBuffer
); // buffer for path
714 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
718 path
.Format(_T("%s"),lpPathBuffer
);
720 CString
GetTempFile()
722 TCHAR lpPathBuffer
[BUFSIZE
];
724 DWORD dwBufSize
=BUFSIZE
;
725 TCHAR szTempName
[BUFSIZE
];
728 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
729 lpPathBuffer
); // buffer for path
730 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
734 // Create a temporary file.
735 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
736 TEXT("Patch"), // temp file name prefix
737 0, // create unique name
738 szTempName
); // buffer for name
746 return CString(szTempName
);
750 int CGit::RunLogFile(CString cmd
,CString
&filename
)
753 PROCESS_INFORMATION pi
;
754 si
.cb
=sizeof(STARTUPINFO
);
757 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
758 psa
.bInheritHandle
=TRUE
;
760 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
761 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
763 si
.wShowWindow
= SW_HIDE
;
764 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
765 si
.hStdOutput
= houtfile
;
767 LPTSTR pEnv
= m_Environment
.size()? &m_Environment
[0]: NULL
;
768 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
770 if(cmd
.Find(_T("git")) == 0)
771 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
773 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
776 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
777 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
780 return GIT_ERROR_CREATE_PROCESS
;
783 WaitForSingleObject(pi
.hProcess
,INFINITE
);
785 CloseHandle(pi
.hThread
);
786 CloseHandle(pi
.hProcess
);
787 CloseHandle(houtfile
);
792 git_revnum_t
CGit::GetHash(const CString
&friendname
)
796 cmd
.Format(_T("git.exe rev-parse %s" ),friendname
);
797 Run(cmd
,&out
,CP_UTF8
);
798 // int pos=out.ReverseFind(_T('\n'));
799 int pos
=out
.FindOneOf(_T("\r\n"));
801 return out
.Left(pos
);
805 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
810 cmd
=_T("git.exe ls-files -s -t -z");
812 if(g_Git
.Run(cmd
,&cmdout
))
815 outputlist
.ParserFromLsFile(cmdout
);
816 for(int i
=0;i
<outputlist
.GetCount();i
++)
817 ((int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
821 int CGit::GetCommitDiffList(CString
&rev1
,CString
&rev2
,CTGitPathList
&outputlist
)
825 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
828 if(rev1
== GIT_REV_ZERO
)
829 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
831 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
834 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
838 if(g_Git
.Run(cmd
,&out
))
841 outputlist
.ParserFromLog(out
);
846 int addto_list_each_ref_fn(const char *refname
, const unsigned char *sha1
, int flags
, void *cb_data
)
848 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
850 g_Git
.StringAppend(&str
,(BYTE
*)refname
,CP_ACP
);
851 list
->push_back(str
);
855 int CGit::GetTagList(STRING_VECTOR
&list
)
859 if(this->m_IsUseGitDLL
)
861 return git_for_each_ref_in("refs/tags/",addto_list_each_ref_fn
, &list
);
866 cmd
=_T("git.exe tag -l");
868 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
876 one
=output
.Tokenize(_T("\n"),pos
);
884 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
888 cmd
=_T("git.exe branch --no-color");
890 if(type
==(BRANCH_LOCAL
|BRANCH_REMOTE
))
892 else if(type
==BRANCH_REMOTE
)
896 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
903 one
=output
.Tokenize(_T("\n"),pos
);
904 one
.Trim(L
" \r\n\t");
905 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
906 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
907 if(one
[0] == _T('*'))
920 int CGit::GetRemoteList(STRING_VECTOR
&list
)
924 cmd
=_T("git.exe remote");
925 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
932 one
=output
.Tokenize(_T("\n"),pos
);
939 int CGit::GetRefList(STRING_VECTOR
&list
)
942 if(this->m_IsUseGitDLL
)
944 return git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
949 cmd
=_T("git.exe show-ref -d");
950 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
957 one
=output
.Tokenize(_T("\n"),pos
);
958 int start
=one
.Find(_T(" "),0);
962 name
=one
.Right(one
.GetLength()-start
-1);
963 list
.push_back(name
);
971 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int flags
, void *cb_data
)
973 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
975 g_Git
.StringAppend(&str
,(BYTE
*)refname
,CP_ACP
);
976 CGitHash
hash((char*)sha1
);
978 (*map
)[hash
].push_back(str
);
980 if(strncmp(refname
, "refs/tags", 9) == 0)
983 if(!git_deref_tag(sha1
, refhash
))
985 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
991 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
994 if(this->m_IsUseGitDLL
)
996 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1001 cmd
=_T("git.exe show-ref -d");
1002 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
1009 one
=output
.Tokenize(_T("\n"),pos
);
1010 int start
=one
.Find(_T(" "),0);
1014 name
=one
.Right(one
.GetLength()-start
-1);
1017 hash
=one
.Left(start
);
1019 map
[CGitHash(hash
)].push_back(name
);
1027 BOOL
CGit::CheckMsysGitDir()
1034 this->m_Environment
.clear();
1035 m_Environment
.CopyProcessEnvironment();
1037 TCHAR
*oldpath
,*home
;
1038 size_t homesize
,size
,httpsize
;
1040 // set HOME if not set already
1041 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1044 if ( (!_tdupenv_s(&home
,&size
,_T("USERPROFILE"))) && (home
!= NULL
) )
1046 m_Environment
.SetEnv(_T("HOME"),home
);
1051 ATLTRACE("CGit::CheckMsysGitDir Unable to SetEnv HOME\n");
1057 _tgetenv_s(&httpsize
, NULL
, 0, _T("http_proxy"));
1060 CString regServeraddress_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-host"), _T(""));
1061 CString regServerport_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-port"), _T(""));
1062 CString regUsername_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-username"), _T(""));
1063 CString regPassword_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-password"), _T(""));
1064 CString regTimeout_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-timeout"), _T(""));
1065 CString regExceptions_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-exceptions"), _T(""));
1068 if(!regServeraddress_copy
.IsEmpty())
1070 if(regServeraddress_copy
.Left(4) != _T("http"))
1071 http_proxy
=_T("http://");
1073 if(!regUsername_copy
.IsEmpty())
1075 http_proxy
+= regUsername_copy
;
1076 http_proxy
+= _T(":")+regPassword_copy
;
1077 http_proxy
+= _T("@");
1079 http_proxy
+=regServeraddress_copy
;
1080 if(!regServerport_copy
.IsEmpty())
1082 http_proxy
+=_T(":")+regServerport_copy
;
1084 m_Environment
.SetEnv(_T("http_proxy"),(LPTSTR
)http_proxy
.GetBuffer());
1088 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1090 if(!sshclient
.IsEmpty())
1092 m_Environment
.SetEnv(_T("GIT_SSH"),sshclient
.GetBuffer());
1095 CString ssh
=sshclient
;
1096 ssh
.Replace(_T("/"),_T("\\"));
1097 ssh
.Replace(_T("\\"),_T("\\\\"));
1098 ssh
=CString(_T("\""))+ssh
+_T('\"');
1099 m_Environment
.SetEnv(_T("SVN_SSH"),ssh
.GetBuffer());
1103 TCHAR sPlink
[MAX_PATH
];
1104 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1105 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1107 _tcscpy(ptr
+ 1, _T("TortoisePlink.exe"));
1108 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1112 ssh
.Replace(_T("/"),_T("\\"));
1113 ssh
.Replace(_T("\\"),_T("\\\\"));
1114 ssh
=CString(_T("\""))+ssh
+_T('\"');
1115 m_Environment
.SetEnv(_T("SVN_SSH"),ssh
.GetBuffer());
1120 TCHAR sAskPass
[MAX_PATH
];
1121 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1122 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1125 _tcscpy(ptr
+ 1, _T("SshAskPass.exe"));
1126 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1127 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1128 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1132 // add git/bin path to PATH
1134 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1138 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1140 if ( !str
.IsEmpty() )
1142 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
1144 CGit::ms_LastMsysGitDir
= str
;
1149 // search PATH if git/bin directory is alredy present
1150 if ( FindGitPath() )
1152 m_bInitialized
= TRUE
;
1160 CGit::ms_LastMsysGitDir
= str
;
1164 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1167 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1169 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1171 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1173 CString sOldPath
= oldpath
;
1176 m_bInitialized
= TRUE
;
1181 class CGitCall_EnumFiles
: public CGitCall
1184 CGitCall_EnumFiles(const TCHAR
*pszProjectPath
, const TCHAR
*pszSubPath
, unsigned int nFlags
, WGENUMFILECB
*pEnumCb
, void *pUserData
)
1185 : m_pszProjectPath(pszProjectPath
),
1186 m_pszSubPath(pszSubPath
),
1189 m_pUserData(pUserData
)
1193 typedef std::map
<CStringA
,char> TStrCharMap
;
1195 const TCHAR
* m_pszProjectPath
;
1196 const TCHAR
* m_pszSubPath
;
1197 unsigned int m_nFlags
;
1198 WGENUMFILECB
* m_pEnumCb
;
1201 BYTE_VECTOR m_DataCollector
;
1203 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
1205 m_DataCollector
.append(data
,size
);
1208 // lines from igit.exe are 0 terminated
1209 int found
=m_DataCollector
.findData((const BYTE
*)"",1);
1212 OnSingleLine( (LPCSTR
)&*m_DataCollector
.begin() );
1213 m_DataCollector
.erase(m_DataCollector
.begin(), m_DataCollector
.begin()+found
+1);
1215 return false;//Should never reach this
1217 virtual void OnEnd()
1221 BYTE
HexChar(char ch
)
1223 if (ch
>= '0' && ch
<= '9')
1224 return (UINT
)(ch
- '0');
1225 else if (ch
>= 'A' && ch
<= 'F')
1226 return (UINT
)(ch
- 'A') + 10;
1227 else if (ch
>= 'a' && ch
<= 'f')
1228 return (UINT
)(ch
- 'a') + 10;
1233 bool OnSingleLine(LPCSTR line
)
1237 wgFile_s fileStatus
;
1241 fileStatus
.nFlags
= 0;
1243 fileStatus
.nFlags
|= WGFF_Directory
;
1244 else if (*line
!= 'F')
1251 fileStatus
.nStatus
= WGFS_Unknown
;
1254 case 'N': fileStatus
.nStatus
= WGFS_Normal
; break;
1255 case 'M': fileStatus
.nStatus
= WGFS_Modified
; break;
1256 case 'S': fileStatus
.nStatus
= WGFS_Staged
; break;
1257 case 'A': fileStatus
.nStatus
= WGFS_Added
; break;
1258 case 'C': fileStatus
.nStatus
= WGFS_Conflicted
; break;
1259 case 'D': fileStatus
.nStatus
= WGFS_Deleted
; break;
1260 case 'I': fileStatus
.nStatus
= WGFS_Ignored
; break;
1261 case 'U': fileStatus
.nStatus
= WGFS_Unversioned
; break;
1262 case 'E': fileStatus
.nStatus
= WGFS_Empty
; break;
1263 case '?': fileStatus
.nStatus
= WGFS_Unknown
; break;
1273 fileStatus
.sha1
= NULL
;
1274 if ( !(fileStatus
.nFlags
& WGFF_Directory
) )
1276 for (int i
=0; i
<20; i
++)
1278 sha1
[i
] = (HexChar(line
[0])<<4)&0xF0;
1279 sha1
[i
] |= HexChar(line
[1])&0xF;
1288 int len
= strlen(line
);
1289 if (len
&& len
< 2048)
1291 WCHAR
*buf
= (WCHAR
*)alloca((len
*4+2)*sizeof(WCHAR
));
1293 MultiByteToWideChar(CP_ACP
, 0, line
, len
+1, buf
, len
*4+1);
1294 fileStatus
.sFileName
= buf
;
1296 if (*buf
&& (*m_pEnumCb
)(&fileStatus
,m_pUserData
))
1304 BOOL
CGit::EnumFiles(const TCHAR
*pszProjectPath
, const TCHAR
*pszSubPath
, unsigned int nFlags
, WGENUMFILECB
*pEnumCb
, void *pUserData
)
1306 if(!pszProjectPath
|| *pszProjectPath
=='\0')
1309 CGitCall_EnumFiles
W_GitCall(pszProjectPath
,pszSubPath
,nFlags
,pEnumCb
,pUserData
);
1312 /* char W_szToDir[MAX_PATH];
1313 strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);
1314 if(W_szToDir[strlen(W_szToDir)-1]!='\\')
1315 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);
1317 SetCurrentDirectoryA(W_szToDir);
1318 GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);
1320 SetCurrentDir(pszProjectPath
);
1325 if (nFlags
& WGEFF_NoRecurse
) sMode
+= _T("r");
1326 if (nFlags
& WGEFF_FullPath
) sMode
+= _T("f");
1327 if (nFlags
& WGEFF_DirStatusDelta
) sMode
+= _T("d");
1328 if (nFlags
& WGEFF_DirStatusAll
) sMode
+= _T("D");
1329 if (nFlags
& WGEFF_EmptyAsNormal
) sMode
+= _T("e");
1330 if (nFlags
& WGEFF_SingleFile
) sMode
+= _T("s");
1337 // NOTE: there seems to be some issue with msys based app receiving backslash on commandline, at least
1338 // if followed by " like for example 'igit "C:\"', the commandline igit receives is 'igit.exe C:" status' with
1339 // the 'C:" status' part as a single arg, Maybe it uses unix style processing. In order to avoid this just
1340 // use forward slashes for supplied project and sub paths
1342 CString sProjectPath
= pszProjectPath
;
1343 sProjectPath
.Replace(_T('\\'), _T('/'));
1347 CString sSubPath
= pszSubPath
;
1348 sSubPath
.Replace(_T('\\'), _T('/'));
1350 cmd
.Format(_T("tgit.exe statusex \"%s\" status %s \"%s\""), sProjectPath
, sMode
, sSubPath
);
1354 cmd
.Format(_T("tgit.exe statusex \"%s\" status %s"), sProjectPath
, sMode
);
1357 //OutputDebugStringA("---");OutputDebugStringW(cmd);OutputDebugStringA("\r\n");
1359 W_GitCall
.SetCmd(cmd
);
1360 // NOTE: should igit get added as a part of msysgit then use below line instead of the above one
1361 //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);
1363 if ( Run(&W_GitCall
) )
1369 BOOL
CGit::CheckCleanWorkTree()
1373 cmd
=_T("git.exe rev-parse --verify HEAD");
1375 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1378 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1379 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1382 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1383 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1386 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1387 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1392 int CGit::Revert(CTGitPathList
&list
,bool keep
)
1395 for(int i
=0;i
<list
.GetCount();i
++)
1397 ret
= Revert((CTGitPath
&)list
[i
],keep
);
1403 int CGit::Revert(CTGitPath
&path
,bool keep
)
1407 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
)
1409 cmd
.Format(_T("git.exe mv -- \"%s\" \"%s\""),path
.GetGitPathString(),path
.GetGitOldPathString());
1410 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1413 cmd
.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path
.GetGitOldPathString());
1414 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1417 }else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1418 { //To init git repository, there are not HEAD, so we can use git reset command
1419 cmd
.Format(_T("git.exe rm --cached -- \"%s\""),path
.GetGitPathString());
1421 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1426 cmd
.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path
.GetGitPathString());
1427 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1433 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1439 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1441 cmd
=_T("git.exe ls-files -u -t -z");
1443 if(g_Git
.Run(cmd
,&vector
))
1448 list
.ParserFromLsFile(vector
);
1453 bool CGit::IsFastForward(CString
&from
, CString
&to
)
1457 cmd
.Format(_T("git.exe merge-base %s %s"), to
,from
);
1459 if(g_Git
.Run(cmd
,&base
,CP_ACP
))
1461 //CMessageBox::Show(NULL,base,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1466 hash
=g_Git
.GetHash(from
);
1470 return hash
== base
;
1473 unsigned int CGit::Hash2int(CString
&hash
)
1476 for(int i
=0;i
<8;i
++)
1479 if(hash
[i
]>=_T('a'))
1480 ret
|= (hash
[i
]-_T('a')+10)&0xFF;
1481 else if(hash
[i
]>=_T('A'))
1482 ret
|= (hash
[i
]-_T('A')+10)&0xFF;
1484 ret
|= (hash
[i
]-_T('0'))&0xFF;
1490 int CGit::RefreshGitIndex()
1492 if(g_Git
.m_IsUseGitDLL
)
1496 return git_run_cmd("update-index","update-index -q --refresh");
1506 cmd
=_T("git.exe update-index --refresh");
1507 return Run(cmd
,&output
,CP_ACP
);
1511 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, CString
&outputfile
)
1513 if(g_Git
.m_IsUseGitDLL
)
1517 g_Git
.CheckAndInitDll();
1518 CStringA ref
, patha
, outa
;
1519 ref
= CUnicodeUtils::GetMulti(Refname
,CP_ACP
);
1520 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_ACP
);
1521 outa
= CUnicodeUtils::GetMulti(outputfile
,CP_ACP
);
1522 ::DeleteFile(outputfile
);
1523 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1532 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1533 return g_Git
.RunLogFile(cmd
,outputfile
);
1536 void CEnvironment::CopyProcessEnvironment()
1538 TCHAR
*p
= GetEnvironmentStrings();
1539 while(*p
!=0 || *(p
+1) !=0)
1540 this->push_back(*p
++);
1542 push_back(_T('\0'));
1543 push_back(_T('\0'));
1546 CString
CEnvironment::GetEnv(TCHAR
*name
)
1549 for(int i
=0;i
<size();i
++)
1553 CString sname
= str
.Tokenize(_T("="),start
);
1554 if(sname
.CompareNoCase(name
) == 0)
1556 return &(*this)[i
+start
+1];
1563 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1566 for( i
=0;i
<size();i
++)
1568 CString str
= &(*this)[i
];
1570 CString sname
= str
.Tokenize(_T("="),start
);
1571 if(sname
.CompareNoCase(name
) == 0)
1580 i
-= 1; // roll back terminate \0\0
1581 this->push_back(_T('\0'));
1584 CEnvironment::iterator it
;
1588 while(*it
&& i
<size())
1597 this->insert(it
,*name
++);
1602 this->insert(it
, _T('='));
1608 this->insert(it
,*value
++);
1615 int CGit::GetGitEncode(TCHAR
* configkey
)
1617 CString str
=GetConfigValue(configkey
);
1622 return CUnicodeUtils::GetCPCode(str
);