Merge branch 'upgrade-libgit2'
[TortoiseGit.git] / src / Git / Git.cpp
blobf4bcfb868ec9340f6c8362e85fe8e899df8c68d8
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2011 - 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.
20 #include "StdAfx.h"
21 #include "Git.h"
22 #include "atlconv.h"
23 #include "GitRev.h"
24 #include "registry.h"
25 #include "GitConfig.h"
26 #include <map>
27 #include "UnicodeUtils.h"
28 #include "gitdll.h"
29 #include <fstream>
31 int CGit::m_LogEncode=CP_UTF8;
32 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
34 static LPTSTR nextpath(LPCTSTR src, LPTSTR dst, UINT maxlen)
36 LPCTSTR orgsrc;
38 while (*src == _T(';'))
39 src++;
41 orgsrc = src;
43 if (!--maxlen)
44 goto nullterm;
46 while (*src && *src != _T(';'))
48 if (*src != _T('"'))
50 *dst++ = *src++;
51 if (!--maxlen)
53 orgsrc = src;
54 goto nullterm;
57 else
59 src++;
60 while (*src && *src != _T('"'))
62 *dst++ = *src++;
63 if (!--maxlen)
65 orgsrc = src;
66 goto nullterm;
70 if (*src)
71 src++;
75 while (*src == _T(';'))
76 src++;
78 nullterm:
80 *dst = 0;
82 return (orgsrc != src) ? (LPTSTR)src : NULL;
85 static inline BOOL FileExists(LPCTSTR lpszFileName)
87 struct _stat st;
88 return _tstat(lpszFileName, &st) == 0;
91 static BOOL FindGitPath()
93 size_t size;
94 _tgetenv_s(&size, NULL, 0, _T("PATH"));
96 if (!size)
98 return FALSE;
101 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
102 _tgetenv_s(&size, env, size, _T("PATH"));
104 TCHAR buf[_MAX_PATH];
106 // search in all paths defined in PATH
107 while ((env = nextpath(env, buf, _MAX_PATH-1)) && *buf)
109 TCHAR *pfin = buf + _tcslen(buf)-1;
111 // ensure trailing slash
112 if (*pfin != _T('/') && *pfin != _T('\\'))
113 _tcscpy(++pfin, _T("\\"));
115 const int len = _tcslen(buf);
117 if ((len + 7) < _MAX_PATH)
118 _tcscpy(pfin+1, _T("git.exe"));
119 else
120 break;
122 if ( FileExists(buf) )
124 // dir found
125 pfin[1] = 0;
126 CGit::ms_LastMsysGitDir = buf;
127 return TRUE;
131 return FALSE;
135 #define MAX_DIRBUFFER 1000
136 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
138 CString CGit::ms_LastMsysGitDir;
139 CGit g_Git;
142 CGit::CGit(void)
144 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
145 m_CurrentDir.ReleaseBuffer();
146 m_IsGitDllInited = false;
147 m_GitDiff=0;
148 m_GitSimpleListDiff=0;
149 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
150 this->m_bInitialized =false;
151 CheckMsysGitDir();
152 m_critGitDllSec.Init();
155 CGit::~CGit(void)
157 if(this->m_GitDiff)
159 git_close_diff(m_GitDiff);
160 m_GitDiff=0;
162 if(this->m_GitSimpleListDiff)
164 git_close_diff(m_GitSimpleListDiff);
165 m_GitSimpleListDiff=0;
169 bool CGit::IsBranchNameValid(CString branchname)
171 if (branchname.IsEmpty())
172 return false;
174 for(int i=0; i < branchname.GetLength(); i++)
176 TCHAR c = branchname.GetAt(i);
177 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
178 return false;
181 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
182 return false;
184 CString reverseBranchname = branchname.MakeReverse();
185 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
186 return false;
188 return true;
191 static char g_Buffer[4096];
193 int CGit::RunAsync(CString cmd,PROCESS_INFORMATION *piOut,HANDLE *hReadOut,CString *StdioFile)
195 SECURITY_ATTRIBUTES sa;
196 HANDLE hRead, hWrite;
197 HANDLE hStdioFile = NULL;
199 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
200 sa.lpSecurityDescriptor=NULL;
201 sa.bInheritHandle=TRUE;
202 if(!CreatePipe(&hRead,&hWrite,&sa,0))
204 return TGIT_GIT_ERROR_OPEN_PIP;
207 if(StdioFile)
209 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
210 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
213 STARTUPINFO si;
214 PROCESS_INFORMATION pi;
215 si.cb=sizeof(STARTUPINFO);
216 GetStartupInfo(&si);
218 si.hStdError=hWrite;
219 if(StdioFile)
220 si.hStdOutput=hStdioFile;
221 else
222 si.hStdOutput=hWrite;
224 si.wShowWindow=SW_HIDE;
225 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
227 LPTSTR pEnv = m_Environment.size()? &m_Environment[0]: NULL;
228 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
230 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
231 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
233 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
234 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
236 if(cmd.Find(_T("git")) == 0)
238 int firstSpace = cmd.Find(_T(" "));
239 if (firstSpace > 0)
240 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
241 else
242 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
245 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
247 LPVOID lpMsgBuf;
248 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
249 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
250 (LPTSTR)&lpMsgBuf,
251 0,NULL);
252 return TGIT_GIT_ERROR_CREATE_PROCESS;
255 m_CurrentGitPi = pi;
257 CloseHandle(hWrite);
258 if(piOut)
259 *piOut=pi;
260 if(hReadOut)
261 *hReadOut=hRead;
263 return 0;
266 //Must use sperate function to convert ANSI str to union code string
267 //Becuase A2W use stack as internal convert buffer.
268 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
270 //USES_CONVERSION;
271 //str->Append(A2W_CP((LPCSTR)p,code));
272 if(str == NULL)
273 return ;
275 WCHAR * buf;
277 int len ;
278 if(length<0)
279 len= strlen((const char*)p);
280 else
281 len=length;
282 //if (len==0)
283 // return ;
284 //buf = new WCHAR[len*4 + 1];
285 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
286 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
287 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
288 str->ReleaseBuffer();
289 //str->Append(buf);
290 //delete buf;
292 BOOL CGit::IsInitRepos()
294 CString cmdout;
295 cmdout.Empty();
296 if(g_Git.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout,CP_UTF8))
298 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
299 return TRUE;
301 if(cmdout.IsEmpty())
302 return TRUE;
304 return FALSE;
306 int CGit::Run(CGitCall* pcall)
308 PROCESS_INFORMATION pi;
309 HANDLE hRead;
310 if(RunAsync(pcall->GetCmd(),&pi,&hRead))
311 return TGIT_GIT_ERROR_CREATE_PROCESS;
313 DWORD readnumber;
314 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
315 bool bAborted=false;
316 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
318 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
319 if(!bAborted)//For now, flush output when command aborted.
320 if(pcall->OnOutputData(data,readnumber))
321 bAborted=true;
323 if(!bAborted)
324 pcall->OnEnd();
326 CloseHandle(pi.hThread);
328 WaitForSingleObject(pi.hProcess, INFINITE);
329 DWORD exitcode =0;
331 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
333 return TGIT_GIT_ERROR_GET_EXIT_CODE;
336 CloseHandle(pi.hProcess);
338 CloseHandle(hRead);
339 return exitcode;
341 class CGitCall_ByteVector : public CGitCall
343 public:
344 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector):CGitCall(cmd),m_pvector(pvector){}
345 virtual bool OnOutputData(const BYTE* data, size_t size)
347 size_t oldsize=m_pvector->size();
348 m_pvector->resize(m_pvector->size()+size);
349 memcpy(&*(m_pvector->begin()+oldsize),data,size);
350 return false;
352 BYTE_VECTOR* m_pvector;
355 int CGit::Run(CString cmd,BYTE_VECTOR *vector)
357 CGitCall_ByteVector call(cmd,vector);
358 return Run(&call);
360 int CGit::Run(CString cmd, CString* output,int code)
362 BYTE_VECTOR vector;
363 int ret;
364 ret=Run(cmd,&vector);
366 vector.push_back(0);
368 StringAppend(output,&(vector[0]),code);
369 return ret;
372 CString CGit::GetUserName(void)
374 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
376 CString CGit::GetUserEmail(void)
378 return GetConfigValue(L"user.email");
381 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
383 CString configValue;
384 int start = 0;
385 if(this->m_IsUseGitDLL)
387 CString *git_path=NULL;
391 CTGitPath path;
393 CheckAndInitDll();
394 git_path = GitPath;
396 }catch(...)
399 CStringA key, value;
400 key = CUnicodeUtils::GetMulti(name, encoding);
401 CStringA p;
402 if(git_path)
403 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
405 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
406 return CString();
407 else
409 g_Git.StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
410 if(RemoveCR)
411 return configValue.Tokenize(_T("\n"),start);
412 return configValue;
416 else
418 CString cmd;
419 cmd.Format(L"git.exe config %s", name);
420 Run(cmd,&configValue,encoding);
421 if(RemoveCR)
422 return configValue.Tokenize(_T("\n"),start);
423 return configValue;
427 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
429 if(this->m_IsUseGitDLL)
433 CheckAndInitDll();
435 }catch(...)
438 CStringA keya, valuea;
439 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
440 valuea = CUnicodeUtils::GetMulti(value, encoding);
441 CStringA p;
442 if(GitPath)
443 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
445 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
448 else
450 CString cmd;
451 CString option;
452 switch(type)
454 case CONFIG_GLOBAL:
455 option = _T("--global");
456 break;
457 case CONFIG_SYSTEM:
458 option = _T("--system");
459 break;
460 default:
461 break;
463 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
464 CString out;
465 if(Run(cmd,&out,encoding))
467 return -1;
470 return 0;
474 CString CGit::GetCurrentBranch(void)
476 CString output;
477 //Run(_T("git.exe branch"),&branch);
479 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
481 return _T("(no branch)");
483 else
484 return output;
488 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
490 CString refName;
491 if(this->m_IsUseGitDLL)
493 unsigned char sha1[20];
494 int flag;
496 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
497 if(refs_heads_master && (flag&REF_ISSYMREF))
499 g_Git.StringAppend(&refName,(BYTE*)refs_heads_master);
500 if(bStripRefsHeads)
501 refName = StripRefName(refName);
505 else
507 CString cmd;
508 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
509 if(Run(cmd, &refName, CP_UTF8) != 0)
510 return CString();//Error
511 int iStart = 0;
512 refName = refName.Tokenize(L"\n", iStart);
513 if(bStripRefsHeads)
514 refName = StripRefName(refName);
516 return refName;
519 CString CGit::GetFullRefName(CString shortRefName)
521 CString refName;
522 CString cmd;
523 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
524 if(Run(cmd, &refName, CP_UTF8) != 0)
525 return CString();//Error
526 int iStart = 0;
527 return refName.Tokenize(L"\n", iStart);
530 CString CGit::StripRefName(CString refName)
532 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
533 refName = refName.Mid(11);
534 else if(wcsncmp(refName, L"refs/", 5) == 0)
535 refName = refName.Mid(5);
536 int start =0;
537 return refName.Tokenize(_T("\n"),start);
540 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
542 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
544 if ( sProjectRoot.IsEmpty() )
545 return -1;
547 CString sHeadFile = sProjectRoot + _T("\\") + g_GitAdminDir.GetAdminDirName() + _T("\\HEAD");
549 FILE *pFile;
550 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
552 if (!pFile)
554 return -1;
557 char s[256] = {0};
558 fgets(s, sizeof(s), pFile);
560 fclose(pFile);
562 const char *pfx = "ref: refs/heads/";
563 const int len = 16;//strlen(pfx)
565 if ( !strncmp(s, pfx, len) )
567 //# We're on a branch. It might not exist. But
568 //# HEAD looks good enough to be a branch.
569 sBranchOut = s + len;
570 sBranchOut.TrimRight(_T(" \r\n\t"));
572 if ( sBranchOut.IsEmpty() )
573 return -1;
575 else
577 //# Assume this is a detached head.
578 sBranchOut = "HEAD";
580 return 1;
583 return 0;
586 int CGit::BuildOutputFormat(CString &format,bool IsFull)
588 CString log;
589 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
590 format += log;
591 if(IsFull)
593 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
594 format += log;
595 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
596 format += log;
597 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
598 format += log;
599 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
600 format += log;
601 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
602 format += log;
603 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
604 format += log;
605 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
606 format += log;
609 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
610 format += log;
611 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
612 format += log;
613 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
614 format += log;
616 if(IsFull)
618 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
619 format += log;
621 return 0;
624 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
626 CGitCall_ByteVector gitCall(CString(),&logOut);
627 return GetLog(&gitCall,hash,path,count,mask,from,to);
630 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
631 CFilterData *Filter)
633 CString cmd;
634 CString num;
635 CString since;
637 CString file;
639 if(path)
640 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
642 if(count>0)
643 num.Format(_T("-n%d"),count);
645 CString param;
647 if(mask& LOG_INFO_STAT )
648 param += _T(" --numstat ");
649 if(mask& LOG_INFO_FILESTATE)
650 param += _T(" --raw ");
652 if(mask& LOG_INFO_FULLHISTORY)
653 param += _T(" --full-history ");
655 if(mask& LOG_INFO_BOUNDARY)
656 param += _T(" --left-right --boundary ");
658 if(mask& CGit::LOG_INFO_ALL_BRANCH)
659 param += _T(" --all ");
661 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
662 param += _T(" -C ");
664 if(mask& CGit::LOG_INFO_DETECT_RENAME )
665 param += _T(" -M ");
667 if(mask& CGit::LOG_INFO_FIRST_PARENT )
668 param += _T(" --first-parent ");
670 if(mask& CGit::LOG_INFO_NO_MERGE )
671 param += _T(" --no-merges ");
673 if(mask& CGit::LOG_INFO_FOLLOW)
674 param += _T(" --follow ");
676 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
677 param += _T(" -c ");
679 if(mask& CGit::LOG_INFO_FULL_DIFF)
680 param += _T(" --full-diff ");
682 if(from != NULL && to != NULL)
684 CString range;
685 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
686 param += range;
688 param+=hash;
690 CString st1,st2;
692 if( Filter && (Filter->m_From != -1))
694 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
695 param += st1;
698 if( Filter && (Filter->m_To != -1))
700 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
701 param += st2;
704 bool isgrep = false;
705 if( Filter && (!Filter->m_Author.IsEmpty()))
707 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
708 param += st1;
709 isgrep = true;
712 if( Filter && (!Filter->m_Committer.IsEmpty()))
714 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
715 param += st1;
716 isgrep = true;
719 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
721 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
722 param += st1;
723 isgrep = true;
726 if(Filter && isgrep)
728 if(!Filter->m_IsRegex)
729 param += _T(" --fixed-strings ");
731 param += _T(" --regexp-ignore-case --extended-regexp ");
734 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
735 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
736 else
738 CString log;
739 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
740 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
741 num,param,log);
744 cmd += file;
746 return cmd;
748 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
749 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
751 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
753 return Run(pgitCall);
754 // return Run(cmd,&logOut);
757 #define BUFSIZE 512
758 void GetTempPath(CString &path)
760 TCHAR lpPathBuffer[BUFSIZE];
761 DWORD dwRetVal;
762 DWORD dwBufSize=BUFSIZE;
763 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
764 lpPathBuffer); // buffer for path
765 if (dwRetVal > dwBufSize || (dwRetVal == 0))
767 path=_T("");
769 path.Format(_T("%s"),lpPathBuffer);
771 CString GetTempFile()
773 TCHAR lpPathBuffer[BUFSIZE];
774 DWORD dwRetVal;
775 DWORD dwBufSize=BUFSIZE;
776 TCHAR szTempName[BUFSIZE];
777 UINT uRetVal;
779 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
780 lpPathBuffer); // buffer for path
781 if (dwRetVal > dwBufSize || (dwRetVal == 0))
783 return _T("");
785 // Create a temporary file.
786 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
787 TEXT("Patch"), // temp file name prefix
788 0, // create unique name
789 szTempName); // buffer for name
792 if (uRetVal == 0)
794 return _T("");
797 return CString(szTempName);
801 int CGit::RunLogFile(CString cmd,const CString &filename)
803 STARTUPINFO si;
804 PROCESS_INFORMATION pi;
805 si.cb=sizeof(STARTUPINFO);
806 GetStartupInfo(&si);
808 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
809 psa.bInheritHandle=TRUE;
811 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
812 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
814 si.wShowWindow = SW_HIDE;
815 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
816 si.hStdOutput = houtfile;
818 LPTSTR pEnv = m_Environment.size()? &m_Environment[0]: NULL;
819 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
821 if(cmd.Find(_T("git")) == 0)
822 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
824 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
826 LPVOID lpMsgBuf;
827 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
828 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
829 (LPTSTR)&lpMsgBuf,
830 0,NULL);
831 return TGIT_GIT_ERROR_CREATE_PROCESS;
834 WaitForSingleObject(pi.hProcess,INFINITE);
836 CloseHandle(pi.hThread);
837 CloseHandle(pi.hProcess);
838 CloseHandle(houtfile);
839 return TGIT_GIT_SUCCESS;
840 // return 0;
843 CGitHash CGit::GetHash(TCHAR* friendname)
845 if(this->m_IsUseGitDLL)
847 this->CheckAndInitDll();
849 CGitHash hash;
850 CStringA ref;
851 ref = CUnicodeUtils::GetMulti(FixBranchName(friendname),CP_ACP);
854 git_get_sha1(ref, hash.m_hash);
856 }catch(...)
859 return hash;
862 else
864 CString cmd;
865 CString out;
866 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
867 Run(cmd,&out,CP_UTF8);
868 // int pos=out.ReverseFind(_T('\n'));
869 out.FindOneOf(_T("\r\n"));
870 return CGitHash(out);
874 int CGit::GetInitAddList(CTGitPathList &outputlist)
876 CString cmd;
877 BYTE_VECTOR cmdout;
879 cmd=_T("git.exe ls-files -s -t -z");
880 outputlist.Clear();
881 if(g_Git.Run(cmd,&cmdout))
882 return -1;
884 outputlist.ParserFromLsFile(cmdout);
885 for(int i=0;i<outputlist.GetCount();i++)
886 ((unsigned int)outputlist[i].m_Action) = CTGitPath::LOGACTIONS_ADDED;
888 return 0;
890 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
892 CString cmd;
894 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
896 //rev1=+_T("");
897 if(rev1 == GIT_REV_ZERO)
898 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
899 else
900 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
902 else
904 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
907 BYTE_VECTOR out;
908 if(g_Git.Run(cmd,&out))
909 return -1;
911 outputlist.ParserFromLog(out);
913 return 0;
916 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
918 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
919 CString str;
920 g_Git.StringAppend(&str,(BYTE*)refname,CP_ACP);
921 list->push_back(str);
922 return 0;
925 int CGit::GetTagList(STRING_VECTOR &list)
927 int ret;
929 if(this->m_IsUseGitDLL)
931 return git_for_each_ref_in("refs/tags/",addto_list_each_ref_fn, &list);
934 else
936 CString cmd,output;
937 cmd=_T("git.exe tag -l");
938 int i=0;
939 ret=g_Git.Run(cmd,&output,CP_UTF8);
940 if(!ret)
942 int pos=0;
943 CString one;
944 while( pos>=0 )
946 i++;
947 one=output.Tokenize(_T("\n"),pos);
948 list.push_back(one);
952 return ret;
955 CString CGit::FixBranchName_Mod(CString& branchName)
957 if(branchName == "FETCH_HEAD")
958 branchName = DerefFetchHead();
959 return branchName;
962 CString CGit::FixBranchName(const CString& branchName)
964 CString tempBranchName = branchName;
965 FixBranchName_Mod(tempBranchName);
966 return tempBranchName;
970 CString CGit::DerefFetchHead()
972 using namespace std;
973 ifstream fetchHeadFile((m_CurrentDir + L"\\.git\\FETCH_HEAD").GetString(), ios::in | ios::binary);
974 int forMergeLineCount = 0;
975 string line;
976 string hashToReturn;
977 while(getline(fetchHeadFile, line))
979 //Tokenize this line
980 string::size_type prevPos = 0;
981 string::size_type pos = line.find('\t');
982 if(pos == string::npos) continue; //invalid line
984 string hash = line.substr(0, pos);
985 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
987 bool forMerge = pos == prevPos;
988 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
990 string remoteBranch = line.substr(prevPos, pos - prevPos);
992 //Process this line
993 if(forMerge)
995 hashToReturn = hash;
996 ++forMergeLineCount;
997 if(forMergeLineCount > 1)
998 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1002 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1005 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1007 int ret;
1008 CString cmd,output;
1009 cmd = _T("git.exe branch --no-color");
1011 if((type&BRANCH_ALL) == BRANCH_ALL)
1012 cmd += _T(" -a");
1013 else if(type&BRANCH_REMOTE)
1014 cmd += _T(" -r");
1016 int i=0;
1017 ret=g_Git.Run(cmd,&output,CP_UTF8);
1018 if(!ret)
1020 int pos=0;
1021 CString one;
1022 while( pos>=0 )
1024 one=output.Tokenize(_T("\n"),pos);
1025 one.Trim(L" \r\n\t");
1026 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1027 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1028 if(one[0] == _T('*'))
1030 if(current)
1031 *current=i;
1032 one = one.Mid(2);
1034 if (one != _T("(no branch)"))
1035 list.push_back(one);
1036 i++;
1040 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1041 list.push_back(L"FETCH_HEAD");
1043 return ret;
1046 int CGit::GetRemoteList(STRING_VECTOR &list)
1048 int ret;
1049 CString cmd,output;
1050 cmd=_T("git.exe remote");
1051 ret=g_Git.Run(cmd,&output,CP_UTF8);
1052 if(!ret)
1054 int pos=0;
1055 CString one;
1056 while( pos>=0 )
1058 one=output.Tokenize(_T("\n"),pos);
1059 list.push_back(one);
1062 return ret;
1065 int CGit::GetRefList(STRING_VECTOR &list)
1067 int ret;
1068 if(this->m_IsUseGitDLL)
1070 return git_for_each_ref_in("",addto_list_each_ref_fn, &list);
1073 else
1075 CString cmd,output;
1076 cmd=_T("git.exe show-ref -d");
1077 ret=g_Git.Run(cmd,&output,CP_UTF8);
1078 if(!ret)
1080 int pos=0;
1081 CString one;
1082 while( pos>=0 )
1084 one=output.Tokenize(_T("\n"),pos);
1085 int start=one.Find(_T(" "),0);
1086 if(start>0)
1088 CString name;
1089 name=one.Right(one.GetLength()-start-1);
1090 list.push_back(name);
1095 return ret;
1098 int addto_map_each_ref_fn(const char *refname, const unsigned char *sha1, int /*flags*/, void *cb_data)
1100 MAP_HASH_NAME *map = (MAP_HASH_NAME*)cb_data;
1101 CString str;
1102 g_Git.StringAppend(&str,(BYTE*)refname,CP_ACP);
1103 CGitHash hash((char*)sha1);
1105 (*map)[hash].push_back(str);
1107 if(strncmp(refname, "refs/tags", 9) == 0)
1109 GIT_HASH refhash;
1110 if(!git_deref_tag(sha1, refhash))
1112 (*map)[(char*)refhash].push_back(str+_T("^{}"));
1115 return 0;
1118 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1120 int ret;
1121 if(this->m_IsUseGitDLL)
1123 return git_for_each_ref_in("",addto_map_each_ref_fn, &map);
1126 else
1128 CString cmd,output;
1129 cmd=_T("git.exe show-ref -d");
1130 ret=g_Git.Run(cmd,&output,CP_UTF8);
1131 if(!ret)
1133 int pos=0;
1134 CString one;
1135 while( pos>=0 )
1137 one=output.Tokenize(_T("\n"),pos);
1138 int start=one.Find(_T(" "),0);
1139 if(start>0)
1141 CString name;
1142 name=one.Right(one.GetLength()-start-1);
1144 CString hash;
1145 hash=one.Left(start);
1147 map[CGitHash(hash)].push_back(name);
1152 return ret;
1155 BOOL CGit::CheckMsysGitDir()
1157 if (m_bInitialized)
1159 return TRUE;
1162 this->m_Environment.clear();
1163 m_Environment.CopyProcessEnvironment();
1165 TCHAR *oldpath,*home;
1166 size_t homesize,size,httpsize;
1168 // set HOME if not set already
1169 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1170 if (!homesize)
1172 if ( (!_tdupenv_s(&home,&size,_T("USERPROFILE"))) && (home != NULL) )
1174 m_Environment.SetEnv(_T("HOME"),home);
1175 free(home);
1177 else
1179 ATLTRACE("CGit::CheckMsysGitDir Unable to SetEnv HOME\n");
1182 CString str;
1184 //setup ssh client
1185 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1187 if(!sshclient.IsEmpty())
1189 m_Environment.SetEnv(_T("GIT_SSH"),sshclient.GetBuffer());
1191 //Setup SVN_SSH
1192 CString ssh=sshclient;
1193 ssh.Replace(_T("/"),_T("\\"));
1194 ssh.Replace(_T("\\"),_T("\\\\"));
1195 ssh=CString(_T("\""))+ssh+_T('\"');
1196 m_Environment.SetEnv(_T("SVN_SSH"),ssh.GetBuffer());
1199 else
1201 TCHAR sPlink[MAX_PATH];
1202 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1203 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1204 if (ptr) {
1205 _tcscpy(ptr + 1, _T("TortoisePlink.exe"));
1206 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1208 //Setup SVN_SSH
1209 CString ssh=sPlink;
1210 ssh.Replace(_T("/"),_T("\\"));
1211 ssh.Replace(_T("\\"),_T("\\\\"));
1212 ssh=CString(_T("\""))+ssh+_T('\"');
1213 m_Environment.SetEnv(_T("SVN_SSH"),ssh.GetBuffer());
1218 TCHAR sAskPass[MAX_PATH];
1219 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1220 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1221 if (ptr)
1223 _tcscpy(ptr + 1, _T("SshAskPass.exe"));
1224 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1225 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1226 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1230 // add git/bin path to PATH
1232 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1233 str=msysdir;
1234 if(str.IsEmpty())
1236 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);
1237 str=msysinstalldir;
1238 if ( !str.IsEmpty() )
1240 str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";
1241 msysdir=str;
1242 CGit::ms_LastMsysGitDir = str;
1243 msysdir.write();
1245 else
1247 // search PATH if git/bin directory is already present
1248 if ( FindGitPath() )
1250 m_bInitialized = TRUE;
1251 return TRUE;
1254 return FALSE;
1257 else
1259 CGit::ms_LastMsysGitDir = str;
1262 // check for git.exe existance (maybe it was deinstalled in the meantime)
1263 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1264 return FALSE;
1266 //set path
1267 _tdupenv_s(&oldpath,&size,_T("PATH"));
1269 CString path;
1270 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1272 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1274 CString str1 = m_Environment.GetEnv(_T("PATH"));
1276 CString sOldPath = oldpath;
1277 free(oldpath);
1279 m_bInitialized = TRUE;
1280 return true;
1283 class CGitCall_EnumFiles : public CGitCall
1285 public:
1286 CGitCall_EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)
1287 : m_pszProjectPath(pszProjectPath),
1288 m_pszSubPath(pszSubPath),
1289 m_nFlags(nFlags),
1290 m_pEnumCb(pEnumCb),
1291 m_pUserData(pUserData)
1295 typedef std::map<CStringA,char> TStrCharMap;
1297 const TCHAR * m_pszProjectPath;
1298 const TCHAR * m_pszSubPath;
1299 unsigned int m_nFlags;
1300 WGENUMFILECB * m_pEnumCb;
1301 void * m_pUserData;
1303 BYTE_VECTOR m_DataCollector;
1305 virtual bool OnOutputData(const BYTE* data, size_t size)
1307 m_DataCollector.append(data,size);
1308 while(true)
1310 // lines from igit.exe are 0 terminated
1311 int found=m_DataCollector.findData((const BYTE*)"",1);
1312 if(found<0)
1313 return false;
1314 OnSingleLine( (LPCSTR)&*m_DataCollector.begin() );
1315 m_DataCollector.erase(m_DataCollector.begin(), m_DataCollector.begin()+found+1);
1317 return false;//Should never reach this
1319 virtual void OnEnd()
1323 BYTE HexChar(char ch)
1325 if (ch >= '0' && ch <= '9')
1326 return (UINT)(ch - '0');
1327 else if (ch >= 'A' && ch <= 'F')
1328 return (UINT)(ch - 'A') + 10;
1329 else if (ch >= 'a' && ch <= 'f')
1330 return (UINT)(ch - 'a') + 10;
1331 else
1332 return 0;
1335 bool OnSingleLine(LPCSTR line)
1337 //Parse single line
1339 wgFile_s fileStatus;
1341 // file/dir type
1343 fileStatus.nFlags = 0;
1344 if (*line == 'D')
1345 fileStatus.nFlags |= WGFF_Directory;
1346 else if (*line != 'F')
1347 // parse error
1348 return false;
1349 line += 2;
1351 // status
1353 fileStatus.nStatus = WGFS_Unknown;
1354 switch (*line)
1356 case 'N': fileStatus.nStatus = WGFS_Normal; break;
1357 case 'M': fileStatus.nStatus = WGFS_Modified; break;
1358 case 'S': fileStatus.nStatus = WGFS_Staged; break;
1359 case 'A': fileStatus.nStatus = WGFS_Added; break;
1360 case 'C': fileStatus.nStatus = WGFS_Conflicted; break;
1361 case 'D': fileStatus.nStatus = WGFS_Deleted; break;
1362 case 'I': fileStatus.nStatus = WGFS_Ignored; break;
1363 case 'U': fileStatus.nStatus = WGFS_Unversioned; break;
1364 case 'E': fileStatus.nStatus = WGFS_Empty; break;
1365 case '?': fileStatus.nStatus = WGFS_Unknown; break;
1366 default:
1367 // parse error
1368 return false;
1370 line += 2;
1372 // file sha1
1374 BYTE sha1[20];
1375 fileStatus.sha1 = NULL;
1376 if ( !(fileStatus.nFlags & WGFF_Directory) )
1378 for (int i=0; i<20; i++)
1380 sha1[i] = (HexChar(line[0])<<4)&0xF0;
1381 sha1[i] |= HexChar(line[1])&0xF;
1383 line += 2;
1386 line++;
1389 // filename
1390 int len = strlen(line);
1391 if (len && len < 2048)
1393 WCHAR *buf = (WCHAR*)alloca((len*4+2)*sizeof(WCHAR));
1394 *buf = 0;
1395 MultiByteToWideChar(CP_ACP, 0, line, len+1, buf, len*4+1);
1396 fileStatus.sFileName = buf;
1398 if (*buf && (*m_pEnumCb)(&fileStatus,m_pUserData))
1399 return false;
1402 return true;
1406 BOOL CGit::EnumFiles(const TCHAR *pszProjectPath, const TCHAR *pszSubPath, unsigned int nFlags, WGENUMFILECB *pEnumCb, void *pUserData)
1408 if(!pszProjectPath || *pszProjectPath=='\0')
1409 return FALSE;
1411 CGitCall_EnumFiles W_GitCall(pszProjectPath,pszSubPath,nFlags,pEnumCb,pUserData);
1412 CString cmd;
1414 /* char W_szToDir[MAX_PATH];
1415 strncpy(W_szToDir,pszProjectPath,sizeof(W_szToDir)-1);
1416 if(W_szToDir[strlen(W_szToDir)-1]!='\\')
1417 strncat(W_szToDir,"\\",sizeof(W_szToDir)-1);
1419 SetCurrentDirectoryA(W_szToDir);
1420 GetCurrentDirectoryA(sizeof(W_szToDir)-1,W_szToDir);
1422 SetCurrentDir(pszProjectPath);
1424 CString sMode;
1425 if (nFlags)
1427 if (nFlags & WGEFF_NoRecurse) sMode += _T("r");
1428 if (nFlags & WGEFF_FullPath) sMode += _T("f");
1429 if (nFlags & WGEFF_DirStatusDelta) sMode += _T("d");
1430 if (nFlags & WGEFF_DirStatusAll) sMode += _T("D");
1431 if (nFlags & WGEFF_EmptyAsNormal) sMode += _T("e");
1432 if (nFlags & WGEFF_SingleFile) sMode += _T("s");
1434 else
1436 sMode = _T("-");
1439 // NOTE: there seems to be some issue with msys based app receiving backslash on commandline, at least
1440 // if followed by " like for example 'igit "C:\"', the commandline igit receives is 'igit.exe C:" status' with
1441 // the 'C:" status' part as a single arg, Maybe it uses unix style processing. In order to avoid this just
1442 // use forward slashes for supplied project and sub paths
1444 CString sProjectPath = pszProjectPath;
1445 sProjectPath.Replace(_T('\\'), _T('/'));
1447 if (pszSubPath)
1449 CString sSubPath = pszSubPath;
1450 sSubPath.Replace(_T('\\'), _T('/'));
1452 cmd.Format(_T("tgit.exe statusex \"%s\" status %s \"%s\""), sProjectPath, sMode, sSubPath);
1454 else
1456 cmd.Format(_T("tgit.exe statusex \"%s\" status %s"), sProjectPath, sMode);
1459 //OutputDebugStringA("---");OutputDebugStringW(cmd);OutputDebugStringA("\r\n");
1461 W_GitCall.SetCmd(cmd);
1462 // NOTE: should igit get added as a part of msysgit then use below line instead of the above one
1463 //W_GitCall.SetCmd(CGit::ms_LastMsysGitDir + cmd);
1465 if ( Run(&W_GitCall) )
1466 return FALSE;
1468 return TRUE;
1471 BOOL CGit::CheckCleanWorkTree()
1473 CString out;
1474 CString cmd;
1475 cmd=_T("git.exe rev-parse --verify HEAD");
1477 if(g_Git.Run(cmd,&out,CP_UTF8))
1478 return FALSE;
1480 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1481 if(g_Git.Run(cmd,&out,CP_UTF8))
1482 return FALSE;
1484 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1485 if(g_Git.Run(cmd,&out,CP_UTF8))
1486 return FALSE;
1488 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1489 if(g_Git.Run(cmd,&out,CP_UTF8))
1490 return FALSE;
1492 return TRUE;
1494 int CGit::Revert(CString commit, CTGitPathList &list,bool keep)
1496 int ret;
1497 for(int i=0;i<list.GetCount();i++)
1499 ret = Revert(commit, (CTGitPath&)list[i]);
1500 if(ret)
1501 return ret;
1503 return 0;
1505 int CGit::Revert(CString commit, CTGitPath &path)
1507 CString cmd, out;
1509 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1511 cmd.Format(_T("git.exe mv -- \"%s\" \"%s\""),path.GetGitPathString(),path.GetGitOldPathString());
1512 if(g_Git.Run(cmd,&out,CP_ACP))
1513 return -1;
1515 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1516 if(g_Git.Run(cmd,&out,CP_ACP))
1517 return -1;
1520 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1521 { //To init git repository, there are not HEAD, so we can use git reset command
1522 cmd.Format(_T("git.exe rm --cached -- \"%s\""),path.GetGitPathString());
1524 if(g_Git.Run(cmd,&out,CP_ACP))
1525 return -1;
1527 else
1529 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1530 if(g_Git.Run(cmd,&out,CP_ACP))
1531 return -1;
1533 return 0;
1536 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1538 BYTE_VECTOR vector;
1540 CString cmd;
1541 if(path)
1542 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1543 else
1544 cmd=_T("git.exe ls-files -u -t -z");
1546 if(g_Git.Run(cmd,&vector))
1548 return -1;
1551 list.ParserFromLsFile(vector);
1553 return 0;
1556 bool CGit::IsFastForward(const CString &from, const CString &to)
1558 CString base;
1559 CGitHash basehash,hash;
1560 CString cmd;
1561 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1563 if(g_Git.Run(cmd,&base,CP_ACP))
1565 //CMessageBox::Show(NULL,base,_T("TortoiseGit"),MB_OK|MB_ICONERROR);
1566 return false;
1568 basehash = base;
1570 hash=g_Git.GetHash(from);
1572 return hash == basehash;
1575 unsigned int CGit::Hash2int(CGitHash &hash)
1577 int ret=0;
1578 for(int i=0;i<4;i++)
1580 ret = ret << 8;
1581 ret |= hash.m_hash[i];
1583 return ret;
1586 int CGit::RefreshGitIndex()
1588 if(g_Git.m_IsUseGitDLL)
1592 return git_run_cmd("update-index","update-index -q --refresh");
1594 }catch(...)
1596 return -1;
1600 else
1602 CString cmd,output;
1603 cmd=_T("git.exe update-index --refresh");
1604 return Run(cmd,&output,CP_ACP);
1608 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1610 if(g_Git.m_IsUseGitDLL)
1614 g_Git.CheckAndInitDll();
1615 CStringA ref, patha, outa;
1616 ref = CUnicodeUtils::GetMulti(Refname,CP_ACP);
1617 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_ACP);
1618 outa = CUnicodeUtils::GetMulti(outputfile,CP_ACP);
1619 ::DeleteFile(outputfile);
1620 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1622 }catch(...)
1624 return -1;
1627 else
1629 CString cmd;
1630 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1631 return g_Git.RunLogFile(cmd,outputfile);
1634 void CEnvironment::CopyProcessEnvironment()
1636 TCHAR *p = GetEnvironmentStrings();
1637 while(*p !=0 || *(p+1) !=0)
1638 this->push_back(*p++);
1640 push_back(_T('\0'));
1641 push_back(_T('\0'));
1644 CString CEnvironment::GetEnv(TCHAR *name)
1646 CString str;
1647 for(int i=0;i<size();i++)
1649 str = &(*this)[i];
1650 int start =0;
1651 CString sname = str.Tokenize(_T("="),start);
1652 if(sname.CompareNoCase(name) == 0)
1654 return &(*this)[i+start+1];
1656 i+=str.GetLength();
1658 return _T("");
1661 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
1663 unsigned int i;
1664 for( i=0;i<size();i++)
1666 CString str = &(*this)[i];
1667 int start =0;
1668 CString sname = str.Tokenize(_T("="),start);
1669 if(sname.CompareNoCase(name) == 0)
1671 break;
1673 i+=str.GetLength();
1676 if(i == size())
1678 i -= 1; // roll back terminate \0\0
1679 this->push_back(_T('\0'));
1682 CEnvironment::iterator it;
1683 it=this->begin();
1684 it += i;
1686 while(*it && i<size())
1688 this->erase(it);
1689 it=this->begin();
1690 it += i;
1693 while(*name)
1695 this->insert(it,*name++);
1696 i++;
1697 it= begin()+i;
1700 this->insert(it, _T('='));
1701 i++;
1702 it= begin()+i;
1704 while(*value)
1706 this->insert(it,*value++);
1707 i++;
1708 it= begin()+i;
1713 int CGit::GetGitEncode(TCHAR* configkey)
1715 CString str=GetConfigValue(configkey);
1717 if(str.IsEmpty())
1718 return CP_UTF8;
1720 return CUnicodeUtils::GetCPCode(str);
1724 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
1726 GIT_FILE file=0;
1727 int ret=0;
1728 GIT_DIFF diff=0;
1730 CAutoLocker lock(g_Git.m_critGitDllSec);
1732 if(arg == NULL)
1733 diff = GetGitDiff();
1734 else
1735 git_open_diff(&diff, arg);
1737 if(diff ==NULL)
1738 return -1;
1740 bool isStat = 0;
1741 if(arg == NULL)
1742 isStat = true;
1743 else
1744 isStat = !!strstr(arg, "stat");
1746 int count=0;
1748 if(hash2 == NULL)
1749 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
1750 else
1751 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
1753 if(ret)
1754 return -1;
1756 CTGitPath path;
1757 CString strnewname;
1758 CString stroldname;
1760 for(int j=0;j<count;j++)
1762 path.Reset();
1763 char *newname;
1764 char *oldname;
1766 strnewname.Empty();
1767 stroldname.Empty();
1769 int mode=0,IsBin=0,inc=0,dec=0;
1770 git_get_diff_file(diff,file,j,&newname,&oldname,
1771 &mode,&IsBin,&inc,&dec);
1773 StringAppend(&strnewname,(BYTE*)newname,CP_ACP);
1774 StringAppend(&stroldname,(BYTE*)oldname,CP_ACP);
1776 path.SetFromGit(strnewname,&stroldname);
1777 path.ParserAction((BYTE)mode);
1779 if(IsBin)
1781 path.m_StatAdd=_T("-");
1782 path.m_StatDel=_T("-");
1784 else
1786 path.m_StatAdd.Format(_T("%d"),inc);
1787 path.m_StatDel.Format(_T("%d"),dec);
1789 PathList->AddPath(path);
1791 git_diff_flush(diff);
1793 if(arg)
1794 git_close_diff(diff);
1796 return 0;