Directly use CString to avoid multiple type conversions in a row
[TortoiseGit.git] / src / Git / Git.cpp
blob46ebadb94f2d9311a48a954f28ee314ba092b716
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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 "GitRev.h"
23 #include "registry.h"
24 #include "GitConfig.h"
25 #include <map>
26 #include "UnicodeUtils.h"
27 #include "gitdll.h"
28 #include <fstream>
29 #include "FormatMessageWrapper.h"
31 int CGit::m_LogEncode=CP_UTF8;
32 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
34 static LPTSTR nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
36 wchar_t term, *base = path;
38 if (path == NULL || buf == NULL || buflen == 0)
39 return NULL;
41 term = (*path == L'"') ? *path++ : L';';
43 for (buflen--; *path && *path != term && buflen; buflen--)
44 *buf++ = *path++;
46 *buf = L'\0'; /* reserved a byte via initial subtract */
48 while (*path == term || *path == L';')
49 ++path;
51 return (path != base) ? path : NULL;
54 static inline BOOL FileExists(LPCTSTR lpszFileName)
56 struct _stat st;
57 return _tstat(lpszFileName, &st) == 0;
60 static BOOL FindGitPath()
62 size_t size;
63 _tgetenv_s(&size, NULL, 0, _T("PATH"));
65 if (!size)
67 return FALSE;
70 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
71 _tgetenv_s(&size, env, size, _T("PATH"));
73 TCHAR buf[MAX_PATH] = {0};
75 // search in all paths defined in PATH
76 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
78 TCHAR *pfin = buf + _tcslen(buf)-1;
80 // ensure trailing slash
81 if (*pfin != _T('/') && *pfin != _T('\\'))
82 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len = _tcslen(buf);
86 if ((len + 7) < MAX_PATH)
87 _tcscpy_s(pfin + 1, MAX_PATH - len, _T("git.exe"));
88 else
89 break;
91 if ( FileExists(buf) )
93 // dir found
94 pfin[1] = 0;
95 CGit::ms_LastMsysGitDir = buf;
96 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir))
103 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
105 return TRUE;
109 return FALSE;
112 static bool g_bSortLogical;
113 static bool g_bSortLocalBranchesFirst;
115 static void GetSortOptions()
117 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
118 if (g_bSortLogical)
119 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
120 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
121 if (g_bSortLocalBranchesFirst)
122 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
125 static int LogicalComparePredicate(const CString &left, const CString &right)
127 if (g_bSortLogical)
128 return StrCmpLogicalW(left, right) < 0;
129 return StrCmpI(left, right) < 0;
132 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
134 if (g_bSortLocalBranchesFirst)
136 int leftIsRemote = left.Find(_T("remotes/"));
137 int rightIsRemote = right.Find(_T("remotes/"));
139 if (leftIsRemote == 0 && rightIsRemote < 0)
140 return false;
141 else if (leftIsRemote < 0 && rightIsRemote == 0)
142 return true;
144 if (g_bSortLogical)
145 return StrCmpLogicalW(left, right) < 0;
146 return StrCmpI(left, right) < 0;
149 #define MAX_DIRBUFFER 1000
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString CGit::ms_LastMsysGitDir;
153 int CGit::ms_LastMsysGitVersion = 0;
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 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
170 GetSortOptions();
171 this->m_bInitialized =false;
172 CheckMsysGitDir();
173 m_critGitDllSec.Init();
176 CGit::~CGit(void)
178 if(this->m_GitDiff)
180 git_close_diff(m_GitDiff);
181 m_GitDiff=0;
183 if(this->m_GitSimpleListDiff)
185 git_close_diff(m_GitSimpleListDiff);
186 m_GitSimpleListDiff=0;
190 bool CGit::IsBranchNameValid(const CString& branchname)
192 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
193 return !!git_reference_is_valid_name(branchA);
196 static char g_Buffer[4096];
198 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
200 SECURITY_ATTRIBUTES sa;
201 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
202 HANDLE hStdioFile = NULL;
204 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
205 sa.lpSecurityDescriptor=NULL;
206 sa.bInheritHandle=TRUE;
207 if(!CreatePipe(&hRead,&hWrite,&sa,0))
209 CString err = CFormatMessageWrapper();
210 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
211 return TGIT_GIT_ERROR_OPEN_PIP;
213 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
215 CString err = CFormatMessageWrapper();
216 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
217 return TGIT_GIT_ERROR_OPEN_PIP;
220 if(StdioFile)
222 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
223 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
226 STARTUPINFO si;
227 PROCESS_INFORMATION pi;
228 si.cb=sizeof(STARTUPINFO);
229 GetStartupInfo(&si);
231 if (hErrReadOut)
232 si.hStdError = hWriteErr;
233 else
234 si.hStdError = hWrite;
235 if(StdioFile)
236 si.hStdOutput=hStdioFile;
237 else
238 si.hStdOutput=hWrite;
240 si.wShowWindow=SW_HIDE;
241 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
243 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
244 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
246 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
247 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
249 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
250 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
252 if(cmd.Find(_T("git")) == 0)
254 int firstSpace = cmd.Find(_T(" "));
255 if (firstSpace > 0)
256 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
257 else
258 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
261 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
262 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
264 CString err = CFormatMessageWrapper();
265 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
266 return TGIT_GIT_ERROR_CREATE_PROCESS;
269 m_CurrentGitPi = pi;
271 CloseHandle(hWrite);
272 if (hErrReadOut)
273 CloseHandle(hWriteErr);
274 if(piOut)
275 *piOut=pi;
276 if(hReadOut)
277 *hReadOut=hRead;
278 if(hErrReadOut)
279 *hErrReadOut = hReadErr;
280 return 0;
283 //Must use sperate function to convert ANSI str to union code string
284 //Becuase A2W use stack as internal convert buffer.
285 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
287 if(str == NULL)
288 return ;
290 int len ;
291 if(length<0)
292 len = (int)strlen((const char*)p);
293 else
294 len=length;
295 if (len == 0)
296 return;
297 int currentContentLen = str->GetLength();
298 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
299 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
300 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
303 // This method was originally used to check for orphaned branches
304 BOOL CGit::CanParseRev(CString ref)
306 if (ref.IsEmpty())
307 ref = _T("HEAD");
309 CString cmdout;
310 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
312 return FALSE;
314 if(cmdout.IsEmpty())
315 return FALSE;
317 return TRUE;
320 // Checks if we have an orphaned HEAD
321 BOOL CGit::IsInitRepos()
323 CGitHash hash;
324 // handle error on reading HEAD hash as init repo
325 if (GetHash(hash, _T("HEAD")) != 0)
326 return TRUE;
327 return hash.IsEmpty() ? TRUE : FALSE;
330 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
332 PASYNCREADSTDERRTHREADARGS pDataArray;
333 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
335 DWORD readnumber;
336 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
337 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
339 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
340 break;
343 return 0;
346 int CGit::Run(CGitCall* pcall)
348 PROCESS_INFORMATION pi;
349 HANDLE hRead, hReadErr;
350 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
351 return TGIT_GIT_ERROR_CREATE_PROCESS;
353 HANDLE thread;
354 ASYNCREADSTDERRTHREADARGS threadArguments;
355 threadArguments.fileHandle = hReadErr;
356 threadArguments.pcall = pcall;
357 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
359 DWORD readnumber;
360 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
361 bool bAborted=false;
362 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
364 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
365 if(!bAborted)//For now, flush output when command aborted.
366 if(pcall->OnOutputData(data,readnumber))
367 bAborted=true;
369 if(!bAborted)
370 pcall->OnEnd();
372 if (thread)
373 WaitForSingleObject(thread, INFINITE);
375 CloseHandle(pi.hThread);
377 WaitForSingleObject(pi.hProcess, INFINITE);
378 DWORD exitcode =0;
380 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
382 CString err = CFormatMessageWrapper();
383 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
384 return TGIT_GIT_ERROR_GET_EXIT_CODE;
386 else
387 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
389 CloseHandle(pi.hProcess);
391 CloseHandle(hRead);
392 CloseHandle(hReadErr);
393 return exitcode;
395 class CGitCall_ByteVector : public CGitCall
397 public:
398 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
399 virtual bool OnOutputData(const BYTE* data, size_t size)
401 if (!m_pvector || size == 0)
402 return false;
403 size_t oldsize=m_pvector->size();
404 m_pvector->resize(m_pvector->size()+size);
405 memcpy(&*(m_pvector->begin()+oldsize),data,size);
406 return false;
408 virtual bool OnOutputErrData(const BYTE* data, size_t size)
410 if (!m_pvectorErr || size == 0)
411 return false;
412 size_t oldsize = m_pvectorErr->size();
413 m_pvectorErr->resize(m_pvectorErr->size() + size);
414 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
415 return false;
417 BYTE_VECTOR* m_pvector;
418 BYTE_VECTOR* m_pvectorErr;
421 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
423 CGitCall_ByteVector call(cmd, vector, vectorErr);
424 return Run(&call);
426 int CGit::Run(CString cmd, CString* output, int code)
428 CString err;
429 int ret;
430 ret = Run(cmd, output, &err, code);
432 if (output && !err.IsEmpty())
434 if (!output->IsEmpty())
435 *output += _T("\n");
436 *output += err;
439 return ret;
441 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
443 BYTE_VECTOR vector, vectorErr;
444 int ret;
445 if (outputErr)
446 ret = Run(cmd, &vector, &vectorErr);
447 else
448 ret = Run(cmd, &vector);
450 vector.push_back(0);
451 StringAppend(output, &(vector[0]), code);
453 if (outputErr)
455 vectorErr.push_back(0);
456 StringAppend(outputErr, &(vectorErr[0]), code);
459 return ret;
462 CString CGit::GetUserName(void)
464 CEnvironment env;
465 env.CopyProcessEnvironment();
466 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
467 if (!envname.IsEmpty())
468 return envname;
469 return GetConfigValue(L"user.name");
471 CString CGit::GetUserEmail(void)
473 CEnvironment env;
474 env.CopyProcessEnvironment();
475 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
476 if (!envmail.IsEmpty())
477 return envmail;
479 return GetConfigValue(L"user.email");
482 CString CGit::GetConfigValue(const CString& name, int encoding, BOOL RemoveCR)
484 CString configValue;
485 int start = 0;
486 if(this->m_IsUseGitDLL)
488 CAutoLocker lock(g_Git.m_critGitDllSec);
492 CheckAndInitDll();
493 }catch(...)
496 CStringA key, value;
497 key = CUnicodeUtils::GetMulti(name, encoding);
501 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
502 return CString();
504 catch (const char *msg)
506 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
507 return CString();
510 StringAppend(&configValue, (BYTE*)(LPCSTR)value, encoding);
511 if(RemoveCR)
512 return configValue.Tokenize(_T("\n"),start);
513 return configValue;
515 else
517 CString cmd;
518 cmd.Format(L"git.exe config %s", name);
519 Run(cmd, &configValue, NULL, encoding);
520 if(RemoveCR)
521 return configValue.Tokenize(_T("\n"),start);
522 return configValue;
526 bool CGit::GetConfigValueBool(const CString& name)
528 CString configValue = GetConfigValue(name);
529 configValue.MakeLower();
530 configValue.Trim();
531 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
532 return true;
533 else
534 return false;
537 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type, int encoding)
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);
556 return get_set_config(keya, valuea, type);
558 catch (const char *msg)
560 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
561 return -1;
564 else
566 CString cmd;
567 CString option;
568 switch(type)
570 case CONFIG_GLOBAL:
571 option = _T("--global");
572 break;
573 case CONFIG_SYSTEM:
574 option = _T("--system");
575 break;
576 default:
577 break;
579 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
580 CString out;
581 if (Run(cmd, &out, NULL, encoding))
583 return -1;
586 return 0;
589 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type, int encoding)
591 if(this->m_IsUseGitDLL)
593 CAutoLocker lock(g_Git.m_critGitDllSec);
597 CheckAndInitDll();
598 }catch(...)
601 CStringA keya;
602 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
606 return get_set_config(keya, nullptr, type);
608 catch (const char *msg)
610 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
611 return -1;
614 else
616 CString cmd;
617 CString option;
618 switch(type)
620 case CONFIG_GLOBAL:
621 option = _T("--global");
622 break;
623 case CONFIG_SYSTEM:
624 option = _T("--system");
625 break;
626 default:
627 break;
629 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
630 CString out;
631 if (Run(cmd, &out, NULL, encoding))
633 return -1;
636 return 0;
639 CString CGit::GetCurrentBranch(bool fallback)
641 CString output;
642 //Run(_T("git.exe branch"),&branch);
644 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
645 if (result != 0 && ((result == 1 && !fallback) || result != 1))
647 return _T("(no branch)");
649 else
650 return output;
654 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
656 CString refName;
657 if(this->m_IsUseGitDLL)
659 unsigned char sha1[20] = { 0 };
660 int flag = 0;
662 CAutoLocker lock(g_Git.m_critGitDllSec);
663 const char *refs_heads_master = nullptr;
666 refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
668 catch (const char *err)
670 ::MessageBox(NULL, _T("Could not resolve ref ") + CString(symbolicRefName) + _T(".\nlibgit reports:\n") + CString(err), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
672 if(refs_heads_master && (flag&REF_ISSYMREF))
674 StringAppend(&refName,(BYTE*)refs_heads_master);
675 if(bStripRefsHeads)
676 refName = StripRefName(refName);
680 else
682 CString cmd;
683 cmd.Format(L"git.exe symbolic-ref %s", symbolicRefName);
684 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
685 return CString();//Error
686 int iStart = 0;
687 refName = refName.Tokenize(L"\n", iStart);
688 if(bStripRefsHeads)
689 refName = StripRefName(refName);
691 return refName;
694 CString CGit::GetFullRefName(const CString& shortRefName)
696 CString refName;
697 CString cmd;
698 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
699 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
700 return CString();//Error
701 int iStart = 0;
702 return refName.Tokenize(L"\n", iStart);
705 CString CGit::StripRefName(CString refName)
707 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
708 refName = refName.Mid(11);
709 else if(wcsncmp(refName, L"refs/", 5) == 0)
710 refName = refName.Mid(5);
711 int start =0;
712 return refName.Tokenize(_T("\n"),start);
715 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
717 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
719 if ( sProjectRoot.IsEmpty() )
720 return -1;
722 CString sDotGitPath;
723 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
724 return -1;
726 CString sHeadFile = sDotGitPath + _T("HEAD");
728 FILE *pFile;
729 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
731 if (!pFile)
733 return -1;
736 char s[256] = {0};
737 fgets(s, sizeof(s), pFile);
739 fclose(pFile);
741 const char *pfx = "ref: refs/heads/";
742 const int len = 16;//strlen(pfx)
744 if ( !strncmp(s, pfx, len) )
746 //# We're on a branch. It might not exist. But
747 //# HEAD looks good enough to be a branch.
748 CStringA utf8Branch(s + len);
749 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
750 sBranchOut.TrimRight(_T(" \r\n\t"));
752 if ( sBranchOut.IsEmpty() )
753 return -1;
755 else if (fallback)
757 CStringA utf8Hash(s);
758 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
759 unicodeHash.TrimRight(_T(" \r\n\t"));
760 if (CGitHash::IsValidSHA1(unicodeHash))
761 sBranchOut = unicodeHash;
762 else
763 //# Assume this is a detached head.
764 sBranchOut = _T("HEAD");
765 return 1;
767 else
769 //# Assume this is a detached head.
770 sBranchOut = "HEAD";
772 return 1;
775 return 0;
778 int CGit::BuildOutputFormat(CString &format,bool IsFull)
780 CString log;
781 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
782 format += log;
783 if(IsFull)
785 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
786 format += log;
787 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
788 format += log;
789 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
790 format += log;
791 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
792 format += log;
793 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
794 format += log;
795 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
796 format += log;
797 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
798 format += log;
801 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
802 format += log;
803 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
804 format += log;
805 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
806 format += log;
808 if(IsFull)
810 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
811 format += log;
813 return 0;
816 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
817 CFilterData *Filter)
819 CString cmd;
820 CString num;
821 CString since;
823 CString file = _T(" --");
825 if(path)
826 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
828 if(count>0)
829 num.Format(_T("-n%d"),count);
831 CString param;
833 if(mask& LOG_INFO_STAT )
834 param += _T(" --numstat ");
835 if(mask& LOG_INFO_FILESTATE)
836 param += _T(" --raw ");
838 if(mask& LOG_INFO_FULLHISTORY)
839 param += _T(" --full-history ");
841 if(mask& LOG_INFO_BOUNDARY)
842 param += _T(" --left-right --boundary ");
844 if(mask& CGit::LOG_INFO_ALL_BRANCH)
845 param += _T(" --all ");
847 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
848 param += _T(" --branches ");
850 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
851 param += _T(" -C ");
853 if(mask& CGit::LOG_INFO_DETECT_RENAME )
854 param += _T(" -M ");
856 if(mask& CGit::LOG_INFO_FIRST_PARENT )
857 param += _T(" --first-parent ");
859 if(mask& CGit::LOG_INFO_NO_MERGE )
860 param += _T(" --no-merges ");
862 if(mask& CGit::LOG_INFO_FOLLOW)
863 param += _T(" --follow ");
865 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
866 param += _T(" -c ");
868 if(mask& CGit::LOG_INFO_FULL_DIFF)
869 param += _T(" --full-diff ");
871 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
872 param += _T(" --simplify-by-decoration ");
874 param += range;
876 CString st1,st2;
878 if( Filter && (Filter->m_From != -1))
880 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
881 param += st1;
884 if( Filter && (Filter->m_To != -1))
886 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
887 param += st2;
890 bool isgrep = false;
891 if( Filter && (!Filter->m_Author.IsEmpty()))
893 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
894 param += st1;
895 isgrep = true;
898 if( Filter && (!Filter->m_Committer.IsEmpty()))
900 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
901 param += st1;
902 isgrep = true;
905 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
907 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
908 param += st1;
909 isgrep = true;
912 if(Filter && isgrep)
914 if(!Filter->m_IsRegex)
915 param += _T(" --fixed-strings ");
917 param += _T(" --regexp-ignore-case --extended-regexp ");
920 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
921 if (logOrderBy == LOG_ORDER_TOPOORDER)
922 param += _T(" --topo-order");
923 else if (logOrderBy == LOG_ORDER_DATEORDER)
924 param += _T(" --date-order");
926 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
927 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
928 else
930 CString log;
931 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
932 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
933 num,param,log);
936 cmd += file;
938 return cmd;
940 #define BUFSIZE 512
941 void GetTempPath(CString &path)
943 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
944 DWORD dwRetVal;
945 DWORD dwBufSize=BUFSIZE;
946 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
947 lpPathBuffer); // buffer for path
948 if (dwRetVal > dwBufSize || (dwRetVal == 0))
950 path=_T("");
952 path.Format(_T("%s"),lpPathBuffer);
954 CString GetTempFile()
956 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
957 DWORD dwRetVal;
958 DWORD dwBufSize=BUFSIZE;
959 TCHAR szTempName[BUFSIZE] = { 0 };
960 UINT uRetVal;
962 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
963 lpPathBuffer); // buffer for path
964 if (dwRetVal > dwBufSize || (dwRetVal == 0))
966 return _T("");
968 // Create a temporary file.
969 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
970 TEXT("Patch"), // temp file name prefix
971 0, // create unique name
972 szTempName); // buffer for name
975 if (uRetVal == 0)
977 return _T("");
980 return CString(szTempName);
984 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
986 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
987 if (result == 0) return 0;
988 if (lpBuffer == NULL || (result + 13 > nBufferLength))
990 if (lpBuffer)
991 lpBuffer[0] = '\0';
992 return result + 13;
995 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
996 CreateDirectory(lpBuffer, NULL);
998 return result + 13;
1001 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1003 STARTUPINFO si;
1004 PROCESS_INFORMATION pi;
1005 si.cb=sizeof(STARTUPINFO);
1006 GetStartupInfo(&si);
1008 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1009 psa.bInheritHandle=TRUE;
1011 HANDLE hReadErr, hWriteErr;
1012 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1014 CString err = CFormatMessageWrapper();
1015 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1016 return TGIT_GIT_ERROR_OPEN_PIP;
1019 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1020 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1022 if (houtfile == INVALID_HANDLE_VALUE)
1024 CString err = CFormatMessageWrapper();
1025 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1026 return TGIT_GIT_ERROR_OPEN_PIP;
1029 si.wShowWindow = SW_HIDE;
1030 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1031 si.hStdOutput = houtfile;
1032 si.hStdError = hWriteErr;
1034 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1035 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1037 if(cmd.Find(_T("git")) == 0)
1038 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1040 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1041 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1043 CString err = CFormatMessageWrapper();
1044 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1045 stdErr = &err;
1046 return TGIT_GIT_ERROR_CREATE_PROCESS;
1049 BYTE_VECTOR stderrVector;
1050 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1051 HANDLE thread;
1052 ASYNCREADSTDERRTHREADARGS threadArguments;
1053 threadArguments.fileHandle = hReadErr;
1054 threadArguments.pcall = &pcall;
1055 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1057 WaitForSingleObject(pi.hProcess,INFINITE);
1059 CloseHandle(hWriteErr);
1060 CloseHandle(hReadErr);
1062 if (thread)
1063 WaitForSingleObject(thread, INFINITE);
1065 stderrVector.push_back(0);
1066 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1068 DWORD exitcode = 0;
1069 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1071 CString err = CFormatMessageWrapper();
1072 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1073 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1075 else
1076 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1078 CloseHandle(pi.hThread);
1079 CloseHandle(pi.hProcess);
1080 CloseHandle(houtfile);
1081 return exitcode;
1084 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1086 // no need to parse a ref if it's already a 40-byte hash
1087 if (CGitHash::IsValidSHA1(friendname))
1089 CString sHash(friendname);
1090 hash = CGitHash(sHash);
1091 return 0;
1094 if (m_IsUseLibGit2)
1096 git_repository *repo = NULL;
1097 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1098 if (git_repository_open(&repo, gitdirA))
1099 return -1;
1101 int isHeadOrphan = git_repository_head_unborn(repo);
1102 if (isHeadOrphan != 0)
1104 git_repository_free(repo);
1105 hash.Empty();
1106 if (isHeadOrphan == 1)
1107 return 0;
1108 else
1109 return -1;
1112 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1114 git_object * gitObject = NULL;
1115 if (git_revparse_single(&gitObject, repo, refnameA))
1117 git_repository_free(repo);
1118 return -1;
1121 const git_oid * oid = git_object_id(gitObject);
1122 if (oid == NULL)
1124 git_object_free(gitObject);
1125 git_repository_free(repo);
1126 return -1;
1129 hash = CGitHash((char *)oid->id);
1131 git_object_free(gitObject); // also frees oid
1132 git_repository_free(repo);
1134 return 0;
1136 else
1138 CString cmd;
1139 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1140 gitLastErr.Empty();
1141 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1142 hash = CGitHash(gitLastErr.Trim());
1143 if (ret == 0)
1144 gitLastErr.Empty();
1145 return ret;
1149 int CGit::GetInitAddList(CTGitPathList &outputlist)
1151 CString cmd;
1152 BYTE_VECTOR cmdout;
1154 cmd=_T("git.exe ls-files -s -t -z");
1155 outputlist.Clear();
1156 if (Run(cmd, &cmdout))
1157 return -1;
1159 if (outputlist.ParserFromLsFile(cmdout))
1160 return -1;
1161 for(int i = 0; i < outputlist.GetCount(); ++i)
1162 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1164 return 0;
1166 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1168 CString cmd;
1170 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1172 //rev1=+_T("");
1173 if(rev1 == GIT_REV_ZERO)
1174 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s --"), rev2);
1175 else
1176 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), rev1);
1178 else
1180 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s --"), rev2, rev1);
1183 BYTE_VECTOR out;
1184 if (Run(cmd, &out))
1185 return -1;
1187 outputlist.ParserFromLog(out);
1189 return 0;
1192 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1194 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1195 CString str;
1196 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1197 list->push_back(str);
1198 return 0;
1201 int CGit::GetTagList(STRING_VECTOR &list)
1203 if (this->m_IsUseLibGit2)
1205 git_repository *repo = NULL;
1207 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1208 if (git_repository_open(&repo, gitdir))
1209 return -1;
1211 git_strarray tag_names;
1213 if (git_tag_list(&tag_names, repo))
1215 git_repository_free(repo);
1216 return -1;
1219 for (size_t i = 0; i < tag_names.count; ++i)
1221 CStringA tagName(tag_names.strings[i]);
1222 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1225 git_strarray_free(&tag_names);
1227 git_repository_free(repo);
1229 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1231 return 0;
1233 else
1235 CString cmd, output;
1236 cmd=_T("git.exe tag -l");
1237 int ret = Run(cmd, &output, NULL, CP_UTF8);
1238 if(!ret)
1240 int pos=0;
1241 CString one;
1242 while( pos>=0 )
1244 one=output.Tokenize(_T("\n"),pos);
1245 if (!one.IsEmpty())
1246 list.push_back(one);
1248 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1250 return ret;
1255 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1256 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1258 CString CGit::GetGitLastErr(const CString& msg)
1260 if (this->m_IsUseLibGit2)
1261 return GetLibGit2LastErr(msg);
1262 else if (gitLastErr.IsEmpty())
1263 return msg + _T("\nUnknown git.exe error.");
1264 else
1266 CString lastError = gitLastErr;
1267 gitLastErr.Empty();
1268 return msg + _T("\n") + lastError;
1272 CString CGit::GetGitLastErr(const CString& msg, int cmd)
1274 if (UsingLibGit2(cmd))
1275 return GetLibGit2LastErr(msg);
1276 else if (gitLastErr.IsEmpty())
1277 return msg + _T("\nUnknown git.exe error.");
1278 else
1280 CString lastError = gitLastErr;
1281 gitLastErr.Empty();
1282 return msg + _T("\n") + lastError;
1286 CString CGit::GetLibGit2LastErr()
1288 const git_error *libgit2err = giterr_last();
1289 if (libgit2err)
1291 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1292 giterr_clear();
1293 return _T("libgit2 returned: ") + lastError;
1295 else
1296 return _T("An error occoured in libgit2, but no message is available.");
1299 CString CGit::GetLibGit2LastErr(const CString& msg)
1301 if (!msg.IsEmpty())
1302 return msg + _T("\n") + GetLibGit2LastErr();
1303 return GetLibGit2LastErr();
1306 CString CGit::FixBranchName_Mod(CString& branchName)
1308 if(branchName == "FETCH_HEAD")
1309 branchName = DerefFetchHead();
1310 return branchName;
1313 CString CGit::FixBranchName(const CString& branchName)
1315 CString tempBranchName = branchName;
1316 FixBranchName_Mod(tempBranchName);
1317 return tempBranchName;
1320 bool CGit::IsBranchTagNameUnique(const CString& name)
1322 CString output;
1324 CString cmd;
1325 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1326 int ret = Run(cmd, &output, NULL, CP_UTF8);
1327 if (!ret)
1329 int i = 0, pos = 0;
1330 while (pos >= 0)
1332 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1333 ++i;
1335 if (i >= 2)
1336 return false;
1339 return true;
1343 Checks if a branch or tag with the given name exists
1344 isBranch is true -> branch, tag otherwise
1346 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1348 CString cmd, output;
1350 cmd = _T("git.exe show-ref ");
1351 if (isBranch)
1352 cmd += _T("--heads ");
1353 else
1354 cmd += _T("--tags ");
1356 cmd += _T("refs/heads/") + name;
1357 cmd += _T(" refs/tags/") + name;
1359 int ret = Run(cmd, &output, NULL, CP_UTF8);
1360 if (!ret)
1362 if (!output.IsEmpty())
1363 return true;
1366 return false;
1369 CString CGit::DerefFetchHead()
1371 CString dotGitPath;
1372 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1373 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1374 int forMergeLineCount = 0;
1375 std::string line;
1376 std::string hashToReturn;
1377 while(getline(fetchHeadFile, line))
1379 //Tokenize this line
1380 std::string::size_type prevPos = 0;
1381 std::string::size_type pos = line.find('\t');
1382 if(pos == std::string::npos) continue; //invalid line
1384 std::string hash = line.substr(0, pos);
1385 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1387 bool forMerge = pos == prevPos;
1388 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1390 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1392 //Process this line
1393 if(forMerge)
1395 hashToReturn = hash;
1396 ++forMergeLineCount;
1397 if(forMergeLineCount > 1)
1398 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1402 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1405 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1407 int ret;
1408 CString cmd, output, cur;
1409 cmd = _T("git.exe branch --no-color");
1411 if((type&BRANCH_ALL) == BRANCH_ALL)
1412 cmd += _T(" -a");
1413 else if(type&BRANCH_REMOTE)
1414 cmd += _T(" -r");
1416 ret = Run(cmd, &output, NULL, CP_UTF8);
1417 if(!ret)
1419 int pos=0;
1420 CString one;
1421 while( pos>=0 )
1423 one=output.Tokenize(_T("\n"),pos);
1424 one.Trim(L" \r\n\t");
1425 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1426 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1427 if(one[0] == _T('*'))
1429 one = one.Mid(2);
1430 cur = one;
1432 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1433 list.push_back(one);
1437 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1438 list.push_back(L"FETCH_HEAD");
1440 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1442 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1444 for (unsigned int i = 0; i < list.size(); ++i)
1446 if (list[i] == cur)
1448 *current = i;
1449 break;
1454 return ret;
1457 int CGit::GetRemoteList(STRING_VECTOR &list)
1459 if (this->m_IsUseLibGit2)
1461 git_repository *repo = NULL;
1463 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1464 if (git_repository_open(&repo, gitdir))
1465 return -1;
1467 git_strarray remotes;
1469 if (git_remote_list(&remotes, repo))
1471 git_repository_free(repo);
1472 return -1;
1475 for (size_t i = 0; i < remotes.count; ++i)
1477 CStringA remote(remotes.strings[i]);
1478 list.push_back(CUnicodeUtils::GetUnicode(remote));
1481 git_strarray_free(&remotes);
1483 git_repository_free(repo);
1485 std::sort(list.begin(), list.end());
1487 return 0;
1489 else
1491 int ret;
1492 CString cmd, output;
1493 cmd=_T("git.exe remote");
1494 ret = Run(cmd, &output, NULL, CP_UTF8);
1495 if(!ret)
1497 int pos=0;
1498 CString one;
1499 while( pos>=0 )
1501 one=output.Tokenize(_T("\n"),pos);
1502 if (!one.IsEmpty())
1503 list.push_back(one);
1506 return ret;
1510 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR &list)
1512 CString cmd, out, err;
1513 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1514 if (Run(cmd, &out, &err, CP_UTF8))
1516 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1517 return -1;
1520 int pos = 0;
1521 while (pos >= 0)
1523 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1524 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1525 if (one.Find(_T("^{}")) >= 1)
1526 continue;
1527 if (!one.IsEmpty())
1528 list.push_back(one);
1530 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1531 return 0;
1534 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1536 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1537 CString str;
1538 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1539 list->push_back(str);
1540 return 0;
1543 int CGit::GetRefList(STRING_VECTOR &list)
1545 if (this->m_IsUseLibGit2)
1547 git_repository *repo = NULL;
1549 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1550 if (git_repository_open(&repo, gitdir))
1551 return -1;
1553 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1555 git_repository_free(repo);
1556 return -1;
1559 git_repository_free(repo);
1561 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1563 return 0;
1565 else
1567 CString cmd, output;
1568 cmd=_T("git.exe show-ref -d");
1569 int ret = Run(cmd, &output, NULL, CP_UTF8);
1570 if(!ret)
1572 int pos=0;
1573 CString one;
1574 while( pos>=0 )
1576 one=output.Tokenize(_T("\n"),pos);
1577 int start=one.Find(_T(" "),0);
1578 if(start>0)
1580 CString name;
1581 name=one.Right(one.GetLength()-start-1);
1582 list.push_back(name);
1585 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1587 return ret;
1591 typedef struct map_each_ref_payload {
1592 git_repository * repo;
1593 MAP_HASH_NAME * map;
1594 } map_each_ref_payload;
1596 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1598 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1600 CString str;
1601 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1603 git_object * gitObject = NULL;
1607 if (git_revparse_single(&gitObject, payloadContent->repo, git_reference_name(ref)))
1609 break;
1612 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1614 str += _T("^{}"); // deref tag
1615 git_object * derefedTag = NULL;
1616 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1618 break;
1620 git_object_free(gitObject);
1621 gitObject = derefedTag;
1624 const git_oid * oid = git_object_id(gitObject);
1625 if (oid == NULL)
1627 break;
1630 CGitHash hash((char *)oid->id);
1631 (*payloadContent->map)[hash].push_back(str);
1632 } while (false);
1634 if (gitObject)
1636 git_object_free(gitObject);
1637 return 0;
1640 return 1;
1643 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1645 if (this->m_IsUseLibGit2)
1647 git_repository *repo = NULL;
1649 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1650 if (git_repository_open(&repo, gitdir))
1651 return -1;
1653 map_each_ref_payload payloadContent = { repo, &map };
1655 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1657 git_repository_free(repo);
1658 return -1;
1661 git_repository_free(repo);
1663 for (auto it = map.begin(); it != map.end(); ++it)
1665 std::sort(it->second.begin(), it->second.end());
1668 return 0;
1670 else
1672 CString cmd, output;
1673 cmd=_T("git.exe show-ref -d");
1674 int ret = Run(cmd, &output, NULL, CP_UTF8);
1675 if(!ret)
1677 int pos=0;
1678 CString one;
1679 while( pos>=0 )
1681 one=output.Tokenize(_T("\n"),pos);
1682 int start=one.Find(_T(" "),0);
1683 if(start>0)
1685 CString name;
1686 name=one.Right(one.GetLength()-start-1);
1688 CString hash;
1689 hash=one.Left(start);
1691 map[CGitHash(hash)].push_back(name);
1695 return ret;
1699 static void SetLibGit2SearchPath(int level, const CString &value)
1701 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1702 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1705 static void SetLibGit2TemplatePath(const CString &value)
1707 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1708 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1711 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1713 if (m_bInitialized)
1715 return TRUE;
1718 this->m_Environment.clear();
1719 m_Environment.CopyProcessEnvironment();
1721 TCHAR *oldpath;
1722 size_t homesize,size;
1724 // set HOME if not set already
1725 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1726 if (!homesize)
1728 CString home = GetHomeDirectory();
1729 m_Environment.SetEnv(_T("HOME"), home);
1731 CString str;
1733 //setup ssh client
1734 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1735 if (sshclient.IsEmpty())
1736 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1738 if(!sshclient.IsEmpty())
1740 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1741 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1743 else
1745 TCHAR sPlink[MAX_PATH] = {0};
1746 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1747 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1748 if (ptr) {
1749 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1750 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1751 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1756 TCHAR sAskPass[MAX_PATH] = {0};
1757 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1758 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1759 if (ptr)
1761 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1762 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1763 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1764 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1768 // add git/bin path to PATH
1770 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1771 str=msysdir;
1772 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1774 if (!bFallback)
1775 return FALSE;
1777 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1778 str = msyslocalinstalldir;
1779 str.TrimRight(_T("\\"));
1780 if (str.IsEmpty())
1782 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1783 str = msysinstalldir;
1784 str.TrimRight(_T("\\"));
1786 if ( !str.IsEmpty() )
1788 str += "\\bin";
1789 msysdir=str;
1790 CGit::ms_LastMsysGitDir = str;
1791 msysdir.write();
1793 else
1795 // search PATH if git/bin directory is already present
1796 if ( FindGitPath() )
1798 m_bInitialized = TRUE;
1799 msysdir = CGit::ms_LastMsysGitDir;
1800 msysdir.write();
1801 return TRUE;
1804 return FALSE;
1807 else
1809 CGit::ms_LastMsysGitDir = str;
1812 // check for git.exe existance (maybe it was deinstalled in the meantime)
1813 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1814 return FALSE;
1816 // Configure libgit2 search paths
1817 CString msysGitDir;
1818 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
1819 msysGitDir.ReleaseBuffer();
1820 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
1821 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
1822 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
1823 CString msysGitTemplateDir;
1824 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
1825 msysGitTemplateDir.ReleaseBuffer();
1826 SetLibGit2TemplatePath(msysGitTemplateDir);
1828 //set path
1829 _tdupenv_s(&oldpath,&size,_T("PATH"));
1831 CString path;
1832 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1834 m_Environment.SetEnv(_T("PATH"), path);
1836 CString str1 = m_Environment.GetEnv(_T("PATH"));
1838 CString sOldPath = oldpath;
1839 free(oldpath);
1841 m_bInitialized = TRUE;
1842 return true;
1845 CString CGit::GetHomeDirectory()
1847 const wchar_t * homeDir = wget_windows_home_directory();
1848 return CString(homeDir, (int)wcslen(homeDir));
1851 CString CGit::GetGitLocalConfig()
1853 CString path;
1854 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
1855 path += _T("config");
1856 return path;
1859 CStringA CGit::GetGitPathStringA(const CString &path)
1861 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
1864 CString CGit::GetGitGlobalConfig()
1866 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1869 CString CGit::GetGitGlobalXDGConfigPath()
1871 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1874 CString CGit::GetGitGlobalXDGConfig()
1876 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1879 CString CGit::GetGitSystemConfig()
1881 const wchar_t * systemConfig = wget_msysgit_etc();
1882 return CString(systemConfig, (int)wcslen(systemConfig));
1885 BOOL CGit::CheckCleanWorkTree()
1887 CString out;
1888 CString cmd;
1889 cmd=_T("git.exe rev-parse --verify HEAD");
1891 if(Run(cmd,&out,CP_UTF8))
1892 return FALSE;
1894 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1895 if(Run(cmd,&out,CP_UTF8))
1896 return FALSE;
1898 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1899 if(Run(cmd,&out,CP_UTF8))
1900 return FALSE;
1902 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1903 if(Run(cmd,&out,CP_UTF8))
1904 return FALSE;
1906 return TRUE;
1908 int CGit::Revert(const CString& commit, const CTGitPathList &list, bool)
1910 int ret;
1911 for (int i = 0; i < list.GetCount(); ++i)
1913 ret = Revert(commit, (CTGitPath&)list[i]);
1914 if(ret)
1915 return ret;
1917 return 0;
1919 int CGit::Revert(const CString& commit, const CTGitPath &path)
1921 CString cmd, out;
1923 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1925 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1927 CString err;
1928 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1929 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1930 return -1;
1932 CString force;
1933 // if the filenames only differ in case, we have to pass "-f"
1934 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1935 force = _T("-f ");
1936 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1937 if (Run(cmd, &out, CP_UTF8))
1939 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1940 return -1;
1943 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1944 if (Run(cmd, &out, CP_UTF8))
1946 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1947 return -1;
1951 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1952 { //To init git repository, there are not HEAD, so we can use git reset command
1953 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1955 if (Run(cmd, &out, CP_UTF8))
1957 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1958 return -1;
1961 else
1963 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1964 if (Run(cmd, &out, CP_UTF8))
1966 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1967 return -1;
1971 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1973 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1974 if (Run(cmd, &out, CP_UTF8))
1976 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1977 return -1;
1981 return 0;
1984 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
1986 BYTE_VECTOR vector;
1988 CString cmd;
1989 if(path)
1990 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1991 else
1992 cmd=_T("git.exe ls-files -u -t -z");
1994 if (Run(cmd, &vector))
1996 return -1;
1999 if (list.ParserFromLsFile(vector))
2000 return -1;
2002 return 0;
2005 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2007 CString base;
2008 CGitHash basehash,hash;
2009 CString cmd, err;
2010 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2012 if (Run(cmd, &base, &err, CP_UTF8))
2014 return false;
2016 basehash = base.Trim();
2018 GetHash(hash, from);
2020 if (commonAncestor)
2021 *commonAncestor = basehash;
2023 return hash == basehash;
2026 unsigned int CGit::Hash2int(const CGitHash &hash)
2028 int ret=0;
2029 for (int i = 0; i < 4; ++i)
2031 ret = ret << 8;
2032 ret |= hash.m_hash[i];
2034 return ret;
2037 int CGit::RefreshGitIndex()
2039 if(g_Git.m_IsUseGitDLL)
2041 CAutoLocker lock(g_Git.m_critGitDllSec);
2044 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2046 }catch(...)
2048 return -1;
2052 else
2054 CString cmd,output;
2055 cmd=_T("git.exe update-index --refresh");
2056 return Run(cmd, &output, CP_UTF8);
2060 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2062 if(g_Git.m_IsUseGitDLL)
2064 CAutoLocker lock(g_Git.m_critGitDllSec);
2067 g_Git.CheckAndInitDll();
2068 CStringA ref, patha, outa;
2069 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2070 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2071 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2072 ::DeleteFile(outputfile);
2073 return git_checkout_file(ref, patha, outa);
2075 }catch(...)
2077 return -1;
2080 else
2082 CString cmd;
2083 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2084 return RunLogFile(cmd, outputfile, &gitLastErr);
2087 void CEnvironment::CopyProcessEnvironment()
2089 TCHAR *porig = GetEnvironmentStrings();
2090 TCHAR *p = porig;
2091 while(*p !=0 || *(p+1) !=0)
2092 this->push_back(*p++);
2094 push_back(_T('\0'));
2095 push_back(_T('\0'));
2097 FreeEnvironmentStrings(porig);
2100 CString CEnvironment::GetEnv(const TCHAR *name)
2102 CString str;
2103 for (size_t i = 0; i < size(); ++i)
2105 str = &(*this)[i];
2106 int start =0;
2107 CString sname = str.Tokenize(_T("="),start);
2108 if(sname.CompareNoCase(name) == 0)
2110 return &(*this)[i+start];
2112 i+=str.GetLength();
2114 return _T("");
2117 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2119 unsigned int i;
2120 for (i = 0; i < size(); ++i)
2122 CString str = &(*this)[i];
2123 int start =0;
2124 CString sname = str.Tokenize(_T("="),start);
2125 if(sname.CompareNoCase(name) == 0)
2127 break;
2129 i+=str.GetLength();
2132 if(i == size())
2134 i -= 1; // roll back terminate \0\0
2135 this->push_back(_T('\0'));
2138 CEnvironment::iterator it;
2139 it=this->begin();
2140 it += i;
2142 while(*it && i<size())
2144 this->erase(it);
2145 it=this->begin();
2146 it += i;
2149 while(*name)
2151 this->insert(it,*name++);
2152 ++i;
2153 it= begin()+i;
2156 this->insert(it, _T('='));
2157 ++i;
2158 it= begin()+i;
2160 while(*value)
2162 this->insert(it,*value++);
2163 ++i;
2164 it= begin()+i;
2169 int CGit::GetGitEncode(TCHAR* configkey)
2171 CString str=GetConfigValue(configkey);
2173 if(str.IsEmpty())
2174 return CP_UTF8;
2176 return CUnicodeUtils::GetCPCode(str);
2180 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2182 GIT_FILE file=0;
2183 int ret=0;
2184 GIT_DIFF diff=0;
2186 CAutoLocker lock(g_Git.m_critGitDllSec);
2188 if(arg == NULL)
2189 diff = GetGitDiff();
2190 else
2191 git_open_diff(&diff, arg);
2193 if(diff ==NULL)
2194 return -1;
2196 bool isStat = 0;
2197 if(arg == NULL)
2198 isStat = true;
2199 else
2200 isStat = !!strstr(arg, "stat");
2202 int count=0;
2204 if(hash2 == NULL)
2205 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2206 else
2207 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2209 if(ret)
2210 return -1;
2212 CTGitPath path;
2213 CString strnewname;
2214 CString stroldname;
2216 for (int j = 0; j < count; ++j)
2218 path.Reset();
2219 char *newname;
2220 char *oldname;
2222 strnewname.Empty();
2223 stroldname.Empty();
2225 int mode=0,IsBin=0,inc=0,dec=0;
2226 git_get_diff_file(diff,file,j,&newname,&oldname,
2227 &mode,&IsBin,&inc,&dec);
2229 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2230 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2232 path.SetFromGit(strnewname,&stroldname);
2233 path.ParserAction((BYTE)mode);
2235 if(IsBin)
2237 path.m_StatAdd=_T("-");
2238 path.m_StatDel=_T("-");
2240 else
2242 path.m_StatAdd.Format(_T("%d"),inc);
2243 path.m_StatDel.Format(_T("%d"),dec);
2245 PathList->AddPath(path);
2247 git_diff_flush(diff);
2249 if(arg)
2250 git_close_diff(diff);
2252 return 0;
2255 int CGit::GetShortHASHLength()
2257 return 7;
2260 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2262 CString str=ref;
2263 CString shortname;
2264 REF_TYPE type = CGit::UNKNOWN;
2266 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2268 type = CGit::LOCAL_BRANCH;
2271 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2273 type = CGit::REMOTE_BRANCH;
2275 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2277 type = CGit::TAG;
2279 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2281 type = CGit::STASH;
2282 shortname=_T("stash");
2284 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2286 if (shortname.Find(_T("good")) == 0)
2288 type = CGit::BISECT_GOOD;
2289 shortname = _T("good");
2292 if (shortname.Find(_T("bad")) == 0)
2294 type = CGit::BISECT_BAD;
2295 shortname = _T("bad");
2298 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2300 type = CGit::NOTES;
2302 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2304 type = CGit::UNKNOWN;
2306 else
2308 type = CGit::UNKNOWN;
2309 shortname = ref;
2312 if(out_type)
2313 *out_type = type;
2315 return shortname;
2318 bool CGit::UsingLibGit2(int cmd)
2320 if (cmd >= 0 && cmd < 32)
2321 return ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2322 return false;
2325 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2327 CString cmd;
2328 if (rev2 == GitRev::GetWorkingCopy())
2329 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2330 else if (rev1 == GitRev::GetWorkingCopy())
2331 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2332 else
2334 CString merge;
2335 if (bMerge)
2336 merge += _T(" -m");
2338 if (bCombine)
2339 merge += _T(" -c");
2341 CString unified;
2342 if (diffContext > 0)
2343 unified.Format(_T(" --unified=%d"), diffContext);
2344 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2347 if (!path.IsEmpty())
2349 cmd += _T(" \"");
2350 cmd += path.GetGitPathString();
2351 cmd += _T("\"");
2354 return cmd;
2357 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2359 ATLASSERT(payload && line);
2360 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2361 fwrite(&line->origin, 1, 1, (FILE *)payload);
2362 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2363 return 0;
2366 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2368 ATLASSERT(repo && identifier && tree);
2370 /* try to resolve identifier */
2371 git_object *obj = nullptr;
2372 if (git_revparse_single(&obj, repo, identifier))
2373 return -1;
2375 if (obj == nullptr)
2376 return GIT_ENOTFOUND;
2378 int err = 0;
2379 switch (git_object_type(obj))
2381 case GIT_OBJ_TREE:
2382 *tree = (git_tree *)obj;
2383 break;
2384 case GIT_OBJ_COMMIT:
2385 err = git_commit_tree(tree, (git_commit *)obj);
2386 git_object_free(obj);
2387 break;
2388 default:
2389 err = GIT_ENOTFOUND;
2392 return err;
2395 /* use libgit2 get unified diff */
2396 static int GetUnifiedDiffLibGit2(const CTGitPath& /*path*/, const git_revnum_t& rev1, const git_revnum_t& rev2, git_diff_line_cb callback, void *data, bool /* bMerge */)
2398 git_repository *repo = nullptr;
2399 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(g_Git.m_CurrentDir).GetGitPathString(), CP_UTF8);
2400 CStringA tree1 = CUnicodeUtils::GetMulti(rev1, CP_UTF8);
2401 CStringA tree2 = CUnicodeUtils::GetMulti(rev2, CP_UTF8);
2402 int ret = 0;
2404 if (git_repository_open(&repo, gitdirA))
2405 return -1;
2407 int isHeadOrphan = git_repository_head_unborn(repo);
2408 if (isHeadOrphan != 0)
2410 git_repository_free(repo);
2411 if (isHeadOrphan == 1)
2412 return 0;
2413 else
2414 return -1;
2417 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2418 git_diff *diff = nullptr;
2420 if (rev1 == GitRev::GetWorkingCopy() || rev2 == GitRev::GetWorkingCopy())
2422 git_tree *t1 = nullptr;
2423 git_diff *diff2 = nullptr;
2427 if (rev1 != GitRev::GetWorkingCopy())
2429 if (resolve_to_tree(repo, tree1, &t1))
2431 ret = -1;
2432 break;
2435 if (rev2 != GitRev::GetWorkingCopy())
2437 if (resolve_to_tree(repo, tree2, &t1))
2439 ret = -1;
2440 break;
2444 ret = git_diff_tree_to_index(&diff, repo, t1, nullptr, &opts);
2445 if (ret)
2446 break;
2448 ret = git_diff_index_to_workdir(&diff2, repo, nullptr, &opts);
2449 if (ret)
2450 break;
2452 ret = git_diff_merge(diff, diff2);
2453 if (ret)
2454 break;
2456 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2458 git_patch *patch;
2459 if (git_patch_from_diff(&patch, diff, i))
2461 ret = -1;
2462 break;
2465 if (git_patch_print(patch, callback, data))
2467 git_patch_free(patch);
2468 ret = -1;
2469 break;
2472 git_patch_free(patch);
2474 } while(0);
2475 if (diff)
2476 git_diff_free(diff);
2477 if (diff2)
2478 git_diff_free(diff2);
2479 if (t1)
2480 git_tree_free(t1);
2482 else
2484 git_tree *t1 = nullptr, *t2 = nullptr;
2487 if (tree1.IsEmpty() && tree2.IsEmpty())
2489 ret = -1;
2490 break;
2493 if (tree1.IsEmpty())
2495 tree1 = tree2;
2496 tree2.Empty();
2499 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, &t1))
2501 ret = -1;
2502 break;
2505 if (tree2.IsEmpty())
2507 /* don't check return value, there are not parent commit at first commit*/
2508 resolve_to_tree(repo, tree1 + "~1", &t2);
2510 else if (resolve_to_tree(repo, tree2, &t2))
2512 ret = -1;
2513 break;
2515 if (git_diff_tree_to_tree(&diff, repo, t2, t1, &opts))
2517 ret = -1;
2518 break;
2521 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2523 git_patch *patch;
2524 if (git_patch_from_diff(&patch, diff, i))
2526 ret = -1;
2527 break;
2530 if (git_patch_print(patch, callback, data))
2532 git_patch_free(patch);
2533 ret = -1;
2534 break;
2537 git_patch_free(patch);
2539 } while(0);
2541 if (diff)
2542 git_diff_free(diff);
2543 if (t1)
2544 git_tree_free(t1);
2545 if (t2)
2546 git_tree_free(t2);
2548 git_repository_free(repo);
2550 return ret;
2553 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2555 if (UsingLibGit2(GIT_CMD_DIFF))
2557 FILE *file = nullptr;
2558 _tfopen_s(&file, patchfile, _T("w"));
2559 if (file == nullptr)
2560 return -1;
2561 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToFile, file, bMerge);
2562 fclose(file);
2563 return ret;
2565 else
2567 CString cmd;
2568 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2569 return g_Git.RunLogFile(cmd, patchfile, &gitLastErr);
2573 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2575 ATLASSERT(payload && line);
2576 CStringA *str = (CStringA*) payload;
2577 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2578 str->Append(&line->origin, 1);
2579 str->Append(line->content, (int)line->content_len);
2580 return 0;
2583 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2585 if (UsingLibGit2(GIT_CMD_DIFF))
2586 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToStringA, buffer, bMerge);
2587 else
2589 CString cmd;
2590 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2591 BYTE_VECTOR vector;
2592 int ret = Run(cmd, &vector);
2593 if (!vector.empty())
2594 buffer->Append((char *)&vector[0]);
2595 return ret;