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
;
121 // contains system environment that should be used by child processes (RunAsync)
122 // initialized by CheckMsysGitDir
123 static LPTSTR l_processEnv
= NULL
;
129 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
130 m_CurrentDir
.ReleaseBuffer();
131 m_IsGitDllInited
= false;
134 m_critGitDllSec
.Init();
141 git_close_diff(m_GitDiff
);
146 static char g_Buffer
[4096];
148 int CGit::RunAsync(CString cmd
,PROCESS_INFORMATION
*piOut
,HANDLE
*hReadOut
,CString
*StdioFile
)
150 SECURITY_ATTRIBUTES sa
;
151 HANDLE hRead
, hWrite
;
152 HANDLE hStdioFile
= NULL
;
154 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
155 sa
.lpSecurityDescriptor
=NULL
;
156 sa
.bInheritHandle
=TRUE
;
157 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
159 return GIT_ERROR_OPEN_PIP
;
164 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
165 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
169 PROCESS_INFORMATION pi
;
170 si
.cb
=sizeof(STARTUPINFO
);
175 si
.hStdOutput
=hStdioFile
;
177 si
.hStdOutput
=hWrite
;
179 si
.wShowWindow
=SW_HIDE
;
180 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
182 LPTSTR pEnv
= l_processEnv
;
183 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
185 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
186 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
188 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
190 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
193 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
194 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
197 return GIT_ERROR_CREATE_PROCESS
;
211 //Must use sperate function to convert ANSI str to union code string
212 //Becuase A2W use stack as internal convert buffer.
213 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
216 //str->Append(A2W_CP((LPCSTR)p,code));
224 len
= strlen((const char*)p
);
229 //buf = new WCHAR[len*4 + 1];
230 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
231 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
232 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
233 str
->ReleaseBuffer();
237 BOOL
CGit::IsInitRepos()
241 if(g_Git
.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout
,CP_UTF8
))
243 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
251 int CGit::Run(CGitCall
* pcall
)
253 PROCESS_INFORMATION pi
;
255 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
))
256 return GIT_ERROR_CREATE_PROCESS
;
259 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
261 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
263 //Todo: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
264 if(!bAborted
)//For now, flush output when command aborted.
265 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");
322 CString
CGit::GetUserEmail(void)
324 return GetConfigValue(L
"user.email");
327 CString
CGit::GetConfigValue(CString name
)
331 cmd
.Format(L
"git.exe config %s", name
);
332 Run(cmd
,&configValue
,CP_UTF8
);
334 return configValue
.Tokenize(_T("\n"),start
);
338 CString
CGit::GetCurrentBranch(void)
341 //Run(_T("git.exe branch"),&branch);
343 int ret
=g_Git
.Run(_T("git.exe branch --no-color"),&output
,CP_UTF8
);
351 one
=output
.Tokenize(_T("\n"),pos
);
352 //list.push_back(one.Right(one.GetLength()-2));
353 if(one
[0] == _T('*'))
354 return one
.Right(one
.GetLength()-2);
360 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
364 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
365 if(Run(cmd
, &refName
, CP_UTF8
) != 0)
366 return CString();//Error
368 refName
= refName
.Tokenize(L
"\n", iStart
);
370 refName
= StripRefName(refName
);
374 CString
CGit::GetFullRefName(CString shortRefName
)
378 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
379 if(Run(cmd
, &refName
, CP_UTF8
) != 0)
380 return CString();//Error
382 return refName
.Tokenize(L
"\n", iStart
);
385 CString
CGit::StripRefName(CString refName
)
387 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
388 refName
= refName
.Mid(11);
389 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
390 refName
= refName
.Mid(5);
394 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
396 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
398 if ( sProjectRoot
.IsEmpty() )
401 CString sHeadFile
= sProjectRoot
+ _T("\\") + g_GitAdminDir
.GetAdminDirName() + _T("\\HEAD");
404 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
412 fgets(s
, sizeof(s
), pFile
);
416 const char *pfx
= "ref: refs/heads/";
417 const int len
= 16;//strlen(pfx)
419 if ( !strncmp(s
, pfx
, len
) )
421 //# We're on a branch. It might not exist. But
422 //# HEAD looks good enough to be a branch.
423 sBranchOut
= s
+ len
;
424 sBranchOut
.TrimRight(_T(" \r\n\t"));
426 if ( sBranchOut
.IsEmpty() )
431 //# Assume this is a detached head.
440 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
443 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
447 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
449 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
451 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
453 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
455 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
457 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
459 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
463 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
465 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
467 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
472 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
478 int CGit::GetLog(BYTE_VECTOR
& logOut
, CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
480 CGitCall_ByteVector
gitCall(CString(),&logOut
);
481 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
484 CString
CGit::GetLogCmd( CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
)
494 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
497 num
.Format(_T("-n%d"),count
);
501 if(mask
& LOG_INFO_STAT
)
502 param
+= _T(" --numstat ");
503 if(mask
& LOG_INFO_FILESTATE
)
504 param
+= _T(" --raw ");
506 if(mask
& LOG_INFO_FULLHISTORY
)
507 param
+= _T(" --full-history ");
509 if(mask
& LOG_INFO_BOUNDARY
)
510 param
+= _T(" --left-right --boundary ");
512 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
513 param
+= _T(" --all ");
515 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
518 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
521 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
522 param
+= _T(" --first-parent ");
524 if(mask
& CGit::LOG_INFO_NO_MERGE
)
525 param
+= _T(" --no-merges ");
527 if(mask
& CGit::LOG_INFO_FOLLOW
)
528 param
+= _T(" --follow ");
530 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
533 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
534 param
+= _T(" --full-diff ");
536 if(from
!= NULL
&& to
!= NULL
)
539 range
.Format(_T(" %s..%s "),*from
,*to
);
545 cmd
.Format(_T("%s -z --topo-order %s --parents "),
548 cmd
.Format(_T("git.exe log %s -z --topo-order %s --parents --pretty=format:\""),
551 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
555 cmd
+= _T("-- ")+file
;
559 cmd
+= CString(_T("\" -- "))+file
;
564 //int CGit::GetLog(CGitCall* pgitCall, CString &hash, CTGitPath *path ,int count,int mask)
565 int CGit::GetLog(CGitCall
* pgitCall
, CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
567 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
569 return Run(pgitCall
);
570 // return Run(cmd,&logOut);
574 void GetTempPath(CString
&path
)
576 TCHAR lpPathBuffer
[BUFSIZE
];
578 DWORD dwBufSize
=BUFSIZE
;
579 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
580 lpPathBuffer
); // buffer for path
581 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
585 path
.Format(_T("%s"),lpPathBuffer
);
587 CString
GetTempFile()
589 TCHAR lpPathBuffer
[BUFSIZE
];
591 DWORD dwBufSize
=BUFSIZE
;
592 TCHAR szTempName
[BUFSIZE
];
595 dwRetVal
= GetTempPath(dwBufSize
, // length of the buffer
596 lpPathBuffer
); // buffer for path
597 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
601 // Create a temporary file.
602 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
603 TEXT("Patch"), // temp file name prefix
604 0, // create unique name
605 szTempName
); // buffer for name
613 return CString(szTempName
);
617 int CGit::RunLogFile(CString cmd
,CString
&filename
)
620 PROCESS_INFORMATION pi
;
621 si
.cb
=sizeof(STARTUPINFO
);
624 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
625 psa
.bInheritHandle
=TRUE
;
627 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
628 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
631 si
.wShowWindow
=SW_HIDE
;
632 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
633 si
.hStdOutput
= houtfile
;
635 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,NULL
,NULL
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
638 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
639 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
642 return GIT_ERROR_CREATE_PROCESS
;
645 WaitForSingleObject(pi
.hProcess
,INFINITE
);
647 CloseHandle(pi
.hThread
);
648 CloseHandle(pi
.hProcess
);
649 CloseHandle(houtfile
);
654 git_revnum_t
CGit::GetHash(const CString
&friendname
)
658 cmd
.Format(_T("git.exe rev-parse %s" ),friendname
);
659 Run(cmd
,&out
,CP_UTF8
);
660 // int pos=out.ReverseFind(_T('\n'));
661 int pos
=out
.FindOneOf(_T("\r\n"));
663 return out
.Left(pos
);
667 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
672 cmd
=_T("git.exe ls-files -s -t -z");
674 if(g_Git
.Run(cmd
,&cmdout
))
677 outputlist
.ParserFromLsFile(cmdout
);
678 for(int i
=0;i
<outputlist
.GetCount();i
++)
679 ((int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
683 int CGit::GetCommitDiffList(CString
&rev1
,CString
&rev2
,CTGitPathList
&outputlist
)
687 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
690 if(rev1
== GIT_REV_ZERO
)
691 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
693 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
696 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
700 if(g_Git
.Run(cmd
,&out
))
703 outputlist
.ParserFromLog(out
);
707 int CGit::GetTagList(STRING_VECTOR
&list
)
711 cmd
=_T("git.exe tag -l");
713 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
721 one
=output
.Tokenize(_T("\n"),pos
);
728 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
732 cmd
=_T("git.exe branch --no-color");
734 if(type
==(BRANCH_LOCAL
|BRANCH_REMOTE
))
736 else if(type
==BRANCH_REMOTE
)
740 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
747 one
=output
.Tokenize(_T("\n"),pos
);
748 one
.Trim(L
" \r\n\t");
749 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
750 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
751 if(one
[0] == _T('*'))
764 int CGit::GetRemoteList(STRING_VECTOR
&list
)
768 cmd
=_T("git.exe config --get-regexp \"^^remote[.].*[.]url\"");
769 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
776 one
=output
.Tokenize(_T("\n"),pos
);
777 int start
=one
.Find(_T("."),0);
781 url
=one
.Right(one
.GetLength()-start
-1);
783 one
=one
.Left(one
.Find(_T("."),0));
791 int CGit::GetRefList(STRING_VECTOR
&list
)
795 cmd
=_T("git show-ref -d");
796 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
803 one
=output
.Tokenize(_T("\n"),pos
);
804 int start
=one
.Find(_T(" "),0);
808 name
=one
.Right(one
.GetLength()-start
-1);
809 list
.push_back(name
);
815 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
819 cmd
=_T("git show-ref -d");
820 ret
=g_Git
.Run(cmd
,&output
,CP_UTF8
);
827 one
=output
.Tokenize(_T("\n"),pos
);
828 int start
=one
.Find(_T(" "),0);
832 name
=one
.Right(one
.GetLength()-start
-1);
835 hash
=one
.Left(start
);
837 map
[hash
].push_back(name
);
844 BOOL
CGit::CheckMsysGitDir()
846 static BOOL bInitialized
= FALSE
;
853 TCHAR
*oldpath
,*home
;
854 size_t homesize
,size
,httpsize
;
856 // set HOME if not set already
857 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
860 _tdupenv_s(&home
,&size
,_T("USERPROFILE"));
861 _tputenv_s(_T("HOME"),home
);
866 #ifndef _TORTOISESHELL
868 _tgetenv_s(&httpsize
, NULL
, 0, _T("http_proxy"));
871 CString regServeraddress_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-host"), _T(""));
872 CString regServerport_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-port"), _T(""));
873 CString regUsername_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-username"), _T(""));
874 CString regPassword_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-password"), _T(""));
875 CString regTimeout_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-timeout"), _T(""));
876 CString regExceptions_copy
= CRegString(_T("Software\\TortoiseGit\\Servers\\global\\http-proxy-exceptions"), _T(""));
879 if(!regServeraddress_copy
.IsEmpty())
881 if(regServeraddress_copy
.Left(4) != _T("http"))
882 http_proxy
=_T("http://");
884 if(!regUsername_copy
.IsEmpty())
886 http_proxy
+= regUsername_copy
;
887 http_proxy
+= _T(":")+regPassword_copy
;
888 http_proxy
+= _T("@");
890 http_proxy
+=regServeraddress_copy
;
891 if(!regServerport_copy
.IsEmpty())
893 http_proxy
+=_T(":")+regServerport_copy
;
895 _tputenv_s(_T("http_proxy"),http_proxy
);
899 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
901 if(!sshclient
.IsEmpty())
903 _tputenv_s(_T("GIT_SSH"),sshclient
);
906 CString ssh
=sshclient
;
907 ssh
.Replace(_T("/"),_T("\\"));
908 ssh
.Replace(_T("\\"),_T("\\\\"));
909 ssh
=CString(_T("\""))+ssh
+_T('\"');
910 _tputenv_s(_T("SVN_SSH"),ssh
);
914 TCHAR sPlink
[MAX_PATH
];
915 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
916 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
918 _tcscpy(ptr
+ 1, _T("TortoisePlink.exe"));
919 _tputenv_s(_T("GIT_SSH"), sPlink
);
923 ssh
.Replace(_T("/"),_T("\\"));
924 ssh
.Replace(_T("\\"),_T("\\\\"));
925 ssh
=CString(_T("\""))+ssh
+_T('\"');
926 _tputenv_s(_T("SVN_SSH"),ssh
);
931 TCHAR sAskPass
[MAX_PATH
];
932 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
933 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
936 _tcscpy(ptr
+ 1, _T("SshAskPass.exe"));
937 _tputenv_s(_T("DISPLAY"),_T(":9999"));
938 _tputenv_s(_T("SSH_ASKPASS"),sAskPass
);
941 // search PATH if git/bin directory is alredy present
948 // add git/bin path to PATH
950 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
954 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
956 if ( !str
.IsEmpty() )
958 str
+= (str
[str
.GetLength()-1] != '\\') ? "\\bin" : "bin";
968 //CGit::m_MsysGitPath=str;
972 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
975 path
.Format(_T("%s;%s"),oldpath
,str
);
977 _tputenv_s(_T("PATH"),path
);
979 CString sOldPath
= oldpath
;
987 _tputenv_s(_T("HOME"),_T(""));
993 #ifdef _TORTOISESHELL
994 l_processEnv
= GetEnvironmentStrings();
995 // updated environment is now duplicated for use in CreateProcess, restore original PATH for current process
996 _tputenv_s(_T("PATH"),sOldPath
);
999 _tputenv_s(_T("HOME"),_T(""));
1003 bInitialized
= TRUE
;
1009 class CGitCall_EnumFiles
: public CGitCall
1012 CGitCall_EnumFiles(const TCHAR
*pszProjectPath
, const TCHAR
*pszSubPath
, unsigned int nFlags
, WGENUMFILECB
*pEnumCb
, void *pUserData
)
1013 : m_pszProjectPath(pszProjectPath
),
1014 m_pszSubPath(pszSubPath
),
1017 m_pUserData(pUserData
)
1021 typedef std::map
<CStringA
,char> TStrCharMap
;
1023 const TCHAR
* m_pszProjectPath
;
1024 const TCHAR
* m_pszSubPath
;
1025 unsigned int m_nFlags
;
1026 WGENUMFILECB
* m_pEnumCb
;
1029 BYTE_VECTOR m_DataCollector
;
1031 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
1033 m_DataCollector
.append(data
,size
);
1036 // lines from igit.exe are 0 terminated
1037 int found
=m_DataCollector
.findData((const BYTE
*)"",1);
1040 OnSingleLine( (LPCSTR
)&*m_DataCollector
.begin() );
1041 m_DataCollector
.erase(m_DataCollector
.begin(), m_DataCollector
.begin()+found
+1);
1043 return false;//Should never reach this
1045 virtual void OnEnd()
1049 BYTE
HexChar(char ch
)
1051 if (ch
>= '0' && ch
<= '9')
1052 return (UINT
)(ch
- '0');
1053 else if (ch
>= 'A' && ch
<= 'F')
1054 return (UINT
)(ch
- 'A') + 10;
1055 else if (ch
>= 'a' && ch
<= 'f')
1056 return (UINT
)(ch
- 'a') + 10;
1061 bool OnSingleLine(LPCSTR line
)
1065 wgFile_s fileStatus
;
1069 fileStatus
.nFlags
= 0;
1071 fileStatus
.nFlags
|= WGFF_Directory
;
1072 else if (*line
!= 'F')
1079 fileStatus
.nStatus
= WGFS_Unknown
;
1082 case 'N': fileStatus
.nStatus
= WGFS_Normal
; break;
1083 case 'M': fileStatus
.nStatus
= WGFS_Modified
; break;
1084 case 'S': fileStatus
.nStatus
= WGFS_Staged
; break;
1085 case 'A': fileStatus
.nStatus
= WGFS_Added
; break;
1086 case 'C': fileStatus
.nStatus
= WGFS_Conflicted
; break;
1087 case 'D': fileStatus
.nStatus
= WGFS_Deleted
; break;
1088 case 'I': fileStatus
.nStatus
= WGFS_Ignored
; break;
1089 case 'U': fileStatus
.nStatus
= WGFS_Unversioned
; break;
1090 case 'E': fileStatus
.nStatus
= WGFS_Empty
; break;
1091 case '?': fileStatus
.nStatus
= WGFS_Unknown
; break;
1101 fileStatus
.sha1
= NULL
;
1102 if ( !(fileStatus
.nFlags
& WGFF_Directory
) )
1104 for (int i
=0; i
<20; i
++)
1106 sha1
[i
] = (HexChar(line
[0])<<4)&0xF0;
1107 sha1
[i
] |= HexChar(line
[1])&0xF;
1116 int len
= strlen(line
);
1117 if (len
&& len
< 2048)
1119 WCHAR
*buf
= (WCHAR
*)alloca((len
*4+2)*sizeof(WCHAR
));
1121 MultiByteToWideChar(CP_ACP
, 0, line
, len
+1, buf
, len
*4+1);
1122 fileStatus
.sFileName
= buf
;
1124 if (*buf
&& (*m_pEnumCb
)(&fileStatus
,m_pUserData
))
1132 BOOL
CGit::EnumFiles(const TCHAR
*pszProjectPath
, const TCHAR
*pszSubPath
, unsigned int nFlags
, WGENUMFILECB
*pEnumCb
, void *pUserData
)
1134 if(!pszProjectPath
|| *pszProjectPath
=='\0')
1137 CGitCall_EnumFiles
W_GitCall(pszProjectPath
,pszSubPath
,nFlags
,pEnumCb
,pUserData
);
1140 /* char W_szToDir[MAX_PATH];
1141 strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);
1142 if(W_szToDir[strlen(W_szToDir)-1]!='\\')
1143 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);
1145 SetCurrentDirectoryA(W_szToDir);
1146 GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);
1148 SetCurrentDir(pszProjectPath
);
1153 if (nFlags
& WGEFF_NoRecurse
) sMode
+= _T("r");
1154 if (nFlags
& WGEFF_FullPath
) sMode
+= _T("f");
1155 if (nFlags
& WGEFF_DirStatusDelta
) sMode
+= _T("d");
1156 if (nFlags
& WGEFF_DirStatusAll
) sMode
+= _T("D");
1157 if (nFlags
& WGEFF_EmptyAsNormal
) sMode
+= _T("e");
1158 if (nFlags
& WGEFF_SingleFile
) sMode
+= _T("s");
1165 // NOTE: there seems to be some issue with msys based app receiving backslash on commandline, at least
1166 // if followed by " like for example 'igit "C:\"', the commandline igit receives is 'igit.exe C:" status' with
1167 // the 'C:" status' part as a single arg, Maybe it uses unix style processing. In order to avoid this just
1168 // use forward slashes for supplied project and sub paths
1170 CString sProjectPath
= pszProjectPath
;
1171 sProjectPath
.Replace(_T('\\'), _T('/'));
1175 CString sSubPath
= pszSubPath
;
1176 sSubPath
.Replace(_T('\\'), _T('/'));
1178 cmd
.Format(_T("tgit.exe statusex \"%s\" status %s \"%s\""), sProjectPath
, sMode
, sSubPath
);
1182 cmd
.Format(_T("tgit.exe statusex \"%s\" status %s"), sProjectPath
, sMode
);
1185 //OutputDebugStringA("---");OutputDebugStringW(cmd);OutputDebugStringA("\r\n");
1187 W_GitCall
.SetCmd(cmd
);
1188 // NOTE: should igit get added as a part of msysgit then use below line instead of the above one
1189 //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);
1191 if ( Run(&W_GitCall
) )
1197 BOOL
CGit::CheckCleanWorkTree()
1201 cmd
=_T("git.exe rev-parse --verify HEAD");
1203 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1206 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1207 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1210 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1211 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1214 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1215 if(g_Git
.Run(cmd
,&out
,CP_UTF8
))
1220 int CGit::Revert(CTGitPathList
&list
,bool keep
)
1223 for(int i
=0;i
<list
.GetCount();i
++)
1225 ret
= Revert((CTGitPath
&)list
[i
],keep
);
1231 int CGit::Revert(CTGitPath
&path
,bool keep
)
1234 if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1235 { //To init git repository, there are not HEAD, so we can use git reset command
1236 cmd
.Format(_T("git.exe rm --cached -- \"%s\""),path
.GetGitPathString());
1238 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1241 else if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
)
1243 cmd
.Format(_T("git.exe mv -- \"%s\" \"%s\""),path
.GetGitPathString(),path
.GetGitOldPathString());
1244 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1247 cmd
.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path
.GetGitOldPathString());
1248 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1253 cmd
.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path
.GetGitPathString());
1254 if(g_Git
.Run(cmd
,&out
,CP_ACP
))
1260 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1266 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1268 cmd
=_T("git.exe ls-files -u -t -z");
1270 if(g_Git
.Run(cmd
,&vector
))
1275 list
.ParserFromLsFile(vector
);
1280 bool CGit::IsFastForward(CString
&from
, CString
&to
)
1284 cmd
.Format(_T("git.exe merge-base %s %s"), to
,from
);
1286 if(g_Git
.Run(cmd
,&base
,CP_ACP
))
1288 //CMessageBox::Show(NULL,base,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1293 hash
=g_Git
.GetHash(from
);
1297 return hash
== base
;
1300 unsigned int CGit::Hash2int(CString
&hash
)
1303 for(int i
=0;i
<8;i
++)
1306 if(hash
[i
]>=_T('a'))
1307 ret
|= (hash
[i
]-_T('a')+10)&0xFF;
1308 else if(hash
[i
]>=_T('A'))
1309 ret
|= (hash
[i
]-_T('A')+10)&0xFF;
1311 ret
|= (hash
[i
]-_T('0'))&0xFF;
1317 int CGit::RefreshGitIndex()
1320 cmd
=_T("git.exe update-index --refresh");
1321 return Run(cmd
,&output
,CP_ACP
);