Moved #include "git2.h" to stdafx.h
[TortoiseGit.git] / src / Git / Git.cpp
blob3c9531c2f0fb9c3bf3e78faadcc4b0fbba38830f
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2013 - 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(wchar_t *path, wchar_t *buf, size_t buflen)
36 wchar_t term, *base = path;
38 if (path == NULL || buf == NULL || buflen == 0)
39 return NULL;
41 term = (*path == L'"') ? *path++ : L';';
43 for (buflen--; *path && *path != term && buflen; buflen--)
44 *buf++ = *path++;
46 *buf = L'\0'; /* reserved a byte via initial subtract */
48 while (*path == term || *path == L';')
49 ++path;
51 return (path != base) ? path : NULL;
54 static inline BOOL FileExists(LPCTSTR lpszFileName)
56 struct _stat st;
57 return _tstat(lpszFileName, &st) == 0;
60 static BOOL FindGitPath()
62 size_t size;
63 _tgetenv_s(&size, NULL, 0, _T("PATH"));
65 if (!size)
67 return FALSE;
70 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
71 _tgetenv_s(&size, env, size, _T("PATH"));
73 TCHAR buf[MAX_PATH];
75 // search in all paths defined in PATH
76 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
78 TCHAR *pfin = buf + _tcslen(buf)-1;
80 // ensure trailing slash
81 if (*pfin != _T('/') && *pfin != _T('\\'))
82 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len = _tcslen(buf);
86 if ((len + 7) < MAX_PATH)
87 _tcscpy_s(pfin + 1, MAX_PATH - len, _T("git.exe"));
88 else
89 break;
91 if ( FileExists(buf) )
93 // dir found
94 pfin[1] = 0;
95 CGit::ms_LastMsysGitDir = buf;
96 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir))
103 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
105 return TRUE;
109 return FALSE;
112 static bool g_bSortLogical;
113 static bool g_bSortLocalBranchesFirst;
115 static void GetSortOptions()
117 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
118 if (g_bSortLogical)
119 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
120 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
121 if (g_bSortLocalBranchesFirst)
122 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
125 static int LogicalComparePredicate(CString &left, CString &right)
127 if (g_bSortLogical)
128 return StrCmpLogicalW(left, right) < 0;
129 return StrCmpI(left, right) < 0;
132 static int LogicalCompareBranchesPredicate(CString &left, CString &right)
134 if (g_bSortLocalBranchesFirst)
136 int leftIsRemote = left.Find(_T("remotes/"));
137 int rightIsRemote = right.Find(_T("remotes/"));
139 if (leftIsRemote == 0 && rightIsRemote < 0)
140 return false;
141 else if (leftIsRemote < 0 && rightIsRemote == 0)
142 return true;
144 if (g_bSortLogical)
145 return StrCmpLogicalW(left, right) < 0;
146 return StrCmpI(left, right) < 0;
149 #define MAX_DIRBUFFER 1000
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString CGit::ms_LastMsysGitDir;
153 CGit g_Git;
156 CGit::CGit(void)
158 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
159 m_CurrentDir.ReleaseBuffer();
160 m_IsGitDllInited = false;
161 m_GitDiff=0;
162 m_GitSimpleListDiff=0;
163 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
164 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
165 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), 0);
167 GetSortOptions();
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;
319 BOOL CGit::IsOrphanBranch(CString ref)
321 if (ref.IsEmpty())
322 ref = _T("HEAD");
324 CString cmdout;
325 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
327 return TRUE;
329 if(cmdout.IsEmpty())
330 return TRUE;
332 return FALSE;
335 BOOL CGit::IsInitRepos()
337 return IsOrphanBranch(_T("HEAD"));
340 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
342 PASYNCREADSTDERRTHREADARGS pDataArray;
343 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
345 DWORD readnumber;
346 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
347 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
349 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
350 break;
353 return 0;
356 int CGit::Run(CGitCall* pcall)
358 PROCESS_INFORMATION pi;
359 HANDLE hRead, hReadErr;
360 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
361 return TGIT_GIT_ERROR_CREATE_PROCESS;
363 HANDLE thread;
364 ASYNCREADSTDERRTHREADARGS threadArguments;
365 threadArguments.fileHandle = hReadErr;
366 threadArguments.pcall = pcall;
367 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
369 DWORD readnumber;
370 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
371 bool bAborted=false;
372 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
374 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
375 if(!bAborted)//For now, flush output when command aborted.
376 if(pcall->OnOutputData(data,readnumber))
377 bAborted=true;
379 if(!bAborted)
380 pcall->OnEnd();
382 if (thread)
383 WaitForSingleObject(thread, INFINITE);
385 CloseHandle(pi.hThread);
387 WaitForSingleObject(pi.hProcess, INFINITE);
388 DWORD exitcode =0;
390 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
392 return TGIT_GIT_ERROR_GET_EXIT_CODE;
395 CloseHandle(pi.hProcess);
397 CloseHandle(hRead);
398 CloseHandle(hReadErr);
399 return exitcode;
401 class CGitCall_ByteVector : public CGitCall
403 public:
404 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
405 virtual bool OnOutputData(const BYTE* data, size_t size)
407 if (size == 0)
408 return false;
409 size_t oldsize=m_pvector->size();
410 m_pvector->resize(m_pvector->size()+size);
411 memcpy(&*(m_pvector->begin()+oldsize),data,size);
412 return false;
414 virtual bool OnOutputErrData(const BYTE* data, size_t size)
416 if (!m_pvectorErr || size == 0)
417 return false;
418 size_t oldsize = m_pvectorErr->size();
419 m_pvectorErr->resize(m_pvectorErr->size() + size);
420 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
421 return false;
423 BYTE_VECTOR* m_pvector;
424 BYTE_VECTOR* m_pvectorErr;
427 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
429 CGitCall_ByteVector call(cmd, vector, vectorErr);
430 return Run(&call);
432 int CGit::Run(CString cmd, CString* output, int code)
434 CString err;
435 int ret;
436 ret = Run(cmd, output, &err, code);
438 if (output && !err.IsEmpty())
440 if (!output->IsEmpty())
441 *output += _T("\n");
442 *output += err;
445 return ret;
447 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
449 BYTE_VECTOR vector, vectorErr;
450 int ret;
451 if (outputErr)
452 ret = Run(cmd, &vector, &vectorErr);
453 else
454 ret = Run(cmd, &vector);
456 vector.push_back(0);
457 StringAppend(output, &(vector[0]), code);
459 if (outputErr)
461 vectorErr.push_back(0);
462 StringAppend(outputErr, &(vectorErr[0]), code);
465 return ret;
468 CString CGit::GetUserName(void)
470 CEnvironment env;
471 env.CopyProcessEnvironment();
472 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
473 if (!envname.IsEmpty())
474 return envname;
475 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
477 CString CGit::GetUserEmail(void)
479 CEnvironment env;
480 env.CopyProcessEnvironment();
481 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
482 if (!envmail.IsEmpty())
483 return envmail;
485 return GetConfigValue(L"user.email");
488 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
490 CString configValue;
491 int start = 0;
492 if(this->m_IsUseGitDLL)
494 CString *git_path=NULL;
496 CAutoLocker lock(g_Git.m_critGitDllSec);
500 CTGitPath path;
502 CheckAndInitDll();
503 git_path = GitPath;
505 }catch(...)
508 CStringA key, value;
509 key = CUnicodeUtils::GetMulti(name, encoding);
510 CStringA p;
511 if(git_path)
512 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
514 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
515 return CString();
516 else
518 StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
519 if(RemoveCR)
520 return configValue.Tokenize(_T("\n"),start);
521 return configValue;
525 else
527 CString cmd;
528 cmd.Format(L"git.exe config %s", name);
529 Run(cmd, &configValue, NULL, encoding);
530 if(RemoveCR)
531 return configValue.Tokenize(_T("\n"),start);
532 return configValue;
536 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
538 if(this->m_IsUseGitDLL)
540 CAutoLocker lock(g_Git.m_critGitDllSec);
544 CheckAndInitDll();
546 }catch(...)
549 CStringA keya, valuea;
550 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
551 valuea = CUnicodeUtils::GetMulti(value, encoding);
552 CStringA p;
553 if(GitPath)
554 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
556 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
559 else
561 CString cmd;
562 CString option;
563 switch(type)
565 case CONFIG_GLOBAL:
566 option = _T("--global");
567 break;
568 case CONFIG_SYSTEM:
569 option = _T("--system");
570 break;
571 default:
572 break;
574 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
575 CString out;
576 if (Run(cmd, &out, NULL, encoding))
578 return -1;
581 return 0;
584 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
586 if(this->m_IsUseGitDLL)
588 CAutoLocker lock(g_Git.m_critGitDllSec);
592 CheckAndInitDll();
593 }catch(...)
596 CStringA keya;
597 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
598 CStringA p;
599 if(GitPath)
600 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
602 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
604 else
606 CString cmd;
607 CString option;
608 switch(type)
610 case CONFIG_GLOBAL:
611 option = _T("--global");
612 break;
613 case CONFIG_SYSTEM:
614 option = _T("--system");
615 break;
616 default:
617 break;
619 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
620 CString out;
621 if (Run(cmd, &out, NULL, encoding))
623 return -1;
626 return 0;
629 CString CGit::GetCurrentBranch(void)
631 CString output;
632 //Run(_T("git.exe branch"),&branch);
634 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
636 return _T("(no branch)");
638 else
639 return output;
643 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
645 CString refName;
646 if(this->m_IsUseGitDLL)
648 unsigned char sha1[20];
649 int flag;
651 CAutoLocker lock(g_Git.m_critGitDllSec);
652 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
653 if(refs_heads_master && (flag&REF_ISSYMREF))
655 StringAppend(&refName,(BYTE*)refs_heads_master);
656 if(bStripRefsHeads)
657 refName = StripRefName(refName);
661 else
663 CString cmd;
664 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
665 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
666 return CString();//Error
667 int iStart = 0;
668 refName = refName.Tokenize(L"\n", iStart);
669 if(bStripRefsHeads)
670 refName = StripRefName(refName);
672 return refName;
675 CString CGit::GetFullRefName(CString shortRefName)
677 CString refName;
678 CString cmd;
679 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
680 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
681 return CString();//Error
682 int iStart = 0;
683 return refName.Tokenize(L"\n", iStart);
686 CString CGit::StripRefName(CString refName)
688 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
689 refName = refName.Mid(11);
690 else if(wcsncmp(refName, L"refs/", 5) == 0)
691 refName = refName.Mid(5);
692 int start =0;
693 return refName.Tokenize(_T("\n"),start);
696 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
698 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
700 if ( sProjectRoot.IsEmpty() )
701 return -1;
703 CString sDotGitPath;
704 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
705 return -1;
707 CString sHeadFile = sDotGitPath + _T("HEAD");
709 FILE *pFile;
710 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
712 if (!pFile)
714 return -1;
717 char s[256] = {0};
718 fgets(s, sizeof(s), pFile);
720 fclose(pFile);
722 const char *pfx = "ref: refs/heads/";
723 const int len = 16;//strlen(pfx)
725 if ( !strncmp(s, pfx, len) )
727 //# We're on a branch. It might not exist. But
728 //# HEAD looks good enough to be a branch.
729 CStringA utf8Branch(s + len);
730 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
731 sBranchOut.TrimRight(_T(" \r\n\t"));
733 if ( sBranchOut.IsEmpty() )
734 return -1;
736 else
738 //# Assume this is a detached head.
739 sBranchOut = "HEAD";
741 return 1;
744 return 0;
747 int CGit::BuildOutputFormat(CString &format,bool IsFull)
749 CString log;
750 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
751 format += log;
752 if(IsFull)
754 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
755 format += log;
756 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
757 format += log;
758 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
759 format += log;
760 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
761 format += log;
762 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
763 format += log;
764 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
765 format += log;
766 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
767 format += log;
770 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
771 format += log;
772 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
773 format += log;
774 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
775 format += log;
777 if(IsFull)
779 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
780 format += log;
782 return 0;
785 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
787 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
788 return GetLog(&gitCall,hash,path,count,mask,from,to);
791 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
792 CFilterData *Filter)
794 CString cmd;
795 CString num;
796 CString since;
798 CString file;
800 if(path)
801 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
803 if(count>0)
804 num.Format(_T("-n%d"),count);
806 CString param;
808 if(mask& LOG_INFO_STAT )
809 param += _T(" --numstat ");
810 if(mask& LOG_INFO_FILESTATE)
811 param += _T(" --raw ");
813 if(mask& LOG_INFO_FULLHISTORY)
814 param += _T(" --full-history ");
816 if(mask& LOG_INFO_BOUNDARY)
817 param += _T(" --left-right --boundary ");
819 if(mask& CGit::LOG_INFO_ALL_BRANCH)
820 param += _T(" --all ");
822 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
823 param += _T(" -C ");
825 if(mask& CGit::LOG_INFO_DETECT_RENAME )
826 param += _T(" -M ");
828 if(mask& CGit::LOG_INFO_FIRST_PARENT )
829 param += _T(" --first-parent ");
831 if(mask& CGit::LOG_INFO_NO_MERGE )
832 param += _T(" --no-merges ");
834 if(mask& CGit::LOG_INFO_FOLLOW)
835 param += _T(" --follow ");
837 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
838 param += _T(" -c ");
840 if(mask& CGit::LOG_INFO_FULL_DIFF)
841 param += _T(" --full-diff ");
843 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
844 param += _T(" --simplify-by-decoration ");
846 if(from != NULL && to != NULL)
848 CString range;
849 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
850 param += range;
852 else if(to != NULL && hash.IsEmpty())
854 CString range;
855 range.Format(_T(" %s "), FixBranchName(*to));
856 param += range;
858 param+=hash;
860 CString st1,st2;
862 if( Filter && (Filter->m_From != -1))
864 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
865 param += st1;
868 if( Filter && (Filter->m_To != -1))
870 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
871 param += st2;
874 bool isgrep = false;
875 if( Filter && (!Filter->m_Author.IsEmpty()))
877 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
878 param += st1;
879 isgrep = true;
882 if( Filter && (!Filter->m_Committer.IsEmpty()))
884 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
885 param += st1;
886 isgrep = true;
889 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
891 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
892 param += st1;
893 isgrep = true;
896 if(Filter && isgrep)
898 if(!Filter->m_IsRegex)
899 param += _T(" --fixed-strings ");
901 param += _T(" --regexp-ignore-case --extended-regexp ");
904 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
905 param += _T(" --topo-order");
907 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
908 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
909 else
911 CString log;
912 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
913 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
914 num,param,log);
917 cmd += file;
919 return cmd;
921 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
922 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
924 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
926 return Run(pgitCall);
927 // return Run(cmd,&logOut);
930 #define BUFSIZE 512
931 void GetTempPath(CString &path)
933 TCHAR lpPathBuffer[BUFSIZE];
934 DWORD dwRetVal;
935 DWORD dwBufSize=BUFSIZE;
936 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
937 lpPathBuffer); // buffer for path
938 if (dwRetVal > dwBufSize || (dwRetVal == 0))
940 path=_T("");
942 path.Format(_T("%s"),lpPathBuffer);
944 CString GetTempFile()
946 TCHAR lpPathBuffer[BUFSIZE];
947 DWORD dwRetVal;
948 DWORD dwBufSize=BUFSIZE;
949 TCHAR szTempName[BUFSIZE];
950 UINT uRetVal;
952 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
953 lpPathBuffer); // buffer for path
954 if (dwRetVal > dwBufSize || (dwRetVal == 0))
956 return _T("");
958 // Create a temporary file.
959 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
960 TEXT("Patch"), // temp file name prefix
961 0, // create unique name
962 szTempName); // buffer for name
965 if (uRetVal == 0)
967 return _T("");
970 return CString(szTempName);
974 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
976 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
977 if (result == 0) return 0;
978 if (lpBuffer == NULL || (result + 13 > nBufferLength))
980 if (lpBuffer)
981 lpBuffer[0] = '\0';
982 return result + 13;
985 _tcscat(lpBuffer, _T("TortoiseGit\\"));
986 CreateDirectory(lpBuffer, NULL);
988 return result + 13;
991 int CGit::RunLogFile(CString cmd,const CString &filename)
993 STARTUPINFO si;
994 PROCESS_INFORMATION pi;
995 si.cb=sizeof(STARTUPINFO);
996 GetStartupInfo(&si);
998 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
999 psa.bInheritHandle=TRUE;
1001 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1002 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1004 si.wShowWindow = SW_HIDE;
1005 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1006 si.hStdOutput = houtfile;
1008 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1009 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1011 if(cmd.Find(_T("git")) == 0)
1012 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1014 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1016 LPVOID lpMsgBuf;
1017 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1018 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1019 (LPTSTR)&lpMsgBuf,
1020 0,NULL);
1021 return TGIT_GIT_ERROR_CREATE_PROCESS;
1024 WaitForSingleObject(pi.hProcess,INFINITE);
1026 CloseHandle(pi.hThread);
1027 CloseHandle(pi.hProcess);
1028 CloseHandle(houtfile);
1029 return TGIT_GIT_SUCCESS;
1030 // return 0;
1033 int CGit::GetHash(CGitHash &hash, TCHAR* friendname)
1035 // no need to parse a ref if it's already a 40-byte hash
1036 if (CGitHash::IsValidSHA1(friendname))
1038 CString sHash(friendname);
1039 hash = CGitHash(sHash);
1040 return 0;
1043 if (m_IsUseLibGit2)
1045 git_repository *repo = NULL;
1046 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1047 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1049 gitdirA.ReleaseBuffer();
1050 return -1;
1052 gitdirA.ReleaseBuffer();
1054 int isHeadOrphan = git_repository_head_orphan(repo);
1055 if (isHeadOrphan != 0)
1057 git_repository_free(repo);
1058 hash.Empty();
1059 if (isHeadOrphan == 1)
1060 return 0;
1061 else
1062 return -1;
1065 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1067 git_object * gitObject = NULL;
1068 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1070 refnameA.ReleaseBuffer();
1071 git_repository_free(repo);
1072 return -1;
1074 refnameA.ReleaseBuffer();
1076 const git_oid * oid = git_object_id(gitObject);
1077 if (oid == NULL)
1079 git_object_free(gitObject);
1080 git_repository_free(repo);
1081 return -1;
1084 hash = CGitHash((char *)oid->id);
1086 git_object_free(gitObject); // also frees oid
1087 git_repository_free(repo);
1089 return 0;
1091 else
1093 CString cmd;
1094 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1095 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1096 hash = CGitHash(gitLastErr.Trim());
1097 return ret;
1101 int CGit::GetInitAddList(CTGitPathList &outputlist)
1103 CString cmd;
1104 BYTE_VECTOR cmdout;
1106 cmd=_T("git.exe ls-files -s -t -z");
1107 outputlist.Clear();
1108 if (Run(cmd, &cmdout))
1109 return -1;
1111 outputlist.ParserFromLsFile(cmdout);
1112 for(int i = 0; i < outputlist.GetCount(); ++i)
1113 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1115 return 0;
1117 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1119 CString cmd;
1121 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1123 //rev1=+_T("");
1124 if(rev1 == GIT_REV_ZERO)
1125 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1126 else
1127 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1129 else
1131 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1134 BYTE_VECTOR out;
1135 if (Run(cmd, &out))
1136 return -1;
1138 outputlist.ParserFromLog(out);
1140 return 0;
1143 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1145 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1146 CString str;
1147 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1148 list->push_back(str);
1149 return 0;
1152 int CGit::GetTagList(STRING_VECTOR &list)
1154 if (this->m_IsUseLibGit2)
1156 git_repository *repo = NULL;
1158 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1159 if (git_repository_open(&repo, gitdir.GetBuffer()))
1161 gitdir.ReleaseBuffer();
1162 return -1;
1164 gitdir.ReleaseBuffer();
1166 git_strarray tag_names;
1168 if (git_tag_list(&tag_names, repo))
1170 git_repository_free(repo);
1171 return -1;
1174 for (size_t i = 0; i < tag_names.count; ++i)
1176 CStringA tagName(tag_names.strings[i]);
1177 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1180 git_strarray_free(&tag_names);
1182 git_repository_free(repo);
1184 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1186 return 0;
1188 else
1190 CString cmd, output;
1191 cmd=_T("git.exe tag -l");
1192 int ret = Run(cmd, &output, NULL, CP_UTF8);
1193 if(!ret)
1195 int pos=0;
1196 CString one;
1197 while( pos>=0 )
1199 one=output.Tokenize(_T("\n"),pos);
1200 if (!one.IsEmpty())
1201 list.push_back(one);
1203 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1205 return ret;
1210 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1211 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1213 CString CGit::GetGitLastErr(CString msg)
1215 if (this->m_IsUseLibGit2)
1216 return GetLibGit2LastErr(msg);
1217 else if (gitLastErr.IsEmpty())
1218 return msg + _T("\nUnknown git.exe error.");
1219 else
1221 CString lastError = gitLastErr;
1222 gitLastErr.Empty();
1223 return msg + _T("\n") + lastError;
1227 CString CGit::GetLibGit2LastErr()
1229 const git_error *libgit2err = giterr_last();
1230 if (libgit2err)
1232 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1233 giterr_clear();
1234 return _T("libgit2 returned: ") + lastError;
1236 else
1237 return _T("An error occoured in libgit2, but no message is available.");
1240 CString CGit::GetLibGit2LastErr(CString msg)
1242 if (!msg.IsEmpty())
1243 return msg + _T("\n") + GetLibGit2LastErr();
1244 return GetLibGit2LastErr();
1247 CString CGit::FixBranchName_Mod(CString& branchName)
1249 if(branchName == "FETCH_HEAD")
1250 branchName = DerefFetchHead();
1251 return branchName;
1254 CString CGit::FixBranchName(const CString& branchName)
1256 CString tempBranchName = branchName;
1257 FixBranchName_Mod(tempBranchName);
1258 return tempBranchName;
1261 bool CGit::IsBranchTagNameUnique(const CString& name)
1263 CString output;
1265 CString cmd;
1266 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1267 int ret = Run(cmd, &output, NULL, CP_UTF8);
1268 if (!ret)
1270 int i = 0, pos = 0;
1271 while (pos >= 0)
1273 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1274 ++i;
1276 if (i >= 2)
1277 return false;
1280 return true;
1284 Checks if a branch or tag with the given name exists
1285 isBranch is true -> branch, tag otherwise
1287 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1289 CString cmd, output;
1291 cmd = _T("git show-ref ");
1292 if (isBranch)
1293 cmd += _T("--heads ");
1294 else
1295 cmd += _T("--tags ");
1297 cmd += _T("refs/heads/") + name;
1298 cmd += _T(" refs/tags/") + name;
1300 int ret = Run(cmd, &output, NULL, CP_UTF8);
1301 if (!ret)
1303 if (!output.IsEmpty())
1304 return true;
1307 return false;
1310 CString CGit::DerefFetchHead()
1312 using namespace std;
1313 CString dotGitPath;
1314 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1315 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1316 int forMergeLineCount = 0;
1317 string line;
1318 string hashToReturn;
1319 while(getline(fetchHeadFile, line))
1321 //Tokenize this line
1322 string::size_type prevPos = 0;
1323 string::size_type pos = line.find('\t');
1324 if(pos == string::npos) continue; //invalid line
1326 string hash = line.substr(0, pos);
1327 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1329 bool forMerge = pos == prevPos;
1330 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1332 string remoteBranch = line.substr(prevPos, pos - prevPos);
1334 //Process this line
1335 if(forMerge)
1337 hashToReturn = hash;
1338 ++forMergeLineCount;
1339 if(forMergeLineCount > 1)
1340 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1344 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1347 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1349 int ret;
1350 CString cmd, output, cur;
1351 cmd = _T("git.exe branch --no-color");
1353 if((type&BRANCH_ALL) == BRANCH_ALL)
1354 cmd += _T(" -a");
1355 else if(type&BRANCH_REMOTE)
1356 cmd += _T(" -r");
1358 ret = Run(cmd, &output, NULL, CP_UTF8);
1359 if(!ret)
1361 int pos=0;
1362 CString one;
1363 while( pos>=0 )
1365 one=output.Tokenize(_T("\n"),pos);
1366 one.Trim(L" \r\n\t");
1367 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1368 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1369 if(one[0] == _T('*'))
1371 one = one.Mid(2);
1372 cur = one;
1374 if (one != _T("(no branch)"))
1375 list.push_back(one);
1379 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1380 list.push_back(L"FETCH_HEAD");
1382 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1384 if (current && cur != _T("(no branch)"))
1386 for (unsigned int i = 0; i < list.size(); ++i)
1388 if (list[i] == cur)
1390 *current = i;
1391 break;
1396 return ret;
1399 int CGit::GetRemoteList(STRING_VECTOR &list)
1401 if (this->m_IsUseLibGit2)
1403 git_repository *repo = NULL;
1405 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1406 if (git_repository_open(&repo, gitdir.GetBuffer()))
1408 gitdir.ReleaseBuffer();
1409 return -1;
1411 gitdir.ReleaseBuffer();
1413 git_strarray remotes;
1415 if (git_remote_list(&remotes, repo))
1417 git_repository_free(repo);
1418 return -1;
1421 for (size_t i = 0; i < remotes.count; ++i)
1423 CStringA remote(remotes.strings[i]);
1424 list.push_back(CUnicodeUtils::GetUnicode(remote));
1427 git_strarray_free(&remotes);
1429 git_repository_free(repo);
1431 std::sort(list.begin(), list.end());
1433 return 0;
1435 else
1437 int ret;
1438 CString cmd, output;
1439 cmd=_T("git.exe remote");
1440 ret = Run(cmd, &output, NULL, CP_UTF8);
1441 if(!ret)
1443 int pos=0;
1444 CString one;
1445 while( pos>=0 )
1447 one=output.Tokenize(_T("\n"),pos);
1448 if (!one.IsEmpty())
1449 list.push_back(one);
1452 return ret;
1456 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1458 CString cmd, out, err;
1459 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1460 if (Run(cmd, &out, &err, CP_UTF8))
1462 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1463 return -1;
1466 int pos = 0;
1467 while (pos >= 0)
1469 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1470 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1471 if (one.Find(_T("^{}")) >= 1)
1472 continue;
1473 if (!one.IsEmpty())
1474 list.push_back(one);
1476 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1477 return 0;
1480 int libgit2_addto_list_each_ref_fn(const char *refname, void *payload)
1482 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1483 CString str;
1484 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1485 list->push_back(str);
1486 return 0;
1489 int CGit::GetRefList(STRING_VECTOR &list)
1491 if (this->m_IsUseLibGit2)
1493 git_repository *repo = NULL;
1495 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1496 if (git_repository_open(&repo, gitdir.GetBuffer()))
1498 gitdir.ReleaseBuffer();
1499 return -1;
1501 gitdir.ReleaseBuffer();
1503 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_list_each_ref_fn, &list))
1505 git_repository_free(repo);
1506 return -1;
1509 git_repository_free(repo);
1511 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1513 return 0;
1515 else
1517 CString cmd, output;
1518 cmd=_T("git.exe show-ref -d");
1519 int ret = Run(cmd, &output, NULL, CP_UTF8);
1520 if(!ret)
1522 int pos=0;
1523 CString one;
1524 while( pos>=0 )
1526 one=output.Tokenize(_T("\n"),pos);
1527 int start=one.Find(_T(" "),0);
1528 if(start>0)
1530 CString name;
1531 name=one.Right(one.GetLength()-start-1);
1532 list.push_back(name);
1535 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1537 return ret;
1541 typedef struct map_each_ref_payload {
1542 git_repository * repo;
1543 MAP_HASH_NAME * map;
1544 } map_each_ref_payload;
1546 int libgit2_addto_map_each_ref_fn(const char *refname, void *payload)
1548 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1550 CString str;
1551 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1553 git_object * gitObject = NULL;
1557 if (git_revparse_single(&gitObject, payloadContent->repo, refname))
1559 break;
1562 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1564 str += _T("^{}"); // deref tag
1565 git_object * derefedTag = NULL;
1566 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1568 break;
1570 git_object_free(gitObject);
1571 gitObject = derefedTag;
1574 const git_oid * oid = git_object_id(gitObject);
1575 if (oid == NULL)
1577 break;
1580 CGitHash hash((char *)oid->id);
1581 (*payloadContent->map)[hash].push_back(str);
1582 } while (false);
1584 if (gitObject)
1586 git_object_free(gitObject);
1587 return 0;
1590 return 1;
1593 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1595 if (this->m_IsUseLibGit2)
1597 git_repository *repo = NULL;
1599 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1600 if (git_repository_open(&repo, gitdir.GetBuffer()))
1602 gitdir.ReleaseBuffer();
1603 return -1;
1605 gitdir.ReleaseBuffer();
1607 map_each_ref_payload payloadContent = { repo, &map };
1609 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_map_each_ref_fn, &payloadContent))
1611 git_repository_free(repo);
1612 return -1;
1615 git_repository_free(repo);
1617 for (auto it = map.begin(); it != map.end(); ++it)
1619 std::sort(it->second.begin(), it->second.end());
1622 return 0;
1624 else
1626 CString cmd, output;
1627 cmd=_T("git.exe show-ref -d");
1628 int ret = Run(cmd, &output, NULL, CP_UTF8);
1629 if(!ret)
1631 int pos=0;
1632 CString one;
1633 while( pos>=0 )
1635 one=output.Tokenize(_T("\n"),pos);
1636 int start=one.Find(_T(" "),0);
1637 if(start>0)
1639 CString name;
1640 name=one.Right(one.GetLength()-start-1);
1642 CString hash;
1643 hash=one.Left(start);
1645 map[CGitHash(hash)].push_back(name);
1649 return ret;
1653 BOOL CGit::CheckMsysGitDir()
1655 if (m_bInitialized)
1657 return TRUE;
1660 this->m_Environment.clear();
1661 m_Environment.CopyProcessEnvironment();
1663 TCHAR *oldpath;
1664 size_t homesize,size;
1666 // set HOME if not set already
1667 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1668 if (!homesize)
1670 CString home = GetHomeDirectory();
1671 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1672 home.ReleaseBuffer();
1674 CString str;
1676 //setup ssh client
1677 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1679 if(!sshclient.IsEmpty())
1681 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1682 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1684 else
1686 TCHAR sPlink[MAX_PATH];
1687 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1688 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1689 if (ptr) {
1690 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1691 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1692 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1697 TCHAR sAskPass[MAX_PATH];
1698 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1699 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1700 if (ptr)
1702 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1703 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1704 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1705 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1709 // add git/bin path to PATH
1711 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1712 str=msysdir;
1713 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1715 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1716 str = msyslocalinstalldir;
1717 str.TrimRight(_T("\\"));
1718 if (str.IsEmpty())
1720 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1721 str = msysinstalldir;
1722 str.TrimRight(_T("\\"));
1724 if ( !str.IsEmpty() )
1726 str += "\\bin";
1727 msysdir=str;
1728 CGit::ms_LastMsysGitDir = str;
1729 msysdir.write();
1731 else
1733 // search PATH if git/bin directory is already present
1734 if ( FindGitPath() )
1736 m_bInitialized = TRUE;
1737 msysdir = CGit::ms_LastMsysGitDir;
1738 msysdir.write();
1739 return TRUE;
1742 return FALSE;
1745 else
1747 CGit::ms_LastMsysGitDir = str;
1750 // check for git.exe existance (maybe it was deinstalled in the meantime)
1751 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1752 return FALSE;
1754 //set path
1755 _tdupenv_s(&oldpath,&size,_T("PATH"));
1757 CString path;
1758 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1760 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1762 CString str1 = m_Environment.GetEnv(_T("PATH"));
1764 CString sOldPath = oldpath;
1765 free(oldpath);
1767 m_bInitialized = TRUE;
1768 return true;
1771 CString CGit::GetHomeDirectory()
1773 const wchar_t * homeDir = wget_windows_home_directory();
1774 return CString(homeDir, (int)wcslen(homeDir));
1777 CString CGit::GetGitLocalConfig()
1779 CString path;
1780 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, path);
1781 path += _T("config");
1782 return path;
1785 CString CGit::GetGitGlobalConfig()
1787 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1790 CString CGit::GetGitGlobalXDGConfigPath()
1792 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1795 CString CGit::GetGitGlobalXDGConfig()
1797 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1800 CString CGit::GetGitSystemConfig()
1802 const wchar_t * systemConfig = wget_msysgit_etc();
1803 return CString(systemConfig, (int)wcslen(systemConfig));
1806 BOOL CGit::CheckCleanWorkTree()
1808 CString out;
1809 CString cmd;
1810 cmd=_T("git.exe rev-parse --verify HEAD");
1812 if(Run(cmd,&out,CP_UTF8))
1813 return FALSE;
1815 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1816 if(Run(cmd,&out,CP_UTF8))
1817 return FALSE;
1819 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1820 if(Run(cmd,&out,CP_UTF8))
1821 return FALSE;
1823 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1824 if(Run(cmd,&out,CP_UTF8))
1825 return FALSE;
1827 return TRUE;
1829 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1831 int ret;
1832 for (int i = 0; i < list.GetCount(); ++i)
1834 ret = Revert(commit, (CTGitPath&)list[i]);
1835 if(ret)
1836 return ret;
1838 return 0;
1840 int CGit::Revert(CString commit, CTGitPath &path)
1842 CString cmd, out;
1844 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1846 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1848 CString err;
1849 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1850 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1851 return -1;
1853 CString force;
1854 // if the filenames only differ in case, we have to pass "-f"
1855 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1856 force = _T("-f ");
1857 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1858 if (Run(cmd, &out, CP_UTF8))
1860 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1861 return -1;
1864 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1865 if (Run(cmd, &out, CP_UTF8))
1867 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1868 return -1;
1872 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1873 { //To init git repository, there are not HEAD, so we can use git reset command
1874 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1876 if (Run(cmd, &out, CP_UTF8))
1878 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1879 return -1;
1882 else
1884 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1885 if (Run(cmd, &out, CP_UTF8))
1887 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1888 return -1;
1892 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1894 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1895 if (Run(cmd, &out, CP_UTF8))
1897 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1898 return -1;
1902 return 0;
1905 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1907 BYTE_VECTOR vector;
1909 CString cmd;
1910 if(path)
1911 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1912 else
1913 cmd=_T("git.exe ls-files -u -t -z");
1915 if (Run(cmd, &vector))
1917 return -1;
1920 list.ParserFromLsFile(vector);
1922 return 0;
1925 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1927 CString base;
1928 CGitHash basehash,hash;
1929 CString cmd, err;
1930 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1932 if (Run(cmd, &base, &err, CP_UTF8))
1934 return false;
1936 basehash = base.Trim();
1938 GetHash(hash, from);
1940 if (commonAncestor)
1941 *commonAncestor = basehash;
1943 return hash == basehash;
1946 unsigned int CGit::Hash2int(CGitHash &hash)
1948 int ret=0;
1949 for (int i = 0; i < 4; ++i)
1951 ret = ret << 8;
1952 ret |= hash.m_hash[i];
1954 return ret;
1957 int CGit::RefreshGitIndex()
1959 if(g_Git.m_IsUseGitDLL)
1961 CAutoLocker lock(g_Git.m_critGitDllSec);
1964 return git_run_cmd("update-index","update-index -q --refresh");
1966 }catch(...)
1968 return -1;
1972 else
1974 CString cmd,output;
1975 cmd=_T("git.exe update-index --refresh");
1976 return Run(cmd, &output, CP_UTF8);
1980 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1982 if(g_Git.m_IsUseGitDLL)
1984 CAutoLocker lock(g_Git.m_critGitDllSec);
1987 g_Git.CheckAndInitDll();
1988 CStringA ref, patha, outa;
1989 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1990 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1991 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1992 ::DeleteFile(outputfile);
1993 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1995 }catch(...)
1997 return -1;
2000 else
2002 CString cmd;
2003 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2004 return RunLogFile(cmd,outputfile);
2007 void CEnvironment::CopyProcessEnvironment()
2009 TCHAR *p = GetEnvironmentStrings();
2010 while(*p !=0 || *(p+1) !=0)
2011 this->push_back(*p++);
2013 push_back(_T('\0'));
2014 push_back(_T('\0'));
2017 CString CEnvironment::GetEnv(TCHAR *name)
2019 CString str;
2020 for (size_t i = 0; i < size(); ++i)
2022 str = &(*this)[i];
2023 int start =0;
2024 CString sname = str.Tokenize(_T("="),start);
2025 if(sname.CompareNoCase(name) == 0)
2027 return &(*this)[i+start];
2029 i+=str.GetLength();
2031 return _T("");
2034 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
2036 unsigned int i;
2037 for (i = 0; i < size(); ++i)
2039 CString str = &(*this)[i];
2040 int start =0;
2041 CString sname = str.Tokenize(_T("="),start);
2042 if(sname.CompareNoCase(name) == 0)
2044 break;
2046 i+=str.GetLength();
2049 if(i == size())
2051 i -= 1; // roll back terminate \0\0
2052 this->push_back(_T('\0'));
2055 CEnvironment::iterator it;
2056 it=this->begin();
2057 it += i;
2059 while(*it && i<size())
2061 this->erase(it);
2062 it=this->begin();
2063 it += i;
2066 while(*name)
2068 this->insert(it,*name++);
2069 ++i;
2070 it= begin()+i;
2073 this->insert(it, _T('='));
2074 ++i;
2075 it= begin()+i;
2077 while(*value)
2079 this->insert(it,*value++);
2080 ++i;
2081 it= begin()+i;
2086 int CGit::GetGitEncode(TCHAR* configkey)
2088 CString str=GetConfigValue(configkey);
2090 if(str.IsEmpty())
2091 return CP_UTF8;
2093 return CUnicodeUtils::GetCPCode(str);
2097 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2099 GIT_FILE file=0;
2100 int ret=0;
2101 GIT_DIFF diff=0;
2103 CAutoLocker lock(g_Git.m_critGitDllSec);
2105 if(arg == NULL)
2106 diff = GetGitDiff();
2107 else
2108 git_open_diff(&diff, arg);
2110 if(diff ==NULL)
2111 return -1;
2113 bool isStat = 0;
2114 if(arg == NULL)
2115 isStat = true;
2116 else
2117 isStat = !!strstr(arg, "stat");
2119 int count=0;
2121 if(hash2 == NULL)
2122 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2123 else
2124 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2126 if(ret)
2127 return -1;
2129 CTGitPath path;
2130 CString strnewname;
2131 CString stroldname;
2133 for (int j = 0; j < count; ++j)
2135 path.Reset();
2136 char *newname;
2137 char *oldname;
2139 strnewname.Empty();
2140 stroldname.Empty();
2142 int mode=0,IsBin=0,inc=0,dec=0;
2143 git_get_diff_file(diff,file,j,&newname,&oldname,
2144 &mode,&IsBin,&inc,&dec);
2146 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2147 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2149 path.SetFromGit(strnewname,&stroldname);
2150 path.ParserAction((BYTE)mode);
2152 if(IsBin)
2154 path.m_StatAdd=_T("-");
2155 path.m_StatDel=_T("-");
2157 else
2159 path.m_StatAdd.Format(_T("%d"),inc);
2160 path.m_StatDel.Format(_T("%d"),dec);
2162 PathList->AddPath(path);
2164 git_diff_flush(diff);
2166 if(arg)
2167 git_close_diff(diff);
2169 return 0;
2172 int CGit::GetShortHASHLength()
2174 return 7;
2177 CString CGit::GetShortName(CString ref, REF_TYPE *out_type)
2179 CString str=ref;
2180 CString shortname;
2181 REF_TYPE type = CGit::UNKNOWN;
2183 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2185 type = CGit::LOCAL_BRANCH;
2188 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2190 type = CGit::REMOTE_BRANCH;
2192 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2194 type = CGit::TAG;
2196 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2198 type = CGit::STASH;
2199 shortname=_T("stash");
2201 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2203 if (shortname.Find(_T("good")) == 0)
2205 type = CGit::BISECT_GOOD;
2206 shortname = _T("good");
2209 if (shortname.Find(_T("bad")) == 0)
2211 type = CGit::BISECT_BAD;
2212 shortname = _T("bad");
2215 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2217 type = CGit::NOTES;
2219 else
2221 type = CGit::UNKNOWN;
2222 shortname = _T("Unknown");
2225 if(out_type)
2226 *out_type = type;
2228 return shortname;
2231 BOOL CGit::UsingLibGit2(int cmd)
2233 if (cmd >= 0 && cmd < 32)
2234 return ((1 << cmd) & m_IsUseLibGit2_mask) ? FALSE : TRUE;
2235 return FALSE;