git.exe of msysgit cmd folder does not work, so try to guess bin folder
[TortoiseGit.git] / src / Git / Git.cpp
blob0acdb5eae5062a916a5228d70938da80d563aa1d
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>
30 #include "git2.h"
32 int CGit::m_LogEncode=CP_UTF8;
33 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
35 static LPTSTR nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
37 wchar_t term, *base = path;
39 if (path == NULL || buf == NULL || buflen == 0)
40 return NULL;
42 term = (*path == L'"') ? *path++ : L';';
44 for (buflen--; *path && *path != term && buflen; buflen--)
45 *buf++ = *path++;
47 *buf = L'\0'; /* reserved a byte via initial subtract */
49 while (*path == term || *path == L';')
50 path++;
52 return (path != base) ? path : NULL;
55 static inline BOOL FileExists(LPCTSTR lpszFileName)
57 struct _stat st;
58 return _tstat(lpszFileName, &st) == 0;
61 static BOOL FindGitPath()
63 size_t size;
64 _tgetenv_s(&size, NULL, 0, _T("PATH"));
66 if (!size)
68 return FALSE;
71 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
72 _tgetenv_s(&size, env, size, _T("PATH"));
74 TCHAR buf[MAX_PATH];
76 // search in all paths defined in PATH
77 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
79 TCHAR *pfin = buf + _tcslen(buf)-1;
81 // ensure trailing slash
82 if (*pfin != _T('/') && *pfin != _T('\\'))
83 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
85 const size_t len = _tcslen(buf);
87 if ((len + 7) < MAX_PATH)
88 _tcscpy_s(pfin + 1, MAX_PATH - len, _T("git.exe"));
89 else
90 break;
92 if ( FileExists(buf) )
94 // dir found
95 pfin[1] = 0;
96 CGit::ms_LastMsysGitDir = buf;
97 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
98 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
100 // often the msysgit\cmd folder is on the %PATH%, but
101 // that git.exe does not work, so try to guess the bin folder
102 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
103 if (FileExists(binDir))
104 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
106 return TRUE;
110 return FALSE;
113 static bool g_bSortLogical;
114 static bool g_bSortLocalBranchesFirst;
116 static void GetSortOptions()
118 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
119 if (g_bSortLogical)
120 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
121 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
122 if (g_bSortLocalBranchesFirst)
123 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
126 static int LogicalComparePredicate(CString &left, CString &right)
128 if (g_bSortLogical)
129 return StrCmpLogicalW(left, right) < 0;
130 return StrCmpI(left, right) < 0;
133 static int LogicalCompareBranchesPredicate(CString &left, CString &right)
135 if (g_bSortLocalBranchesFirst)
137 int leftIsRemote = left.Find(_T("remotes/"));
138 int rightIsRemote = right.Find(_T("remotes/"));
140 if (leftIsRemote == 0 && rightIsRemote < 0)
141 return false;
142 else if (leftIsRemote < 0 && rightIsRemote == 0)
143 return true;
145 if (g_bSortLogical)
146 return StrCmpLogicalW(left, right) < 0;
147 return StrCmpI(left, right) < 0;
150 #define MAX_DIRBUFFER 1000
151 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
153 CString CGit::ms_LastMsysGitDir;
154 CGit g_Git;
157 CGit::CGit(void)
159 GetCurrentDirectory(MAX_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
160 m_CurrentDir.ReleaseBuffer();
161 m_IsGitDllInited = false;
162 m_GitDiff=0;
163 m_GitSimpleListDiff=0;
164 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
165 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
166 GetSortOptions();
167 this->m_bInitialized =false;
168 CheckMsysGitDir();
169 m_critGitDllSec.Init();
172 CGit::~CGit(void)
174 if(this->m_GitDiff)
176 git_close_diff(m_GitDiff);
177 m_GitDiff=0;
179 if(this->m_GitSimpleListDiff)
181 git_close_diff(m_GitSimpleListDiff);
182 m_GitSimpleListDiff=0;
186 bool CGit::IsBranchNameValid(CString branchname)
188 if (branchname.IsEmpty())
189 return false;
191 for(int i=0; i < branchname.GetLength(); i++)
193 TCHAR c = branchname.GetAt(i);
194 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
195 return false;
198 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
199 return false;
201 CString reverseBranchname = branchname.MakeReverse();
202 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
203 return false;
205 return true;
208 static char g_Buffer[4096];
210 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
212 SECURITY_ATTRIBUTES sa;
213 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
214 HANDLE hStdioFile = NULL;
216 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
217 sa.lpSecurityDescriptor=NULL;
218 sa.bInheritHandle=TRUE;
219 if(!CreatePipe(&hRead,&hWrite,&sa,0))
221 return TGIT_GIT_ERROR_OPEN_PIP;
223 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
224 return TGIT_GIT_ERROR_OPEN_PIP;
226 if(StdioFile)
228 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
229 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
232 STARTUPINFO si;
233 PROCESS_INFORMATION pi;
234 si.cb=sizeof(STARTUPINFO);
235 GetStartupInfo(&si);
237 if (hErrReadOut)
238 si.hStdError = hWriteErr;
239 else
240 si.hStdError = hWrite;
241 if(StdioFile)
242 si.hStdOutput=hStdioFile;
243 else
244 si.hStdOutput=hWrite;
246 si.wShowWindow=SW_HIDE;
247 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
249 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
250 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
252 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
253 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
255 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
256 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
258 if(cmd.Find(_T("git")) == 0)
260 int firstSpace = cmd.Find(_T(" "));
261 if (firstSpace > 0)
262 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
263 else
264 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
267 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
269 LPVOID lpMsgBuf;
270 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
271 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
272 (LPTSTR)&lpMsgBuf,
273 0,NULL);
274 return TGIT_GIT_ERROR_CREATE_PROCESS;
277 m_CurrentGitPi = pi;
279 CloseHandle(hWrite);
280 if (hErrReadOut)
281 CloseHandle(hWriteErr);
282 if(piOut)
283 *piOut=pi;
284 if(hReadOut)
285 *hReadOut=hRead;
286 if(hErrReadOut)
287 *hErrReadOut = hReadErr;
288 return 0;
291 //Must use sperate function to convert ANSI str to union code string
292 //Becuase A2W use stack as internal convert buffer.
293 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
295 //USES_CONVERSION;
296 //str->Append(A2W_CP((LPCSTR)p,code));
297 if(str == NULL)
298 return ;
300 WCHAR * buf;
302 int len ;
303 if(length<0)
304 len = (int)strlen((const char*)p);
305 else
306 len=length;
307 //if (len==0)
308 // return ;
309 //buf = new WCHAR[len*4 + 1];
310 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
311 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
312 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
313 str->ReleaseBuffer();
314 //str->Append(buf);
315 //delete buf;
318 BOOL CGit::IsOrphanBranch(CString ref)
320 if (ref.IsEmpty())
321 ref = _T("HEAD");
323 CString cmdout;
324 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
326 return TRUE;
328 if(cmdout.IsEmpty())
329 return TRUE;
331 return FALSE;
334 BOOL CGit::IsInitRepos()
336 return IsOrphanBranch(_T("HEAD"));
339 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
341 PASYNCREADSTDERRTHREADARGS pDataArray;
342 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
344 DWORD readnumber;
345 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
346 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
348 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
349 break;
352 return 0;
355 int CGit::Run(CGitCall* pcall)
357 PROCESS_INFORMATION pi;
358 HANDLE hRead, hReadErr;
359 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
360 return TGIT_GIT_ERROR_CREATE_PROCESS;
362 HANDLE thread;
363 ASYNCREADSTDERRTHREADARGS threadArguments;
364 threadArguments.fileHandle = hReadErr;
365 threadArguments.pcall = pcall;
366 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
368 DWORD readnumber;
369 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
370 bool bAborted=false;
371 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
373 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
374 if(!bAborted)//For now, flush output when command aborted.
375 if(pcall->OnOutputData(data,readnumber))
376 bAborted=true;
378 if(!bAborted)
379 pcall->OnEnd();
381 if (thread)
382 WaitForSingleObject(thread, INFINITE);
384 CloseHandle(pi.hThread);
386 WaitForSingleObject(pi.hProcess, INFINITE);
387 DWORD exitcode =0;
389 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
391 return TGIT_GIT_ERROR_GET_EXIT_CODE;
394 CloseHandle(pi.hProcess);
396 CloseHandle(hRead);
397 CloseHandle(hReadErr);
398 return exitcode;
400 class CGitCall_ByteVector : public CGitCall
402 public:
403 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
404 virtual bool OnOutputData(const BYTE* data, size_t size)
406 if (size == 0)
407 return false;
408 size_t oldsize=m_pvector->size();
409 m_pvector->resize(m_pvector->size()+size);
410 memcpy(&*(m_pvector->begin()+oldsize),data,size);
411 return false;
413 virtual bool OnOutputErrData(const BYTE* data, size_t size)
415 if (!m_pvectorErr || size == 0)
416 return false;
417 size_t oldsize = m_pvectorErr->size();
418 m_pvectorErr->resize(m_pvectorErr->size() + size);
419 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
420 return false;
422 BYTE_VECTOR* m_pvector;
423 BYTE_VECTOR* m_pvectorErr;
426 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
428 CGitCall_ByteVector call(cmd, vector, vectorErr);
429 return Run(&call);
431 int CGit::Run(CString cmd, CString* output, int code)
433 CString err;
434 int ret;
435 ret = Run(cmd, output, &err, code);
437 if (output && !err.IsEmpty())
439 if (!output->IsEmpty())
440 *output += _T("\n");
441 *output += err;
444 return ret;
446 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
448 BYTE_VECTOR vector, vectorErr;
449 int ret;
450 if (outputErr)
451 ret = Run(cmd, &vector, &vectorErr);
452 else
453 ret = Run(cmd, &vector);
455 vector.push_back(0);
456 StringAppend(output, &(vector[0]), code);
458 if (outputErr)
460 vectorErr.push_back(0);
461 StringAppend(outputErr, &(vectorErr[0]), code);
464 return ret;
467 CString CGit::GetUserName(void)
469 CEnvironment env;
470 env.CopyProcessEnvironment();
471 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
472 if (!envname.IsEmpty())
473 return envname;
474 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
476 CString CGit::GetUserEmail(void)
478 CEnvironment env;
479 env.CopyProcessEnvironment();
480 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
481 if (!envmail.IsEmpty())
482 return envmail;
484 return GetConfigValue(L"user.email");
487 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
489 CString configValue;
490 int start = 0;
491 if(this->m_IsUseGitDLL)
493 CString *git_path=NULL;
495 CAutoLocker lock(g_Git.m_critGitDllSec);
499 CTGitPath path;
501 CheckAndInitDll();
502 git_path = GitPath;
504 }catch(...)
507 CStringA key, value;
508 key = CUnicodeUtils::GetMulti(name, encoding);
509 CStringA p;
510 if(git_path)
511 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
513 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
514 return CString();
515 else
517 StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
518 if(RemoveCR)
519 return configValue.Tokenize(_T("\n"),start);
520 return configValue;
524 else
526 CString cmd;
527 cmd.Format(L"git.exe config %s", name);
528 Run(cmd, &configValue, NULL, encoding);
529 if(RemoveCR)
530 return configValue.Tokenize(_T("\n"),start);
531 return configValue;
535 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
537 if(this->m_IsUseGitDLL)
539 CAutoLocker lock(g_Git.m_critGitDllSec);
543 CheckAndInitDll();
545 }catch(...)
548 CStringA keya, valuea;
549 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
550 valuea = CUnicodeUtils::GetMulti(value, encoding);
551 CStringA p;
552 if(GitPath)
553 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
555 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
558 else
560 CString cmd;
561 CString option;
562 switch(type)
564 case CONFIG_GLOBAL:
565 option = _T("--global");
566 break;
567 case CONFIG_SYSTEM:
568 option = _T("--system");
569 break;
570 default:
571 break;
573 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
574 CString out;
575 if (Run(cmd, &out, NULL, encoding))
577 return -1;
580 return 0;
583 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
585 if(this->m_IsUseGitDLL)
587 CAutoLocker lock(g_Git.m_critGitDllSec);
591 CheckAndInitDll();
592 }catch(...)
595 CStringA keya;
596 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
597 CStringA p;
598 if(GitPath)
599 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
601 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
603 else
605 CString cmd;
606 CString option;
607 switch(type)
609 case CONFIG_GLOBAL:
610 option = _T("--global");
611 break;
612 case CONFIG_SYSTEM:
613 option = _T("--system");
614 break;
615 default:
616 break;
618 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
619 CString out;
620 if (Run(cmd, &out, NULL, encoding))
622 return -1;
625 return 0;
628 CString CGit::GetCurrentBranch(void)
630 CString output;
631 //Run(_T("git.exe branch"),&branch);
633 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
635 return _T("(no branch)");
637 else
638 return output;
642 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
644 CString refName;
645 if(this->m_IsUseGitDLL)
647 unsigned char sha1[20];
648 int flag;
650 CAutoLocker lock(g_Git.m_critGitDllSec);
651 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
652 if(refs_heads_master && (flag&REF_ISSYMREF))
654 StringAppend(&refName,(BYTE*)refs_heads_master);
655 if(bStripRefsHeads)
656 refName = StripRefName(refName);
660 else
662 CString cmd;
663 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
664 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
665 return CString();//Error
666 int iStart = 0;
667 refName = refName.Tokenize(L"\n", iStart);
668 if(bStripRefsHeads)
669 refName = StripRefName(refName);
671 return refName;
674 CString CGit::GetFullRefName(CString shortRefName)
676 CString refName;
677 CString cmd;
678 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
679 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
680 return CString();//Error
681 int iStart = 0;
682 return refName.Tokenize(L"\n", iStart);
685 CString CGit::StripRefName(CString refName)
687 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
688 refName = refName.Mid(11);
689 else if(wcsncmp(refName, L"refs/", 5) == 0)
690 refName = refName.Mid(5);
691 int start =0;
692 return refName.Tokenize(_T("\n"),start);
695 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
697 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
699 if ( sProjectRoot.IsEmpty() )
700 return -1;
702 CString sDotGitPath;
703 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
704 return -1;
706 CString sHeadFile = sDotGitPath + _T("HEAD");
708 FILE *pFile;
709 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
711 if (!pFile)
713 return -1;
716 char s[256] = {0};
717 fgets(s, sizeof(s), pFile);
719 fclose(pFile);
721 const char *pfx = "ref: refs/heads/";
722 const int len = 16;//strlen(pfx)
724 if ( !strncmp(s, pfx, len) )
726 //# We're on a branch. It might not exist. But
727 //# HEAD looks good enough to be a branch.
728 CStringA utf8Branch(s + len);
729 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
730 sBranchOut.TrimRight(_T(" \r\n\t"));
732 if ( sBranchOut.IsEmpty() )
733 return -1;
735 else
737 //# Assume this is a detached head.
738 sBranchOut = "HEAD";
740 return 1;
743 return 0;
746 int CGit::BuildOutputFormat(CString &format,bool IsFull)
748 CString log;
749 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
750 format += log;
751 if(IsFull)
753 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
754 format += log;
755 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
756 format += log;
757 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
758 format += log;
759 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
760 format += log;
761 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
762 format += log;
763 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
764 format += log;
765 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
766 format += log;
769 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
770 format += log;
771 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
772 format += log;
773 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
774 format += log;
776 if(IsFull)
778 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
779 format += log;
781 return 0;
784 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
786 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
787 return GetLog(&gitCall,hash,path,count,mask,from,to);
790 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
791 CFilterData *Filter)
793 CString cmd;
794 CString num;
795 CString since;
797 CString file;
799 if(path)
800 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
802 if(count>0)
803 num.Format(_T("-n%d"),count);
805 CString param;
807 if(mask& LOG_INFO_STAT )
808 param += _T(" --numstat ");
809 if(mask& LOG_INFO_FILESTATE)
810 param += _T(" --raw ");
812 if(mask& LOG_INFO_FULLHISTORY)
813 param += _T(" --full-history ");
815 if(mask& LOG_INFO_BOUNDARY)
816 param += _T(" --left-right --boundary ");
818 if(mask& CGit::LOG_INFO_ALL_BRANCH)
819 param += _T(" --all ");
821 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
822 param += _T(" -C ");
824 if(mask& CGit::LOG_INFO_DETECT_RENAME )
825 param += _T(" -M ");
827 if(mask& CGit::LOG_INFO_FIRST_PARENT )
828 param += _T(" --first-parent ");
830 if(mask& CGit::LOG_INFO_NO_MERGE )
831 param += _T(" --no-merges ");
833 if(mask& CGit::LOG_INFO_FOLLOW)
834 param += _T(" --follow ");
836 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
837 param += _T(" -c ");
839 if(mask& CGit::LOG_INFO_FULL_DIFF)
840 param += _T(" --full-diff ");
842 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
843 param += _T(" --simplify-by-decoration ");
845 if(from != NULL && to != NULL)
847 CString range;
848 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
849 param += range;
851 else if(to != NULL && hash.IsEmpty())
853 CString range;
854 range.Format(_T(" %s "), FixBranchName(*to));
855 param += range;
857 param+=hash;
859 CString st1,st2;
861 if( Filter && (Filter->m_From != -1))
863 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
864 param += st1;
867 if( Filter && (Filter->m_To != -1))
869 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
870 param += st2;
873 bool isgrep = false;
874 if( Filter && (!Filter->m_Author.IsEmpty()))
876 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
877 param += st1;
878 isgrep = true;
881 if( Filter && (!Filter->m_Committer.IsEmpty()))
883 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
884 param += st1;
885 isgrep = true;
888 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
890 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
891 param += st1;
892 isgrep = true;
895 if(Filter && isgrep)
897 if(!Filter->m_IsRegex)
898 param += _T(" --fixed-strings ");
900 param += _T(" --regexp-ignore-case --extended-regexp ");
903 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
904 param += _T(" --topo-order");
906 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
907 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
908 else
910 CString log;
911 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
912 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
913 num,param,log);
916 cmd += file;
918 return cmd;
920 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
921 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
923 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
925 return Run(pgitCall);
926 // return Run(cmd,&logOut);
929 #define BUFSIZE 512
930 void GetTempPath(CString &path)
932 TCHAR lpPathBuffer[BUFSIZE];
933 DWORD dwRetVal;
934 DWORD dwBufSize=BUFSIZE;
935 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
936 lpPathBuffer); // buffer for path
937 if (dwRetVal > dwBufSize || (dwRetVal == 0))
939 path=_T("");
941 path.Format(_T("%s"),lpPathBuffer);
943 CString GetTempFile()
945 TCHAR lpPathBuffer[BUFSIZE];
946 DWORD dwRetVal;
947 DWORD dwBufSize=BUFSIZE;
948 TCHAR szTempName[BUFSIZE];
949 UINT uRetVal;
951 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
952 lpPathBuffer); // buffer for path
953 if (dwRetVal > dwBufSize || (dwRetVal == 0))
955 return _T("");
957 // Create a temporary file.
958 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
959 TEXT("Patch"), // temp file name prefix
960 0, // create unique name
961 szTempName); // buffer for name
964 if (uRetVal == 0)
966 return _T("");
969 return CString(szTempName);
973 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
975 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
976 if (result == 0) return 0;
977 if (lpBuffer == NULL || (result + 13 > nBufferLength))
979 if (lpBuffer)
980 lpBuffer[0] = '\0';
981 return result + 13;
984 _tcscat(lpBuffer, _T("TortoiseGit\\"));
985 CreateDirectory(lpBuffer, NULL);
987 return result + 13;
990 int CGit::RunLogFile(CString cmd,const CString &filename)
992 STARTUPINFO si;
993 PROCESS_INFORMATION pi;
994 si.cb=sizeof(STARTUPINFO);
995 GetStartupInfo(&si);
997 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
998 psa.bInheritHandle=TRUE;
1000 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1001 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1003 si.wShowWindow = SW_HIDE;
1004 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1005 si.hStdOutput = houtfile;
1007 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1008 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1010 if(cmd.Find(_T("git")) == 0)
1011 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1013 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1015 LPVOID lpMsgBuf;
1016 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1017 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1018 (LPTSTR)&lpMsgBuf,
1019 0,NULL);
1020 return TGIT_GIT_ERROR_CREATE_PROCESS;
1023 WaitForSingleObject(pi.hProcess,INFINITE);
1025 CloseHandle(pi.hThread);
1026 CloseHandle(pi.hProcess);
1027 CloseHandle(houtfile);
1028 return TGIT_GIT_SUCCESS;
1029 // return 0;
1032 int CGit::GetHash(CGitHash &hash, TCHAR* friendname)
1034 // no need to parse a ref if it's already a 40-byte hash
1035 if (CGitHash::IsValidSHA1(friendname))
1037 CString sHash(friendname);
1038 hash = CGitHash(sHash);
1039 return 0;
1042 if (m_IsUseLibGit2)
1044 git_repository *repo = NULL;
1045 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1046 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1048 gitdirA.ReleaseBuffer();
1049 return -1;
1051 gitdirA.ReleaseBuffer();
1053 int isHeadOrphan = git_repository_head_orphan(repo);
1054 if (isHeadOrphan != 0)
1056 git_repository_free(repo);
1057 hash.Empty();
1058 if (isHeadOrphan == 1)
1059 return 0;
1060 else
1061 return -1;
1064 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1066 git_object * gitObject = NULL;
1067 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1069 refnameA.ReleaseBuffer();
1070 git_repository_free(repo);
1071 return -1;
1073 refnameA.ReleaseBuffer();
1075 const git_oid * oid = git_object_id(gitObject);
1076 if (oid == NULL)
1078 git_object_free(gitObject);
1079 git_repository_free(repo);
1080 return -1;
1083 hash = CGitHash((char *)oid->id);
1085 git_object_free(gitObject); // also frees oid
1086 git_repository_free(repo);
1088 return 0;
1090 else
1092 CString cmd;
1093 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1094 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1095 hash = CGitHash(gitLastErr.Trim());
1096 return ret;
1100 int CGit::GetInitAddList(CTGitPathList &outputlist)
1102 CString cmd;
1103 BYTE_VECTOR cmdout;
1105 cmd=_T("git.exe ls-files -s -t -z");
1106 outputlist.Clear();
1107 if (Run(cmd, &cmdout))
1108 return -1;
1110 outputlist.ParserFromLsFile(cmdout);
1111 for(int i=0;i<outputlist.GetCount();i++)
1112 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1114 return 0;
1116 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1118 CString cmd;
1120 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1122 //rev1=+_T("");
1123 if(rev1 == GIT_REV_ZERO)
1124 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1125 else
1126 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1128 else
1130 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1133 BYTE_VECTOR out;
1134 if (Run(cmd, &out))
1135 return -1;
1137 outputlist.ParserFromLog(out);
1139 return 0;
1142 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1144 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1145 CString str;
1146 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1147 list->push_back(str);
1148 return 0;
1151 int CGit::GetTagList(STRING_VECTOR &list)
1153 if (this->m_IsUseLibGit2)
1155 git_repository *repo = NULL;
1157 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1158 if (git_repository_open(&repo, gitdir.GetBuffer()))
1160 gitdir.ReleaseBuffer();
1161 return -1;
1163 gitdir.ReleaseBuffer();
1165 git_strarray tag_names;
1167 if (git_tag_list(&tag_names, repo))
1169 git_repository_free(repo);
1170 return -1;
1173 for (size_t i = 0; i < tag_names.count; i++)
1175 CStringA tagName(tag_names.strings[i]);
1176 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1179 git_strarray_free(&tag_names);
1181 git_repository_free(repo);
1183 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1185 return 0;
1187 else
1189 CString cmd, output;
1190 cmd=_T("git.exe tag -l");
1191 int ret = Run(cmd, &output, NULL, CP_UTF8);
1192 if(!ret)
1194 int pos=0;
1195 CString one;
1196 while( pos>=0 )
1198 one=output.Tokenize(_T("\n"),pos);
1199 if (!one.IsEmpty())
1200 list.push_back(one);
1202 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1204 return ret;
1208 CString CGit::GetGitLastErr(CString msg)
1210 if (this->m_IsUseLibGit2)
1212 const git_error *libgit2err = giterr_last();
1213 if (libgit2err)
1215 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1216 giterr_clear();
1217 return msg + _T("\nlibgit2 returned: ") + lastError;
1219 else
1221 return msg + _T("\nUnknown libgit2 error.");
1224 else if (gitLastErr.IsEmpty())
1225 return msg + _T("\nUnknown git.exe error.");
1226 else
1228 CString lastError = gitLastErr;
1229 gitLastErr.Empty();
1230 return msg + _T("\n") + lastError;
1234 CString CGit::FixBranchName_Mod(CString& branchName)
1236 if(branchName == "FETCH_HEAD")
1237 branchName = DerefFetchHead();
1238 return branchName;
1241 CString CGit::FixBranchName(const CString& branchName)
1243 CString tempBranchName = branchName;
1244 FixBranchName_Mod(tempBranchName);
1245 return tempBranchName;
1248 bool CGit::IsBranchTagNameUnique(const CString& name)
1250 CString output;
1252 CString cmd;
1253 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1254 int ret = Run(cmd, &output, NULL, CP_UTF8);
1255 if (!ret)
1257 int i = 0, pos = 0;
1258 while (pos >= 0)
1260 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1261 i++;
1263 if (i >= 2)
1264 return false;
1267 return true;
1271 Checks if a branch or tag with the given name exists
1272 isBranch is true -> branch, tag otherwise
1274 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1276 CString cmd, output;
1278 cmd = _T("git show-ref ");
1279 if (isBranch)
1280 cmd += _T("--heads ");
1281 else
1282 cmd += _T("--tags ");
1284 cmd += _T("refs/heads/") + name;
1285 cmd += _T(" refs/tags/") + name;
1287 int ret = Run(cmd, &output, NULL, CP_UTF8);
1288 if (!ret)
1290 if (!output.IsEmpty())
1291 return true;
1294 return false;
1297 CString CGit::DerefFetchHead()
1299 using namespace std;
1300 CString dotGitPath;
1301 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1302 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1303 int forMergeLineCount = 0;
1304 string line;
1305 string hashToReturn;
1306 while(getline(fetchHeadFile, line))
1308 //Tokenize this line
1309 string::size_type prevPos = 0;
1310 string::size_type pos = line.find('\t');
1311 if(pos == string::npos) continue; //invalid line
1313 string hash = line.substr(0, pos);
1314 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1316 bool forMerge = pos == prevPos;
1317 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1319 string remoteBranch = line.substr(prevPos, pos - prevPos);
1321 //Process this line
1322 if(forMerge)
1324 hashToReturn = hash;
1325 ++forMergeLineCount;
1326 if(forMergeLineCount > 1)
1327 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1331 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1334 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1336 int ret;
1337 CString cmd, output, cur;
1338 cmd = _T("git.exe branch --no-color");
1340 if((type&BRANCH_ALL) == BRANCH_ALL)
1341 cmd += _T(" -a");
1342 else if(type&BRANCH_REMOTE)
1343 cmd += _T(" -r");
1345 ret = Run(cmd, &output, NULL, CP_UTF8);
1346 if(!ret)
1348 int pos=0;
1349 CString one;
1350 while( pos>=0 )
1352 one=output.Tokenize(_T("\n"),pos);
1353 one.Trim(L" \r\n\t");
1354 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1355 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1356 if(one[0] == _T('*'))
1358 one = one.Mid(2);
1359 cur = one;
1361 if (one != _T("(no branch)"))
1362 list.push_back(one);
1366 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1367 list.push_back(L"FETCH_HEAD");
1369 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1371 if (current && cur != _T("(no branch)"))
1373 for (unsigned int i = 0; i < list.size(); i++)
1375 if (list[i] == cur)
1377 *current = i;
1378 break;
1383 return ret;
1386 int CGit::GetRemoteList(STRING_VECTOR &list)
1388 if (this->m_IsUseLibGit2)
1390 git_repository *repo = NULL;
1392 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1393 if (git_repository_open(&repo, gitdir.GetBuffer()))
1395 gitdir.ReleaseBuffer();
1396 return -1;
1398 gitdir.ReleaseBuffer();
1400 git_strarray remotes;
1402 if (git_remote_list(&remotes, repo))
1404 git_repository_free(repo);
1405 return -1;
1408 for (size_t i = 0; i < remotes.count; i++)
1410 CStringA remote(remotes.strings[i]);
1411 list.push_back(CUnicodeUtils::GetUnicode(remote));
1414 git_strarray_free(&remotes);
1416 git_repository_free(repo);
1418 std::sort(list.begin(), list.end());
1420 return 0;
1422 else
1424 int ret;
1425 CString cmd, output;
1426 cmd=_T("git.exe remote");
1427 ret = Run(cmd, &output, NULL, CP_UTF8);
1428 if(!ret)
1430 int pos=0;
1431 CString one;
1432 while( pos>=0 )
1434 one=output.Tokenize(_T("\n"),pos);
1435 if (!one.IsEmpty())
1436 list.push_back(one);
1439 return ret;
1443 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1445 CString cmd, out, err;
1446 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1447 if (Run(cmd, &out, &err, CP_UTF8))
1449 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1450 return -1;
1453 int pos = 0;
1454 while (pos >= 0)
1456 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1457 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1458 if (one.Find(_T("^{}")) >= 1)
1459 continue;
1460 if (!one.IsEmpty())
1461 list.push_back(one);
1463 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1464 return 0;
1467 int libgit2_addto_list_each_ref_fn(const char *refname, void *payload)
1469 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1470 CString str;
1471 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1472 list->push_back(str);
1473 return 0;
1476 int CGit::GetRefList(STRING_VECTOR &list)
1478 if (this->m_IsUseLibGit2)
1480 git_repository *repo = NULL;
1482 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1483 if (git_repository_open(&repo, gitdir.GetBuffer()))
1485 gitdir.ReleaseBuffer();
1486 return -1;
1488 gitdir.ReleaseBuffer();
1490 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_list_each_ref_fn, &list))
1492 git_repository_free(repo);
1493 return -1;
1496 git_repository_free(repo);
1498 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1500 return 0;
1502 else
1504 CString cmd, output;
1505 cmd=_T("git.exe show-ref -d");
1506 int ret = Run(cmd, &output, NULL, CP_UTF8);
1507 if(!ret)
1509 int pos=0;
1510 CString one;
1511 while( pos>=0 )
1513 one=output.Tokenize(_T("\n"),pos);
1514 int start=one.Find(_T(" "),0);
1515 if(start>0)
1517 CString name;
1518 name=one.Right(one.GetLength()-start-1);
1519 list.push_back(name);
1522 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1524 return ret;
1528 typedef struct map_each_ref_payload {
1529 git_repository * repo;
1530 MAP_HASH_NAME * map;
1531 } map_each_ref_payload;
1533 int libgit2_addto_map_each_ref_fn(const char *refname, void *payload)
1535 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1537 CString str;
1538 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1540 git_object * gitObject = NULL;
1544 if (git_revparse_single(&gitObject, payloadContent->repo, refname))
1546 break;
1549 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1551 str += _T("^{}"); // deref tag
1552 git_object * derefedTag = NULL;
1553 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1555 break;
1557 git_object_free(gitObject);
1558 gitObject = derefedTag;
1561 const git_oid * oid = git_object_id(gitObject);
1562 if (oid == NULL)
1564 break;
1567 CGitHash hash((char *)oid->id);
1568 (*payloadContent->map)[hash].push_back(str);
1569 } while (false);
1571 if (gitObject)
1573 git_object_free(gitObject);
1574 return 0;
1577 return 1;
1580 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1582 if (this->m_IsUseLibGit2)
1584 git_repository *repo = NULL;
1586 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1587 if (git_repository_open(&repo, gitdir.GetBuffer()))
1589 gitdir.ReleaseBuffer();
1590 return -1;
1592 gitdir.ReleaseBuffer();
1594 map_each_ref_payload payloadContent = { repo, &map };
1596 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_map_each_ref_fn, &payloadContent))
1598 git_repository_free(repo);
1599 return -1;
1602 git_repository_free(repo);
1604 for (auto it = map.begin(); it != map.end(); ++it)
1606 std::sort(it->second.begin(), it->second.end());
1609 return 0;
1611 else
1613 CString cmd, output;
1614 cmd=_T("git.exe show-ref -d");
1615 int ret = Run(cmd, &output, NULL, CP_UTF8);
1616 if(!ret)
1618 int pos=0;
1619 CString one;
1620 while( pos>=0 )
1622 one=output.Tokenize(_T("\n"),pos);
1623 int start=one.Find(_T(" "),0);
1624 if(start>0)
1626 CString name;
1627 name=one.Right(one.GetLength()-start-1);
1629 CString hash;
1630 hash=one.Left(start);
1632 map[CGitHash(hash)].push_back(name);
1636 return ret;
1640 BOOL CGit::CheckMsysGitDir()
1642 if (m_bInitialized)
1644 return TRUE;
1647 this->m_Environment.clear();
1648 m_Environment.CopyProcessEnvironment();
1650 TCHAR *oldpath;
1651 size_t homesize,size;
1653 // set HOME if not set already
1654 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1655 if (!homesize)
1657 CString home = GetHomeDirectory();
1658 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1659 home.ReleaseBuffer();
1661 CString str;
1663 //setup ssh client
1664 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1666 if(!sshclient.IsEmpty())
1668 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1669 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1671 else
1673 TCHAR sPlink[MAX_PATH];
1674 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1675 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1676 if (ptr) {
1677 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1678 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1679 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1684 TCHAR sAskPass[MAX_PATH];
1685 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1686 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1687 if (ptr)
1689 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1690 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1691 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1692 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1696 // add git/bin path to PATH
1698 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1699 str=msysdir;
1700 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1702 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL32, _T(""), FALSE, HKEY_CURRENT_USER);
1703 str = msyslocalinstalldir;
1704 str.TrimRight(_T("\\"));
1705 if (str.IsEmpty())
1707 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1708 str = msysinstalldir;
1709 str.TrimRight(_T("\\"));
1711 if ( !str.IsEmpty() )
1713 str += "\\bin";
1714 msysdir=str;
1715 CGit::ms_LastMsysGitDir = str;
1716 msysdir.write();
1718 else
1720 // search PATH if git/bin directory is already present
1721 if ( FindGitPath() )
1723 m_bInitialized = TRUE;
1724 msysdir = CGit::ms_LastMsysGitDir;
1725 msysdir.write();
1726 return TRUE;
1729 return FALSE;
1732 else
1734 CGit::ms_LastMsysGitDir = str;
1737 // check for git.exe existance (maybe it was deinstalled in the meantime)
1738 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1739 return FALSE;
1741 //set path
1742 _tdupenv_s(&oldpath,&size,_T("PATH"));
1744 CString path;
1745 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1747 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1749 CString str1 = m_Environment.GetEnv(_T("PATH"));
1751 CString sOldPath = oldpath;
1752 free(oldpath);
1754 m_bInitialized = TRUE;
1755 return true;
1758 CString CGit::GetHomeDirectory()
1760 const wchar_t * homeDir = wget_windows_home_directory();
1761 return CString(homeDir, (int)wcslen(homeDir));
1764 CString CGit::GetGitLocalConfig()
1766 CString path;
1767 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, path);
1768 path += _T("config");
1769 return path;
1772 CString CGit::GetGitGlobalConfig()
1774 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1777 CString CGit::GetGitGlobalXDGConfigPath()
1779 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1782 CString CGit::GetGitGlobalXDGConfig()
1784 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1787 CString CGit::GetGitSystemConfig()
1789 const wchar_t * systemConfig = wget_msysgit_etc();
1790 return CString(systemConfig, (int)wcslen(systemConfig));
1793 BOOL CGit::CheckCleanWorkTree()
1795 CString out;
1796 CString cmd;
1797 cmd=_T("git.exe rev-parse --verify HEAD");
1799 if(Run(cmd,&out,CP_UTF8))
1800 return FALSE;
1802 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1803 if(Run(cmd,&out,CP_UTF8))
1804 return FALSE;
1806 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1807 if(Run(cmd,&out,CP_UTF8))
1808 return FALSE;
1810 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1811 if(Run(cmd,&out,CP_UTF8))
1812 return FALSE;
1814 return TRUE;
1816 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1818 int ret;
1819 for(int i=0;i<list.GetCount();i++)
1821 ret = Revert(commit, (CTGitPath&)list[i]);
1822 if(ret)
1823 return ret;
1825 return 0;
1827 int CGit::Revert(CString commit, CTGitPath &path)
1829 CString cmd, out;
1831 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1833 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1835 CString err;
1836 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1837 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1838 return -1;
1840 CString force;
1841 // if the filenames only differ in case, we have to pass "-f"
1842 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1843 force = _T("-f ");
1844 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1845 if (Run(cmd, &out, CP_UTF8))
1847 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1848 return -1;
1851 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1852 if (Run(cmd, &out, CP_UTF8))
1854 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1855 return -1;
1859 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1860 { //To init git repository, there are not HEAD, so we can use git reset command
1861 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1863 if (Run(cmd, &out, CP_UTF8))
1865 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1866 return -1;
1869 else
1871 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1872 if (Run(cmd, &out, CP_UTF8))
1874 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1875 return -1;
1879 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1881 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1882 if (Run(cmd, &out, CP_UTF8))
1884 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1885 return -1;
1889 return 0;
1892 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1894 BYTE_VECTOR vector;
1896 CString cmd;
1897 if(path)
1898 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1899 else
1900 cmd=_T("git.exe ls-files -u -t -z");
1902 if (Run(cmd, &vector))
1904 return -1;
1907 list.ParserFromLsFile(vector);
1909 return 0;
1912 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1914 CString base;
1915 CGitHash basehash,hash;
1916 CString cmd, err;
1917 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1919 if (Run(cmd, &base, &err, CP_UTF8))
1921 return false;
1923 basehash = base.Trim();
1925 GetHash(hash, from);
1927 if (commonAncestor)
1928 *commonAncestor = basehash;
1930 return hash == basehash;
1933 unsigned int CGit::Hash2int(CGitHash &hash)
1935 int ret=0;
1936 for(int i=0;i<4;i++)
1938 ret = ret << 8;
1939 ret |= hash.m_hash[i];
1941 return ret;
1944 int CGit::RefreshGitIndex()
1946 if(g_Git.m_IsUseGitDLL)
1948 CAutoLocker lock(g_Git.m_critGitDllSec);
1951 return git_run_cmd("update-index","update-index -q --refresh");
1953 }catch(...)
1955 return -1;
1959 else
1961 CString cmd,output;
1962 cmd=_T("git.exe update-index --refresh");
1963 return Run(cmd, &output, CP_UTF8);
1967 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1969 if(g_Git.m_IsUseGitDLL)
1971 CAutoLocker lock(g_Git.m_critGitDllSec);
1974 g_Git.CheckAndInitDll();
1975 CStringA ref, patha, outa;
1976 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1977 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1978 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1979 ::DeleteFile(outputfile);
1980 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1982 }catch(...)
1984 return -1;
1987 else
1989 CString cmd;
1990 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1991 return RunLogFile(cmd,outputfile);
1994 void CEnvironment::CopyProcessEnvironment()
1996 TCHAR *p = GetEnvironmentStrings();
1997 while(*p !=0 || *(p+1) !=0)
1998 this->push_back(*p++);
2000 push_back(_T('\0'));
2001 push_back(_T('\0'));
2004 CString CEnvironment::GetEnv(TCHAR *name)
2006 CString str;
2007 for (size_t i = 0; i < size(); i++)
2009 str = &(*this)[i];
2010 int start =0;
2011 CString sname = str.Tokenize(_T("="),start);
2012 if(sname.CompareNoCase(name) == 0)
2014 return &(*this)[i+start];
2016 i+=str.GetLength();
2018 return _T("");
2021 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
2023 unsigned int i;
2024 for( i=0;i<size();i++)
2026 CString str = &(*this)[i];
2027 int start =0;
2028 CString sname = str.Tokenize(_T("="),start);
2029 if(sname.CompareNoCase(name) == 0)
2031 break;
2033 i+=str.GetLength();
2036 if(i == size())
2038 i -= 1; // roll back terminate \0\0
2039 this->push_back(_T('\0'));
2042 CEnvironment::iterator it;
2043 it=this->begin();
2044 it += i;
2046 while(*it && i<size())
2048 this->erase(it);
2049 it=this->begin();
2050 it += i;
2053 while(*name)
2055 this->insert(it,*name++);
2056 i++;
2057 it= begin()+i;
2060 this->insert(it, _T('='));
2061 i++;
2062 it= begin()+i;
2064 while(*value)
2066 this->insert(it,*value++);
2067 i++;
2068 it= begin()+i;
2073 int CGit::GetGitEncode(TCHAR* configkey)
2075 CString str=GetConfigValue(configkey);
2077 if(str.IsEmpty())
2078 return CP_UTF8;
2080 return CUnicodeUtils::GetCPCode(str);
2084 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2086 GIT_FILE file=0;
2087 int ret=0;
2088 GIT_DIFF diff=0;
2090 CAutoLocker lock(g_Git.m_critGitDllSec);
2092 if(arg == NULL)
2093 diff = GetGitDiff();
2094 else
2095 git_open_diff(&diff, arg);
2097 if(diff ==NULL)
2098 return -1;
2100 bool isStat = 0;
2101 if(arg == NULL)
2102 isStat = true;
2103 else
2104 isStat = !!strstr(arg, "stat");
2106 int count=0;
2108 if(hash2 == NULL)
2109 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2110 else
2111 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2113 if(ret)
2114 return -1;
2116 CTGitPath path;
2117 CString strnewname;
2118 CString stroldname;
2120 for(int j=0;j<count;j++)
2122 path.Reset();
2123 char *newname;
2124 char *oldname;
2126 strnewname.Empty();
2127 stroldname.Empty();
2129 int mode=0,IsBin=0,inc=0,dec=0;
2130 git_get_diff_file(diff,file,j,&newname,&oldname,
2131 &mode,&IsBin,&inc,&dec);
2133 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2134 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2136 path.SetFromGit(strnewname,&stroldname);
2137 path.ParserAction((BYTE)mode);
2139 if(IsBin)
2141 path.m_StatAdd=_T("-");
2142 path.m_StatDel=_T("-");
2144 else
2146 path.m_StatAdd.Format(_T("%d"),inc);
2147 path.m_StatDel.Format(_T("%d"),dec);
2149 PathList->AddPath(path);
2151 git_diff_flush(diff);
2153 if(arg)
2154 git_close_diff(diff);
2156 return 0;
2159 int CGit::GetShortHASHLength()
2161 return 7;
2164 CString CGit::GetShortName(CString ref, REF_TYPE *out_type)
2166 CString str=ref;
2167 CString shortname;
2168 REF_TYPE type = CGit::UNKNOWN;
2170 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2172 type = CGit::LOCAL_BRANCH;
2175 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2177 type = CGit::REMOTE_BRANCH;
2179 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2181 type = CGit::TAG;
2183 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2185 type = CGit::STASH;
2186 shortname=_T("stash");
2188 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2190 if (shortname.Find(_T("good")) == 0)
2192 type = CGit::BISECT_GOOD;
2193 shortname = _T("good");
2196 if (shortname.Find(_T("bad")) == 0)
2198 type = CGit::BISECT_BAD;
2199 shortname = _T("bad");
2202 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2204 type = CGit::NOTES;
2206 else
2208 type = CGit::UNKNOWN;
2209 shortname = _T("Unknown");
2212 if(out_type)
2213 *out_type = type;
2215 return shortname;