Deduplicate code for retrieving libgit2 errors
[TortoiseGit.git] / src / Git / Git.cpp
blob185ccb8d1c7c04bdfca66e5d208010ba4df4167a
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 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), 0);
168 GetSortOptions();
169 this->m_bInitialized =false;
170 CheckMsysGitDir();
171 m_critGitDllSec.Init();
174 CGit::~CGit(void)
176 if(this->m_GitDiff)
178 git_close_diff(m_GitDiff);
179 m_GitDiff=0;
181 if(this->m_GitSimpleListDiff)
183 git_close_diff(m_GitSimpleListDiff);
184 m_GitSimpleListDiff=0;
188 bool CGit::IsBranchNameValid(CString branchname)
190 if (branchname.IsEmpty())
191 return false;
193 for (int i = 0; i < branchname.GetLength(); ++i)
195 TCHAR c = branchname.GetAt(i);
196 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
197 return false;
200 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
201 return false;
203 CString reverseBranchname = branchname.MakeReverse();
204 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
205 return false;
207 return true;
210 static char g_Buffer[4096];
212 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
214 SECURITY_ATTRIBUTES sa;
215 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
216 HANDLE hStdioFile = NULL;
218 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
219 sa.lpSecurityDescriptor=NULL;
220 sa.bInheritHandle=TRUE;
221 if(!CreatePipe(&hRead,&hWrite,&sa,0))
223 return TGIT_GIT_ERROR_OPEN_PIP;
225 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
226 return TGIT_GIT_ERROR_OPEN_PIP;
228 if(StdioFile)
230 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
231 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
234 STARTUPINFO si;
235 PROCESS_INFORMATION pi;
236 si.cb=sizeof(STARTUPINFO);
237 GetStartupInfo(&si);
239 if (hErrReadOut)
240 si.hStdError = hWriteErr;
241 else
242 si.hStdError = hWrite;
243 if(StdioFile)
244 si.hStdOutput=hStdioFile;
245 else
246 si.hStdOutput=hWrite;
248 si.wShowWindow=SW_HIDE;
249 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
251 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
252 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
254 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
255 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
257 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
258 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
260 if(cmd.Find(_T("git")) == 0)
262 int firstSpace = cmd.Find(_T(" "));
263 if (firstSpace > 0)
264 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
265 else
266 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
269 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
271 LPVOID lpMsgBuf;
272 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
273 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
274 (LPTSTR)&lpMsgBuf,
275 0,NULL);
276 return TGIT_GIT_ERROR_CREATE_PROCESS;
279 m_CurrentGitPi = pi;
281 CloseHandle(hWrite);
282 if (hErrReadOut)
283 CloseHandle(hWriteErr);
284 if(piOut)
285 *piOut=pi;
286 if(hReadOut)
287 *hReadOut=hRead;
288 if(hErrReadOut)
289 *hErrReadOut = hReadErr;
290 return 0;
293 //Must use sperate function to convert ANSI str to union code string
294 //Becuase A2W use stack as internal convert buffer.
295 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
297 //USES_CONVERSION;
298 //str->Append(A2W_CP((LPCSTR)p,code));
299 if(str == NULL)
300 return ;
302 WCHAR * buf;
304 int len ;
305 if(length<0)
306 len = (int)strlen((const char*)p);
307 else
308 len=length;
309 //if (len==0)
310 // return ;
311 //buf = new WCHAR[len*4 + 1];
312 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
313 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
314 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
315 str->ReleaseBuffer();
316 //str->Append(buf);
317 //delete buf;
320 BOOL CGit::IsOrphanBranch(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 TRUE;
330 if(cmdout.IsEmpty())
331 return TRUE;
333 return FALSE;
336 BOOL CGit::IsInitRepos()
338 return IsOrphanBranch(_T("HEAD"));
341 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
343 PASYNCREADSTDERRTHREADARGS pDataArray;
344 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
346 DWORD readnumber;
347 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
348 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
350 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
351 break;
354 return 0;
357 int CGit::Run(CGitCall* pcall)
359 PROCESS_INFORMATION pi;
360 HANDLE hRead, hReadErr;
361 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
362 return TGIT_GIT_ERROR_CREATE_PROCESS;
364 HANDLE thread;
365 ASYNCREADSTDERRTHREADARGS threadArguments;
366 threadArguments.fileHandle = hReadErr;
367 threadArguments.pcall = pcall;
368 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
370 DWORD readnumber;
371 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
372 bool bAborted=false;
373 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
375 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
376 if(!bAborted)//For now, flush output when command aborted.
377 if(pcall->OnOutputData(data,readnumber))
378 bAborted=true;
380 if(!bAborted)
381 pcall->OnEnd();
383 if (thread)
384 WaitForSingleObject(thread, INFINITE);
386 CloseHandle(pi.hThread);
388 WaitForSingleObject(pi.hProcess, INFINITE);
389 DWORD exitcode =0;
391 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
393 return TGIT_GIT_ERROR_GET_EXIT_CODE;
396 CloseHandle(pi.hProcess);
398 CloseHandle(hRead);
399 CloseHandle(hReadErr);
400 return exitcode;
402 class CGitCall_ByteVector : public CGitCall
404 public:
405 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
406 virtual bool OnOutputData(const BYTE* data, size_t size)
408 if (size == 0)
409 return false;
410 size_t oldsize=m_pvector->size();
411 m_pvector->resize(m_pvector->size()+size);
412 memcpy(&*(m_pvector->begin()+oldsize),data,size);
413 return false;
415 virtual bool OnOutputErrData(const BYTE* data, size_t size)
417 if (!m_pvectorErr || size == 0)
418 return false;
419 size_t oldsize = m_pvectorErr->size();
420 m_pvectorErr->resize(m_pvectorErr->size() + size);
421 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
422 return false;
424 BYTE_VECTOR* m_pvector;
425 BYTE_VECTOR* m_pvectorErr;
428 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
430 CGitCall_ByteVector call(cmd, vector, vectorErr);
431 return Run(&call);
433 int CGit::Run(CString cmd, CString* output, int code)
435 CString err;
436 int ret;
437 ret = Run(cmd, output, &err, code);
439 if (output && !err.IsEmpty())
441 if (!output->IsEmpty())
442 *output += _T("\n");
443 *output += err;
446 return ret;
448 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
450 BYTE_VECTOR vector, vectorErr;
451 int ret;
452 if (outputErr)
453 ret = Run(cmd, &vector, &vectorErr);
454 else
455 ret = Run(cmd, &vector);
457 vector.push_back(0);
458 StringAppend(output, &(vector[0]), code);
460 if (outputErr)
462 vectorErr.push_back(0);
463 StringAppend(outputErr, &(vectorErr[0]), code);
466 return ret;
469 CString CGit::GetUserName(void)
471 CEnvironment env;
472 env.CopyProcessEnvironment();
473 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
474 if (!envname.IsEmpty())
475 return envname;
476 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
478 CString CGit::GetUserEmail(void)
480 CEnvironment env;
481 env.CopyProcessEnvironment();
482 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
483 if (!envmail.IsEmpty())
484 return envmail;
486 return GetConfigValue(L"user.email");
489 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
491 CString configValue;
492 int start = 0;
493 if(this->m_IsUseGitDLL)
495 CString *git_path=NULL;
497 CAutoLocker lock(g_Git.m_critGitDllSec);
501 CTGitPath path;
503 CheckAndInitDll();
504 git_path = GitPath;
506 }catch(...)
509 CStringA key, value;
510 key = CUnicodeUtils::GetMulti(name, encoding);
511 CStringA p;
512 if(git_path)
513 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
515 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
516 return CString();
517 else
519 StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
520 if(RemoveCR)
521 return configValue.Tokenize(_T("\n"),start);
522 return configValue;
526 else
528 CString cmd;
529 cmd.Format(L"git.exe config %s", name);
530 Run(cmd, &configValue, NULL, encoding);
531 if(RemoveCR)
532 return configValue.Tokenize(_T("\n"),start);
533 return configValue;
537 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
539 if(this->m_IsUseGitDLL)
541 CAutoLocker lock(g_Git.m_critGitDllSec);
545 CheckAndInitDll();
547 }catch(...)
550 CStringA keya, valuea;
551 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
552 valuea = CUnicodeUtils::GetMulti(value, encoding);
553 CStringA p;
554 if(GitPath)
555 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
557 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
560 else
562 CString cmd;
563 CString option;
564 switch(type)
566 case CONFIG_GLOBAL:
567 option = _T("--global");
568 break;
569 case CONFIG_SYSTEM:
570 option = _T("--system");
571 break;
572 default:
573 break;
575 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
576 CString out;
577 if (Run(cmd, &out, NULL, encoding))
579 return -1;
582 return 0;
585 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
587 if(this->m_IsUseGitDLL)
589 CAutoLocker lock(g_Git.m_critGitDllSec);
593 CheckAndInitDll();
594 }catch(...)
597 CStringA keya;
598 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
599 CStringA p;
600 if(GitPath)
601 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
603 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
605 else
607 CString cmd;
608 CString option;
609 switch(type)
611 case CONFIG_GLOBAL:
612 option = _T("--global");
613 break;
614 case CONFIG_SYSTEM:
615 option = _T("--system");
616 break;
617 default:
618 break;
620 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
621 CString out;
622 if (Run(cmd, &out, NULL, encoding))
624 return -1;
627 return 0;
630 CString CGit::GetCurrentBranch(void)
632 CString output;
633 //Run(_T("git.exe branch"),&branch);
635 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
637 return _T("(no branch)");
639 else
640 return output;
644 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
646 CString refName;
647 if(this->m_IsUseGitDLL)
649 unsigned char sha1[20];
650 int flag;
652 CAutoLocker lock(g_Git.m_critGitDllSec);
653 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
654 if(refs_heads_master && (flag&REF_ISSYMREF))
656 StringAppend(&refName,(BYTE*)refs_heads_master);
657 if(bStripRefsHeads)
658 refName = StripRefName(refName);
662 else
664 CString cmd;
665 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
666 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
667 return CString();//Error
668 int iStart = 0;
669 refName = refName.Tokenize(L"\n", iStart);
670 if(bStripRefsHeads)
671 refName = StripRefName(refName);
673 return refName;
676 CString CGit::GetFullRefName(CString shortRefName)
678 CString refName;
679 CString cmd;
680 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
681 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
682 return CString();//Error
683 int iStart = 0;
684 return refName.Tokenize(L"\n", iStart);
687 CString CGit::StripRefName(CString refName)
689 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
690 refName = refName.Mid(11);
691 else if(wcsncmp(refName, L"refs/", 5) == 0)
692 refName = refName.Mid(5);
693 int start =0;
694 return refName.Tokenize(_T("\n"),start);
697 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
699 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
701 if ( sProjectRoot.IsEmpty() )
702 return -1;
704 CString sDotGitPath;
705 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
706 return -1;
708 CString sHeadFile = sDotGitPath + _T("HEAD");
710 FILE *pFile;
711 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
713 if (!pFile)
715 return -1;
718 char s[256] = {0};
719 fgets(s, sizeof(s), pFile);
721 fclose(pFile);
723 const char *pfx = "ref: refs/heads/";
724 const int len = 16;//strlen(pfx)
726 if ( !strncmp(s, pfx, len) )
728 //# We're on a branch. It might not exist. But
729 //# HEAD looks good enough to be a branch.
730 CStringA utf8Branch(s + len);
731 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
732 sBranchOut.TrimRight(_T(" \r\n\t"));
734 if ( sBranchOut.IsEmpty() )
735 return -1;
737 else
739 //# Assume this is a detached head.
740 sBranchOut = "HEAD";
742 return 1;
745 return 0;
748 int CGit::BuildOutputFormat(CString &format,bool IsFull)
750 CString log;
751 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
752 format += log;
753 if(IsFull)
755 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
756 format += log;
757 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
758 format += log;
759 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
760 format += log;
761 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
762 format += log;
763 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
764 format += log;
765 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
766 format += log;
767 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
768 format += log;
771 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
772 format += log;
773 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
774 format += log;
775 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
776 format += log;
778 if(IsFull)
780 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
781 format += log;
783 return 0;
786 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
788 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
789 return GetLog(&gitCall,hash,path,count,mask,from,to);
792 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
793 CFilterData *Filter)
795 CString cmd;
796 CString num;
797 CString since;
799 CString file;
801 if(path)
802 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
804 if(count>0)
805 num.Format(_T("-n%d"),count);
807 CString param;
809 if(mask& LOG_INFO_STAT )
810 param += _T(" --numstat ");
811 if(mask& LOG_INFO_FILESTATE)
812 param += _T(" --raw ");
814 if(mask& LOG_INFO_FULLHISTORY)
815 param += _T(" --full-history ");
817 if(mask& LOG_INFO_BOUNDARY)
818 param += _T(" --left-right --boundary ");
820 if(mask& CGit::LOG_INFO_ALL_BRANCH)
821 param += _T(" --all ");
823 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
824 param += _T(" -C ");
826 if(mask& CGit::LOG_INFO_DETECT_RENAME )
827 param += _T(" -M ");
829 if(mask& CGit::LOG_INFO_FIRST_PARENT )
830 param += _T(" --first-parent ");
832 if(mask& CGit::LOG_INFO_NO_MERGE )
833 param += _T(" --no-merges ");
835 if(mask& CGit::LOG_INFO_FOLLOW)
836 param += _T(" --follow ");
838 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
839 param += _T(" -c ");
841 if(mask& CGit::LOG_INFO_FULL_DIFF)
842 param += _T(" --full-diff ");
844 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
845 param += _T(" --simplify-by-decoration ");
847 if(from != NULL && to != NULL)
849 CString range;
850 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
851 param += range;
853 else if(to != NULL && hash.IsEmpty())
855 CString range;
856 range.Format(_T(" %s "), FixBranchName(*to));
857 param += range;
859 param+=hash;
861 CString st1,st2;
863 if( Filter && (Filter->m_From != -1))
865 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
866 param += st1;
869 if( Filter && (Filter->m_To != -1))
871 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
872 param += st2;
875 bool isgrep = false;
876 if( Filter && (!Filter->m_Author.IsEmpty()))
878 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
879 param += st1;
880 isgrep = true;
883 if( Filter && (!Filter->m_Committer.IsEmpty()))
885 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
886 param += st1;
887 isgrep = true;
890 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
892 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
893 param += st1;
894 isgrep = true;
897 if(Filter && isgrep)
899 if(!Filter->m_IsRegex)
900 param += _T(" --fixed-strings ");
902 param += _T(" --regexp-ignore-case --extended-regexp ");
905 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
906 param += _T(" --topo-order");
908 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
909 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
910 else
912 CString log;
913 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
914 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
915 num,param,log);
918 cmd += file;
920 return cmd;
922 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
923 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
925 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
927 return Run(pgitCall);
928 // return Run(cmd,&logOut);
931 #define BUFSIZE 512
932 void GetTempPath(CString &path)
934 TCHAR lpPathBuffer[BUFSIZE];
935 DWORD dwRetVal;
936 DWORD dwBufSize=BUFSIZE;
937 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
938 lpPathBuffer); // buffer for path
939 if (dwRetVal > dwBufSize || (dwRetVal == 0))
941 path=_T("");
943 path.Format(_T("%s"),lpPathBuffer);
945 CString GetTempFile()
947 TCHAR lpPathBuffer[BUFSIZE];
948 DWORD dwRetVal;
949 DWORD dwBufSize=BUFSIZE;
950 TCHAR szTempName[BUFSIZE];
951 UINT uRetVal;
953 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
954 lpPathBuffer); // buffer for path
955 if (dwRetVal > dwBufSize || (dwRetVal == 0))
957 return _T("");
959 // Create a temporary file.
960 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
961 TEXT("Patch"), // temp file name prefix
962 0, // create unique name
963 szTempName); // buffer for name
966 if (uRetVal == 0)
968 return _T("");
971 return CString(szTempName);
975 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
977 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
978 if (result == 0) return 0;
979 if (lpBuffer == NULL || (result + 13 > nBufferLength))
981 if (lpBuffer)
982 lpBuffer[0] = '\0';
983 return result + 13;
986 _tcscat(lpBuffer, _T("TortoiseGit\\"));
987 CreateDirectory(lpBuffer, NULL);
989 return result + 13;
992 int CGit::RunLogFile(CString cmd,const CString &filename)
994 STARTUPINFO si;
995 PROCESS_INFORMATION pi;
996 si.cb=sizeof(STARTUPINFO);
997 GetStartupInfo(&si);
999 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1000 psa.bInheritHandle=TRUE;
1002 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1003 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1005 si.wShowWindow = SW_HIDE;
1006 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1007 si.hStdOutput = houtfile;
1009 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1010 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1012 if(cmd.Find(_T("git")) == 0)
1013 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1015 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1017 LPVOID lpMsgBuf;
1018 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1019 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1020 (LPTSTR)&lpMsgBuf,
1021 0,NULL);
1022 return TGIT_GIT_ERROR_CREATE_PROCESS;
1025 WaitForSingleObject(pi.hProcess,INFINITE);
1027 CloseHandle(pi.hThread);
1028 CloseHandle(pi.hProcess);
1029 CloseHandle(houtfile);
1030 return TGIT_GIT_SUCCESS;
1031 // return 0;
1034 int CGit::GetHash(CGitHash &hash, TCHAR* friendname)
1036 // no need to parse a ref if it's already a 40-byte hash
1037 if (CGitHash::IsValidSHA1(friendname))
1039 CString sHash(friendname);
1040 hash = CGitHash(sHash);
1041 return 0;
1044 if (m_IsUseLibGit2)
1046 git_repository *repo = NULL;
1047 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1048 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1050 gitdirA.ReleaseBuffer();
1051 return -1;
1053 gitdirA.ReleaseBuffer();
1055 int isHeadOrphan = git_repository_head_orphan(repo);
1056 if (isHeadOrphan != 0)
1058 git_repository_free(repo);
1059 hash.Empty();
1060 if (isHeadOrphan == 1)
1061 return 0;
1062 else
1063 return -1;
1066 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1068 git_object * gitObject = NULL;
1069 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1071 refnameA.ReleaseBuffer();
1072 git_repository_free(repo);
1073 return -1;
1075 refnameA.ReleaseBuffer();
1077 const git_oid * oid = git_object_id(gitObject);
1078 if (oid == NULL)
1080 git_object_free(gitObject);
1081 git_repository_free(repo);
1082 return -1;
1085 hash = CGitHash((char *)oid->id);
1087 git_object_free(gitObject); // also frees oid
1088 git_repository_free(repo);
1090 return 0;
1092 else
1094 CString cmd;
1095 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1096 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1097 hash = CGitHash(gitLastErr.Trim());
1098 return ret;
1102 int CGit::GetInitAddList(CTGitPathList &outputlist)
1104 CString cmd;
1105 BYTE_VECTOR cmdout;
1107 cmd=_T("git.exe ls-files -s -t -z");
1108 outputlist.Clear();
1109 if (Run(cmd, &cmdout))
1110 return -1;
1112 outputlist.ParserFromLsFile(cmdout);
1113 for(int i = 0; i < outputlist.GetCount(); ++i)
1114 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1116 return 0;
1118 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1120 CString cmd;
1122 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1124 //rev1=+_T("");
1125 if(rev1 == GIT_REV_ZERO)
1126 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1127 else
1128 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1130 else
1132 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1135 BYTE_VECTOR out;
1136 if (Run(cmd, &out))
1137 return -1;
1139 outputlist.ParserFromLog(out);
1141 return 0;
1144 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1146 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1147 CString str;
1148 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1149 list->push_back(str);
1150 return 0;
1153 int CGit::GetTagList(STRING_VECTOR &list)
1155 if (this->m_IsUseLibGit2)
1157 git_repository *repo = NULL;
1159 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1160 if (git_repository_open(&repo, gitdir.GetBuffer()))
1162 gitdir.ReleaseBuffer();
1163 return -1;
1165 gitdir.ReleaseBuffer();
1167 git_strarray tag_names;
1169 if (git_tag_list(&tag_names, repo))
1171 git_repository_free(repo);
1172 return -1;
1175 for (size_t i = 0; i < tag_names.count; ++i)
1177 CStringA tagName(tag_names.strings[i]);
1178 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1181 git_strarray_free(&tag_names);
1183 git_repository_free(repo);
1185 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1187 return 0;
1189 else
1191 CString cmd, output;
1192 cmd=_T("git.exe tag -l");
1193 int ret = Run(cmd, &output, NULL, CP_UTF8);
1194 if(!ret)
1196 int pos=0;
1197 CString one;
1198 while( pos>=0 )
1200 one=output.Tokenize(_T("\n"),pos);
1201 if (!one.IsEmpty())
1202 list.push_back(one);
1204 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1206 return ret;
1211 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1212 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1214 CString CGit::GetGitLastErr(CString msg)
1216 if (this->m_IsUseLibGit2)
1217 return GetLibGit2LastErr(msg);
1218 else if (gitLastErr.IsEmpty())
1219 return msg + _T("\nUnknown git.exe error.");
1220 else
1222 CString lastError = gitLastErr;
1223 gitLastErr.Empty();
1224 return msg + _T("\n") + lastError;
1228 CString CGit::GetLibGit2LastErr()
1230 const git_error *libgit2err = giterr_last();
1231 if (libgit2err)
1233 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1234 giterr_clear();
1235 return _T("libgit2 returned: ") + lastError;
1237 else
1238 return _T("An error occoured in libgit2, but no message is available.");
1241 CString CGit::GetLibGit2LastErr(CString msg)
1243 if (!msg.IsEmpty())
1244 return msg + _T("\n") + GetLibGit2LastErr();
1245 return GetLibGit2LastErr();
1248 CString CGit::FixBranchName_Mod(CString& branchName)
1250 if(branchName == "FETCH_HEAD")
1251 branchName = DerefFetchHead();
1252 return branchName;
1255 CString CGit::FixBranchName(const CString& branchName)
1257 CString tempBranchName = branchName;
1258 FixBranchName_Mod(tempBranchName);
1259 return tempBranchName;
1262 bool CGit::IsBranchTagNameUnique(const CString& name)
1264 CString output;
1266 CString cmd;
1267 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1268 int ret = Run(cmd, &output, NULL, CP_UTF8);
1269 if (!ret)
1271 int i = 0, pos = 0;
1272 while (pos >= 0)
1274 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1275 ++i;
1277 if (i >= 2)
1278 return false;
1281 return true;
1285 Checks if a branch or tag with the given name exists
1286 isBranch is true -> branch, tag otherwise
1288 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1290 CString cmd, output;
1292 cmd = _T("git show-ref ");
1293 if (isBranch)
1294 cmd += _T("--heads ");
1295 else
1296 cmd += _T("--tags ");
1298 cmd += _T("refs/heads/") + name;
1299 cmd += _T(" refs/tags/") + name;
1301 int ret = Run(cmd, &output, NULL, CP_UTF8);
1302 if (!ret)
1304 if (!output.IsEmpty())
1305 return true;
1308 return false;
1311 CString CGit::DerefFetchHead()
1313 using namespace std;
1314 CString dotGitPath;
1315 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1316 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1317 int forMergeLineCount = 0;
1318 string line;
1319 string hashToReturn;
1320 while(getline(fetchHeadFile, line))
1322 //Tokenize this line
1323 string::size_type prevPos = 0;
1324 string::size_type pos = line.find('\t');
1325 if(pos == string::npos) continue; //invalid line
1327 string hash = line.substr(0, pos);
1328 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1330 bool forMerge = pos == prevPos;
1331 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1333 string remoteBranch = line.substr(prevPos, pos - prevPos);
1335 //Process this line
1336 if(forMerge)
1338 hashToReturn = hash;
1339 ++forMergeLineCount;
1340 if(forMergeLineCount > 1)
1341 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1345 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1348 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1350 int ret;
1351 CString cmd, output, cur;
1352 cmd = _T("git.exe branch --no-color");
1354 if((type&BRANCH_ALL) == BRANCH_ALL)
1355 cmd += _T(" -a");
1356 else if(type&BRANCH_REMOTE)
1357 cmd += _T(" -r");
1359 ret = Run(cmd, &output, NULL, CP_UTF8);
1360 if(!ret)
1362 int pos=0;
1363 CString one;
1364 while( pos>=0 )
1366 one=output.Tokenize(_T("\n"),pos);
1367 one.Trim(L" \r\n\t");
1368 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1369 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1370 if(one[0] == _T('*'))
1372 one = one.Mid(2);
1373 cur = one;
1375 if (one != _T("(no branch)"))
1376 list.push_back(one);
1380 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1381 list.push_back(L"FETCH_HEAD");
1383 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1385 if (current && cur != _T("(no branch)"))
1387 for (unsigned int i = 0; i < list.size(); ++i)
1389 if (list[i] == cur)
1391 *current = i;
1392 break;
1397 return ret;
1400 int CGit::GetRemoteList(STRING_VECTOR &list)
1402 if (this->m_IsUseLibGit2)
1404 git_repository *repo = NULL;
1406 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1407 if (git_repository_open(&repo, gitdir.GetBuffer()))
1409 gitdir.ReleaseBuffer();
1410 return -1;
1412 gitdir.ReleaseBuffer();
1414 git_strarray remotes;
1416 if (git_remote_list(&remotes, repo))
1418 git_repository_free(repo);
1419 return -1;
1422 for (size_t i = 0; i < remotes.count; ++i)
1424 CStringA remote(remotes.strings[i]);
1425 list.push_back(CUnicodeUtils::GetUnicode(remote));
1428 git_strarray_free(&remotes);
1430 git_repository_free(repo);
1432 std::sort(list.begin(), list.end());
1434 return 0;
1436 else
1438 int ret;
1439 CString cmd, output;
1440 cmd=_T("git.exe remote");
1441 ret = Run(cmd, &output, NULL, CP_UTF8);
1442 if(!ret)
1444 int pos=0;
1445 CString one;
1446 while( pos>=0 )
1448 one=output.Tokenize(_T("\n"),pos);
1449 if (!one.IsEmpty())
1450 list.push_back(one);
1453 return ret;
1457 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1459 CString cmd, out, err;
1460 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1461 if (Run(cmd, &out, &err, CP_UTF8))
1463 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1464 return -1;
1467 int pos = 0;
1468 while (pos >= 0)
1470 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1471 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1472 if (one.Find(_T("^{}")) >= 1)
1473 continue;
1474 if (!one.IsEmpty())
1475 list.push_back(one);
1477 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1478 return 0;
1481 int libgit2_addto_list_each_ref_fn(const char *refname, void *payload)
1483 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1484 CString str;
1485 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1486 list->push_back(str);
1487 return 0;
1490 int CGit::GetRefList(STRING_VECTOR &list)
1492 if (this->m_IsUseLibGit2)
1494 git_repository *repo = NULL;
1496 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1497 if (git_repository_open(&repo, gitdir.GetBuffer()))
1499 gitdir.ReleaseBuffer();
1500 return -1;
1502 gitdir.ReleaseBuffer();
1504 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_list_each_ref_fn, &list))
1506 git_repository_free(repo);
1507 return -1;
1510 git_repository_free(repo);
1512 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1514 return 0;
1516 else
1518 CString cmd, output;
1519 cmd=_T("git.exe show-ref -d");
1520 int ret = Run(cmd, &output, NULL, CP_UTF8);
1521 if(!ret)
1523 int pos=0;
1524 CString one;
1525 while( pos>=0 )
1527 one=output.Tokenize(_T("\n"),pos);
1528 int start=one.Find(_T(" "),0);
1529 if(start>0)
1531 CString name;
1532 name=one.Right(one.GetLength()-start-1);
1533 list.push_back(name);
1536 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1538 return ret;
1542 typedef struct map_each_ref_payload {
1543 git_repository * repo;
1544 MAP_HASH_NAME * map;
1545 } map_each_ref_payload;
1547 int libgit2_addto_map_each_ref_fn(const char *refname, void *payload)
1549 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1551 CString str;
1552 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1554 git_object * gitObject = NULL;
1558 if (git_revparse_single(&gitObject, payloadContent->repo, refname))
1560 break;
1563 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1565 str += _T("^{}"); // deref tag
1566 git_object * derefedTag = NULL;
1567 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1569 break;
1571 git_object_free(gitObject);
1572 gitObject = derefedTag;
1575 const git_oid * oid = git_object_id(gitObject);
1576 if (oid == NULL)
1578 break;
1581 CGitHash hash((char *)oid->id);
1582 (*payloadContent->map)[hash].push_back(str);
1583 } while (false);
1585 if (gitObject)
1587 git_object_free(gitObject);
1588 return 0;
1591 return 1;
1594 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1596 if (this->m_IsUseLibGit2)
1598 git_repository *repo = NULL;
1600 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1601 if (git_repository_open(&repo, gitdir.GetBuffer()))
1603 gitdir.ReleaseBuffer();
1604 return -1;
1606 gitdir.ReleaseBuffer();
1608 map_each_ref_payload payloadContent = { repo, &map };
1610 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_map_each_ref_fn, &payloadContent))
1612 git_repository_free(repo);
1613 return -1;
1616 git_repository_free(repo);
1618 for (auto it = map.begin(); it != map.end(); ++it)
1620 std::sort(it->second.begin(), it->second.end());
1623 return 0;
1625 else
1627 CString cmd, output;
1628 cmd=_T("git.exe show-ref -d");
1629 int ret = Run(cmd, &output, NULL, CP_UTF8);
1630 if(!ret)
1632 int pos=0;
1633 CString one;
1634 while( pos>=0 )
1636 one=output.Tokenize(_T("\n"),pos);
1637 int start=one.Find(_T(" "),0);
1638 if(start>0)
1640 CString name;
1641 name=one.Right(one.GetLength()-start-1);
1643 CString hash;
1644 hash=one.Left(start);
1646 map[CGitHash(hash)].push_back(name);
1650 return ret;
1654 BOOL CGit::CheckMsysGitDir()
1656 if (m_bInitialized)
1658 return TRUE;
1661 this->m_Environment.clear();
1662 m_Environment.CopyProcessEnvironment();
1664 TCHAR *oldpath;
1665 size_t homesize,size;
1667 // set HOME if not set already
1668 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1669 if (!homesize)
1671 CString home = GetHomeDirectory();
1672 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1673 home.ReleaseBuffer();
1675 CString str;
1677 //setup ssh client
1678 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1680 if(!sshclient.IsEmpty())
1682 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1683 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1685 else
1687 TCHAR sPlink[MAX_PATH];
1688 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1689 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1690 if (ptr) {
1691 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1692 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1693 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1698 TCHAR sAskPass[MAX_PATH];
1699 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1700 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1701 if (ptr)
1703 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1704 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1705 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1706 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1710 // add git/bin path to PATH
1712 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1713 str=msysdir;
1714 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1716 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1717 str = msyslocalinstalldir;
1718 str.TrimRight(_T("\\"));
1719 if (str.IsEmpty())
1721 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1722 str = msysinstalldir;
1723 str.TrimRight(_T("\\"));
1725 if ( !str.IsEmpty() )
1727 str += "\\bin";
1728 msysdir=str;
1729 CGit::ms_LastMsysGitDir = str;
1730 msysdir.write();
1732 else
1734 // search PATH if git/bin directory is already present
1735 if ( FindGitPath() )
1737 m_bInitialized = TRUE;
1738 msysdir = CGit::ms_LastMsysGitDir;
1739 msysdir.write();
1740 return TRUE;
1743 return FALSE;
1746 else
1748 CGit::ms_LastMsysGitDir = str;
1751 // check for git.exe existance (maybe it was deinstalled in the meantime)
1752 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1753 return FALSE;
1755 //set path
1756 _tdupenv_s(&oldpath,&size,_T("PATH"));
1758 CString path;
1759 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1761 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1763 CString str1 = m_Environment.GetEnv(_T("PATH"));
1765 CString sOldPath = oldpath;
1766 free(oldpath);
1768 m_bInitialized = TRUE;
1769 return true;
1772 CString CGit::GetHomeDirectory()
1774 const wchar_t * homeDir = wget_windows_home_directory();
1775 return CString(homeDir, (int)wcslen(homeDir));
1778 CString CGit::GetGitLocalConfig()
1780 CString path;
1781 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, path);
1782 path += _T("config");
1783 return path;
1786 CString CGit::GetGitGlobalConfig()
1788 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1791 CString CGit::GetGitGlobalXDGConfigPath()
1793 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1796 CString CGit::GetGitGlobalXDGConfig()
1798 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1801 CString CGit::GetGitSystemConfig()
1803 const wchar_t * systemConfig = wget_msysgit_etc();
1804 return CString(systemConfig, (int)wcslen(systemConfig));
1807 BOOL CGit::CheckCleanWorkTree()
1809 CString out;
1810 CString cmd;
1811 cmd=_T("git.exe rev-parse --verify HEAD");
1813 if(Run(cmd,&out,CP_UTF8))
1814 return FALSE;
1816 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1817 if(Run(cmd,&out,CP_UTF8))
1818 return FALSE;
1820 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1821 if(Run(cmd,&out,CP_UTF8))
1822 return FALSE;
1824 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1825 if(Run(cmd,&out,CP_UTF8))
1826 return FALSE;
1828 return TRUE;
1830 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1832 int ret;
1833 for (int i = 0; i < list.GetCount(); ++i)
1835 ret = Revert(commit, (CTGitPath&)list[i]);
1836 if(ret)
1837 return ret;
1839 return 0;
1841 int CGit::Revert(CString commit, CTGitPath &path)
1843 CString cmd, out;
1845 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1847 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1849 CString err;
1850 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1851 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1852 return -1;
1854 CString force;
1855 // if the filenames only differ in case, we have to pass "-f"
1856 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1857 force = _T("-f ");
1858 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1859 if (Run(cmd, &out, CP_UTF8))
1861 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1862 return -1;
1865 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1866 if (Run(cmd, &out, CP_UTF8))
1868 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1869 return -1;
1873 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1874 { //To init git repository, there are not HEAD, so we can use git reset command
1875 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1877 if (Run(cmd, &out, CP_UTF8))
1879 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1880 return -1;
1883 else
1885 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1886 if (Run(cmd, &out, CP_UTF8))
1888 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1889 return -1;
1893 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1895 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1896 if (Run(cmd, &out, CP_UTF8))
1898 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1899 return -1;
1903 return 0;
1906 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1908 BYTE_VECTOR vector;
1910 CString cmd;
1911 if(path)
1912 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1913 else
1914 cmd=_T("git.exe ls-files -u -t -z");
1916 if (Run(cmd, &vector))
1918 return -1;
1921 list.ParserFromLsFile(vector);
1923 return 0;
1926 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1928 CString base;
1929 CGitHash basehash,hash;
1930 CString cmd, err;
1931 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1933 if (Run(cmd, &base, &err, CP_UTF8))
1935 return false;
1937 basehash = base.Trim();
1939 GetHash(hash, from);
1941 if (commonAncestor)
1942 *commonAncestor = basehash;
1944 return hash == basehash;
1947 unsigned int CGit::Hash2int(CGitHash &hash)
1949 int ret=0;
1950 for (int i = 0; i < 4; ++i)
1952 ret = ret << 8;
1953 ret |= hash.m_hash[i];
1955 return ret;
1958 int CGit::RefreshGitIndex()
1960 if(g_Git.m_IsUseGitDLL)
1962 CAutoLocker lock(g_Git.m_critGitDllSec);
1965 return git_run_cmd("update-index","update-index -q --refresh");
1967 }catch(...)
1969 return -1;
1973 else
1975 CString cmd,output;
1976 cmd=_T("git.exe update-index --refresh");
1977 return Run(cmd, &output, CP_UTF8);
1981 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1983 if(g_Git.m_IsUseGitDLL)
1985 CAutoLocker lock(g_Git.m_critGitDllSec);
1988 g_Git.CheckAndInitDll();
1989 CStringA ref, patha, outa;
1990 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1991 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1992 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1993 ::DeleteFile(outputfile);
1994 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1996 }catch(...)
1998 return -1;
2001 else
2003 CString cmd;
2004 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2005 return RunLogFile(cmd,outputfile);
2008 void CEnvironment::CopyProcessEnvironment()
2010 TCHAR *p = GetEnvironmentStrings();
2011 while(*p !=0 || *(p+1) !=0)
2012 this->push_back(*p++);
2014 push_back(_T('\0'));
2015 push_back(_T('\0'));
2018 CString CEnvironment::GetEnv(TCHAR *name)
2020 CString str;
2021 for (size_t i = 0; i < size(); ++i)
2023 str = &(*this)[i];
2024 int start =0;
2025 CString sname = str.Tokenize(_T("="),start);
2026 if(sname.CompareNoCase(name) == 0)
2028 return &(*this)[i+start];
2030 i+=str.GetLength();
2032 return _T("");
2035 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
2037 unsigned int i;
2038 for (i = 0; i < size(); ++i)
2040 CString str = &(*this)[i];
2041 int start =0;
2042 CString sname = str.Tokenize(_T("="),start);
2043 if(sname.CompareNoCase(name) == 0)
2045 break;
2047 i+=str.GetLength();
2050 if(i == size())
2052 i -= 1; // roll back terminate \0\0
2053 this->push_back(_T('\0'));
2056 CEnvironment::iterator it;
2057 it=this->begin();
2058 it += i;
2060 while(*it && i<size())
2062 this->erase(it);
2063 it=this->begin();
2064 it += i;
2067 while(*name)
2069 this->insert(it,*name++);
2070 ++i;
2071 it= begin()+i;
2074 this->insert(it, _T('='));
2075 ++i;
2076 it= begin()+i;
2078 while(*value)
2080 this->insert(it,*value++);
2081 ++i;
2082 it= begin()+i;
2087 int CGit::GetGitEncode(TCHAR* configkey)
2089 CString str=GetConfigValue(configkey);
2091 if(str.IsEmpty())
2092 return CP_UTF8;
2094 return CUnicodeUtils::GetCPCode(str);
2098 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2100 GIT_FILE file=0;
2101 int ret=0;
2102 GIT_DIFF diff=0;
2104 CAutoLocker lock(g_Git.m_critGitDllSec);
2106 if(arg == NULL)
2107 diff = GetGitDiff();
2108 else
2109 git_open_diff(&diff, arg);
2111 if(diff ==NULL)
2112 return -1;
2114 bool isStat = 0;
2115 if(arg == NULL)
2116 isStat = true;
2117 else
2118 isStat = !!strstr(arg, "stat");
2120 int count=0;
2122 if(hash2 == NULL)
2123 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2124 else
2125 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2127 if(ret)
2128 return -1;
2130 CTGitPath path;
2131 CString strnewname;
2132 CString stroldname;
2134 for (int j = 0; j < count; ++j)
2136 path.Reset();
2137 char *newname;
2138 char *oldname;
2140 strnewname.Empty();
2141 stroldname.Empty();
2143 int mode=0,IsBin=0,inc=0,dec=0;
2144 git_get_diff_file(diff,file,j,&newname,&oldname,
2145 &mode,&IsBin,&inc,&dec);
2147 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2148 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2150 path.SetFromGit(strnewname,&stroldname);
2151 path.ParserAction((BYTE)mode);
2153 if(IsBin)
2155 path.m_StatAdd=_T("-");
2156 path.m_StatDel=_T("-");
2158 else
2160 path.m_StatAdd.Format(_T("%d"),inc);
2161 path.m_StatDel.Format(_T("%d"),dec);
2163 PathList->AddPath(path);
2165 git_diff_flush(diff);
2167 if(arg)
2168 git_close_diff(diff);
2170 return 0;
2173 int CGit::GetShortHASHLength()
2175 return 7;
2178 CString CGit::GetShortName(CString ref, REF_TYPE *out_type)
2180 CString str=ref;
2181 CString shortname;
2182 REF_TYPE type = CGit::UNKNOWN;
2184 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2186 type = CGit::LOCAL_BRANCH;
2189 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2191 type = CGit::REMOTE_BRANCH;
2193 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2195 type = CGit::TAG;
2197 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2199 type = CGit::STASH;
2200 shortname=_T("stash");
2202 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2204 if (shortname.Find(_T("good")) == 0)
2206 type = CGit::BISECT_GOOD;
2207 shortname = _T("good");
2210 if (shortname.Find(_T("bad")) == 0)
2212 type = CGit::BISECT_BAD;
2213 shortname = _T("bad");
2216 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2218 type = CGit::NOTES;
2220 else
2222 type = CGit::UNKNOWN;
2223 shortname = _T("Unknown");
2226 if(out_type)
2227 *out_type = type;
2229 return shortname;
2232 BOOL CGit::UsingLibGit2(int cmd)
2234 if (cmd >= 0 && cmd < 32)
2235 return ((1 << cmd) & m_IsUseLibGit2_mask) ? FALSE : TRUE;
2236 return FALSE;