Fixed issue #1294: TortoiseGit might crash on concurrent access on CGitHeadFileList
[TortoiseGit.git] / src / Git / Git.cpp
blobd42bc3e33c076654b72c10b96d02bebd4c183b3a
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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>
30 #include "git2.h"
32 int CGit::m_LogEncode=CP_UTF8;
33 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
35 static LPTSTR nextpath(LPCTSTR src, LPTSTR dst, UINT maxlen)
37 LPCTSTR orgsrc;
39 while (*src == _T(';'))
40 src++;
42 orgsrc = src;
44 if (!--maxlen)
45 goto nullterm;
47 while (*src && *src != _T(';'))
49 if (*src != _T('"'))
51 *dst++ = *src++;
52 if (!--maxlen)
54 orgsrc = src;
55 goto nullterm;
58 else
60 src++;
61 while (*src && *src != _T('"'))
63 *dst++ = *src++;
64 if (!--maxlen)
66 orgsrc = src;
67 goto nullterm;
71 if (*src)
72 src++;
76 while (*src == _T(';'))
77 src++;
79 nullterm:
81 *dst = 0;
83 return (orgsrc != src) ? (LPTSTR)src : NULL;
86 static inline BOOL FileExists(LPCTSTR lpszFileName)
88 struct _stat st;
89 return _tstat(lpszFileName, &st) == 0;
92 static BOOL FindGitPath()
94 size_t size;
95 _tgetenv_s(&size, NULL, 0, _T("PATH"));
97 if (!size)
99 return FALSE;
102 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
103 _tgetenv_s(&size, env, size, _T("PATH"));
105 TCHAR buf[_MAX_PATH];
107 // search in all paths defined in PATH
108 while ((env = nextpath(env, buf, _MAX_PATH-1)) && *buf)
110 TCHAR *pfin = buf + _tcslen(buf)-1;
112 // ensure trailing slash
113 if (*pfin != _T('/') && *pfin != _T('\\'))
114 _tcscpy(++pfin, _T("\\"));
116 const int len = _tcslen(buf);
118 if ((len + 7) < _MAX_PATH)
119 _tcscpy(pfin+1, _T("git.exe"));
120 else
121 break;
123 if ( FileExists(buf) )
125 // dir found
126 pfin[1] = 0;
127 CGit::ms_LastMsysGitDir = buf;
128 return TRUE;
132 return FALSE;
136 #define MAX_DIRBUFFER 1000
137 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
139 CString CGit::ms_LastMsysGitDir;
140 CGit g_Git;
143 CGit::CGit(void)
145 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
146 m_CurrentDir.ReleaseBuffer();
147 m_IsGitDllInited = false;
148 m_GitDiff=0;
149 m_GitSimpleListDiff=0;
150 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
151 this->m_bInitialized =false;
152 CheckMsysGitDir();
153 m_critGitDllSec.Init();
156 CGit::~CGit(void)
158 if(this->m_GitDiff)
160 git_close_diff(m_GitDiff);
161 m_GitDiff=0;
163 if(this->m_GitSimpleListDiff)
165 git_close_diff(m_GitSimpleListDiff);
166 m_GitSimpleListDiff=0;
170 bool CGit::IsBranchNameValid(CString branchname)
172 if (branchname.IsEmpty())
173 return false;
175 for(int i=0; i < branchname.GetLength(); i++)
177 TCHAR c = branchname.GetAt(i);
178 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
179 return false;
182 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
183 return false;
185 CString reverseBranchname = branchname.MakeReverse();
186 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
187 return false;
189 return true;
192 static char g_Buffer[4096];
194 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
196 SECURITY_ATTRIBUTES sa;
197 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
198 HANDLE hStdioFile = NULL;
200 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
201 sa.lpSecurityDescriptor=NULL;
202 sa.bInheritHandle=TRUE;
203 if(!CreatePipe(&hRead,&hWrite,&sa,0))
205 return TGIT_GIT_ERROR_OPEN_PIP;
207 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
208 return TGIT_GIT_ERROR_OPEN_PIP;
210 if(StdioFile)
212 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
213 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
216 STARTUPINFO si;
217 PROCESS_INFORMATION pi;
218 si.cb=sizeof(STARTUPINFO);
219 GetStartupInfo(&si);
221 if (hErrReadOut)
222 si.hStdError = hWriteErr;
223 else
224 si.hStdError = hWrite;
225 if(StdioFile)
226 si.hStdOutput=hStdioFile;
227 else
228 si.hStdOutput=hWrite;
230 si.wShowWindow=SW_HIDE;
231 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
233 LPTSTR pEnv = m_Environment.size()? &m_Environment[0]: NULL;
234 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
236 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
237 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
239 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
240 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
242 if(cmd.Find(_T("git")) == 0)
244 int firstSpace = cmd.Find(_T(" "));
245 if (firstSpace > 0)
246 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
247 else
248 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
251 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
253 LPVOID lpMsgBuf;
254 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
255 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
256 (LPTSTR)&lpMsgBuf,
257 0,NULL);
258 return TGIT_GIT_ERROR_CREATE_PROCESS;
261 m_CurrentGitPi = pi;
263 CloseHandle(hWrite);
264 if (hErrReadOut)
265 CloseHandle(hWriteErr);
266 if(piOut)
267 *piOut=pi;
268 if(hReadOut)
269 *hReadOut=hRead;
270 if(hErrReadOut)
271 *hErrReadOut = hReadErr;
272 return 0;
275 //Must use sperate function to convert ANSI str to union code string
276 //Becuase A2W use stack as internal convert buffer.
277 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
279 //USES_CONVERSION;
280 //str->Append(A2W_CP((LPCSTR)p,code));
281 if(str == NULL)
282 return ;
284 WCHAR * buf;
286 int len ;
287 if(length<0)
288 len= strlen((const char*)p);
289 else
290 len=length;
291 //if (len==0)
292 // return ;
293 //buf = new WCHAR[len*4 + 1];
294 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
295 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
296 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
297 str->ReleaseBuffer();
298 //str->Append(buf);
299 //delete buf;
301 BOOL CGit::IsInitRepos()
303 CString cmdout;
304 cmdout.Empty();
305 if(g_Git.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout,CP_UTF8))
307 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
308 return TRUE;
310 if(cmdout.IsEmpty())
311 return TRUE;
313 return FALSE;
316 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
318 PASYNCREADSTDERRTHREADARGS pDataArray;
319 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
321 DWORD readnumber;
322 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
323 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
325 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
326 break;
329 return 0;
332 int CGit::Run(CGitCall* pcall)
334 PROCESS_INFORMATION pi;
335 HANDLE hRead, hReadErr;
336 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
337 return TGIT_GIT_ERROR_CREATE_PROCESS;
339 HANDLE thread;
340 ASYNCREADSTDERRTHREADARGS threadArguments;
341 threadArguments.fileHandle = hReadErr;
342 threadArguments.pcall = pcall;
343 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
345 DWORD readnumber;
346 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
347 bool bAborted=false;
348 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
350 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
351 if(!bAborted)//For now, flush output when command aborted.
352 if(pcall->OnOutputData(data,readnumber))
353 bAborted=true;
355 if(!bAborted)
356 pcall->OnEnd();
358 if (thread)
359 WaitForSingleObject(thread, INFINITE);
361 CloseHandle(pi.hThread);
363 WaitForSingleObject(pi.hProcess, INFINITE);
364 DWORD exitcode =0;
366 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
368 return TGIT_GIT_ERROR_GET_EXIT_CODE;
371 CloseHandle(pi.hProcess);
373 CloseHandle(hRead);
374 CloseHandle(hReadErr);
375 return exitcode;
377 class CGitCall_ByteVector : public CGitCall
379 public:
380 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
381 virtual bool OnOutputData(const BYTE* data, size_t size)
383 if (size == 0)
384 return false;
385 size_t oldsize=m_pvector->size();
386 m_pvector->resize(m_pvector->size()+size);
387 memcpy(&*(m_pvector->begin()+oldsize),data,size);
388 return false;
390 virtual bool OnOutputErrData(const BYTE* data, size_t size)
392 if (!m_pvectorErr || size == 0)
393 return false;
394 size_t oldsize = m_pvectorErr->size();
395 m_pvectorErr->resize(m_pvectorErr->size() + size);
396 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
397 return false;
399 BYTE_VECTOR* m_pvector;
400 BYTE_VECTOR* m_pvectorErr;
403 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
405 CGitCall_ByteVector call(cmd, vector, vectorErr);
406 return Run(&call);
408 int CGit::Run(CString cmd, CString* output, int code)
410 CString err;
411 int ret;
412 ret = Run(cmd, output, &err, code);
414 if (output && !err.IsEmpty())
416 if (!output->IsEmpty())
417 *output += _T("\n");
418 *output += err;
421 return ret;
423 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
425 BYTE_VECTOR vector, vectorErr;
426 int ret;
427 if (outputErr)
428 ret = Run(cmd, &vector, &vectorErr);
429 else
430 ret = Run(cmd, &vector);
432 vector.push_back(0);
433 StringAppend(output, &(vector[0]), code);
435 if (outputErr)
437 vectorErr.push_back(0);
438 StringAppend(outputErr, &(vectorErr[0]), code);
441 return ret;
444 CString CGit::GetUserName(void)
446 CEnvironment env;
447 env.CopyProcessEnvironment();
448 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
449 if (!envname.IsEmpty())
450 return envname;
451 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
453 CString CGit::GetUserEmail(void)
455 CEnvironment env;
456 env.CopyProcessEnvironment();
457 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
458 if (!envmail.IsEmpty())
459 return envmail;
461 return GetConfigValue(L"user.email");
464 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
466 CString configValue;
467 int start = 0;
468 if(this->m_IsUseGitDLL)
470 CString *git_path=NULL;
472 CAutoLocker lock(g_Git.m_critGitDllSec);
476 CTGitPath path;
478 CheckAndInitDll();
479 git_path = GitPath;
481 }catch(...)
484 CStringA key, value;
485 key = CUnicodeUtils::GetMulti(name, encoding);
486 CStringA p;
487 if(git_path)
488 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
490 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
491 return CString();
492 else
494 g_Git.StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
495 if(RemoveCR)
496 return configValue.Tokenize(_T("\n"),start);
497 return configValue;
501 else
503 CString cmd;
504 cmd.Format(L"git.exe config %s", name);
505 Run(cmd, &configValue, NULL, encoding);
506 if(RemoveCR)
507 return configValue.Tokenize(_T("\n"),start);
508 return configValue;
512 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
514 if(this->m_IsUseGitDLL)
516 CAutoLocker lock(g_Git.m_critGitDllSec);
520 CheckAndInitDll();
522 }catch(...)
525 CStringA keya, valuea;
526 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
527 valuea = CUnicodeUtils::GetMulti(value, encoding);
528 CStringA p;
529 if(GitPath)
530 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
532 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
535 else
537 CString cmd;
538 CString option;
539 switch(type)
541 case CONFIG_GLOBAL:
542 option = _T("--global");
543 break;
544 case CONFIG_SYSTEM:
545 option = _T("--system");
546 break;
547 default:
548 break;
550 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
551 CString out;
552 if (Run(cmd, &out, NULL, encoding))
554 return -1;
557 return 0;
560 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
562 if(this->m_IsUseGitDLL)
564 CAutoLocker lock(g_Git.m_critGitDllSec);
568 CheckAndInitDll();
569 }catch(...)
572 CStringA keya;
573 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
574 CStringA p;
575 if(GitPath)
576 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
578 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
580 else
582 CString cmd;
583 CString option;
584 switch(type)
586 case CONFIG_GLOBAL:
587 option = _T("--global");
588 break;
589 case CONFIG_SYSTEM:
590 option = _T("--system");
591 break;
592 default:
593 break;
595 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
596 CString out;
597 if (Run(cmd, &out, NULL, encoding))
599 return -1;
602 return 0;
605 CString CGit::GetCurrentBranch(void)
607 CString output;
608 //Run(_T("git.exe branch"),&branch);
610 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
612 return _T("(no branch)");
614 else
615 return output;
619 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
621 CString refName;
622 if(this->m_IsUseGitDLL)
624 unsigned char sha1[20];
625 int flag;
627 CAutoLocker lock(g_Git.m_critGitDllSec);
628 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
629 if(refs_heads_master && (flag&REF_ISSYMREF))
631 g_Git.StringAppend(&refName,(BYTE*)refs_heads_master);
632 if(bStripRefsHeads)
633 refName = StripRefName(refName);
637 else
639 CString cmd;
640 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
641 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
642 return CString();//Error
643 int iStart = 0;
644 refName = refName.Tokenize(L"\n", iStart);
645 if(bStripRefsHeads)
646 refName = StripRefName(refName);
648 return refName;
651 CString CGit::GetFullRefName(CString shortRefName)
653 CString refName;
654 CString cmd;
655 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
656 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
657 return CString();//Error
658 int iStart = 0;
659 return refName.Tokenize(L"\n", iStart);
662 CString CGit::StripRefName(CString refName)
664 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
665 refName = refName.Mid(11);
666 else if(wcsncmp(refName, L"refs/", 5) == 0)
667 refName = refName.Mid(5);
668 int start =0;
669 return refName.Tokenize(_T("\n"),start);
672 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
674 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
676 if ( sProjectRoot.IsEmpty() )
677 return -1;
679 CString sDotGitPath;
680 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
681 return -1;
683 CString sHeadFile = sDotGitPath + _T("HEAD");
685 FILE *pFile;
686 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
688 if (!pFile)
690 return -1;
693 char s[256] = {0};
694 fgets(s, sizeof(s), pFile);
696 fclose(pFile);
698 const char *pfx = "ref: refs/heads/";
699 const int len = 16;//strlen(pfx)
701 if ( !strncmp(s, pfx, len) )
703 //# We're on a branch. It might not exist. But
704 //# HEAD looks good enough to be a branch.
705 CStringA utf8Branch(s + len);
706 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
707 sBranchOut.TrimRight(_T(" \r\n\t"));
709 if ( sBranchOut.IsEmpty() )
710 return -1;
712 else
714 //# Assume this is a detached head.
715 sBranchOut = "HEAD";
717 return 1;
720 return 0;
723 int CGit::BuildOutputFormat(CString &format,bool IsFull)
725 CString log;
726 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
727 format += log;
728 if(IsFull)
730 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
731 format += log;
732 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
733 format += log;
734 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
735 format += log;
736 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
737 format += log;
738 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
739 format += log;
740 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
741 format += log;
742 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
743 format += log;
746 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
747 format += log;
748 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
749 format += log;
750 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
751 format += log;
753 if(IsFull)
755 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
756 format += log;
758 return 0;
761 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
763 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
764 return GetLog(&gitCall,hash,path,count,mask,from,to);
767 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
768 CFilterData *Filter)
770 CString cmd;
771 CString num;
772 CString since;
774 CString file;
776 if(path)
777 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
779 if(count>0)
780 num.Format(_T("-n%d"),count);
782 CString param;
784 if(mask& LOG_INFO_STAT )
785 param += _T(" --numstat ");
786 if(mask& LOG_INFO_FILESTATE)
787 param += _T(" --raw ");
789 if(mask& LOG_INFO_FULLHISTORY)
790 param += _T(" --full-history ");
792 if(mask& LOG_INFO_BOUNDARY)
793 param += _T(" --left-right --boundary ");
795 if(mask& CGit::LOG_INFO_ALL_BRANCH)
796 param += _T(" --all ");
798 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
799 param += _T(" -C ");
801 if(mask& CGit::LOG_INFO_DETECT_RENAME )
802 param += _T(" -M ");
804 if(mask& CGit::LOG_INFO_FIRST_PARENT )
805 param += _T(" --first-parent ");
807 if(mask& CGit::LOG_INFO_NO_MERGE )
808 param += _T(" --no-merges ");
810 if(mask& CGit::LOG_INFO_FOLLOW)
811 param += _T(" --follow ");
813 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
814 param += _T(" -c ");
816 if(mask& CGit::LOG_INFO_FULL_DIFF)
817 param += _T(" --full-diff ");
819 if(from != NULL && to != NULL)
821 CString range;
822 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
823 param += range;
825 else if(to != NULL && hash.IsEmpty())
827 CString range;
828 range.Format(_T(" %s "), FixBranchName(*to));
829 param += range;
831 param+=hash;
833 CString st1,st2;
835 if( Filter && (Filter->m_From != -1))
837 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
838 param += st1;
841 if( Filter && (Filter->m_To != -1))
843 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
844 param += st2;
847 bool isgrep = false;
848 if( Filter && (!Filter->m_Author.IsEmpty()))
850 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
851 param += st1;
852 isgrep = true;
855 if( Filter && (!Filter->m_Committer.IsEmpty()))
857 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
858 param += st1;
859 isgrep = true;
862 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
864 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
865 param += st1;
866 isgrep = true;
869 if(Filter && isgrep)
871 if(!Filter->m_IsRegex)
872 param += _T(" --fixed-strings ");
874 param += _T(" --regexp-ignore-case --extended-regexp ");
877 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
878 param += _T(" --topo-order");
880 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
881 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
882 else
884 CString log;
885 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
886 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
887 num,param,log);
890 cmd += file;
892 return cmd;
894 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
895 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
897 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
899 return Run(pgitCall);
900 // return Run(cmd,&logOut);
903 #define BUFSIZE 512
904 void GetTempPath(CString &path)
906 TCHAR lpPathBuffer[BUFSIZE];
907 DWORD dwRetVal;
908 DWORD dwBufSize=BUFSIZE;
909 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
910 lpPathBuffer); // buffer for path
911 if (dwRetVal > dwBufSize || (dwRetVal == 0))
913 path=_T("");
915 path.Format(_T("%s"),lpPathBuffer);
917 CString GetTempFile()
919 TCHAR lpPathBuffer[BUFSIZE];
920 DWORD dwRetVal;
921 DWORD dwBufSize=BUFSIZE;
922 TCHAR szTempName[BUFSIZE];
923 UINT uRetVal;
925 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
926 lpPathBuffer); // buffer for path
927 if (dwRetVal > dwBufSize || (dwRetVal == 0))
929 return _T("");
931 // Create a temporary file.
932 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
933 TEXT("Patch"), // temp file name prefix
934 0, // create unique name
935 szTempName); // buffer for name
938 if (uRetVal == 0)
940 return _T("");
943 return CString(szTempName);
947 int CGit::RunLogFile(CString cmd,const CString &filename)
949 STARTUPINFO si;
950 PROCESS_INFORMATION pi;
951 si.cb=sizeof(STARTUPINFO);
952 GetStartupInfo(&si);
954 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
955 psa.bInheritHandle=TRUE;
957 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
958 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
960 si.wShowWindow = SW_HIDE;
961 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
962 si.hStdOutput = houtfile;
964 LPTSTR pEnv = m_Environment.size()? &m_Environment[0]: NULL;
965 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
967 if(cmd.Find(_T("git")) == 0)
968 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
970 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
972 LPVOID lpMsgBuf;
973 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
974 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
975 (LPTSTR)&lpMsgBuf,
976 0,NULL);
977 return TGIT_GIT_ERROR_CREATE_PROCESS;
980 WaitForSingleObject(pi.hProcess,INFINITE);
982 CloseHandle(pi.hThread);
983 CloseHandle(pi.hProcess);
984 CloseHandle(houtfile);
985 return TGIT_GIT_SUCCESS;
986 // return 0;
989 CGitHash CGit::GetHash(TCHAR* friendname)
991 if(this->m_IsUseGitDLL)
993 CAutoLocker lock(g_Git.m_critGitDllSec);
995 this->CheckAndInitDll();
997 CGitHash hash;
998 CStringA ref;
999 ref = CUnicodeUtils::GetMulti(FixBranchName(friendname), CP_UTF8);
1002 git_get_sha1(ref, hash.m_hash);
1004 }catch(...)
1007 return hash;
1010 else
1012 CString cmd;
1013 CString out;
1014 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1015 Run(cmd, &out, NULL, CP_UTF8);
1016 // int pos=out.ReverseFind(_T('\n'));
1017 out.FindOneOf(_T("\r\n"));
1018 return CGitHash(out);
1022 int CGit::GetInitAddList(CTGitPathList &outputlist)
1024 CString cmd;
1025 BYTE_VECTOR cmdout;
1027 cmd=_T("git.exe ls-files -s -t -z");
1028 outputlist.Clear();
1029 if (g_Git.Run(cmd, &cmdout))
1030 return -1;
1032 outputlist.ParserFromLsFile(cmdout);
1033 for(int i=0;i<outputlist.GetCount();i++)
1034 ((unsigned int)outputlist[i].m_Action) = CTGitPath::LOGACTIONS_ADDED;
1036 return 0;
1038 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1040 CString cmd;
1042 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1044 //rev1=+_T("");
1045 if(rev1 == GIT_REV_ZERO)
1046 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1047 else
1048 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1050 else
1052 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1055 BYTE_VECTOR out;
1056 if (g_Git.Run(cmd, &out))
1057 return -1;
1059 outputlist.ParserFromLog(out);
1061 return 0;
1064 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1066 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1067 CString str;
1068 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1069 list->push_back(str);
1070 return 0;
1073 int CGit::GetTagList(STRING_VECTOR &list)
1075 int ret;
1077 if(this->m_IsUseGitDLL)
1079 CAutoLocker lock(g_Git.m_critGitDllSec);
1080 return git_for_each_ref_in("refs/tags/",addto_list_each_ref_fn, &list);
1083 else
1085 CString cmd, output;
1086 cmd=_T("git.exe tag -l");
1087 int i=0;
1088 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1089 if(!ret)
1091 int pos=0;
1092 CString one;
1093 while( pos>=0 )
1095 i++;
1096 one=output.Tokenize(_T("\n"),pos);
1097 list.push_back(one);
1101 return ret;
1104 CString CGit::FixBranchName_Mod(CString& branchName)
1106 if(branchName == "FETCH_HEAD")
1107 branchName = DerefFetchHead();
1108 return branchName;
1111 CString CGit::FixBranchName(const CString& branchName)
1113 CString tempBranchName = branchName;
1114 FixBranchName_Mod(tempBranchName);
1115 return tempBranchName;
1118 bool CGit::IsBranchTagNameUnique(const CString& name)
1120 CString output;
1122 int ret = g_Git.Run(_T("git show-ref --tags --heads ") + name, &output, NULL, CP_UTF8);
1123 if (!ret)
1125 int i = 0, pos = 0;
1126 while (pos >= 0)
1128 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1129 i++;
1131 if (i >= 2)
1132 return false;
1135 return true;
1139 Checks if a branch or tag with the given name exists
1140 isBranch is true -> branch, tag otherwise
1142 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1144 CString cmd, output;
1146 cmd = _T("git show-ref ");
1147 if (isBranch)
1148 cmd += _T("--heads ");
1149 else
1150 cmd += _T("--tags ");
1152 int ret = g_Git.Run(cmd + name, &output, NULL, CP_UTF8);
1153 if (!ret)
1155 if (!output.IsEmpty())
1156 return true;
1159 return false;
1162 CString CGit::DerefFetchHead()
1164 using namespace std;
1165 CString dotGitPath;
1166 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1167 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1168 int forMergeLineCount = 0;
1169 string line;
1170 string hashToReturn;
1171 while(getline(fetchHeadFile, line))
1173 //Tokenize this line
1174 string::size_type prevPos = 0;
1175 string::size_type pos = line.find('\t');
1176 if(pos == string::npos) continue; //invalid line
1178 string hash = line.substr(0, pos);
1179 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1181 bool forMerge = pos == prevPos;
1182 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1184 string remoteBranch = line.substr(prevPos, pos - prevPos);
1186 //Process this line
1187 if(forMerge)
1189 hashToReturn = hash;
1190 ++forMergeLineCount;
1191 if(forMergeLineCount > 1)
1192 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1196 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1199 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1201 int ret;
1202 CString cmd, output;
1203 cmd = _T("git.exe branch --no-color");
1205 if((type&BRANCH_ALL) == BRANCH_ALL)
1206 cmd += _T(" -a");
1207 else if(type&BRANCH_REMOTE)
1208 cmd += _T(" -r");
1210 int i=0;
1211 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1212 if(!ret)
1214 int pos=0;
1215 CString one;
1216 while( pos>=0 )
1218 one=output.Tokenize(_T("\n"),pos);
1219 one.Trim(L" \r\n\t");
1220 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1221 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1222 if(one[0] == _T('*'))
1224 if(current)
1225 *current=i;
1226 one = one.Mid(2);
1228 if (one != _T("(no branch)"))
1229 list.push_back(one);
1230 i++;
1234 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1235 list.push_back(L"FETCH_HEAD");
1237 return ret;
1240 int CGit::GetRemoteList(STRING_VECTOR &list)
1242 int ret;
1243 CString cmd, output;
1244 cmd=_T("git.exe remote");
1245 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1246 if(!ret)
1248 int pos=0;
1249 CString one;
1250 while( pos>=0 )
1252 one=output.Tokenize(_T("\n"),pos);
1253 if (!one.IsEmpty())
1254 list.push_back(one);
1257 return ret;
1260 int CGit::GetRefList(STRING_VECTOR &list)
1262 int ret;
1263 if(this->m_IsUseGitDLL)
1265 CAutoLocker lock(g_Git.m_critGitDllSec);
1266 return git_for_each_ref_in("",addto_list_each_ref_fn, &list);
1269 else
1271 CString cmd, output;
1272 cmd=_T("git.exe show-ref -d");
1273 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1274 if(!ret)
1276 int pos=0;
1277 CString one;
1278 while( pos>=0 )
1280 one=output.Tokenize(_T("\n"),pos);
1281 int start=one.Find(_T(" "),0);
1282 if(start>0)
1284 CString name;
1285 name=one.Right(one.GetLength()-start-1);
1286 list.push_back(name);
1291 return ret;
1294 int addto_map_each_ref_fn(const char *refname, const unsigned char *sha1, int /*flags*/, void *cb_data)
1296 MAP_HASH_NAME *map = (MAP_HASH_NAME*)cb_data;
1297 CString str;
1298 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1299 CGitHash hash((char*)sha1);
1301 (*map)[hash].push_back(str);
1303 if(strncmp(refname, "refs/tags", 9) == 0)
1307 GIT_HASH refhash;
1308 if(!git_deref_tag(sha1, refhash))
1310 (*map)[(char*)refhash].push_back(str+_T("^{}"));
1313 catch (char* msg)
1315 CString err(msg);
1316 ::MessageBox(NULL, _T("Could not get (readable) reference for hash ") + hash.ToString() + _T(".\nlibgit reports:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
1319 return 0;
1322 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1324 int ret;
1325 if(this->m_IsUseGitDLL)
1327 CAutoLocker lock(g_Git.m_critGitDllSec);
1328 return git_for_each_ref_in("",addto_map_each_ref_fn, &map);
1331 else
1333 CString cmd, output;
1334 cmd=_T("git.exe show-ref -d");
1335 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1336 if(!ret)
1338 int pos=0;
1339 CString one;
1340 while( pos>=0 )
1342 one=output.Tokenize(_T("\n"),pos);
1343 int start=one.Find(_T(" "),0);
1344 if(start>0)
1346 CString name;
1347 name=one.Right(one.GetLength()-start-1);
1349 CString hash;
1350 hash=one.Left(start);
1352 map[CGitHash(hash)].push_back(name);
1357 return ret;
1360 BOOL CGit::CheckMsysGitDir()
1362 if (m_bInitialized)
1364 return TRUE;
1367 this->m_Environment.clear();
1368 m_Environment.CopyProcessEnvironment();
1370 TCHAR *oldpath;
1371 size_t homesize,size;
1373 // set HOME if not set already
1374 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1375 if (!homesize)
1377 CString home = g_Git.GetHomeDirectory();
1378 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1379 home.ReleaseBuffer();
1381 CString str;
1383 //setup ssh client
1384 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1386 if(!sshclient.IsEmpty())
1388 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1389 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1391 else
1393 TCHAR sPlink[MAX_PATH];
1394 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1395 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1396 if (ptr) {
1397 _tcscpy(ptr + 1, _T("TortoisePlink.exe"));
1398 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1399 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1404 TCHAR sAskPass[MAX_PATH];
1405 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1406 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1407 if (ptr)
1409 _tcscpy(ptr + 1, _T("SshAskPass.exe"));
1410 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1411 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1412 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1416 // add git/bin path to PATH
1418 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1419 str=msysdir;
1420 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1422 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);
1423 str=msysinstalldir;
1424 if ( !str.IsEmpty() )
1426 str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";
1427 msysdir=str;
1428 CGit::ms_LastMsysGitDir = str;
1429 msysdir.write();
1431 else
1433 // search PATH if git/bin directory is already present
1434 if ( FindGitPath() )
1436 m_bInitialized = TRUE;
1437 msysdir = CGit::ms_LastMsysGitDir;
1438 msysdir.write();
1439 return TRUE;
1442 return FALSE;
1445 else
1447 CGit::ms_LastMsysGitDir = str;
1450 // check for git.exe existance (maybe it was deinstalled in the meantime)
1451 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1452 return FALSE;
1454 //set path
1455 _tdupenv_s(&oldpath,&size,_T("PATH"));
1457 CString path;
1458 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1460 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1462 CString str1 = m_Environment.GetEnv(_T("PATH"));
1464 CString sOldPath = oldpath;
1465 free(oldpath);
1467 m_bInitialized = TRUE;
1468 return true;
1471 CString CGit::GetHomeDirectory()
1473 const wchar_t * homeDir = wget_windows_home_directory();
1474 return CString(homeDir, wcslen(homeDir));
1477 CString CGit::GetGitSystemConfig()
1479 const wchar_t * systemConfig = wget_msysgit_etc();
1480 return CString(systemConfig, wcslen(systemConfig));
1483 BOOL CGit::CheckCleanWorkTree()
1485 CString out;
1486 CString cmd;
1487 cmd=_T("git.exe rev-parse --verify HEAD");
1489 if(g_Git.Run(cmd,&out,CP_UTF8))
1490 return FALSE;
1492 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1493 if(g_Git.Run(cmd,&out,CP_UTF8))
1494 return FALSE;
1496 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1497 if(g_Git.Run(cmd,&out,CP_UTF8))
1498 return FALSE;
1500 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1501 if(g_Git.Run(cmd,&out,CP_UTF8))
1502 return FALSE;
1504 return TRUE;
1506 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1508 int ret;
1509 for(int i=0;i<list.GetCount();i++)
1511 ret = Revert(commit, (CTGitPath&)list[i]);
1512 if(ret)
1513 return ret;
1515 return 0;
1517 int CGit::Revert(CString commit, CTGitPath &path)
1519 CString cmd, out;
1521 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1523 cmd.Format(_T("git.exe mv -- \"%s\" \"%s\""),path.GetGitPathString(),path.GetGitOldPathString());
1524 if (g_Git.Run(cmd, &out, CP_UTF8))
1526 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1527 return -1;
1530 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1531 if (g_Git.Run(cmd, &out, CP_UTF8))
1533 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1534 return -1;
1538 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1539 { //To init git repository, there are not HEAD, so we can use git reset command
1540 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1542 if (g_Git.Run(cmd, &out, CP_UTF8))
1544 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1545 return -1;
1548 else
1550 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1551 if (g_Git.Run(cmd, &out, CP_UTF8))
1553 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1554 return -1;
1558 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1560 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1561 if (g_Git.Run(cmd, &out, CP_UTF8))
1563 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1564 return -1;
1568 return 0;
1571 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1573 BYTE_VECTOR vector;
1575 CString cmd;
1576 if(path)
1577 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1578 else
1579 cmd=_T("git.exe ls-files -u -t -z");
1581 if (g_Git.Run(cmd, &vector))
1583 return -1;
1586 list.ParserFromLsFile(vector);
1588 return 0;
1591 bool CGit::IsFastForward(const CString &from, const CString &to)
1593 CString base;
1594 CGitHash basehash,hash;
1595 CString cmd, err;
1596 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1598 if (g_Git.Run(cmd, &base, &err, CP_UTF8))
1600 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1601 return false;
1603 basehash = base;
1605 hash=g_Git.GetHash(from);
1607 return hash == basehash;
1610 unsigned int CGit::Hash2int(CGitHash &hash)
1612 int ret=0;
1613 for(int i=0;i<4;i++)
1615 ret = ret << 8;
1616 ret |= hash.m_hash[i];
1618 return ret;
1621 int CGit::RefreshGitIndex()
1623 if(g_Git.m_IsUseGitDLL)
1625 CAutoLocker lock(g_Git.m_critGitDllSec);
1628 return git_run_cmd("update-index","update-index -q --refresh");
1630 }catch(...)
1632 return -1;
1636 else
1638 CString cmd,output;
1639 cmd=_T("git.exe update-index --refresh");
1640 return Run(cmd, &output, CP_UTF8);
1644 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1646 if(g_Git.m_IsUseGitDLL)
1648 CAutoLocker lock(g_Git.m_critGitDllSec);
1651 g_Git.CheckAndInitDll();
1652 CStringA ref, patha, outa;
1653 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1654 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1655 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1656 ::DeleteFile(outputfile);
1657 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1659 }catch(...)
1661 return -1;
1664 else
1666 CString cmd;
1667 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1668 return g_Git.RunLogFile(cmd,outputfile);
1671 void CEnvironment::CopyProcessEnvironment()
1673 TCHAR *p = GetEnvironmentStrings();
1674 while(*p !=0 || *(p+1) !=0)
1675 this->push_back(*p++);
1677 push_back(_T('\0'));
1678 push_back(_T('\0'));
1681 CString CEnvironment::GetEnv(TCHAR *name)
1683 CString str;
1684 for(int i=0;i<size();i++)
1686 str = &(*this)[i];
1687 int start =0;
1688 CString sname = str.Tokenize(_T("="),start);
1689 if(sname.CompareNoCase(name) == 0)
1691 return &(*this)[i+start];
1693 i+=str.GetLength();
1695 return _T("");
1698 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
1700 unsigned int i;
1701 for( i=0;i<size();i++)
1703 CString str = &(*this)[i];
1704 int start =0;
1705 CString sname = str.Tokenize(_T("="),start);
1706 if(sname.CompareNoCase(name) == 0)
1708 break;
1710 i+=str.GetLength();
1713 if(i == size())
1715 i -= 1; // roll back terminate \0\0
1716 this->push_back(_T('\0'));
1719 CEnvironment::iterator it;
1720 it=this->begin();
1721 it += i;
1723 while(*it && i<size())
1725 this->erase(it);
1726 it=this->begin();
1727 it += i;
1730 while(*name)
1732 this->insert(it,*name++);
1733 i++;
1734 it= begin()+i;
1737 this->insert(it, _T('='));
1738 i++;
1739 it= begin()+i;
1741 while(*value)
1743 this->insert(it,*value++);
1744 i++;
1745 it= begin()+i;
1750 int CGit::GetGitEncode(TCHAR* configkey)
1752 CString str=GetConfigValue(configkey);
1754 if(str.IsEmpty())
1755 return CP_UTF8;
1757 return CUnicodeUtils::GetCPCode(str);
1761 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
1763 GIT_FILE file=0;
1764 int ret=0;
1765 GIT_DIFF diff=0;
1767 CAutoLocker lock(g_Git.m_critGitDllSec);
1769 if(arg == NULL)
1770 diff = GetGitDiff();
1771 else
1772 git_open_diff(&diff, arg);
1774 if(diff ==NULL)
1775 return -1;
1777 bool isStat = 0;
1778 if(arg == NULL)
1779 isStat = true;
1780 else
1781 isStat = !!strstr(arg, "stat");
1783 int count=0;
1785 if(hash2 == NULL)
1786 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
1787 else
1788 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
1790 if(ret)
1791 return -1;
1793 CTGitPath path;
1794 CString strnewname;
1795 CString stroldname;
1797 for(int j=0;j<count;j++)
1799 path.Reset();
1800 char *newname;
1801 char *oldname;
1803 strnewname.Empty();
1804 stroldname.Empty();
1806 int mode=0,IsBin=0,inc=0,dec=0;
1807 git_get_diff_file(diff,file,j,&newname,&oldname,
1808 &mode,&IsBin,&inc,&dec);
1810 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
1811 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
1813 path.SetFromGit(strnewname,&stroldname);
1814 path.ParserAction((BYTE)mode);
1816 if(IsBin)
1818 path.m_StatAdd=_T("-");
1819 path.m_StatDel=_T("-");
1821 else
1823 path.m_StatAdd.Format(_T("%d"),inc);
1824 path.m_StatDel.Format(_T("%d"),dec);
1826 PathList->AddPath(path);
1828 git_diff_flush(diff);
1830 if(arg)
1831 git_close_diff(diff);
1833 return 0;
1836 int CGit::GetShortHASHLength()
1838 return 7;