fb662cbabfd53572165a2142ae0960faa6e506e8
[TortoiseGit.git] / src / Git / Git.cpp
blobfb662cbabfd53572165a2142ae0960faa6e506e8
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 // This method was originally used to check for orphaned branches
320 BOOL CGit::CanParseRev(CString ref)
322 if (ref.IsEmpty())
323 ref = _T("HEAD");
325 CString cmdout;
326 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
328 return FALSE;
330 if(cmdout.IsEmpty())
331 return FALSE;
333 return TRUE;
336 // Checks if we have an orphaned HEAD
337 BOOL CGit::IsInitRepos()
339 CGitHash hash;
340 // handle error on reading HEAD hash as init repo
341 if (GetHash(hash, _T("HEAD")) != 0)
342 return TRUE;
343 return hash.IsEmpty() ? TRUE : FALSE;
346 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
348 PASYNCREADSTDERRTHREADARGS pDataArray;
349 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
351 DWORD readnumber;
352 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
353 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
355 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
356 break;
359 return 0;
362 int CGit::Run(CGitCall* pcall)
364 PROCESS_INFORMATION pi;
365 HANDLE hRead, hReadErr;
366 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
367 return TGIT_GIT_ERROR_CREATE_PROCESS;
369 HANDLE thread;
370 ASYNCREADSTDERRTHREADARGS threadArguments;
371 threadArguments.fileHandle = hReadErr;
372 threadArguments.pcall = pcall;
373 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
375 DWORD readnumber;
376 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
377 bool bAborted=false;
378 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
380 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
381 if(!bAborted)//For now, flush output when command aborted.
382 if(pcall->OnOutputData(data,readnumber))
383 bAborted=true;
385 if(!bAborted)
386 pcall->OnEnd();
388 if (thread)
389 WaitForSingleObject(thread, INFINITE);
391 CloseHandle(pi.hThread);
393 WaitForSingleObject(pi.hProcess, INFINITE);
394 DWORD exitcode =0;
396 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
398 return TGIT_GIT_ERROR_GET_EXIT_CODE;
401 CloseHandle(pi.hProcess);
403 CloseHandle(hRead);
404 CloseHandle(hReadErr);
405 return exitcode;
407 class CGitCall_ByteVector : public CGitCall
409 public:
410 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
411 virtual bool OnOutputData(const BYTE* data, size_t size)
413 if (size == 0)
414 return false;
415 size_t oldsize=m_pvector->size();
416 m_pvector->resize(m_pvector->size()+size);
417 memcpy(&*(m_pvector->begin()+oldsize),data,size);
418 return false;
420 virtual bool OnOutputErrData(const BYTE* data, size_t size)
422 if (!m_pvectorErr || size == 0)
423 return false;
424 size_t oldsize = m_pvectorErr->size();
425 m_pvectorErr->resize(m_pvectorErr->size() + size);
426 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
427 return false;
429 BYTE_VECTOR* m_pvector;
430 BYTE_VECTOR* m_pvectorErr;
433 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
435 CGitCall_ByteVector call(cmd, vector, vectorErr);
436 return Run(&call);
438 int CGit::Run(CString cmd, CString* output, int code)
440 CString err;
441 int ret;
442 ret = Run(cmd, output, &err, code);
444 if (output && !err.IsEmpty())
446 if (!output->IsEmpty())
447 *output += _T("\n");
448 *output += err;
451 return ret;
453 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
455 BYTE_VECTOR vector, vectorErr;
456 int ret;
457 if (outputErr)
458 ret = Run(cmd, &vector, &vectorErr);
459 else
460 ret = Run(cmd, &vector);
462 vector.push_back(0);
463 StringAppend(output, &(vector[0]), code);
465 if (outputErr)
467 vectorErr.push_back(0);
468 StringAppend(outputErr, &(vectorErr[0]), code);
471 return ret;
474 CString CGit::GetUserName(void)
476 CEnvironment env;
477 env.CopyProcessEnvironment();
478 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
479 if (!envname.IsEmpty())
480 return envname;
481 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
483 CString CGit::GetUserEmail(void)
485 CEnvironment env;
486 env.CopyProcessEnvironment();
487 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
488 if (!envmail.IsEmpty())
489 return envmail;
491 return GetConfigValue(L"user.email");
494 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
496 CString configValue;
497 int start = 0;
498 if(this->m_IsUseGitDLL)
500 CString *git_path=NULL;
502 CAutoLocker lock(g_Git.m_critGitDllSec);
506 CTGitPath path;
508 CheckAndInitDll();
509 git_path = GitPath;
511 }catch(...)
514 CStringA key, value;
515 key = CUnicodeUtils::GetMulti(name, encoding);
516 CStringA p;
517 if(git_path)
518 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
520 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
521 return CString();
522 else
524 StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
525 if(RemoveCR)
526 return configValue.Tokenize(_T("\n"),start);
527 return configValue;
531 else
533 CString cmd;
534 cmd.Format(L"git.exe config %s", name);
535 Run(cmd, &configValue, NULL, encoding);
536 if(RemoveCR)
537 return configValue.Tokenize(_T("\n"),start);
538 return configValue;
542 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
544 if(this->m_IsUseGitDLL)
546 CAutoLocker lock(g_Git.m_critGitDllSec);
550 CheckAndInitDll();
552 }catch(...)
555 CStringA keya, valuea;
556 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
557 valuea = CUnicodeUtils::GetMulti(value, encoding);
558 CStringA p;
559 if(GitPath)
560 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
562 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
565 else
567 CString cmd;
568 CString option;
569 switch(type)
571 case CONFIG_GLOBAL:
572 option = _T("--global");
573 break;
574 case CONFIG_SYSTEM:
575 option = _T("--system");
576 break;
577 default:
578 break;
580 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
581 CString out;
582 if (Run(cmd, &out, NULL, encoding))
584 return -1;
587 return 0;
590 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
592 if(this->m_IsUseGitDLL)
594 CAutoLocker lock(g_Git.m_critGitDllSec);
598 CheckAndInitDll();
599 }catch(...)
602 CStringA keya;
603 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
604 CStringA p;
605 if(GitPath)
606 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
608 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
610 else
612 CString cmd;
613 CString option;
614 switch(type)
616 case CONFIG_GLOBAL:
617 option = _T("--global");
618 break;
619 case CONFIG_SYSTEM:
620 option = _T("--system");
621 break;
622 default:
623 break;
625 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
626 CString out;
627 if (Run(cmd, &out, NULL, encoding))
629 return -1;
632 return 0;
635 CString CGit::GetCurrentBranch(void)
637 CString output;
638 //Run(_T("git.exe branch"),&branch);
640 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
642 return _T("(no branch)");
644 else
645 return output;
649 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
651 CString refName;
652 if(this->m_IsUseGitDLL)
654 unsigned char sha1[20];
655 int flag;
657 CAutoLocker lock(g_Git.m_critGitDllSec);
658 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
659 if(refs_heads_master && (flag&REF_ISSYMREF))
661 StringAppend(&refName,(BYTE*)refs_heads_master);
662 if(bStripRefsHeads)
663 refName = StripRefName(refName);
667 else
669 CString cmd;
670 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
671 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
672 return CString();//Error
673 int iStart = 0;
674 refName = refName.Tokenize(L"\n", iStart);
675 if(bStripRefsHeads)
676 refName = StripRefName(refName);
678 return refName;
681 CString CGit::GetFullRefName(CString shortRefName)
683 CString refName;
684 CString cmd;
685 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
686 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
687 return CString();//Error
688 int iStart = 0;
689 return refName.Tokenize(L"\n", iStart);
692 CString CGit::StripRefName(CString refName)
694 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
695 refName = refName.Mid(11);
696 else if(wcsncmp(refName, L"refs/", 5) == 0)
697 refName = refName.Mid(5);
698 int start =0;
699 return refName.Tokenize(_T("\n"),start);
702 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
704 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
706 if ( sProjectRoot.IsEmpty() )
707 return -1;
709 CString sDotGitPath;
710 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
711 return -1;
713 CString sHeadFile = sDotGitPath + _T("HEAD");
715 FILE *pFile;
716 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
718 if (!pFile)
720 return -1;
723 char s[256] = {0};
724 fgets(s, sizeof(s), pFile);
726 fclose(pFile);
728 const char *pfx = "ref: refs/heads/";
729 const int len = 16;//strlen(pfx)
731 if ( !strncmp(s, pfx, len) )
733 //# We're on a branch. It might not exist. But
734 //# HEAD looks good enough to be a branch.
735 CStringA utf8Branch(s + len);
736 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
737 sBranchOut.TrimRight(_T(" \r\n\t"));
739 if ( sBranchOut.IsEmpty() )
740 return -1;
742 else
744 //# Assume this is a detached head.
745 sBranchOut = "HEAD";
747 return 1;
750 return 0;
753 int CGit::BuildOutputFormat(CString &format,bool IsFull)
755 CString log;
756 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
757 format += log;
758 if(IsFull)
760 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
761 format += log;
762 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
763 format += log;
764 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
765 format += log;
766 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
767 format += log;
768 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
769 format += log;
770 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
771 format += log;
772 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
773 format += log;
776 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
777 format += log;
778 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
779 format += log;
780 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
781 format += log;
783 if(IsFull)
785 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
786 format += log;
788 return 0;
791 CString CGit::GetLogCmd(CString &range, CTGitPath *path, int count, int mask, 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 param += range;
848 CString st1,st2;
850 if( Filter && (Filter->m_From != -1))
852 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
853 param += st1;
856 if( Filter && (Filter->m_To != -1))
858 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
859 param += st2;
862 bool isgrep = false;
863 if( Filter && (!Filter->m_Author.IsEmpty()))
865 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
866 param += st1;
867 isgrep = true;
870 if( Filter && (!Filter->m_Committer.IsEmpty()))
872 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
873 param += st1;
874 isgrep = true;
877 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
879 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
880 param += st1;
881 isgrep = true;
884 if(Filter && isgrep)
886 if(!Filter->m_IsRegex)
887 param += _T(" --fixed-strings ");
889 param += _T(" --regexp-ignore-case --extended-regexp ");
892 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
893 if (logOrderBy == LOG_ORDER_TOPOORDER)
894 param += _T(" --topo-order");
895 else if (logOrderBy == LOG_ORDER_DATEORDER)
896 param += _T(" --date-order");
898 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
899 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
900 else
902 CString log;
903 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
904 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
905 num,param,log);
908 cmd += file;
910 return cmd;
912 #define BUFSIZE 512
913 void GetTempPath(CString &path)
915 TCHAR lpPathBuffer[BUFSIZE];
916 DWORD dwRetVal;
917 DWORD dwBufSize=BUFSIZE;
918 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
919 lpPathBuffer); // buffer for path
920 if (dwRetVal > dwBufSize || (dwRetVal == 0))
922 path=_T("");
924 path.Format(_T("%s"),lpPathBuffer);
926 CString GetTempFile()
928 TCHAR lpPathBuffer[BUFSIZE];
929 DWORD dwRetVal;
930 DWORD dwBufSize=BUFSIZE;
931 TCHAR szTempName[BUFSIZE];
932 UINT uRetVal;
934 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
935 lpPathBuffer); // buffer for path
936 if (dwRetVal > dwBufSize || (dwRetVal == 0))
938 return _T("");
940 // Create a temporary file.
941 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
942 TEXT("Patch"), // temp file name prefix
943 0, // create unique name
944 szTempName); // buffer for name
947 if (uRetVal == 0)
949 return _T("");
952 return CString(szTempName);
956 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
958 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
959 if (result == 0) return 0;
960 if (lpBuffer == NULL || (result + 13 > nBufferLength))
962 if (lpBuffer)
963 lpBuffer[0] = '\0';
964 return result + 13;
967 _tcscat(lpBuffer, _T("TortoiseGit\\"));
968 CreateDirectory(lpBuffer, NULL);
970 return result + 13;
973 int CGit::RunLogFile(CString cmd,const CString &filename)
975 STARTUPINFO si;
976 PROCESS_INFORMATION pi;
977 si.cb=sizeof(STARTUPINFO);
978 GetStartupInfo(&si);
980 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
981 psa.bInheritHandle=TRUE;
983 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
984 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
986 si.wShowWindow = SW_HIDE;
987 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
988 si.hStdOutput = houtfile;
990 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
991 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
993 if(cmd.Find(_T("git")) == 0)
994 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
996 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
998 LPVOID lpMsgBuf;
999 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1000 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1001 (LPTSTR)&lpMsgBuf,
1002 0,NULL);
1003 return TGIT_GIT_ERROR_CREATE_PROCESS;
1006 WaitForSingleObject(pi.hProcess,INFINITE);
1008 CloseHandle(pi.hThread);
1009 CloseHandle(pi.hProcess);
1010 CloseHandle(houtfile);
1011 return TGIT_GIT_SUCCESS;
1012 // return 0;
1015 int CGit::GetHash(CGitHash &hash, TCHAR* friendname)
1017 // no need to parse a ref if it's already a 40-byte hash
1018 if (CGitHash::IsValidSHA1(friendname))
1020 CString sHash(friendname);
1021 hash = CGitHash(sHash);
1022 return 0;
1025 if (m_IsUseLibGit2)
1027 git_repository *repo = NULL;
1028 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1029 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1031 gitdirA.ReleaseBuffer();
1032 return -1;
1034 gitdirA.ReleaseBuffer();
1036 int isHeadOrphan = git_repository_head_orphan(repo);
1037 if (isHeadOrphan != 0)
1039 git_repository_free(repo);
1040 hash.Empty();
1041 if (isHeadOrphan == 1)
1042 return 0;
1043 else
1044 return -1;
1047 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1049 git_object * gitObject = NULL;
1050 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1052 refnameA.ReleaseBuffer();
1053 git_repository_free(repo);
1054 return -1;
1056 refnameA.ReleaseBuffer();
1058 const git_oid * oid = git_object_id(gitObject);
1059 if (oid == NULL)
1061 git_object_free(gitObject);
1062 git_repository_free(repo);
1063 return -1;
1066 hash = CGitHash((char *)oid->id);
1068 git_object_free(gitObject); // also frees oid
1069 git_repository_free(repo);
1071 return 0;
1073 else
1075 CString cmd;
1076 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1077 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1078 hash = CGitHash(gitLastErr.Trim());
1079 return ret;
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 (Run(cmd, &cmdout))
1091 return -1;
1093 outputlist.ParserFromLsFile(cmdout);
1094 for(int i = 0; i < outputlist.GetCount(); ++i)
1095 const_cast<CTGitPath&>(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 (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(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 = 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;
1192 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1193 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1195 CString CGit::GetGitLastErr(CString msg)
1197 if (this->m_IsUseLibGit2)
1198 return GetLibGit2LastErr(msg);
1199 else if (gitLastErr.IsEmpty())
1200 return msg + _T("\nUnknown git.exe error.");
1201 else
1203 CString lastError = gitLastErr;
1204 gitLastErr.Empty();
1205 return msg + _T("\n") + lastError;
1209 CString CGit::GetLibGit2LastErr()
1211 const git_error *libgit2err = giterr_last();
1212 if (libgit2err)
1214 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1215 giterr_clear();
1216 return _T("libgit2 returned: ") + lastError;
1218 else
1219 return _T("An error occoured in libgit2, but no message is available.");
1222 CString CGit::GetLibGit2LastErr(CString msg)
1224 if (!msg.IsEmpty())
1225 return msg + _T("\n") + GetLibGit2LastErr();
1226 return GetLibGit2LastErr();
1229 CString CGit::FixBranchName_Mod(CString& branchName)
1231 if(branchName == "FETCH_HEAD")
1232 branchName = DerefFetchHead();
1233 return branchName;
1236 CString CGit::FixBranchName(const CString& branchName)
1238 CString tempBranchName = branchName;
1239 FixBranchName_Mod(tempBranchName);
1240 return tempBranchName;
1243 bool CGit::IsBranchTagNameUnique(const CString& name)
1245 CString output;
1247 CString cmd;
1248 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1249 int ret = Run(cmd, &output, NULL, CP_UTF8);
1250 if (!ret)
1252 int i = 0, pos = 0;
1253 while (pos >= 0)
1255 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1256 ++i;
1258 if (i >= 2)
1259 return false;
1262 return true;
1266 Checks if a branch or tag with the given name exists
1267 isBranch is true -> branch, tag otherwise
1269 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1271 CString cmd, output;
1273 cmd = _T("git show-ref ");
1274 if (isBranch)
1275 cmd += _T("--heads ");
1276 else
1277 cmd += _T("--tags ");
1279 cmd += _T("refs/heads/") + name;
1280 cmd += _T(" refs/tags/") + name;
1282 int ret = Run(cmd, &output, NULL, CP_UTF8);
1283 if (!ret)
1285 if (!output.IsEmpty())
1286 return true;
1289 return false;
1292 CString CGit::DerefFetchHead()
1294 using namespace std;
1295 CString dotGitPath;
1296 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1297 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1298 int forMergeLineCount = 0;
1299 string line;
1300 string hashToReturn;
1301 while(getline(fetchHeadFile, line))
1303 //Tokenize this line
1304 string::size_type prevPos = 0;
1305 string::size_type pos = line.find('\t');
1306 if(pos == string::npos) continue; //invalid line
1308 string hash = line.substr(0, pos);
1309 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1311 bool forMerge = pos == prevPos;
1312 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1314 string remoteBranch = line.substr(prevPos, pos - prevPos);
1316 //Process this line
1317 if(forMerge)
1319 hashToReturn = hash;
1320 ++forMergeLineCount;
1321 if(forMergeLineCount > 1)
1322 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1326 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1329 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1331 int ret;
1332 CString cmd, output, cur;
1333 cmd = _T("git.exe branch --no-color");
1335 if((type&BRANCH_ALL) == BRANCH_ALL)
1336 cmd += _T(" -a");
1337 else if(type&BRANCH_REMOTE)
1338 cmd += _T(" -r");
1340 ret = Run(cmd, &output, NULL, CP_UTF8);
1341 if(!ret)
1343 int pos=0;
1344 CString one;
1345 while( pos>=0 )
1347 one=output.Tokenize(_T("\n"),pos);
1348 one.Trim(L" \r\n\t");
1349 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1350 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1351 if(one[0] == _T('*'))
1353 one = one.Mid(2);
1354 cur = one;
1356 if (one != _T("(no branch)"))
1357 list.push_back(one);
1361 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1362 list.push_back(L"FETCH_HEAD");
1364 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1366 if (current && cur != _T("(no branch)"))
1368 for (unsigned int i = 0; i < list.size(); ++i)
1370 if (list[i] == cur)
1372 *current = i;
1373 break;
1378 return ret;
1381 int CGit::GetRemoteList(STRING_VECTOR &list)
1383 if (this->m_IsUseLibGit2)
1385 git_repository *repo = NULL;
1387 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1388 if (git_repository_open(&repo, gitdir.GetBuffer()))
1390 gitdir.ReleaseBuffer();
1391 return -1;
1393 gitdir.ReleaseBuffer();
1395 git_strarray remotes;
1397 if (git_remote_list(&remotes, repo))
1399 git_repository_free(repo);
1400 return -1;
1403 for (size_t i = 0; i < remotes.count; ++i)
1405 CStringA remote(remotes.strings[i]);
1406 list.push_back(CUnicodeUtils::GetUnicode(remote));
1409 git_strarray_free(&remotes);
1411 git_repository_free(repo);
1413 std::sort(list.begin(), list.end());
1415 return 0;
1417 else
1419 int ret;
1420 CString cmd, output;
1421 cmd=_T("git.exe remote");
1422 ret = Run(cmd, &output, NULL, CP_UTF8);
1423 if(!ret)
1425 int pos=0;
1426 CString one;
1427 while( pos>=0 )
1429 one=output.Tokenize(_T("\n"),pos);
1430 if (!one.IsEmpty())
1431 list.push_back(one);
1434 return ret;
1438 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1440 CString cmd, out, err;
1441 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1442 if (Run(cmd, &out, &err, CP_UTF8))
1444 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1445 return -1;
1448 int pos = 0;
1449 while (pos >= 0)
1451 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1452 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1453 if (one.Find(_T("^{}")) >= 1)
1454 continue;
1455 if (!one.IsEmpty())
1456 list.push_back(one);
1458 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1459 return 0;
1462 int libgit2_addto_list_each_ref_fn(const char *refname, void *payload)
1464 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1465 CString str;
1466 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1467 list->push_back(str);
1468 return 0;
1471 int CGit::GetRefList(STRING_VECTOR &list)
1473 if (this->m_IsUseLibGit2)
1475 git_repository *repo = NULL;
1477 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1478 if (git_repository_open(&repo, gitdir.GetBuffer()))
1480 gitdir.ReleaseBuffer();
1481 return -1;
1483 gitdir.ReleaseBuffer();
1485 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_list_each_ref_fn, &list))
1487 git_repository_free(repo);
1488 return -1;
1491 git_repository_free(repo);
1493 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1495 return 0;
1497 else
1499 CString cmd, output;
1500 cmd=_T("git.exe show-ref -d");
1501 int ret = Run(cmd, &output, NULL, CP_UTF8);
1502 if(!ret)
1504 int pos=0;
1505 CString one;
1506 while( pos>=0 )
1508 one=output.Tokenize(_T("\n"),pos);
1509 int start=one.Find(_T(" "),0);
1510 if(start>0)
1512 CString name;
1513 name=one.Right(one.GetLength()-start-1);
1514 list.push_back(name);
1517 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1519 return ret;
1523 typedef struct map_each_ref_payload {
1524 git_repository * repo;
1525 MAP_HASH_NAME * map;
1526 } map_each_ref_payload;
1528 int libgit2_addto_map_each_ref_fn(const char *refname, void *payload)
1530 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1532 CString str;
1533 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1535 git_object * gitObject = NULL;
1539 if (git_revparse_single(&gitObject, payloadContent->repo, refname))
1541 break;
1544 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1546 str += _T("^{}"); // deref tag
1547 git_object * derefedTag = NULL;
1548 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1550 break;
1552 git_object_free(gitObject);
1553 gitObject = derefedTag;
1556 const git_oid * oid = git_object_id(gitObject);
1557 if (oid == NULL)
1559 break;
1562 CGitHash hash((char *)oid->id);
1563 (*payloadContent->map)[hash].push_back(str);
1564 } while (false);
1566 if (gitObject)
1568 git_object_free(gitObject);
1569 return 0;
1572 return 1;
1575 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1577 if (this->m_IsUseLibGit2)
1579 git_repository *repo = NULL;
1581 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1582 if (git_repository_open(&repo, gitdir.GetBuffer()))
1584 gitdir.ReleaseBuffer();
1585 return -1;
1587 gitdir.ReleaseBuffer();
1589 map_each_ref_payload payloadContent = { repo, &map };
1591 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_map_each_ref_fn, &payloadContent))
1593 git_repository_free(repo);
1594 return -1;
1597 git_repository_free(repo);
1599 for (auto it = map.begin(); it != map.end(); ++it)
1601 std::sort(it->second.begin(), it->second.end());
1604 return 0;
1606 else
1608 CString cmd, output;
1609 cmd=_T("git.exe show-ref -d");
1610 int ret = Run(cmd, &output, NULL, CP_UTF8);
1611 if(!ret)
1613 int pos=0;
1614 CString one;
1615 while( pos>=0 )
1617 one=output.Tokenize(_T("\n"),pos);
1618 int start=one.Find(_T(" "),0);
1619 if(start>0)
1621 CString name;
1622 name=one.Right(one.GetLength()-start-1);
1624 CString hash;
1625 hash=one.Left(start);
1627 map[CGitHash(hash)].push_back(name);
1631 return ret;
1635 BOOL CGit::CheckMsysGitDir()
1637 if (m_bInitialized)
1639 return TRUE;
1642 this->m_Environment.clear();
1643 m_Environment.CopyProcessEnvironment();
1645 TCHAR *oldpath;
1646 size_t homesize,size;
1648 // set HOME if not set already
1649 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1650 if (!homesize)
1652 CString home = GetHomeDirectory();
1653 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1654 home.ReleaseBuffer();
1656 CString str;
1658 //setup ssh client
1659 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1661 if(!sshclient.IsEmpty())
1663 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1664 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1666 else
1668 TCHAR sPlink[MAX_PATH];
1669 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1670 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1671 if (ptr) {
1672 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1673 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1674 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1679 TCHAR sAskPass[MAX_PATH];
1680 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1681 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1682 if (ptr)
1684 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1685 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1686 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1687 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1691 // add git/bin path to PATH
1693 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1694 str=msysdir;
1695 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1697 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1698 str = msyslocalinstalldir;
1699 str.TrimRight(_T("\\"));
1700 if (str.IsEmpty())
1702 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1703 str = msysinstalldir;
1704 str.TrimRight(_T("\\"));
1706 if ( !str.IsEmpty() )
1708 str += "\\bin";
1709 msysdir=str;
1710 CGit::ms_LastMsysGitDir = str;
1711 msysdir.write();
1713 else
1715 // search PATH if git/bin directory is already present
1716 if ( FindGitPath() )
1718 m_bInitialized = TRUE;
1719 msysdir = CGit::ms_LastMsysGitDir;
1720 msysdir.write();
1721 return TRUE;
1724 return FALSE;
1727 else
1729 CGit::ms_LastMsysGitDir = str;
1732 // check for git.exe existance (maybe it was deinstalled in the meantime)
1733 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1734 return FALSE;
1736 //set path
1737 _tdupenv_s(&oldpath,&size,_T("PATH"));
1739 CString path;
1740 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1742 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1744 CString str1 = m_Environment.GetEnv(_T("PATH"));
1746 CString sOldPath = oldpath;
1747 free(oldpath);
1749 m_bInitialized = TRUE;
1750 return true;
1753 CString CGit::GetHomeDirectory()
1755 const wchar_t * homeDir = wget_windows_home_directory();
1756 return CString(homeDir, (int)wcslen(homeDir));
1759 CString CGit::GetGitLocalConfig()
1761 CString path;
1762 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, path);
1763 path += _T("config");
1764 return path;
1767 CString CGit::GetGitGlobalConfig()
1769 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1772 CString CGit::GetGitGlobalXDGConfigPath()
1774 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1777 CString CGit::GetGitGlobalXDGConfig()
1779 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1782 CString CGit::GetGitSystemConfig()
1784 const wchar_t * systemConfig = wget_msysgit_etc();
1785 return CString(systemConfig, (int)wcslen(systemConfig));
1788 BOOL CGit::CheckCleanWorkTree()
1790 CString out;
1791 CString cmd;
1792 cmd=_T("git.exe rev-parse --verify HEAD");
1794 if(Run(cmd,&out,CP_UTF8))
1795 return FALSE;
1797 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1798 if(Run(cmd,&out,CP_UTF8))
1799 return FALSE;
1801 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1802 if(Run(cmd,&out,CP_UTF8))
1803 return FALSE;
1805 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1806 if(Run(cmd,&out,CP_UTF8))
1807 return FALSE;
1809 return TRUE;
1811 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1813 int ret;
1814 for (int i = 0; i < list.GetCount(); ++i)
1816 ret = Revert(commit, (CTGitPath&)list[i]);
1817 if(ret)
1818 return ret;
1820 return 0;
1822 int CGit::Revert(CString commit, CTGitPath &path)
1824 CString cmd, out;
1826 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1828 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1830 CString err;
1831 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1832 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1833 return -1;
1835 CString force;
1836 // if the filenames only differ in case, we have to pass "-f"
1837 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1838 force = _T("-f ");
1839 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1840 if (Run(cmd, &out, CP_UTF8))
1842 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1843 return -1;
1846 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1847 if (Run(cmd, &out, CP_UTF8))
1849 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1850 return -1;
1854 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1855 { //To init git repository, there are not HEAD, so we can use git reset command
1856 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1858 if (Run(cmd, &out, CP_UTF8))
1860 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1861 return -1;
1864 else
1866 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1867 if (Run(cmd, &out, CP_UTF8))
1869 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1870 return -1;
1874 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1876 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1877 if (Run(cmd, &out, CP_UTF8))
1879 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1880 return -1;
1884 return 0;
1887 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1889 BYTE_VECTOR vector;
1891 CString cmd;
1892 if(path)
1893 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1894 else
1895 cmd=_T("git.exe ls-files -u -t -z");
1897 if (Run(cmd, &vector))
1899 return -1;
1902 list.ParserFromLsFile(vector);
1904 return 0;
1907 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1909 CString base;
1910 CGitHash basehash,hash;
1911 CString cmd, err;
1912 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1914 if (Run(cmd, &base, &err, CP_UTF8))
1916 return false;
1918 basehash = base.Trim();
1920 GetHash(hash, from);
1922 if (commonAncestor)
1923 *commonAncestor = basehash;
1925 return hash == basehash;
1928 unsigned int CGit::Hash2int(CGitHash &hash)
1930 int ret=0;
1931 for (int i = 0; i < 4; ++i)
1933 ret = ret << 8;
1934 ret |= hash.m_hash[i];
1936 return ret;
1939 int CGit::RefreshGitIndex()
1941 if(g_Git.m_IsUseGitDLL)
1943 CAutoLocker lock(g_Git.m_critGitDllSec);
1946 return git_run_cmd("update-index","update-index -q --refresh");
1948 }catch(...)
1950 return -1;
1954 else
1956 CString cmd,output;
1957 cmd=_T("git.exe update-index --refresh");
1958 return Run(cmd, &output, CP_UTF8);
1962 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1964 if(g_Git.m_IsUseGitDLL)
1966 CAutoLocker lock(g_Git.m_critGitDllSec);
1969 g_Git.CheckAndInitDll();
1970 CStringA ref, patha, outa;
1971 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1972 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1973 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1974 ::DeleteFile(outputfile);
1975 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1977 }catch(...)
1979 return -1;
1982 else
1984 CString cmd;
1985 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1986 return RunLogFile(cmd,outputfile);
1989 void CEnvironment::CopyProcessEnvironment()
1991 TCHAR *p = GetEnvironmentStrings();
1992 while(*p !=0 || *(p+1) !=0)
1993 this->push_back(*p++);
1995 push_back(_T('\0'));
1996 push_back(_T('\0'));
1999 CString CEnvironment::GetEnv(TCHAR *name)
2001 CString str;
2002 for (size_t i = 0; i < size(); ++i)
2004 str = &(*this)[i];
2005 int start =0;
2006 CString sname = str.Tokenize(_T("="),start);
2007 if(sname.CompareNoCase(name) == 0)
2009 return &(*this)[i+start];
2011 i+=str.GetLength();
2013 return _T("");
2016 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
2018 unsigned int i;
2019 for (i = 0; i < size(); ++i)
2021 CString str = &(*this)[i];
2022 int start =0;
2023 CString sname = str.Tokenize(_T("="),start);
2024 if(sname.CompareNoCase(name) == 0)
2026 break;
2028 i+=str.GetLength();
2031 if(i == size())
2033 i -= 1; // roll back terminate \0\0
2034 this->push_back(_T('\0'));
2037 CEnvironment::iterator it;
2038 it=this->begin();
2039 it += i;
2041 while(*it && i<size())
2043 this->erase(it);
2044 it=this->begin();
2045 it += i;
2048 while(*name)
2050 this->insert(it,*name++);
2051 ++i;
2052 it= begin()+i;
2055 this->insert(it, _T('='));
2056 ++i;
2057 it= begin()+i;
2059 while(*value)
2061 this->insert(it,*value++);
2062 ++i;
2063 it= begin()+i;
2068 int CGit::GetGitEncode(TCHAR* configkey)
2070 CString str=GetConfigValue(configkey);
2072 if(str.IsEmpty())
2073 return CP_UTF8;
2075 return CUnicodeUtils::GetCPCode(str);
2079 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2081 GIT_FILE file=0;
2082 int ret=0;
2083 GIT_DIFF diff=0;
2085 CAutoLocker lock(g_Git.m_critGitDllSec);
2087 if(arg == NULL)
2088 diff = GetGitDiff();
2089 else
2090 git_open_diff(&diff, arg);
2092 if(diff ==NULL)
2093 return -1;
2095 bool isStat = 0;
2096 if(arg == NULL)
2097 isStat = true;
2098 else
2099 isStat = !!strstr(arg, "stat");
2101 int count=0;
2103 if(hash2 == NULL)
2104 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2105 else
2106 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2108 if(ret)
2109 return -1;
2111 CTGitPath path;
2112 CString strnewname;
2113 CString stroldname;
2115 for (int j = 0; j < count; ++j)
2117 path.Reset();
2118 char *newname;
2119 char *oldname;
2121 strnewname.Empty();
2122 stroldname.Empty();
2124 int mode=0,IsBin=0,inc=0,dec=0;
2125 git_get_diff_file(diff,file,j,&newname,&oldname,
2126 &mode,&IsBin,&inc,&dec);
2128 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2129 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2131 path.SetFromGit(strnewname,&stroldname);
2132 path.ParserAction((BYTE)mode);
2134 if(IsBin)
2136 path.m_StatAdd=_T("-");
2137 path.m_StatDel=_T("-");
2139 else
2141 path.m_StatAdd.Format(_T("%d"),inc);
2142 path.m_StatDel.Format(_T("%d"),dec);
2144 PathList->AddPath(path);
2146 git_diff_flush(diff);
2148 if(arg)
2149 git_close_diff(diff);
2151 return 0;
2154 int CGit::GetShortHASHLength()
2156 return 7;
2159 CString CGit::GetShortName(CString ref, REF_TYPE *out_type)
2161 CString str=ref;
2162 CString shortname;
2163 REF_TYPE type = CGit::UNKNOWN;
2165 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2167 type = CGit::LOCAL_BRANCH;
2170 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2172 type = CGit::REMOTE_BRANCH;
2174 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2176 type = CGit::TAG;
2178 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2180 type = CGit::STASH;
2181 shortname=_T("stash");
2183 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2185 if (shortname.Find(_T("good")) == 0)
2187 type = CGit::BISECT_GOOD;
2188 shortname = _T("good");
2191 if (shortname.Find(_T("bad")) == 0)
2193 type = CGit::BISECT_BAD;
2194 shortname = _T("bad");
2197 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2199 type = CGit::NOTES;
2201 else
2203 type = CGit::UNKNOWN;
2204 shortname = _T("Unknown");
2207 if(out_type)
2208 *out_type = type;
2210 return shortname;
2213 bool CGit::UsingLibGit2(int cmd)
2215 if (cmd >= 0 && cmd < 32)
2216 return ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2217 return false;