Fixed issue #1396: Sync Dialog Pull show wrong commit range in "In commits"
[TortoiseGit.git] / src / Git / Git.cpp
blob503102f42b31d89235751753d34d3c933a72d653
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)) != NULL && *buf)
110 TCHAR *pfin = buf + _tcslen(buf)-1;
112 // ensure trailing slash
113 if (*pfin != _T('/') && *pfin != _T('\\'))
114 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, _MAX_PATH-1 is used in nextpath above
116 const size_t len = _tcslen(buf);
118 if ((len + 7) < _MAX_PATH)
119 _tcscpy_s(pfin + 1, _MAX_PATH - len, _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;
135 static bool g_bSortLogical;
137 static void GetSortLogicalEnabled()
139 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
140 if (g_bSortLogical)
141 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
144 static int LogicalComparePredicate(CString &left, CString &right)
146 if (g_bSortLogical)
147 return StrCmpLogicalW(left, right) < 0;
148 return StrCmpI(left, right) < 0;
151 #define MAX_DIRBUFFER 1000
152 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
154 CString CGit::ms_LastMsysGitDir;
155 CGit g_Git;
158 CGit::CGit(void)
160 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
161 m_CurrentDir.ReleaseBuffer();
162 m_IsGitDllInited = false;
163 m_GitDiff=0;
164 m_GitSimpleListDiff=0;
165 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
166 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
167 GetSortLogicalEnabled();
168 this->m_bInitialized =false;
169 CheckMsysGitDir();
170 m_critGitDllSec.Init();
173 CGit::~CGit(void)
175 if(this->m_GitDiff)
177 git_close_diff(m_GitDiff);
178 m_GitDiff=0;
180 if(this->m_GitSimpleListDiff)
182 git_close_diff(m_GitSimpleListDiff);
183 m_GitSimpleListDiff=0;
187 bool CGit::IsBranchNameValid(CString branchname)
189 if (branchname.IsEmpty())
190 return false;
192 for(int i=0; i < branchname.GetLength(); i++)
194 TCHAR c = branchname.GetAt(i);
195 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
196 return false;
199 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
200 return false;
202 CString reverseBranchname = branchname.MakeReverse();
203 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
204 return false;
206 return true;
209 static char g_Buffer[4096];
211 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
213 SECURITY_ATTRIBUTES sa;
214 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
215 HANDLE hStdioFile = NULL;
217 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
218 sa.lpSecurityDescriptor=NULL;
219 sa.bInheritHandle=TRUE;
220 if(!CreatePipe(&hRead,&hWrite,&sa,0))
222 return TGIT_GIT_ERROR_OPEN_PIP;
224 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
225 return TGIT_GIT_ERROR_OPEN_PIP;
227 if(StdioFile)
229 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
230 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
233 STARTUPINFO si;
234 PROCESS_INFORMATION pi;
235 si.cb=sizeof(STARTUPINFO);
236 GetStartupInfo(&si);
238 if (hErrReadOut)
239 si.hStdError = hWriteErr;
240 else
241 si.hStdError = hWrite;
242 if(StdioFile)
243 si.hStdOutput=hStdioFile;
244 else
245 si.hStdOutput=hWrite;
247 si.wShowWindow=SW_HIDE;
248 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
250 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
251 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
253 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
254 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
256 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
257 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
259 if(cmd.Find(_T("git")) == 0)
261 int firstSpace = cmd.Find(_T(" "));
262 if (firstSpace > 0)
263 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
264 else
265 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
268 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
270 LPVOID lpMsgBuf;
271 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
272 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
273 (LPTSTR)&lpMsgBuf,
274 0,NULL);
275 return TGIT_GIT_ERROR_CREATE_PROCESS;
278 m_CurrentGitPi = pi;
280 CloseHandle(hWrite);
281 if (hErrReadOut)
282 CloseHandle(hWriteErr);
283 if(piOut)
284 *piOut=pi;
285 if(hReadOut)
286 *hReadOut=hRead;
287 if(hErrReadOut)
288 *hErrReadOut = hReadErr;
289 return 0;
292 //Must use sperate function to convert ANSI str to union code string
293 //Becuase A2W use stack as internal convert buffer.
294 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
296 //USES_CONVERSION;
297 //str->Append(A2W_CP((LPCSTR)p,code));
298 if(str == NULL)
299 return ;
301 WCHAR * buf;
303 int len ;
304 if(length<0)
305 len = (int)strlen((const char*)p);
306 else
307 len=length;
308 //if (len==0)
309 // return ;
310 //buf = new WCHAR[len*4 + 1];
311 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
312 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
313 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
314 str->ReleaseBuffer();
315 //str->Append(buf);
316 //delete buf;
318 BOOL CGit::IsInitRepos()
320 CString cmdout;
321 cmdout.Empty();
322 if(g_Git.Run(_T("git.exe rev-parse --revs-only HEAD"),&cmdout,CP_UTF8))
324 // CMessageBox::Show(NULL,cmdout,_T("TortoiseGit"),MB_OK);
325 return TRUE;
327 if(cmdout.IsEmpty())
328 return TRUE;
330 return FALSE;
333 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
335 PASYNCREADSTDERRTHREADARGS pDataArray;
336 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
338 DWORD readnumber;
339 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
340 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
342 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
343 break;
346 return 0;
349 int CGit::Run(CGitCall* pcall)
351 PROCESS_INFORMATION pi;
352 HANDLE hRead, hReadErr;
353 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
354 return TGIT_GIT_ERROR_CREATE_PROCESS;
356 HANDLE thread;
357 ASYNCREADSTDERRTHREADARGS threadArguments;
358 threadArguments.fileHandle = hReadErr;
359 threadArguments.pcall = pcall;
360 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
362 DWORD readnumber;
363 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
364 bool bAborted=false;
365 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
367 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
368 if(!bAborted)//For now, flush output when command aborted.
369 if(pcall->OnOutputData(data,readnumber))
370 bAborted=true;
372 if(!bAborted)
373 pcall->OnEnd();
375 if (thread)
376 WaitForSingleObject(thread, INFINITE);
378 CloseHandle(pi.hThread);
380 WaitForSingleObject(pi.hProcess, INFINITE);
381 DWORD exitcode =0;
383 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
385 return TGIT_GIT_ERROR_GET_EXIT_CODE;
388 CloseHandle(pi.hProcess);
390 CloseHandle(hRead);
391 CloseHandle(hReadErr);
392 return exitcode;
394 class CGitCall_ByteVector : public CGitCall
396 public:
397 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
398 virtual bool OnOutputData(const BYTE* data, size_t size)
400 if (size == 0)
401 return false;
402 size_t oldsize=m_pvector->size();
403 m_pvector->resize(m_pvector->size()+size);
404 memcpy(&*(m_pvector->begin()+oldsize),data,size);
405 return false;
407 virtual bool OnOutputErrData(const BYTE* data, size_t size)
409 if (!m_pvectorErr || size == 0)
410 return false;
411 size_t oldsize = m_pvectorErr->size();
412 m_pvectorErr->resize(m_pvectorErr->size() + size);
413 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
414 return false;
416 BYTE_VECTOR* m_pvector;
417 BYTE_VECTOR* m_pvectorErr;
420 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
422 CGitCall_ByteVector call(cmd, vector, vectorErr);
423 return Run(&call);
425 int CGit::Run(CString cmd, CString* output, int code)
427 CString err;
428 int ret;
429 ret = Run(cmd, output, &err, code);
431 if (output && !err.IsEmpty())
433 if (!output->IsEmpty())
434 *output += _T("\n");
435 *output += err;
438 return ret;
440 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
442 BYTE_VECTOR vector, vectorErr;
443 int ret;
444 if (outputErr)
445 ret = Run(cmd, &vector, &vectorErr);
446 else
447 ret = Run(cmd, &vector);
449 vector.push_back(0);
450 StringAppend(output, &(vector[0]), code);
452 if (outputErr)
454 vectorErr.push_back(0);
455 StringAppend(outputErr, &(vectorErr[0]), code);
458 return ret;
461 CString CGit::GetUserName(void)
463 CEnvironment env;
464 env.CopyProcessEnvironment();
465 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
466 if (!envname.IsEmpty())
467 return envname;
468 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
470 CString CGit::GetUserEmail(void)
472 CEnvironment env;
473 env.CopyProcessEnvironment();
474 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
475 if (!envmail.IsEmpty())
476 return envmail;
478 return GetConfigValue(L"user.email");
481 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
483 CString configValue;
484 int start = 0;
485 if(this->m_IsUseGitDLL)
487 CString *git_path=NULL;
489 CAutoLocker lock(g_Git.m_critGitDllSec);
493 CTGitPath path;
495 CheckAndInitDll();
496 git_path = GitPath;
498 }catch(...)
501 CStringA key, value;
502 key = CUnicodeUtils::GetMulti(name, encoding);
503 CStringA p;
504 if(git_path)
505 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
507 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
508 return CString();
509 else
511 g_Git.StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
512 if(RemoveCR)
513 return configValue.Tokenize(_T("\n"),start);
514 return configValue;
518 else
520 CString cmd;
521 cmd.Format(L"git.exe config %s", name);
522 Run(cmd, &configValue, NULL, encoding);
523 if(RemoveCR)
524 return configValue.Tokenize(_T("\n"),start);
525 return configValue;
529 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
531 if(this->m_IsUseGitDLL)
533 CAutoLocker lock(g_Git.m_critGitDllSec);
537 CheckAndInitDll();
539 }catch(...)
542 CStringA keya, valuea;
543 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
544 valuea = CUnicodeUtils::GetMulti(value, encoding);
545 CStringA p;
546 if(GitPath)
547 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
549 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
552 else
554 CString cmd;
555 CString option;
556 switch(type)
558 case CONFIG_GLOBAL:
559 option = _T("--global");
560 break;
561 case CONFIG_SYSTEM:
562 option = _T("--system");
563 break;
564 default:
565 break;
567 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
568 CString out;
569 if (Run(cmd, &out, NULL, encoding))
571 return -1;
574 return 0;
577 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
579 if(this->m_IsUseGitDLL)
581 CAutoLocker lock(g_Git.m_critGitDllSec);
585 CheckAndInitDll();
586 }catch(...)
589 CStringA keya;
590 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
591 CStringA p;
592 if(GitPath)
593 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
595 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
597 else
599 CString cmd;
600 CString option;
601 switch(type)
603 case CONFIG_GLOBAL:
604 option = _T("--global");
605 break;
606 case CONFIG_SYSTEM:
607 option = _T("--system");
608 break;
609 default:
610 break;
612 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
613 CString out;
614 if (Run(cmd, &out, NULL, encoding))
616 return -1;
619 return 0;
622 CString CGit::GetCurrentBranch(void)
624 CString output;
625 //Run(_T("git.exe branch"),&branch);
627 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
629 return _T("(no branch)");
631 else
632 return output;
636 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
638 CString refName;
639 if(this->m_IsUseGitDLL)
641 unsigned char sha1[20];
642 int flag;
644 CAutoLocker lock(g_Git.m_critGitDllSec);
645 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
646 if(refs_heads_master && (flag&REF_ISSYMREF))
648 g_Git.StringAppend(&refName,(BYTE*)refs_heads_master);
649 if(bStripRefsHeads)
650 refName = StripRefName(refName);
654 else
656 CString cmd;
657 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
658 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
659 return CString();//Error
660 int iStart = 0;
661 refName = refName.Tokenize(L"\n", iStart);
662 if(bStripRefsHeads)
663 refName = StripRefName(refName);
665 return refName;
668 CString CGit::GetFullRefName(CString shortRefName)
670 CString refName;
671 CString cmd;
672 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
673 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
674 return CString();//Error
675 int iStart = 0;
676 return refName.Tokenize(L"\n", iStart);
679 CString CGit::StripRefName(CString refName)
681 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
682 refName = refName.Mid(11);
683 else if(wcsncmp(refName, L"refs/", 5) == 0)
684 refName = refName.Mid(5);
685 int start =0;
686 return refName.Tokenize(_T("\n"),start);
689 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
691 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
693 if ( sProjectRoot.IsEmpty() )
694 return -1;
696 CString sDotGitPath;
697 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
698 return -1;
700 CString sHeadFile = sDotGitPath + _T("HEAD");
702 FILE *pFile;
703 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
705 if (!pFile)
707 return -1;
710 char s[256] = {0};
711 fgets(s, sizeof(s), pFile);
713 fclose(pFile);
715 const char *pfx = "ref: refs/heads/";
716 const int len = 16;//strlen(pfx)
718 if ( !strncmp(s, pfx, len) )
720 //# We're on a branch. It might not exist. But
721 //# HEAD looks good enough to be a branch.
722 CStringA utf8Branch(s + len);
723 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
724 sBranchOut.TrimRight(_T(" \r\n\t"));
726 if ( sBranchOut.IsEmpty() )
727 return -1;
729 else
731 //# Assume this is a detached head.
732 sBranchOut = "HEAD";
734 return 1;
737 return 0;
740 int CGit::BuildOutputFormat(CString &format,bool IsFull)
742 CString log;
743 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
744 format += log;
745 if(IsFull)
747 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
748 format += log;
749 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
750 format += log;
751 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
752 format += log;
753 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
754 format += log;
755 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
756 format += log;
757 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
758 format += log;
759 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
760 format += log;
763 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
764 format += log;
765 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
766 format += log;
767 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
768 format += log;
770 if(IsFull)
772 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
773 format += log;
775 return 0;
778 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
780 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
781 return GetLog(&gitCall,hash,path,count,mask,from,to);
784 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
785 CFilterData *Filter)
787 CString cmd;
788 CString num;
789 CString since;
791 CString file;
793 if(path)
794 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
796 if(count>0)
797 num.Format(_T("-n%d"),count);
799 CString param;
801 if(mask& LOG_INFO_STAT )
802 param += _T(" --numstat ");
803 if(mask& LOG_INFO_FILESTATE)
804 param += _T(" --raw ");
806 if(mask& LOG_INFO_FULLHISTORY)
807 param += _T(" --full-history ");
809 if(mask& LOG_INFO_BOUNDARY)
810 param += _T(" --left-right --boundary ");
812 if(mask& CGit::LOG_INFO_ALL_BRANCH)
813 param += _T(" --all ");
815 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
816 param += _T(" -C ");
818 if(mask& CGit::LOG_INFO_DETECT_RENAME )
819 param += _T(" -M ");
821 if(mask& CGit::LOG_INFO_FIRST_PARENT )
822 param += _T(" --first-parent ");
824 if(mask& CGit::LOG_INFO_NO_MERGE )
825 param += _T(" --no-merges ");
827 if(mask& CGit::LOG_INFO_FOLLOW)
828 param += _T(" --follow ");
830 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
831 param += _T(" -c ");
833 if(mask& CGit::LOG_INFO_FULL_DIFF)
834 param += _T(" --full-diff ");
836 if(from != NULL && to != NULL)
838 CString range;
839 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
840 param += range;
842 else if(to != NULL && hash.IsEmpty())
844 CString range;
845 range.Format(_T(" %s "), FixBranchName(*to));
846 param += range;
848 param+=hash;
850 CString st1,st2;
852 if( Filter && (Filter->m_From != -1))
854 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
855 param += st1;
858 if( Filter && (Filter->m_To != -1))
860 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
861 param += st2;
864 bool isgrep = false;
865 if( Filter && (!Filter->m_Author.IsEmpty()))
867 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
868 param += st1;
869 isgrep = true;
872 if( Filter && (!Filter->m_Committer.IsEmpty()))
874 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
875 param += st1;
876 isgrep = true;
879 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
881 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
882 param += st1;
883 isgrep = true;
886 if(Filter && isgrep)
888 if(!Filter->m_IsRegex)
889 param += _T(" --fixed-strings ");
891 param += _T(" --regexp-ignore-case --extended-regexp ");
894 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
895 param += _T(" --topo-order");
897 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
898 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
899 else
901 CString log;
902 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
903 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
904 num,param,log);
907 cmd += file;
909 return cmd;
911 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
912 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
914 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
916 return Run(pgitCall);
917 // return Run(cmd,&logOut);
920 #define BUFSIZE 512
921 void GetTempPath(CString &path)
923 TCHAR lpPathBuffer[BUFSIZE];
924 DWORD dwRetVal;
925 DWORD dwBufSize=BUFSIZE;
926 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
927 lpPathBuffer); // buffer for path
928 if (dwRetVal > dwBufSize || (dwRetVal == 0))
930 path=_T("");
932 path.Format(_T("%s"),lpPathBuffer);
934 CString GetTempFile()
936 TCHAR lpPathBuffer[BUFSIZE];
937 DWORD dwRetVal;
938 DWORD dwBufSize=BUFSIZE;
939 TCHAR szTempName[BUFSIZE];
940 UINT uRetVal;
942 dwRetVal = GetTempPath(dwBufSize, // length of the buffer
943 lpPathBuffer); // buffer for path
944 if (dwRetVal > dwBufSize || (dwRetVal == 0))
946 return _T("");
948 // Create a temporary file.
949 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
950 TEXT("Patch"), // temp file name prefix
951 0, // create unique name
952 szTempName); // buffer for name
955 if (uRetVal == 0)
957 return _T("");
960 return CString(szTempName);
964 int CGit::RunLogFile(CString cmd,const CString &filename)
966 STARTUPINFO si;
967 PROCESS_INFORMATION pi;
968 si.cb=sizeof(STARTUPINFO);
969 GetStartupInfo(&si);
971 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
972 psa.bInheritHandle=TRUE;
974 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
975 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
977 si.wShowWindow = SW_HIDE;
978 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
979 si.hStdOutput = houtfile;
981 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
982 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
984 if(cmd.Find(_T("git")) == 0)
985 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
987 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
989 LPVOID lpMsgBuf;
990 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
991 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
992 (LPTSTR)&lpMsgBuf,
993 0,NULL);
994 return TGIT_GIT_ERROR_CREATE_PROCESS;
997 WaitForSingleObject(pi.hProcess,INFINITE);
999 CloseHandle(pi.hThread);
1000 CloseHandle(pi.hProcess);
1001 CloseHandle(houtfile);
1002 return TGIT_GIT_SUCCESS;
1003 // return 0;
1006 CGitHash CGit::GetHash(TCHAR* friendname)
1008 // no need to parse a ref if it's already a 40-byte hash
1009 if (CGitHash::IsValidSHA1(friendname))
1011 CString sHash(friendname);
1012 return CGitHash(sHash);
1015 if (m_IsUseLibGit2)
1017 git_repository *repo = NULL;
1018 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(g_Git.m_CurrentDir).GetGitPathString(), CP_UTF8);
1019 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1021 gitdirA.ReleaseBuffer();
1022 return CGitHash();
1024 gitdirA.ReleaseBuffer();
1026 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1028 git_object * gitObject = NULL;
1029 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1031 refnameA.ReleaseBuffer();
1032 git_repository_free(repo);
1033 return CGitHash();
1035 refnameA.ReleaseBuffer();
1037 const git_oid * oid = git_object_id(gitObject);
1038 if (oid == NULL)
1040 git_object_free(gitObject);
1041 git_repository_free(repo);
1042 return CGitHash();
1045 CGitHash hash((char *)oid->id);
1047 git_object_free(gitObject); // also frees oid
1048 git_repository_free(repo);
1050 return hash;
1052 else if (this->m_IsUseGitDLL)
1054 CAutoLocker lock(g_Git.m_critGitDllSec);
1056 this->CheckAndInitDll();
1058 CGitHash hash;
1059 CStringA ref;
1060 ref = CUnicodeUtils::GetMulti(FixBranchName(friendname), CP_UTF8);
1063 git_get_sha1(ref, hash.m_hash);
1065 }catch(...)
1068 return hash;
1071 else
1073 CString cmd;
1074 CString out;
1075 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1076 Run(cmd, &out, NULL, CP_UTF8);
1077 // int pos=out.ReverseFind(_T('\n'));
1078 out.FindOneOf(_T("\r\n"));
1079 return CGitHash(out);
1083 int CGit::GetInitAddList(CTGitPathList &outputlist)
1085 CString cmd;
1086 BYTE_VECTOR cmdout;
1088 cmd=_T("git.exe ls-files -s -t -z");
1089 outputlist.Clear();
1090 if (g_Git.Run(cmd, &cmdout))
1091 return -1;
1093 outputlist.ParserFromLsFile(cmdout);
1094 for(int i=0;i<outputlist.GetCount();i++)
1095 ((unsigned int)outputlist[i].m_Action) = CTGitPath::LOGACTIONS_ADDED;
1097 return 0;
1099 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1101 CString cmd;
1103 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1105 //rev1=+_T("");
1106 if(rev1 == GIT_REV_ZERO)
1107 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1108 else
1109 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1111 else
1113 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1116 BYTE_VECTOR out;
1117 if (g_Git.Run(cmd, &out))
1118 return -1;
1120 outputlist.ParserFromLog(out);
1122 return 0;
1125 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1127 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1128 CString str;
1129 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1130 list->push_back(str);
1131 return 0;
1134 int CGit::GetTagList(STRING_VECTOR &list)
1136 if (this->m_IsUseLibGit2)
1138 git_repository *repo = NULL;
1140 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(g_Git.m_CurrentDir).GetGitPathString(), CP_UTF8);
1141 if (git_repository_open(&repo, gitdir.GetBuffer()))
1143 gitdir.ReleaseBuffer();
1144 return -1;
1146 gitdir.ReleaseBuffer();
1148 git_strarray tag_names;
1150 if (git_tag_list(&tag_names, repo))
1152 git_repository_free(repo);
1153 return -1;
1156 for (size_t i = 0; i < tag_names.count; i++)
1158 CStringA tagName(tag_names.strings[i]);
1159 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1162 git_strarray_free(&tag_names);
1164 git_repository_free(repo);
1166 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1168 return 0;
1170 else
1172 CString cmd, output;
1173 cmd=_T("git.exe tag -l");
1174 int ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1175 if(!ret)
1177 int pos=0;
1178 CString one;
1179 while( pos>=0 )
1181 one=output.Tokenize(_T("\n"),pos);
1182 if (!one.IsEmpty())
1183 list.push_back(one);
1185 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1187 return ret;
1191 CString CGit::FixBranchName_Mod(CString& branchName)
1193 if(branchName == "FETCH_HEAD")
1194 branchName = DerefFetchHead();
1195 return branchName;
1198 CString CGit::FixBranchName(const CString& branchName)
1200 CString tempBranchName = branchName;
1201 FixBranchName_Mod(tempBranchName);
1202 return tempBranchName;
1205 bool CGit::IsBranchTagNameUnique(const CString& name)
1207 CString output;
1209 CString cmd;
1210 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1211 int ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1212 if (!ret)
1214 int i = 0, pos = 0;
1215 while (pos >= 0)
1217 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1218 i++;
1220 if (i >= 2)
1221 return false;
1224 return true;
1228 Checks if a branch or tag with the given name exists
1229 isBranch is true -> branch, tag otherwise
1231 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1233 CString cmd, output;
1235 cmd = _T("git show-ref ");
1236 if (isBranch)
1237 cmd += _T("--heads ");
1238 else
1239 cmd += _T("--tags ");
1241 cmd += _T("refs/heads/") + name;
1242 cmd += _T(" refs/tags/") + name;
1244 int ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1245 if (!ret)
1247 if (!output.IsEmpty())
1248 return true;
1251 return false;
1254 CString CGit::DerefFetchHead()
1256 using namespace std;
1257 CString dotGitPath;
1258 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1259 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1260 int forMergeLineCount = 0;
1261 string line;
1262 string hashToReturn;
1263 while(getline(fetchHeadFile, line))
1265 //Tokenize this line
1266 string::size_type prevPos = 0;
1267 string::size_type pos = line.find('\t');
1268 if(pos == string::npos) continue; //invalid line
1270 string hash = line.substr(0, pos);
1271 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1273 bool forMerge = pos == prevPos;
1274 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1276 string remoteBranch = line.substr(prevPos, pos - prevPos);
1278 //Process this line
1279 if(forMerge)
1281 hashToReturn = hash;
1282 ++forMergeLineCount;
1283 if(forMergeLineCount > 1)
1284 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1288 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1291 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1293 int ret;
1294 CString cmd, output, cur;
1295 cmd = _T("git.exe branch --no-color");
1297 if((type&BRANCH_ALL) == BRANCH_ALL)
1298 cmd += _T(" -a");
1299 else if(type&BRANCH_REMOTE)
1300 cmd += _T(" -r");
1302 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1303 if(!ret)
1305 int pos=0;
1306 CString one;
1307 while( pos>=0 )
1309 one=output.Tokenize(_T("\n"),pos);
1310 one.Trim(L" \r\n\t");
1311 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1312 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1313 if(one[0] == _T('*'))
1315 one = one.Mid(2);
1316 cur = one;
1318 if (one != _T("(no branch)"))
1319 list.push_back(one);
1323 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1324 list.push_back(L"FETCH_HEAD");
1326 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1328 if (current && cur != _T("(no branch)"))
1330 for (unsigned int i = 0; i < list.size(); i++)
1332 if (list[i] == cur)
1334 *current = i;
1335 break;
1340 return ret;
1343 int CGit::GetRemoteList(STRING_VECTOR &list)
1345 if (this->m_IsUseLibGit2)
1347 git_repository *repo = NULL;
1349 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(g_Git.m_CurrentDir).GetGitPathString(), CP_UTF8);
1350 if (git_repository_open(&repo, gitdir.GetBuffer()))
1352 gitdir.ReleaseBuffer();
1353 return -1;
1355 gitdir.ReleaseBuffer();
1357 git_strarray remotes;
1359 if (git_remote_list(&remotes, repo))
1361 git_repository_free(repo);
1362 return -1;
1365 for (size_t i = 0; i < remotes.count; i++)
1367 CStringA remote(remotes.strings[i]);
1368 list.push_back(CUnicodeUtils::GetUnicode(remote));
1371 git_strarray_free(&remotes);
1373 git_repository_free(repo);
1375 std::sort(list.begin(), list.end());
1377 return 0;
1379 else
1381 int ret;
1382 CString cmd, output;
1383 cmd=_T("git.exe remote");
1384 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1385 if(!ret)
1387 int pos=0;
1388 CString one;
1389 while( pos>=0 )
1391 one=output.Tokenize(_T("\n"),pos);
1392 if (!one.IsEmpty())
1393 list.push_back(one);
1396 return ret;
1400 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1402 CString cmd, out, err;
1403 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1404 if (g_Git.Run(cmd, &out, &err, CP_UTF8))
1406 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1407 return -1;
1410 int pos = 0;
1411 while (pos >= 0)
1413 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1414 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1415 if (one.Find(_T("^{}")) >= 1)
1416 continue;
1417 if (!one.IsEmpty())
1418 list.push_back(one);
1420 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1421 return 0;
1424 int CGit::GetRefList(STRING_VECTOR &list)
1426 int ret;
1427 if(this->m_IsUseGitDLL)
1429 CAutoLocker lock(g_Git.m_critGitDllSec);
1430 ret = git_for_each_ref_in("",addto_list_each_ref_fn, &list);
1431 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1433 else
1435 CString cmd, output;
1436 cmd=_T("git.exe show-ref -d");
1437 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1438 if(!ret)
1440 int pos=0;
1441 CString one;
1442 while( pos>=0 )
1444 one=output.Tokenize(_T("\n"),pos);
1445 int start=one.Find(_T(" "),0);
1446 if(start>0)
1448 CString name;
1449 name=one.Right(one.GetLength()-start-1);
1450 list.push_back(name);
1453 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1456 return ret;
1459 int addto_map_each_ref_fn(const char *refname, const unsigned char *sha1, int /*flags*/, void *cb_data)
1461 MAP_HASH_NAME *map = (MAP_HASH_NAME*)cb_data;
1462 CString str;
1463 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1464 CGitHash hash((char*)sha1);
1466 (*map)[hash].push_back(str);
1468 if(strncmp(refname, "refs/tags", 9) == 0)
1472 GIT_HASH refhash;
1473 if(!git_deref_tag(sha1, refhash))
1475 (*map)[(char*)refhash].push_back(str+_T("^{}"));
1478 catch (char* msg)
1480 CString err(msg);
1481 ::MessageBox(NULL, _T("Could not get (readable) reference for hash ") + hash.ToString() + _T(".\nlibgit reports:\n") + err, _T("TortoiseGit"), MB_ICONERROR);
1484 return 0;
1487 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1489 int ret;
1490 if(this->m_IsUseGitDLL)
1492 CAutoLocker lock(g_Git.m_critGitDllSec);
1493 return git_for_each_ref_in("",addto_map_each_ref_fn, &map);
1496 else
1498 CString cmd, output;
1499 cmd=_T("git.exe show-ref -d");
1500 ret = g_Git.Run(cmd, &output, NULL, CP_UTF8);
1501 if(!ret)
1503 int pos=0;
1504 CString one;
1505 while( pos>=0 )
1507 one=output.Tokenize(_T("\n"),pos);
1508 int start=one.Find(_T(" "),0);
1509 if(start>0)
1511 CString name;
1512 name=one.Right(one.GetLength()-start-1);
1514 CString hash;
1515 hash=one.Left(start);
1517 map[CGitHash(hash)].push_back(name);
1522 return ret;
1525 BOOL CGit::CheckMsysGitDir()
1527 if (m_bInitialized)
1529 return TRUE;
1532 this->m_Environment.clear();
1533 m_Environment.CopyProcessEnvironment();
1535 TCHAR *oldpath;
1536 size_t homesize,size;
1538 // set HOME if not set already
1539 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1540 if (!homesize)
1542 CString home = g_Git.GetHomeDirectory();
1543 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1544 home.ReleaseBuffer();
1546 CString str;
1548 //setup ssh client
1549 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1551 if(!sshclient.IsEmpty())
1553 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1554 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1556 else
1558 TCHAR sPlink[MAX_PATH];
1559 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1560 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1561 if (ptr) {
1562 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoisePlink.exe"));
1563 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1564 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1569 TCHAR sAskPass[MAX_PATH];
1570 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1571 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1572 if (ptr)
1574 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1575 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1576 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1577 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1581 // add git/bin path to PATH
1583 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1584 str=msysdir;
1585 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1587 CRegString msysinstalldir=CRegString(REG_MSYSGIT_INSTALL,_T(""),FALSE,HKEY_LOCAL_MACHINE);
1588 str=msysinstalldir;
1589 if ( !str.IsEmpty() )
1591 str += (str[str.GetLength()-1] != '\\') ? "\\bin" : "bin";
1592 msysdir=str;
1593 CGit::ms_LastMsysGitDir = str;
1594 msysdir.write();
1596 else
1598 // search PATH if git/bin directory is already present
1599 if ( FindGitPath() )
1601 m_bInitialized = TRUE;
1602 msysdir = CGit::ms_LastMsysGitDir;
1603 msysdir.write();
1604 return TRUE;
1607 return FALSE;
1610 else
1612 CGit::ms_LastMsysGitDir = str;
1615 // check for git.exe existance (maybe it was deinstalled in the meantime)
1616 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1617 return FALSE;
1619 //set path
1620 _tdupenv_s(&oldpath,&size,_T("PATH"));
1622 CString path;
1623 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1625 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1627 CString str1 = m_Environment.GetEnv(_T("PATH"));
1629 CString sOldPath = oldpath;
1630 free(oldpath);
1632 m_bInitialized = TRUE;
1633 return true;
1636 CString CGit::GetHomeDirectory()
1638 const wchar_t * homeDir = wget_windows_home_directory();
1639 return CString(homeDir, (int)wcslen(homeDir));
1642 CString CGit::GetGitSystemConfig()
1644 const wchar_t * systemConfig = wget_msysgit_etc();
1645 return CString(systemConfig, (int)wcslen(systemConfig));
1648 BOOL CGit::CheckCleanWorkTree()
1650 CString out;
1651 CString cmd;
1652 cmd=_T("git.exe rev-parse --verify HEAD");
1654 if(g_Git.Run(cmd,&out,CP_UTF8))
1655 return FALSE;
1657 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1658 if(g_Git.Run(cmd,&out,CP_UTF8))
1659 return FALSE;
1661 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1662 if(g_Git.Run(cmd,&out,CP_UTF8))
1663 return FALSE;
1665 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1666 if(g_Git.Run(cmd,&out,CP_UTF8))
1667 return FALSE;
1669 return TRUE;
1671 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1673 int ret;
1674 for(int i=0;i<list.GetCount();i++)
1676 ret = Revert(commit, (CTGitPath&)list[i]);
1677 if(ret)
1678 return ret;
1680 return 0;
1682 int CGit::Revert(CString commit, CTGitPath &path)
1684 CString cmd, out;
1686 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1688 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1690 CString err;
1691 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1692 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1693 return -1;
1695 CString force;
1696 // if the filenames only differ in case, we have to pass "-f"
1697 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1698 force = _T("-f ");
1699 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1700 if (g_Git.Run(cmd, &out, CP_UTF8))
1702 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1703 return -1;
1706 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1707 if (g_Git.Run(cmd, &out, CP_UTF8))
1709 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1710 return -1;
1714 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1715 { //To init git repository, there are not HEAD, so we can use git reset command
1716 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1718 if (g_Git.Run(cmd, &out, CP_UTF8))
1720 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1721 return -1;
1724 else
1726 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1727 if (g_Git.Run(cmd, &out, CP_UTF8))
1729 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1730 return -1;
1734 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1736 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1737 if (g_Git.Run(cmd, &out, CP_UTF8))
1739 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1740 return -1;
1744 return 0;
1747 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1749 BYTE_VECTOR vector;
1751 CString cmd;
1752 if(path)
1753 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1754 else
1755 cmd=_T("git.exe ls-files -u -t -z");
1757 if (g_Git.Run(cmd, &vector))
1759 return -1;
1762 list.ParserFromLsFile(vector);
1764 return 0;
1767 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1769 CString base;
1770 CGitHash basehash,hash;
1771 CString cmd, err;
1772 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1774 if (g_Git.Run(cmd, &base, &err, CP_UTF8))
1776 //CMessageBox::Show(NULL, base + _T("\n") + err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1777 return false;
1779 basehash = base.Trim();
1781 hash=g_Git.GetHash(from);
1783 if (commonAncestor)
1784 *commonAncestor = basehash;
1786 return hash == basehash;
1789 unsigned int CGit::Hash2int(CGitHash &hash)
1791 int ret=0;
1792 for(int i=0;i<4;i++)
1794 ret = ret << 8;
1795 ret |= hash.m_hash[i];
1797 return ret;
1800 int CGit::RefreshGitIndex()
1802 if(g_Git.m_IsUseGitDLL)
1804 CAutoLocker lock(g_Git.m_critGitDllSec);
1807 return git_run_cmd("update-index","update-index -q --refresh");
1809 }catch(...)
1811 return -1;
1815 else
1817 CString cmd,output;
1818 cmd=_T("git.exe update-index --refresh");
1819 return Run(cmd, &output, CP_UTF8);
1823 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1825 if(g_Git.m_IsUseGitDLL)
1827 CAutoLocker lock(g_Git.m_critGitDllSec);
1830 g_Git.CheckAndInitDll();
1831 CStringA ref, patha, outa;
1832 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1833 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1834 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1835 ::DeleteFile(outputfile);
1836 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1838 }catch(...)
1840 return -1;
1843 else
1845 CString cmd;
1846 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1847 return g_Git.RunLogFile(cmd,outputfile);
1850 void CEnvironment::CopyProcessEnvironment()
1852 TCHAR *p = GetEnvironmentStrings();
1853 while(*p !=0 || *(p+1) !=0)
1854 this->push_back(*p++);
1856 push_back(_T('\0'));
1857 push_back(_T('\0'));
1860 CString CEnvironment::GetEnv(TCHAR *name)
1862 CString str;
1863 for (size_t i = 0; i < size(); i++)
1865 str = &(*this)[i];
1866 int start =0;
1867 CString sname = str.Tokenize(_T("="),start);
1868 if(sname.CompareNoCase(name) == 0)
1870 return &(*this)[i+start];
1872 i+=str.GetLength();
1874 return _T("");
1877 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
1879 unsigned int i;
1880 for( i=0;i<size();i++)
1882 CString str = &(*this)[i];
1883 int start =0;
1884 CString sname = str.Tokenize(_T("="),start);
1885 if(sname.CompareNoCase(name) == 0)
1887 break;
1889 i+=str.GetLength();
1892 if(i == size())
1894 i -= 1; // roll back terminate \0\0
1895 this->push_back(_T('\0'));
1898 CEnvironment::iterator it;
1899 it=this->begin();
1900 it += i;
1902 while(*it && i<size())
1904 this->erase(it);
1905 it=this->begin();
1906 it += i;
1909 while(*name)
1911 this->insert(it,*name++);
1912 i++;
1913 it= begin()+i;
1916 this->insert(it, _T('='));
1917 i++;
1918 it= begin()+i;
1920 while(*value)
1922 this->insert(it,*value++);
1923 i++;
1924 it= begin()+i;
1929 int CGit::GetGitEncode(TCHAR* configkey)
1931 CString str=GetConfigValue(configkey);
1933 if(str.IsEmpty())
1934 return CP_UTF8;
1936 return CUnicodeUtils::GetCPCode(str);
1940 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
1942 GIT_FILE file=0;
1943 int ret=0;
1944 GIT_DIFF diff=0;
1946 CAutoLocker lock(g_Git.m_critGitDllSec);
1948 if(arg == NULL)
1949 diff = GetGitDiff();
1950 else
1951 git_open_diff(&diff, arg);
1953 if(diff ==NULL)
1954 return -1;
1956 bool isStat = 0;
1957 if(arg == NULL)
1958 isStat = true;
1959 else
1960 isStat = !!strstr(arg, "stat");
1962 int count=0;
1964 if(hash2 == NULL)
1965 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
1966 else
1967 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
1969 if(ret)
1970 return -1;
1972 CTGitPath path;
1973 CString strnewname;
1974 CString stroldname;
1976 for(int j=0;j<count;j++)
1978 path.Reset();
1979 char *newname;
1980 char *oldname;
1982 strnewname.Empty();
1983 stroldname.Empty();
1985 int mode=0,IsBin=0,inc=0,dec=0;
1986 git_get_diff_file(diff,file,j,&newname,&oldname,
1987 &mode,&IsBin,&inc,&dec);
1989 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
1990 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
1992 path.SetFromGit(strnewname,&stroldname);
1993 path.ParserAction((BYTE)mode);
1995 if(IsBin)
1997 path.m_StatAdd=_T("-");
1998 path.m_StatDel=_T("-");
2000 else
2002 path.m_StatAdd.Format(_T("%d"),inc);
2003 path.m_StatDel.Format(_T("%d"),dec);
2005 PathList->AddPath(path);
2007 git_diff_flush(diff);
2009 if(arg)
2010 git_close_diff(diff);
2012 return 0;
2015 int CGit::GetShortHASHLength()
2017 return 7;