Can't change branch name when branch is not default name
[TortoiseGit.git] / src / Git / Git.cpp
blob2fc8b30d6ab8b4e0cd476a04039d3702164ce8bb
1 #include "StdAfx.h"
2 #include "Git.h"
3 #include "atlconv.h"
4 #include "GitRev.h"
5 #include "registry.h"
6 #include "GitConfig.h"
7 #include <map>
8 #include "UnicodeUtils.h"
9 #include "gitdll.h"
11 int CGit::m_LogEncode=CP_UTF8;
14 static LPTSTR nextpath(LPCTSTR src, LPTSTR dst, UINT maxlen)
16 LPCTSTR orgsrc;
18 while (*src == _T(';'))
19 src++;
21 orgsrc = src;
23 if (!--maxlen)
24 goto nullterm;
26 while (*src && *src != _T(';'))
28 if (*src != _T('"'))
30 *dst++ = *src++;
31 if (!--maxlen)
33 orgsrc = src;
34 goto nullterm;
37 else
39 src++;
40 while (*src && *src != _T('"'))
42 *dst++ = *src++;
43 if (!--maxlen)
45 orgsrc = src;
46 goto nullterm;
50 if (*src)
51 src++;
55 while (*src == _T(';'))
56 src++;
58 nullterm:
60 *dst = 0;
62 return (orgsrc != src) ? (LPTSTR)src : NULL;
65 static inline BOOL FileExists(LPCTSTR lpszFileName)
67 struct _stat st;
68 return _tstat(lpszFileName, &st) == 0;
71 static BOOL FindGitPath()
73 size_t size;
74 _tgetenv_s(&size, NULL, 0, _T("PATH"));
76 if (!size)
78 return FALSE;
81 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
82 _tgetenv_s(&size, env, size, _T("PATH"));
84 TCHAR buf[_MAX_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"));
99 else
100 break;
102 if ( FileExists(buf) )
104 // dir found
105 pfin[1] = 0;
106 CGit::ms_LastMsysGitDir = buf;
107 return TRUE;
111 return FALSE;
115 #define MAX_DIRBUFFER 1000
116 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
118 CString CGit::ms_LastMsysGitDir;
119 CGit g_Git;
121 // contains system environment that should be used by child processes (RunAsync)
122 // initialized by CheckMsysGitDir
123 static LPTSTR l_processEnv = NULL;
127 CGit::CGit(void)
129 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
130 m_CurrentDir.ReleaseBuffer();
131 m_IsGitDllInited = false;
132 m_GitDiff=0;
133 CheckMsysGitDir();
134 m_critGitDllSec.Init();
137 CGit::~CGit(void)
139 if(this->m_GitDiff)
141 git_close_diff(m_GitDiff);
142 m_GitDiff=0;
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;
162 if(StdioFile)
164 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
165 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
168 STARTUPINFO si;
169 PROCESS_INFORMATION pi;
170 si.cb=sizeof(STARTUPINFO);
171 GetStartupInfo(&si);
173 si.hStdError=hWrite;
174 if(StdioFile)
175 si.hStdOutput=hStdioFile;
176 else
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))
192 LPVOID lpMsgBuf;
193 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
194 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
195 (LPTSTR)&lpMsgBuf,
196 0,NULL);
197 return GIT_ERROR_CREATE_PROCESS;
200 m_CurrentGitPi = pi;
202 CloseHandle(hWrite);
203 if(piOut)
204 *piOut=pi;
205 if(hReadOut)
206 *hReadOut=hRead;
208 return 0;
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)
215 //USES_CONVERSION;
216 //str->Append(A2W_CP((LPCSTR)p,code));
217 if(str == NULL)
218 return ;
220 WCHAR * buf;
222 int len ;
223 if(length<0)
224 len= strlen((const char*)p);
225 else
226 len=length;
227 //if (len==0)
228 // return ;
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();
234 //str->Append(buf);
235 //delete buf;
237 BOOL CGit::IsInitRepos()
239 CString cmdout;
240 cmdout.Empty();
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);
244 return TRUE;
246 if(cmdout.IsEmpty())
247 return TRUE;
249 return FALSE;
251 int CGit::Run(CGitCall* pcall)
253 PROCESS_INFORMATION pi;
254 HANDLE hRead;
255 if(RunAsync(pcall->GetCmd(),&pi,&hRead))
256 return GIT_ERROR_CREATE_PROCESS;
258 DWORD readnumber;
259 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
260 bool bAborted=false;
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))
266 bAborted=true;
268 if(!bAborted)
269 pcall->OnEnd();
272 CloseHandle(pi.hThread);
274 WaitForSingleObject(pi.hProcess, INFINITE);
275 DWORD exitcode =0;
277 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
279 return GIT_ERROR_GET_EXIT_CODE;
282 CloseHandle(pi.hProcess);
284 CloseHandle(hRead);
285 return exitcode;
287 class CGitCall_ByteVector : public CGitCall
289 public:
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);
296 return false;
298 BYTE_VECTOR* m_pvector;
301 int CGit::Run(CString cmd,BYTE_VECTOR *vector)
303 CGitCall_ByteVector call(cmd,vector);
304 return Run(&call);
306 int CGit::Run(CString cmd, CString* output,int code)
308 BYTE_VECTOR vector;
309 int ret;
310 ret=Run(cmd,&vector);
312 vector.push_back(0);
314 StringAppend(output,&(vector[0]),code);
315 return ret;
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)
329 CString configValue;
330 CString cmd;
331 cmd.Format(L"git.exe config %s", name);
332 Run(cmd,&configValue,CP_UTF8);
333 int start = 0;
334 return configValue.Tokenize(_T("\n"),start);
338 CString CGit::GetCurrentBranch(void)
340 CString output;
341 //Run(_T("git.exe branch"),&branch);
343 int ret=g_Git.Run(_T("git.exe branch --no-color"),&output,CP_UTF8);
344 if(!ret)
346 int pos=0;
347 CString one;
348 while( pos>=0 )
350 //i++;
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);
357 return CString("");
360 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
362 CString refName;
363 CString cmd;
364 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
365 if(Run(cmd, &refName, CP_UTF8) != 0)
366 return CString();//Error
367 int iStart = 0;
368 refName = refName.Tokenize(L"\n", iStart);
369 if(bStripRefsHeads)
370 refName = StripRefName(refName);
371 return refName;
374 CString CGit::GetFullRefName(CString shortRefName)
376 CString refName;
377 CString cmd;
378 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
379 if(Run(cmd, &refName, CP_UTF8) != 0)
380 return CString();//Error
381 int iStart = 0;
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);
391 return refName;
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() )
399 return -1;
401 CString sHeadFile = sProjectRoot + _T("\\") + g_GitAdminDir.GetAdminDirName() + _T("\\HEAD");
403 FILE *pFile;
404 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
406 if (!pFile)
408 return -1;
411 char s[256] = {0};
412 fgets(s, sizeof(s), pFile);
414 fclose(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() )
427 return -1;
429 else
431 //# Assume this is a detached head.
432 sBranchOut = "HEAD";
434 return 1;
437 return 0;
440 int CGit::BuildOutputFormat(CString &format,bool IsFull)
442 CString log;
443 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
444 format += log;
445 if(IsFull)
447 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
448 format += log;
449 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
450 format += log;
451 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
452 format += log;
453 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
454 format += log;
455 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
456 format += log;
457 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
458 format += log;
459 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
460 format += log;
463 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
464 format += log;
465 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
466 format += log;
467 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
468 format += log;
470 if(IsFull)
472 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
473 format += log;
475 return 0;
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)
486 CString cmd;
487 CString log;
488 CString num;
489 CString since;
491 CString file;
493 if(path)
494 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
496 if(count>0)
497 num.Format(_T("-n%d"),count);
499 CString param;
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)
516 param += _T(" -C ");
518 if(mask& CGit::LOG_INFO_DETECT_RENAME )
519 param += _T(" -M ");
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)
531 param += _T(" -c ");
533 if(mask& CGit::LOG_INFO_FULL_DIFF)
534 param += _T(" --full-diff ");
536 if(from != NULL && to != NULL)
538 CString range;
539 range.Format(_T(" %s..%s "),*from,*to);
540 param += range;
542 param+=hash;
544 if(paramonly)
545 cmd.Format(_T("%s -z --topo-order %s --parents "),
546 num,param);
547 else
548 cmd.Format(_T("git.exe log %s -z --topo-order %s --parents --pretty=format:\""),
549 num,param);
551 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
553 if(paramonly)
555 cmd += _T("-- ")+file;
556 }else
558 cmd += log;
559 cmd += CString(_T("\" -- "))+file;
562 return cmd;
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);
573 #define BUFSIZE 512
574 void GetTempPath(CString &path)
576 TCHAR lpPathBuffer[BUFSIZE];
577 DWORD dwRetVal;
578 DWORD dwBufSize=BUFSIZE;
579 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
580 lpPathBuffer); // buffer for path
581 if (dwRetVal > dwBufSize || (dwRetVal == 0))
583 path=_T("");
585 path.Format(_T("%s"),lpPathBuffer);
587 CString GetTempFile()
589 TCHAR lpPathBuffer[BUFSIZE];
590 DWORD dwRetVal;
591 DWORD dwBufSize=BUFSIZE;
592 TCHAR szTempName[BUFSIZE];
593 UINT uRetVal;
595 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
596 lpPathBuffer); // buffer for path
597 if (dwRetVal > dwBufSize || (dwRetVal == 0))
599 return _T("");
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
608 if (uRetVal == 0)
610 return _T("");
613 return CString(szTempName);
617 int CGit::RunLogFile(CString cmd,CString &filename)
619 STARTUPINFO si;
620 PROCESS_INFORMATION pi;
621 si.cb=sizeof(STARTUPINFO);
622 GetStartupInfo(&si);
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))
637 LPVOID lpMsgBuf;
638 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
639 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
640 (LPTSTR)&lpMsgBuf,
641 0,NULL);
642 return GIT_ERROR_CREATE_PROCESS;
645 WaitForSingleObject(pi.hProcess,INFINITE);
647 CloseHandle(pi.hThread);
648 CloseHandle(pi.hProcess);
649 CloseHandle(houtfile);
650 return GIT_SUCCESS;
651 // return 0;
654 git_revnum_t CGit::GetHash(const CString &friendname)
656 CString cmd;
657 CString out;
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"));
662 if(pos>0)
663 return out.Left(pos);
664 return out;
667 int CGit::GetInitAddList(CTGitPathList &outputlist)
669 CString cmd;
670 BYTE_VECTOR cmdout;
672 cmd=_T("git.exe ls-files -s -t -z");
673 outputlist.Clear();
674 if(g_Git.Run(cmd,&cmdout))
675 return -1;
677 outputlist.ParserFromLsFile(cmdout);
678 for(int i=0;i<outputlist.GetCount();i++)
679 ((int)outputlist[i].m_Action) = CTGitPath::LOGACTIONS_ADDED;
681 return 0;
683 int CGit::GetCommitDiffList(CString &rev1,CString &rev2,CTGitPathList &outputlist)
685 CString cmd;
687 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
689 //rev1=+_T("");
690 if(rev1 == GIT_REV_ZERO)
691 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
692 else
693 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
694 }else
696 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
699 BYTE_VECTOR out;
700 if(g_Git.Run(cmd,&out))
701 return -1;
703 outputlist.ParserFromLog(out);
707 int CGit::GetTagList(STRING_VECTOR &list)
709 int ret;
710 CString cmd,output;
711 cmd=_T("git.exe tag -l");
712 int i=0;
713 ret=g_Git.Run(cmd,&output,CP_UTF8);
714 if(!ret)
716 int pos=0;
717 CString one;
718 while( pos>=0 )
720 i++;
721 one=output.Tokenize(_T("\n"),pos);
722 list.push_back(one);
725 return ret;
728 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
730 int ret;
731 CString cmd,output;
732 cmd=_T("git.exe branch --no-color");
734 if(type==(BRANCH_LOCAL|BRANCH_REMOTE))
735 cmd+=_T(" -a");
736 else if(type==BRANCH_REMOTE)
737 cmd+=_T(" -r");
739 int i=0;
740 ret=g_Git.Run(cmd,&output,CP_UTF8);
741 if(!ret)
743 int pos=0;
744 CString one;
745 while( pos>=0 )
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('*'))
753 if(current)
754 *current=i;
755 one = one.Mid(2);
757 list.push_back(one);
758 i++;
761 return ret;
764 int CGit::GetRemoteList(STRING_VECTOR &list)
766 int ret;
767 CString cmd,output;
768 cmd=_T("git.exe config --get-regexp \"^^remote[.].*[.]url\"");
769 ret=g_Git.Run(cmd,&output,CP_UTF8);
770 if(!ret)
772 int pos=0;
773 CString one;
774 while( pos>=0 )
776 one=output.Tokenize(_T("\n"),pos);
777 int start=one.Find(_T("."),0);
778 if(start>0)
780 CString url;
781 url=one.Right(one.GetLength()-start-1);
782 one=url;
783 one=one.Left(one.Find(_T("."),0));
784 list.push_back(one);
788 return ret;
791 int CGit::GetRefList(STRING_VECTOR &list)
793 int ret;
794 CString cmd,output;
795 cmd=_T("git show-ref -d");
796 ret=g_Git.Run(cmd,&output,CP_UTF8);
797 if(!ret)
799 int pos=0;
800 CString one;
801 while( pos>=0 )
803 one=output.Tokenize(_T("\n"),pos);
804 int start=one.Find(_T(" "),0);
805 if(start>0)
807 CString name;
808 name=one.Right(one.GetLength()-start-1);
809 list.push_back(name);
813 return ret;
815 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
817 int ret;
818 CString cmd,output;
819 cmd=_T("git show-ref -d");
820 ret=g_Git.Run(cmd,&output,CP_UTF8);
821 if(!ret)
823 int pos=0;
824 CString one;
825 while( pos>=0 )
827 one=output.Tokenize(_T("\n"),pos);
828 int start=one.Find(_T(" "),0);
829 if(start>0)
831 CString name;
832 name=one.Right(one.GetLength()-start-1);
834 CString hash;
835 hash=one.Left(start);
837 map[hash].push_back(name);
841 return ret;
844 BOOL CGit::CheckMsysGitDir()
846 static BOOL bInitialized = FALSE;
848 if (bInitialized)
850 return TRUE;
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"));
858 if (!homesize)
860 _tdupenv_s(&home,&size,_T("USERPROFILE"));
861 _tputenv_s(_T("HOME"),home);
862 free(home);
864 CString str;
866 #ifndef _TORTOISESHELL
867 //set http_proxy
868 _tgetenv_s(&httpsize, NULL, 0, _T("http_proxy"));
869 if (!httpsize)
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(""));
878 CString http_proxy;
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);
898 //setup ssh client
899 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
901 if(!sshclient.IsEmpty())
903 _tputenv_s(_T("GIT_SSH"),sshclient);
905 //Setup SVN_SSH
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);
912 }else
914 TCHAR sPlink[MAX_PATH];
915 GetModuleFileName(NULL, sPlink, _countof(sPlink));
916 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
917 if (ptr) {
918 _tcscpy(ptr + 1, _T("TortoisePlink.exe"));
919 _tputenv_s(_T("GIT_SSH"), sPlink);
921 //Setup SVN_SSH
922 CString 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('\\'));
934 if (ptr)
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
942 if ( FindGitPath() )
944 bInitialized = TRUE;
945 return TRUE;
948 // add git/bin path to PATH
950 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
951 str=msysdir;
952 if(str.IsEmpty())
954 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);
955 str=msysinstalldir;
956 if ( !str.IsEmpty() )
958 str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";
959 msysdir=str;
960 msysdir.write();
962 else
964 return false;
967 #endif
968 //CGit::m_MsysGitPath=str;
970 //set path
972 _tdupenv_s(&oldpath,&size,_T("PATH"));
974 CString path;
975 path.Format(_T("%s;%s"),oldpath,str);
977 _tputenv_s(_T("PATH"),path);
979 CString sOldPath = oldpath;
980 free(oldpath);
983 if( !FindGitPath() )
985 if(!homesize)
987 _tputenv_s(_T("HOME"),_T(""));
989 return false;
991 else
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);
997 if(!homesize)
999 _tputenv_s(_T("HOME"),_T(""));
1001 #endif
1003 bInitialized = TRUE;
1004 return true;
1009 class CGitCall_EnumFiles : public CGitCall
1011 public:
1012 CGitCall_EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)
1013 : m_pszProjectPath(pszProjectPath),
1014 m_pszSubPath(pszSubPath),
1015 m_nFlags(nFlags),
1016 m_pEnumCb(pEnumCb),
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;
1027 void * m_pUserData;
1029 BYTE_VECTOR m_DataCollector;
1031 virtual bool OnOutputData(const BYTE* data, size_t size)
1033 m_DataCollector.append(data,size);
1034 while(true)
1036 // lines from igit.exe are 0 terminated
1037 int found=m_DataCollector.findData((const BYTE*)"",1);
1038 if(found<0)
1039 return false;
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;
1057 else
1058 return 0;
1061 bool OnSingleLine(LPCSTR line)
1063 //Parse single line
1065 wgFile_s fileStatus;
1067 // file/dir type
1069 fileStatus.nFlags = 0;
1070 if (*line == 'D')
1071 fileStatus.nFlags |= WGFF_Directory;
1072 else if (*line != 'F')
1073 // parse error
1074 return false;
1075 line += 2;
1077 // status
1079 fileStatus.nStatus = WGFS_Unknown;
1080 switch (*line)
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;
1092 default:
1093 // parse error
1094 return false;
1096 line += 2;
1098 // file sha1
1100 BYTE sha1[20];
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;
1109 line += 2;
1112 line++;
1115 // filename
1116 int len = strlen(line);
1117 if (len && len < 2048)
1119 WCHAR *buf = (WCHAR*)alloca((len*4+2)*sizeof(WCHAR));
1120 *buf = 0;
1121 MultiByteToWideChar(CP_ACP, 0, line, len+1, buf, len*4+1);
1122 fileStatus.sFileName = buf;
1124 if (*buf && (*m_pEnumCb)(&fileStatus,m_pUserData))
1125 return false;
1128 return true;
1132 BOOL CGit::EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)
1134 if(!pszProjectPath || *pszProjectPath=='\0')
1135 return FALSE;
1137 CGitCall_EnumFiles W_GitCall(pszProjectPath,pszSubPath,nFlags,pEnumCb,pUserData);
1138 CString cmd;
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);
1150 CString sMode;
1151 if (nFlags)
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");
1160 else
1162 sMode = _T("-");
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('/'));
1173 if (pszSubPath)
1175 CString sSubPath = pszSubPath;
1176 sSubPath.Replace(_T('\\'), _T('/'));
1178 cmd.Format(_T("tgit.exe statusex \"%s\" status %s \"%s\""), sProjectPath, sMode, sSubPath);
1180 else
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) )
1192 return FALSE;
1194 return TRUE;
1197 BOOL CGit::CheckCleanWorkTree()
1199 CString out;
1200 CString cmd;
1201 cmd=_T("git.exe rev-parse --verify HEAD");
1203 if(g_Git.Run(cmd,&out,CP_UTF8))
1204 return FALSE;
1206 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1207 if(g_Git.Run(cmd,&out,CP_UTF8))
1208 return FALSE;
1210 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1211 if(g_Git.Run(cmd,&out,CP_UTF8))
1212 return FALSE;
1214 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1215 if(g_Git.Run(cmd,&out,CP_UTF8))
1216 return FALSE;
1218 return TRUE;
1220 int CGit::Revert(CTGitPathList &list,bool keep)
1222 int ret;
1223 for(int i=0;i<list.GetCount();i++)
1225 ret = Revert((CTGitPath&)list[i],keep);
1226 if(ret)
1227 return ret;
1229 return 0;
1231 int CGit::Revert(CTGitPath &path,bool keep)
1233 CString cmd, out;
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))
1239 return -1;
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))
1245 return -1;
1247 cmd.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path.GetGitOldPathString());
1248 if(g_Git.Run(cmd,&out,CP_ACP))
1249 return -1;
1251 else
1253 cmd.Format(_T("git.exe checkout HEAD -f -- \"%s\""),path.GetGitPathString());
1254 if(g_Git.Run(cmd,&out,CP_ACP))
1255 return -1;
1257 return 0;
1260 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1262 BYTE_VECTOR vector;
1264 CString cmd;
1265 if(path)
1266 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1267 else
1268 cmd=_T("git.exe ls-files -u -t -z");
1270 if(g_Git.Run(cmd,&vector))
1272 return -1;
1275 list.ParserFromLsFile(vector);
1277 return 0;
1280 bool CGit::IsFastForward(CString &from, CString &to)
1282 CString base,hash;
1283 CString cmd;
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);
1289 return false;
1291 base=base.Left(40);
1293 hash=g_Git.GetHash(from);
1295 hash=hash.Left(40);
1297 return hash == base;
1300 unsigned int CGit::Hash2int(CString &hash)
1302 int ret=0;
1303 for(int i=0;i<8;i++)
1305 ret =ret <<4;
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;
1310 else
1311 ret |= (hash[i]-_T('0'))&0xFF;
1314 return ret;
1317 int CGit::RefreshGitIndex()
1319 CString cmd,output;
1320 cmd=_T("git.exe update-index --refresh");
1321 return Run(cmd,&output,CP_ACP);