Support bisect terms
[TortoiseGit.git] / src / Git / Git.cpp
blobe0df6659b7e335cf37d8d7494f135c4d8d2ca626
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - 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 "registry.h"
23 #include "GitForWindows.h"
24 #include "UnicodeUtils.h"
25 #include "gitdll.h"
26 #include <fstream>
27 #include <iterator>
28 #include "FormatMessageWrapper.h"
29 #include "SmartHandle.h"
30 #include "MassiveGitTaskBase.h"
31 #include "git2/sys/filter.h"
32 #include "git2/sys/transport.h"
33 #include "../libgit2/filter-filter.h"
34 #include "../libgit2/ssh-wintunnel.h"
36 bool CGit::ms_bCygwinGit = (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE) == TRUE);
37 bool CGit::ms_bMsys2Git = (CRegDWORD(_T("Software\\TortoiseGit\\Msys2Hack"), FALSE) == TRUE);
38 int CGit::m_LogEncode=CP_UTF8;
39 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
41 static LPCTSTR nextpath(const wchar_t* path, wchar_t* buf, size_t buflen)
43 if (path == NULL || buf == NULL || buflen == 0)
44 return NULL;
46 const wchar_t* base = path;
47 wchar_t term = (*path == L'"') ? *path++ : L';';
49 for (buflen--; *path && *path != term && buflen; buflen--)
50 *buf++ = *path++;
52 *buf = L'\0'; /* reserved a byte via initial subtract */
54 while (*path == term || *path == L';')
55 ++path;
57 return (path != base) ? path : NULL;
60 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
62 TCHAR buf[MAX_PATH] = { 0 };
64 // search in all paths defined in PATH
65 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
67 TCHAR *pfin = buf + _tcslen(buf) - 1;
69 // ensure trailing slash
70 if (*pfin != _T('/') && *pfin != _T('\\'))
71 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
73 const size_t len = _tcslen(buf);
75 if ((len + filename.GetLength()) < MAX_PATH)
76 _tcscpy_s(pfin + 1, MAX_PATH - len, filename);
77 else
78 break;
80 if (PathFileExists(buf))
82 if (wantDirectory)
83 pfin[1] = 0;
84 return buf;
88 return _T("");
91 static BOOL FindGitPath()
93 size_t size;
94 _tgetenv_s(&size, NULL, 0, _T("PATH"));
95 if (!size)
96 return FALSE;
98 TCHAR* env = (TCHAR*)alloca(size * sizeof(TCHAR));
99 if (!env)
100 return FALSE;
101 _tgetenv_s(&size, env, size, _T("PATH"));
103 CString gitExeDirectory = FindFileOnPath(_T("git.exe"), env, true);
104 if (!gitExeDirectory.IsEmpty())
106 CGit::ms_LastMsysGitDir = gitExeDirectory;
107 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
108 if (CGit::ms_LastMsysGitDir.GetLength() > 12 && (CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw64\\bin")))
110 // prefer cmd directory as early Git for Windows 2.x releases only had this
111 CString installRoot = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd\\git.exe");
112 if (PathFileExists(installRoot))
113 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd");
115 if (CGit::ms_LastMsysGitDir.GetLength() > 4 && CGit::ms_LastMsysGitDir.Right(4) == _T("\\cmd"))
117 // often the msysgit\cmd folder is on the %PATH%, but
118 // that git.exe does not work, so try to guess the bin folder
119 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
120 if (PathFileExists(binDir))
121 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
123 return TRUE;
126 return FALSE;
129 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
131 CString filename = executable;
133 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
134 filename += _T(".exe");
136 if (PathFileExists(filename))
137 return filename;
139 filename = FindFileOnPath(filename, env);
140 if (!filename.IsEmpty())
141 return filename;
143 return executable;
146 static bool g_bSortLogical;
147 static bool g_bSortLocalBranchesFirst;
148 static bool g_bSortTagsReversed;
149 static git_cred_acquire_cb g_Git2CredCallback;
150 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
152 static void GetSortOptions()
154 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
155 if (g_bSortLogical)
156 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
157 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
158 if (g_bSortLocalBranchesFirst)
159 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
160 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
161 if (!g_bSortTagsReversed)
162 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
165 static int LogicalComparePredicate(const CString &left, const CString &right)
167 if (g_bSortLogical)
168 return StrCmpLogicalW(left, right) < 0;
169 return StrCmpI(left, right) < 0;
172 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
174 if (g_bSortLogical)
175 return StrCmpLogicalW(left, right) > 0;
176 return StrCmpI(left, right) > 0;
179 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
181 if (g_bSortLocalBranchesFirst)
183 int leftIsRemote = left.Find(_T("remotes/"));
184 int rightIsRemote = right.Find(_T("remotes/"));
186 if (leftIsRemote == 0 && rightIsRemote < 0)
187 return false;
188 else if (leftIsRemote < 0 && rightIsRemote == 0)
189 return true;
191 if (g_bSortLogical)
192 return StrCmpLogicalW(left, right) < 0;
193 return StrCmpI(left, right) < 0;
196 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
198 CString CGit::ms_LastMsysGitDir;
199 CString CGit::ms_MsysGitRootDir;
200 int CGit::ms_LastMsysGitVersion = 0;
201 CGit g_Git;
204 CGit::CGit(void)
206 git_libgit2_init();
207 GetCurrentDirectory(MAX_PATH, CStrBuf(m_CurrentDir, MAX_PATH));
208 m_IsGitDllInited = false;
209 m_GitDiff=0;
210 m_GitSimpleListDiff=0;
211 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
212 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
213 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK);
215 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
217 GetSortOptions();
218 this->m_bInitialized =false;
219 CheckMsysGitDir();
220 m_critGitDllSec.Init();
223 CGit::~CGit(void)
225 if(this->m_GitDiff)
227 git_close_diff(m_GitDiff);
228 m_GitDiff=0;
230 if(this->m_GitSimpleListDiff)
232 git_close_diff(m_GitSimpleListDiff);
233 m_GitSimpleListDiff=0;
235 git_libgit2_shutdown();
238 bool CGit::IsBranchNameValid(const CString& branchname)
240 if (branchname.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
241 return false;
242 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
243 return false;
244 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
245 return !!git_reference_is_valid_name(branchA);
248 static bool IsPowerShell(CString cmd)
250 cmd.MakeLower();
251 int powerShellPos = cmd.Find(_T("powershell"));
252 if (powerShellPos < 0)
253 return false;
255 // found the word powershell, check that it is the command and not any parameter
256 int end = cmd.GetLength();
257 if (cmd.Find(_T('"')) == 0)
259 int secondDoubleQuote = cmd.Find(_T('"'), 1);
260 if (secondDoubleQuote > 0)
261 end = secondDoubleQuote;
263 else
265 int firstSpace = cmd.Find(_T(' '));
266 if (firstSpace > 0)
267 end = firstSpace;
270 return (end - 4 - 10 == powerShellPos || end - 10 == powerShellPos); // len(".exe")==4, len("powershell")==10
273 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
275 SECURITY_ATTRIBUTES sa;
276 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
277 CAutoGeneralHandle hStdioFile;
279 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
280 sa.lpSecurityDescriptor=NULL;
281 sa.bInheritHandle=TRUE;
282 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
284 CString err = CFormatMessageWrapper();
285 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), (LPCTSTR)err.Trim());
286 return TGIT_GIT_ERROR_OPEN_PIP;
288 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
290 CString err = CFormatMessageWrapper();
291 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), (LPCTSTR)err.Trim());
292 return TGIT_GIT_ERROR_OPEN_PIP;
295 if(StdioFile)
297 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
298 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
301 STARTUPINFO si = { 0 };
302 PROCESS_INFORMATION pi = { 0 };
303 si.cb=sizeof(STARTUPINFO);
305 if (hErrReadOut)
306 si.hStdError = hWriteErr;
307 else
308 si.hStdError = hWrite;
309 if(StdioFile)
310 si.hStdOutput=hStdioFile;
311 else
312 si.hStdOutput=hWrite;
314 si.wShowWindow=SW_HIDE;
315 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
317 LPTSTR pEnv = m_Environment;
318 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
320 dwFlags |= CREATE_NEW_PROCESS_GROUP;
322 // CREATE_NEW_CONSOLE makes git (but not ssh.exe, see issue #2257) recognize that it has no console in order to launch askpass to ask for the password,
323 // DETACHED_PROCESS which was originally used here has the same effect (but works with git.exe AND ssh.exe), however, it prevents PowerShell from working (cf. issue #2143)
324 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
325 if (IsPowerShell(cmd))
326 dwFlags |= CREATE_NEW_CONSOLE;
327 else
328 dwFlags |= DETACHED_PROCESS;
330 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
332 if (ms_bMsys2Git && cmd.Find(_T("git")) == 0 && cmd.Find(L"git.exe config ") == -1)
334 cmd.Replace(_T("\\"), _T("\\\\\\\\"));
335 cmd.Replace(_T("\""), _T("\\\""));
336 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/usr/bin/") + cmd + _T('"');
338 else if (ms_bCygwinGit && cmd.Find(_T("git")) == 0 && cmd.Find(L"git.exe config ") == -1)
340 cmd.Replace(_T('\\'), _T('/'));
341 cmd.Replace(_T("\""), _T("\\\""));
342 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
344 else if (cmd.Find(_T("git")) == 0 || cmd.Find(_T("bash")) == 0)
346 int firstSpace = cmd.Find(_T(" "));
347 if (firstSpace > 0)
348 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
349 else
350 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
353 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), (LPCTSTR)cmd);
354 if(!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, TRUE, dwFlags, pEnv, m_CurrentDir.GetBuffer(), &si, &pi))
356 CString err = CFormatMessageWrapper();
357 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), (LPCTSTR)err.Trim());
358 return TGIT_GIT_ERROR_CREATE_PROCESS;
361 m_CurrentGitPi = pi;
363 if(piOut)
364 *piOut=pi;
365 if(hReadOut)
366 *hReadOut = hRead.Detach();
367 if(hErrReadOut)
368 *hErrReadOut = hReadErr.Detach();
369 return 0;
372 //Must use sperate function to convert ANSI str to union code string
373 //Becuase A2W use stack as internal convert buffer.
374 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
376 if(str == NULL)
377 return ;
379 int len ;
380 if(length<0)
381 len = (int)strlen((const char*)p);
382 else
383 len=length;
384 if (len == 0)
385 return;
386 int currentContentLen = str->GetLength();
387 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
388 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
389 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
392 // This method was originally used to check for orphaned branches
393 BOOL CGit::CanParseRev(CString ref)
395 if (ref.IsEmpty())
396 ref = _T("HEAD");
398 CString cmdout;
399 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
401 return FALSE;
403 if(cmdout.IsEmpty())
404 return FALSE;
406 return TRUE;
409 // Checks if we have an orphaned HEAD
410 BOOL CGit::IsInitRepos()
412 CGitHash hash;
413 if (GetHash(hash, _T("HEAD")) != 0)
414 return FALSE;
415 return hash.IsEmpty() ? TRUE : FALSE;
418 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
420 PASYNCREADSTDERRTHREADARGS pDataArray;
421 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
423 DWORD readnumber;
424 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
425 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
427 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
428 break;
431 return 0;
434 int CGit::Run(CGitCall* pcall)
436 PROCESS_INFORMATION pi;
437 CAutoGeneralHandle hRead, hReadErr;
438 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
439 return TGIT_GIT_ERROR_CREATE_PROCESS;
441 CAutoGeneralHandle piThread(pi.hThread);
442 CAutoGeneralHandle piProcess(pi.hProcess);
444 ASYNCREADSTDERRTHREADARGS threadArguments;
445 threadArguments.fileHandle = hReadErr;
446 threadArguments.pcall = pcall;
447 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
449 DWORD readnumber;
450 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
451 bool bAborted=false;
452 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
454 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
455 if(!bAborted)//For now, flush output when command aborted.
456 if(pcall->OnOutputData(data,readnumber))
457 bAborted=true;
459 if(!bAborted)
460 pcall->OnEnd();
462 if (thread)
463 WaitForSingleObject(thread, INFINITE);
465 WaitForSingleObject(pi.hProcess, INFINITE);
466 DWORD exitcode =0;
468 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
470 CString err = CFormatMessageWrapper();
471 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), (LPCTSTR)err.Trim());
472 return TGIT_GIT_ERROR_GET_EXIT_CODE;
474 else
475 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
477 return exitcode;
479 class CGitCall_ByteVector : public CGitCall
481 public:
482 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
483 virtual bool OnOutputData(const BYTE* data, size_t size)
485 if (!m_pvector || size == 0)
486 return false;
487 size_t oldsize=m_pvector->size();
488 m_pvector->resize(m_pvector->size()+size);
489 memcpy(&*(m_pvector->begin()+oldsize),data,size);
490 return false;
492 virtual bool OnOutputErrData(const BYTE* data, size_t size)
494 if (!m_pvectorErr || size == 0)
495 return false;
496 size_t oldsize = m_pvectorErr->size();
497 m_pvectorErr->resize(m_pvectorErr->size() + size);
498 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
499 return false;
501 BYTE_VECTOR* m_pvector;
502 BYTE_VECTOR* m_pvectorErr;
505 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
507 CGitCall_ByteVector call(cmd, vector, vectorErr);
508 return Run(&call);
510 int CGit::Run(CString cmd, CString* output, int code)
512 CString err;
513 int ret;
514 ret = Run(cmd, output, &err, code);
516 if (output && !err.IsEmpty())
518 if (!output->IsEmpty())
519 *output += _T("\n");
520 *output += err;
523 return ret;
525 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
527 BYTE_VECTOR vector, vectorErr;
528 int ret;
529 if (outputErr)
530 ret = Run(cmd, &vector, &vectorErr);
531 else
532 ret = Run(cmd, &vector);
534 vector.push_back(0);
535 StringAppend(output, &(vector[0]), code);
537 if (outputErr)
539 vectorErr.push_back(0);
540 StringAppend(outputErr, &(vectorErr[0]), code);
543 return ret;
546 class CGitCallCb : public CGitCall
548 public:
549 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
551 virtual bool OnOutputData(const BYTE* data, size_t size) override
553 // Add data
554 if (size == 0)
555 return false;
556 int oldEndPos = m_buffer.GetLength();
557 memcpy(m_buffer.GetBuffer(oldEndPos + (int)size) + oldEndPos, data, size);
558 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
560 // Break into lines and feed to m_recv
561 int eolPos;
562 while ((eolPos = m_buffer.Find('\n')) >= 0)
564 m_recv(m_buffer.Left(eolPos));
565 m_buffer = m_buffer.Mid(eolPos + 1);
567 return false;
570 virtual bool OnOutputErrData(const BYTE*, size_t) override
572 return false; // Ignore error output for now
575 virtual void OnEnd() override
577 if (!m_buffer.IsEmpty())
578 m_recv(m_buffer);
579 m_buffer.Empty(); // Just for sure
582 private:
583 GitReceiverFunc m_recv;
584 CStringA m_buffer;
587 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
589 CGitCallCb call(cmd, recv);
590 return Run(&call);
593 CString CGit::GetUserName(void)
595 CEnvironment env;
596 env.CopyProcessEnvironment();
597 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
598 if (!envname.IsEmpty())
599 return envname;
600 return GetConfigValue(L"user.name");
602 CString CGit::GetUserEmail(void)
604 CEnvironment env;
605 env.CopyProcessEnvironment();
606 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
607 if (!envmail.IsEmpty())
608 return envmail;
610 return GetConfigValue(L"user.email");
613 CString CGit::GetConfigValue(const CString& name, const CString& def, bool wantBool)
615 CString configValue;
616 if(this->m_IsUseGitDLL)
618 CAutoLocker lock(g_Git.m_critGitDllSec);
622 CheckAndInitDll();
623 }catch(...)
626 CStringA key, value;
627 key = CUnicodeUtils::GetUTF8(name);
631 if (git_get_config(key, CStrBufA(value, 4096), 4096))
632 return def;
634 catch (const char *msg)
636 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
637 return def;
640 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
641 return configValue;
643 else
645 CString cmd;
646 cmd.Format(L"git.exe config%s %s", wantBool ? _T(" --bool") : _T(""), (LPCTSTR)name);
647 if (Run(cmd, &configValue, nullptr, CP_UTF8))
648 return def;
649 if (configValue.IsEmpty())
650 return configValue;
651 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
655 bool CGit::GetConfigValueBool(const CString& name, const bool def)
657 CString configValue = GetConfigValue(name, def ? _T("true") : _T("false"), true);
658 configValue.MakeLower();
659 configValue.Trim();
660 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
661 return true;
662 else
663 return false;
666 int CGit::GetConfigValueInt32(const CString& name, const int def)
668 CString configValue = GetConfigValue(name);
669 int value = def;
670 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
671 return value;
672 return def;
675 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
677 if(this->m_IsUseGitDLL)
679 CAutoLocker lock(g_Git.m_critGitDllSec);
683 CheckAndInitDll();
685 }catch(...)
688 CStringA keya, valuea;
689 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
690 valuea = CUnicodeUtils::GetUTF8(value);
694 return [=]() { return get_set_config(keya, valuea, type); }();
696 catch (const char *msg)
698 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
699 return -1;
702 else
704 CString cmd;
705 CString option;
706 switch(type)
708 case CONFIG_GLOBAL:
709 option = _T("--global");
710 break;
711 case CONFIG_SYSTEM:
712 option = _T("--system");
713 break;
714 default:
715 break;
717 CString mangledValue = value;
718 mangledValue.Replace(_T("\\\""), _T("\\\\\""));
719 mangledValue.Replace(_T("\""), _T("\\\""));
720 cmd.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR)option, (LPCTSTR)key, (LPCTSTR)mangledValue);
721 CString out;
722 if (Run(cmd, &out, nullptr, CP_UTF8))
724 return -1;
727 return 0;
730 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
732 if(this->m_IsUseGitDLL)
734 CAutoLocker lock(g_Git.m_critGitDllSec);
738 CheckAndInitDll();
739 }catch(...)
742 CStringA keya;
743 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
747 return [=]() { return get_set_config(keya, nullptr, type); }();
749 catch (const char *msg)
751 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
752 return -1;
755 else
757 CString cmd;
758 CString option;
759 switch(type)
761 case CONFIG_GLOBAL:
762 option = _T("--global");
763 break;
764 case CONFIG_SYSTEM:
765 option = _T("--system");
766 break;
767 default:
768 break;
770 cmd.Format(_T("git.exe config %s --unset %s"), (LPCTSTR)option, (LPCTSTR)key);
771 CString out;
772 if (Run(cmd, &out, nullptr, CP_UTF8))
774 return -1;
777 return 0;
780 CString CGit::GetCurrentBranch(bool fallback)
782 CString output;
783 //Run(_T("git.exe branch"),&branch);
785 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
786 if (result != 0 && ((result == 1 && !fallback) || result != 1))
788 return _T("(no branch)");
790 else
791 return output;
795 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
797 if (localBranch.IsEmpty())
798 return;
800 CString configName;
801 configName.Format(L"branch.%s.remote", (LPCTSTR)localBranch);
802 pullRemote = GetConfigValue(configName);
804 //Select pull-branch from current branch
805 configName.Format(L"branch.%s.merge", (LPCTSTR)localBranch);
806 pullBranch = StripRefName(GetConfigValue(configName));
809 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
811 CString refName;
812 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
813 return;
814 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
817 CString CGit::GetFullRefName(const CString& shortRefName)
819 CString refName;
820 CString cmd;
821 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR)shortRefName);
822 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
823 return CString();//Error
824 int iStart = 0;
825 return refName.Tokenize(L"\n", iStart);
828 CString CGit::StripRefName(CString refName)
830 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
831 refName = refName.Mid(11);
832 else if(wcsncmp(refName, L"refs/", 5) == 0)
833 refName = refName.Mid(5);
834 int start =0;
835 return refName.Tokenize(_T("\n"),start);
838 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
840 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
842 if ( sProjectRoot.IsEmpty() )
843 return -1;
845 CString sDotGitPath;
846 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
847 return -1;
849 CString sHeadFile = sDotGitPath + _T("HEAD");
851 CAutoFILE pFile = _tfsopen(sHeadFile.GetString(), _T("r"), SH_DENYWR);
852 if (!pFile)
853 return -1;
855 char s[256] = {0};
856 fgets(s, sizeof(s), pFile);
858 const char *pfx = "ref: refs/heads/";
859 const int len = 16;//strlen(pfx)
861 if ( !strncmp(s, pfx, len) )
863 //# We're on a branch. It might not exist. But
864 //# HEAD looks good enough to be a branch.
865 CStringA utf8Branch(s + len);
866 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
867 sBranchOut.TrimRight(_T(" \r\n\t"));
869 if ( sBranchOut.IsEmpty() )
870 return -1;
872 else if (fallback)
874 CStringA utf8Hash(s);
875 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
876 unicodeHash.TrimRight(_T(" \r\n\t"));
877 if (CGitHash::IsValidSHA1(unicodeHash))
878 sBranchOut = unicodeHash;
879 else
880 //# Assume this is a detached head.
881 sBranchOut = _T("HEAD");
882 return 1;
884 else
886 //# Assume this is a detached head.
887 sBranchOut = "HEAD";
889 return 1;
892 return 0;
895 int CGit::BuildOutputFormat(CString &format,bool IsFull)
897 CString log;
898 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
899 format += log;
900 if(IsFull)
902 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
903 format += log;
904 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
905 format += log;
906 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
907 format += log;
908 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
909 format += log;
910 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
911 format += log;
912 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
913 format += log;
914 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
915 format += log;
918 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
919 format += log;
920 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
921 format += log;
922 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
923 format += log;
925 if(IsFull)
927 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
928 format += log;
930 return 0;
933 CString CGit::GetLogCmd(const CString& range, const CTGitPath* path, int mask,
934 CFilterData *Filter)
936 CString param;
938 if(mask& LOG_INFO_STAT )
939 param += _T(" --numstat");
940 if(mask& LOG_INFO_FILESTATE)
941 param += _T(" --raw");
943 if(mask& LOG_INFO_FULLHISTORY)
944 param += _T(" --full-history");
946 if(mask& LOG_INFO_BOUNDARY)
947 param += _T(" --left-right --boundary");
949 if(mask& CGit::LOG_INFO_ALL_BRANCH)
950 param += _T(" --all");
952 if (mask& CGit::LOG_INFO_BASIC_REFS)
954 param += _T(" --branches");
955 param += _T(" --tags");
956 param += _T(" --remotes");
957 param += _T(" --glob=stas[h]"); // require at least one glob operator
958 param += _T(" --glob=bisect");
961 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
962 param += _T(" --branches");
964 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
965 param += _T(" -C");
967 if(mask& CGit::LOG_INFO_DETECT_RENAME )
968 param += _T(" -M");
970 if(mask& CGit::LOG_INFO_FIRST_PARENT )
971 param += _T(" --first-parent");
973 if(mask& CGit::LOG_INFO_NO_MERGE )
974 param += _T(" --no-merges");
976 if(mask& CGit::LOG_INFO_FOLLOW)
977 param += _T(" --follow");
979 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
980 param += _T(" -c");
982 if(mask& CGit::LOG_INFO_FULL_DIFF)
983 param += _T(" --full-diff");
985 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
986 param += _T(" --simplify-by-decoration");
988 if (Filter)
990 if (Filter->m_NumberOfLogsScale >= CFilterData::SHOW_LAST_N_YEARS)
992 CTime now = CTime::GetCurrentTime();
993 CTime time = CTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0);
994 __time64_t substract = 86400;
995 CString scale;
996 switch (Filter->m_NumberOfLogsScale)
998 case CFilterData::SHOW_LAST_N_YEARS:
999 substract *= 365;
1000 break;
1001 case CFilterData::SHOW_LAST_N_MONTHS:
1002 substract *= 30;
1003 break;
1004 case CFilterData::SHOW_LAST_N_WEEKS:
1005 substract *= 7;
1006 break;
1008 Filter->m_From = (DWORD)time.GetTime() - (Filter->m_NumberOfLogs * substract);
1010 CString st1;
1011 if (Filter->m_NumberOfLogsScale == CFilterData::SHOW_LAST_N_COMMITS)
1012 st1.Format(_T(" -n%ld"), Filter->m_NumberOfLogs);
1013 else if (Filter->m_NumberOfLogsScale >= CFilterData::SHOW_LAST_SEL_DATE && Filter->m_From > 0)
1014 st1.Format(_T(" --max-age=%I64u"), Filter->m_From);
1015 param += st1;
1018 if( Filter && (Filter->m_To != -1))
1020 CString st2;
1021 st2.Format(_T(" --min-age=%I64u"), Filter->m_To);
1022 param += st2;
1025 bool isgrep = false;
1026 if( Filter && (!Filter->m_Author.IsEmpty()))
1028 CString st1;
1029 st1.Format(_T(" --author=\"%s\"" ), (LPCTSTR)Filter->m_Author);
1030 param += st1;
1031 isgrep = true;
1034 if( Filter && (!Filter->m_Committer.IsEmpty()))
1036 CString st1;
1037 st1.Format(_T(" --committer=\"%s\"" ), (LPCTSTR)Filter->m_Author);
1038 param += st1;
1039 isgrep = true;
1042 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1044 CString st1;
1045 st1.Format(_T(" --grep=\"%s\"" ), (LPCTSTR)Filter->m_MessageFilter);
1046 param += st1;
1047 isgrep = true;
1050 if(Filter && isgrep)
1052 if(!Filter->m_IsRegex)
1053 param += _T(" --fixed-strings");
1055 param += _T(" --regexp-ignore-case --extended-regexp");
1058 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1059 if (logOrderBy == LOG_ORDER_TOPOORDER || (mask & CGit::LOG_ORDER_TOPOORDER))
1060 param += _T(" --topo-order");
1061 else if (logOrderBy == LOG_ORDER_DATEORDER)
1062 param += _T(" --date-order");
1064 CString cmd;
1065 CString file;
1066 if (path)
1067 file.Format(_T(" \"%s\""), (LPCTSTR)path->GetGitPathString());
1068 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1069 cmd.Format(_T("--ignore-this-parameter -z%s %s --parents --%s"), (LPCTSTR)param, (LPCTSTR)range, (LPCTSTR)file);
1071 return cmd;
1073 #define BUFSIZE 512
1074 void GetTempPath(CString &path)
1076 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1077 DWORD dwRetVal;
1078 DWORD dwBufSize=BUFSIZE;
1079 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1080 lpPathBuffer); // buffer for path
1081 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1083 path=_T("");
1085 path.Format(_T("%s"),lpPathBuffer);
1087 CString GetTempFile()
1089 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1090 DWORD dwRetVal;
1091 DWORD dwBufSize=BUFSIZE;
1092 TCHAR szTempName[BUFSIZE] = { 0 };
1093 UINT uRetVal;
1095 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1096 lpPathBuffer); // buffer for path
1097 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1099 return _T("");
1101 // Create a temporary file.
1102 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1103 TEXT("Patch"), // temp file name prefix
1104 0, // create unique name
1105 szTempName); // buffer for name
1108 if (uRetVal == 0)
1110 return _T("");
1113 return CString(szTempName);
1117 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1119 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1120 if (result == 0) return 0;
1121 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1123 if (lpBuffer)
1124 lpBuffer[0] = '\0';
1125 return result + 13;
1128 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1129 CreateDirectory(lpBuffer, NULL);
1131 return result + 13;
1134 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1136 STARTUPINFO si;
1137 PROCESS_INFORMATION pi;
1138 si.cb=sizeof(STARTUPINFO);
1139 GetStartupInfo(&si);
1141 SECURITY_ATTRIBUTES psa = {sizeof(psa), nullptr, TRUE};
1142 psa.bInheritHandle=TRUE;
1144 CAutoGeneralHandle hReadErr, hWriteErr;
1145 if (!CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &psa, 0))
1147 CString err = CFormatMessageWrapper();
1148 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), (LPCTSTR)err.Trim());
1149 return TGIT_GIT_ERROR_OPEN_PIP;
1152 CAutoFile houtfile = CreateFile(filename, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &psa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
1153 if (!houtfile)
1155 CString err = CFormatMessageWrapper();
1156 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), (LPCTSTR)err.Trim());
1157 return TGIT_GIT_ERROR_OPEN_PIP;
1160 si.wShowWindow = SW_HIDE;
1161 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1162 si.hStdOutput = houtfile;
1163 si.hStdError = hWriteErr;
1165 LPTSTR pEnv = m_Environment;
1166 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1168 if(cmd.Find(_T("git")) == 0)
1169 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1171 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), (LPCTSTR)cmd);
1172 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1174 CString err = CFormatMessageWrapper();
1175 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), (LPCTSTR)err.Trim());
1176 stdErr = &err;
1177 return TGIT_GIT_ERROR_CREATE_PROCESS;
1180 CAutoGeneralHandle piThread(pi.hThread);
1181 CAutoGeneralHandle piProcess(pi.hProcess);
1183 BYTE_VECTOR stderrVector;
1184 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1185 ASYNCREADSTDERRTHREADARGS threadArguments;
1186 threadArguments.fileHandle = hReadErr;
1187 threadArguments.pcall = &pcall;
1188 CAutoGeneralHandle thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1190 WaitForSingleObject(pi.hProcess,INFINITE);
1192 hWriteErr.CloseHandle();
1193 hReadErr.CloseHandle();
1195 if (thread)
1196 WaitForSingleObject(thread, INFINITE);
1198 stderrVector.push_back(0);
1199 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1201 DWORD exitcode = 0;
1202 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1204 CString err = CFormatMessageWrapper();
1205 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), (LPCTSTR)err.Trim());
1206 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1208 else
1209 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1211 return exitcode;
1214 CAutoRepository CGit::GetGitRepository() const
1216 return CAutoRepository(GetGitPathStringA(m_CurrentDir));
1219 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1221 ATLASSERT(repo);
1223 // no need to parse a ref if it's already a 40-byte hash
1224 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1226 hash = CGitHash(friendname);
1227 return 0;
1230 int isHeadOrphan = git_repository_head_unborn(repo);
1231 if (isHeadOrphan != 0)
1233 hash.Empty();
1234 if (isHeadOrphan == 1)
1235 return 0;
1236 else
1237 return -1;
1240 CAutoObject gitObject;
1241 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1242 return -1;
1244 const git_oid * oid = git_object_id(gitObject);
1245 if (!oid)
1246 return -1;
1248 hash = CGitHash((char *)oid->id);
1250 return 0;
1253 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1255 // no need to parse a ref if it's already a 40-byte hash
1256 if (CGitHash::IsValidSHA1(friendname))
1258 hash = CGitHash(friendname);
1259 return 0;
1262 if (m_IsUseLibGit2)
1264 CAutoRepository repo(GetGitRepository());
1265 if (!repo)
1266 return -1;
1268 return GetHash(repo, hash, friendname, true);
1270 else
1272 CString branch = FixBranchName(friendname);
1273 if (friendname == _T("FETCH_HEAD") && branch.IsEmpty())
1274 branch = friendname;
1275 CString cmd;
1276 cmd.Format(_T("git.exe rev-parse %s"), (LPCTSTR)branch);
1277 gitLastErr.Empty();
1278 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1279 hash = CGitHash(gitLastErr.Trim());
1280 if (ret == 0)
1281 gitLastErr.Empty();
1282 else if (friendname == _T("HEAD")) // special check for unborn branch
1284 CString currentbranch;
1285 if (GetCurrentBranchFromFile(m_CurrentDir, currentbranch))
1286 return -1;
1287 gitLastErr.Empty();
1288 return 0;
1290 return ret;
1294 int CGit::GetInitAddList(CTGitPathList &outputlist)
1296 CString cmd;
1297 BYTE_VECTOR cmdout;
1299 cmd=_T("git.exe ls-files -s -t -z");
1300 outputlist.Clear();
1301 if (Run(cmd, &cmdout))
1302 return -1;
1304 if (outputlist.ParserFromLsFile(cmdout))
1305 return -1;
1306 for(int i = 0; i < outputlist.GetCount(); ++i)
1307 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1309 return 0;
1311 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1313 CString cmd;
1314 CString ignore;
1315 if (ignoreSpaceAtEol)
1316 ignore += _T(" --ignore-space-at-eol");
1317 if (ignoreSpaceChange)
1318 ignore += _T(" --ignore-space-change");
1319 if (ignoreAllSpace)
1320 ignore += _T(" --ignore-all-space");
1321 if (ignoreBlankLines)
1322 ignore += _T(" --ignore-blank-lines");
1324 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1326 //rev1=+_T("");
1327 if(rev1 == GIT_REV_ZERO)
1328 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev2);
1329 else
1330 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev1);
1332 else
1334 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev2, (LPCTSTR)rev1);
1337 BYTE_VECTOR out;
1338 if (Run(cmd, &out))
1339 return -1;
1341 return outputlist.ParserFromLog(out);
1344 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1346 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1347 list->push_back(CUnicodeUtils::GetUnicode(refname));
1348 return 0;
1351 int CGit::GetTagList(STRING_VECTOR &list)
1353 size_t prevCount = list.size();
1354 if (this->m_IsUseLibGit2)
1356 CAutoRepository repo(GetGitRepository());
1357 if (!repo)
1358 return -1;
1360 CAutoStrArray tag_names;
1362 if (git_tag_list(tag_names, repo))
1363 return -1;
1365 for (size_t i = 0; i < tag_names->count; ++i)
1367 CStringA tagName(tag_names->strings[i]);
1368 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1371 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1373 return 0;
1375 else
1377 CString cmd, output;
1378 cmd=_T("git.exe tag -l");
1379 int ret = Run(cmd, &output, NULL, CP_UTF8);
1380 if(!ret)
1382 int pos=0;
1383 CString one;
1384 while( pos>=0 )
1386 one=output.Tokenize(_T("\n"),pos);
1387 if (!one.IsEmpty())
1388 list.push_back(one);
1390 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1392 else if (ret == 1 && IsInitRepos())
1393 return 0;
1394 return ret;
1398 CString CGit::GetGitLastErr(const CString& msg)
1400 if (this->m_IsUseLibGit2)
1401 return GetLibGit2LastErr(msg);
1402 else if (gitLastErr.IsEmpty())
1403 return msg + _T("\nUnknown git.exe error.");
1404 else
1406 CString lastError = gitLastErr;
1407 gitLastErr.Empty();
1408 return msg + _T("\n") + lastError;
1412 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1414 if (UsingLibGit2(cmd))
1415 return GetLibGit2LastErr(msg);
1416 else if (gitLastErr.IsEmpty())
1417 return msg + _T("\nUnknown git.exe error.");
1418 else
1420 CString lastError = gitLastErr;
1421 gitLastErr.Empty();
1422 return msg + _T("\n") + lastError;
1426 CString CGit::GetLibGit2LastErr()
1428 const git_error *libgit2err = giterr_last();
1429 if (libgit2err)
1431 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1432 giterr_clear();
1433 return _T("libgit2 returned: ") + lastError;
1435 else
1436 return _T("An error occoured in libgit2, but no message is available.");
1439 CString CGit::GetLibGit2LastErr(const CString& msg)
1441 if (!msg.IsEmpty())
1442 return msg + _T("\n") + GetLibGit2LastErr();
1443 return GetLibGit2LastErr();
1446 CString CGit::FixBranchName_Mod(CString& branchName)
1448 if(branchName == "FETCH_HEAD")
1449 branchName = DerefFetchHead();
1450 return branchName;
1453 CString CGit::FixBranchName(const CString& branchName)
1455 CString tempBranchName = branchName;
1456 FixBranchName_Mod(tempBranchName);
1457 return tempBranchName;
1460 bool CGit::IsBranchTagNameUnique(const CString& name)
1462 if (m_IsUseLibGit2)
1464 CAutoRepository repo(GetGitRepository());
1465 if (!repo)
1466 return true; // TODO: optimize error reporting
1468 CAutoReference tagRef;
1469 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1470 return true;
1472 CAutoReference branchRef;
1473 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1474 return true;
1476 return false;
1478 // else
1479 CString output;
1481 CString cmd;
1482 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR)name, (LPCTSTR)name);
1483 int ret = Run(cmd, &output, NULL, CP_UTF8);
1484 if (!ret)
1486 int i = 0, pos = 0;
1487 while (pos >= 0)
1489 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1490 ++i;
1492 if (i >= 2)
1493 return false;
1496 return true;
1499 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1501 if (m_IsUseLibGit2)
1503 CAutoRepository repo(GetGitRepository());
1504 if (!repo)
1505 return false; // TODO: optimize error reporting
1507 CString prefix;
1508 if (isBranch)
1509 prefix = _T("refs/heads/");
1510 else
1511 prefix = _T("refs/tags/");
1513 CAutoReference ref;
1514 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1515 return false;
1517 return true;
1519 // else
1520 CString cmd, output;
1522 cmd = _T("git.exe show-ref ");
1523 if (isBranch)
1524 cmd += _T("--heads ");
1525 else
1526 cmd += _T("--tags ");
1528 cmd += _T("refs/heads/") + name;
1529 cmd += _T(" refs/tags/") + name;
1531 int ret = Run(cmd, &output, NULL, CP_UTF8);
1532 if (!ret)
1534 if (!output.IsEmpty())
1535 return true;
1538 return false;
1541 CString CGit::DerefFetchHead()
1543 CString dotGitPath;
1544 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1545 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1546 int forMergeLineCount = 0;
1547 std::string line;
1548 std::string hashToReturn;
1549 while(getline(fetchHeadFile, line))
1551 //Tokenize this line
1552 std::string::size_type prevPos = 0;
1553 std::string::size_type pos = line.find('\t');
1554 if(pos == std::string::npos) continue; //invalid line
1556 std::string hash = line.substr(0, pos);
1557 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1559 bool forMerge = pos == prevPos;
1560 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1562 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1564 //Process this line
1565 if(forMerge)
1567 hashToReturn = hash;
1568 ++forMergeLineCount;
1569 if(forMergeLineCount > 1)
1570 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1574 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1577 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1579 size_t prevCount = list.size();
1580 int ret = 0;
1581 CString cur;
1582 bool headIsDetached = false;
1583 if (m_IsUseLibGit2)
1585 CAutoRepository repo(GetGitRepository());
1586 if (!repo)
1587 return -1;
1589 if (git_repository_head_detached(repo) == 1)
1590 headIsDetached = true;
1592 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1594 git_branch_t flags = GIT_BRANCH_LOCAL;
1595 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1596 flags = GIT_BRANCH_ALL;
1597 else if (type & BRANCH_REMOTE)
1598 flags = GIT_BRANCH_REMOTE;
1600 CAutoBranchIterator it;
1601 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1602 return -1;
1604 git_reference * ref = nullptr;
1605 git_branch_t branchType;
1606 while (git_branch_next(&ref, &branchType, it) == 0)
1608 CAutoReference autoRef(ref);
1609 const char * name = nullptr;
1610 if (git_branch_name(&name, ref))
1611 continue;
1613 CString branchname = CUnicodeUtils::GetUnicode(name);
1614 if (branchType & GIT_BRANCH_REMOTE)
1615 list.push_back(_T("remotes/") + branchname);
1616 else
1618 if (git_branch_is_head(ref))
1619 cur = branchname;
1620 list.push_back(branchname);
1625 else
1627 CString cmd, output;
1628 cmd = _T("git.exe branch --no-color");
1630 if ((type & BRANCH_ALL) == BRANCH_ALL)
1631 cmd += _T(" -a");
1632 else if (type & BRANCH_REMOTE)
1633 cmd += _T(" -r");
1635 ret = Run(cmd, &output, nullptr, CP_UTF8);
1636 if (!ret)
1638 int pos = 0;
1639 CString one;
1640 while (pos >= 0)
1642 one = output.Tokenize(_T("\n"), pos);
1643 one.Trim(L" \r\n\t");
1644 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1645 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1646 if (one[0] == _T('*'))
1648 one = one.Mid(2);
1649 cur = one;
1651 // check whether HEAD is detached
1652 CString currentHead;
1653 if (one.Left(1) == _T("(") && GetCurrentBranchFromFile(m_CurrentDir, currentHead) == 1)
1655 headIsDetached = true;
1656 continue;
1659 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1660 one = _T("remotes/") + one;
1661 list.push_back(one);
1664 else if (ret == 1 && IsInitRepos())
1665 return 0;
1668 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1669 list.push_back(L"FETCH_HEAD");
1671 std::sort(list.begin() + prevCount, list.end(), LogicalCompareBranchesPredicate);
1673 if (current && !headIsDetached)
1675 for (unsigned int i = 0; i < list.size(); ++i)
1677 if (list[i] == cur)
1679 *current = i;
1680 break;
1685 return ret;
1688 int CGit::GetRemoteList(STRING_VECTOR &list)
1690 size_t prevCount = list.size();
1691 if (this->m_IsUseLibGit2)
1693 CAutoRepository repo(GetGitRepository());
1694 if (!repo)
1695 return -1;
1697 CAutoStrArray remotes;
1698 if (git_remote_list(remotes, repo))
1699 return -1;
1701 for (size_t i = 0; i < remotes->count; ++i)
1703 CStringA remote(remotes->strings[i]);
1704 list.push_back(CUnicodeUtils::GetUnicode(remote));
1707 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1709 return 0;
1711 else
1713 int ret;
1714 CString cmd, output;
1715 cmd=_T("git.exe remote");
1716 ret = Run(cmd, &output, NULL, CP_UTF8);
1717 if(!ret)
1719 int pos=0;
1720 CString one;
1721 while( pos>=0 )
1723 one=output.Tokenize(_T("\n"),pos);
1724 if (!one.IsEmpty())
1725 list.push_back(one);
1728 return ret;
1732 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1734 size_t prevCount = list.size();
1735 if (UsingLibGit2(GIT_CMD_FETCH))
1737 CAutoRepository repo(GetGitRepository());
1738 if (!repo)
1739 return -1;
1741 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1742 CAutoRemote gitremote;
1743 if (git_remote_lookup(gitremote.GetPointer(), repo, remoteA) < 0)
1744 return -1;
1746 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1747 callbacks.credentials = g_Git2CredCallback;
1748 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1749 if (git_remote_connect(gitremote, GIT_DIRECTION_FETCH, &callbacks, nullptr) < 0)
1750 return -1;
1752 const git_remote_head** heads = nullptr;
1753 size_t size = 0;
1754 if (git_remote_ls(&heads, &size, gitremote) < 0)
1755 return -1;
1757 for (size_t i = 0; i < size; i++)
1759 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1760 CString shortname;
1761 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1762 continue;
1763 // do not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1764 if (ref.Find(_T("^{}")) >= 1)
1765 continue;
1766 list.push_back(shortname);
1768 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1769 return 0;
1772 CString cmd, out, err;
1773 cmd.Format(_T("git.exe ls-remote -t \"%s\""), (LPCTSTR)remote);
1774 if (Run(cmd, &out, &err, CP_UTF8))
1776 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1777 return -1;
1780 int pos = 0;
1781 while (pos >= 0)
1783 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1784 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1785 if (one.Find(_T("^{}")) >= 1)
1786 continue;
1787 if (!one.IsEmpty())
1788 list.push_back(one);
1790 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1791 return 0;
1794 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1796 if (UsingLibGit2(GIT_CMD_PUSH))
1798 CAutoRepository repo(GetGitRepository());
1799 if (!repo)
1800 return -1;
1802 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1803 CAutoRemote remote;
1804 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1805 return -1;
1807 git_push_options pushOpts = GIT_PUSH_OPTIONS_INIT;
1808 git_remote_callbacks& callbacks = pushOpts.callbacks;
1809 callbacks.credentials = g_Git2CredCallback;
1810 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1811 std::vector<CStringA> refspecs;
1812 for (const auto& ref : list)
1813 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1815 std::vector<char*> vc;
1816 vc.reserve(refspecs.size());
1817 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1818 git_strarray specs = { &vc[0], vc.size() };
1820 if (git_remote_push(remote, &specs, &pushOpts) < 0)
1821 return -1;
1823 else
1825 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1826 for (const auto& ref : list)
1828 CString refspec = _T(":") + ref;
1829 mgtPush.AddFile(refspec);
1832 BOOL cancel = FALSE;
1833 mgtPush.Execute(cancel);
1836 return 0;
1839 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1841 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1842 list->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref)));
1843 return 0;
1846 int CGit::GetRefList(STRING_VECTOR &list)
1848 size_t prevCount = list.size();
1849 if (this->m_IsUseLibGit2)
1851 CAutoRepository repo(GetGitRepository());
1852 if (!repo)
1853 return -1;
1855 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1856 return -1;
1858 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1860 return 0;
1862 else
1864 CString cmd, output;
1865 cmd=_T("git.exe show-ref -d");
1866 int ret = Run(cmd, &output, NULL, CP_UTF8);
1867 if(!ret)
1869 int pos=0;
1870 CString one;
1871 while( pos>=0 )
1873 one=output.Tokenize(_T("\n"),pos);
1874 int start=one.Find(_T(" "),0);
1875 if(start>0)
1877 CString name;
1878 name=one.Right(one.GetLength()-start-1);
1879 if (list.empty() || name != *list.crbegin() + _T("^{}"))
1880 list.push_back(name);
1883 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1885 else if (ret == 1 && IsInitRepos())
1886 return 0;
1887 return ret;
1891 typedef struct map_each_ref_payload {
1892 git_repository * repo;
1893 MAP_HASH_NAME * map;
1894 } map_each_ref_payload;
1896 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1898 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1900 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1902 CAutoObject gitObject;
1903 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1904 return 1;
1906 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1908 str += _T("^{}"); // deref tag
1909 CAutoObject derefedTag;
1910 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1911 return 1;
1912 gitObject.Swap(derefedTag);
1915 const git_oid * oid = git_object_id(gitObject);
1916 if (oid == NULL)
1917 return 1;
1919 CGitHash hash((char *)oid->id);
1920 (*payloadContent->map)[hash].push_back(str);
1922 return 0;
1924 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1926 ATLASSERT(repo);
1928 map_each_ref_payload payloadContent = { repo, &map };
1930 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1931 return -1;
1933 for (auto it = map.begin(); it != map.end(); ++it)
1935 std::sort(it->second.begin(), it->second.end());
1938 return 0;
1941 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1943 if (this->m_IsUseLibGit2)
1945 CAutoRepository repo(GetGitRepository());
1946 if (!repo)
1947 return -1;
1949 return GetMapHashToFriendName(repo, map);
1951 else
1953 CString cmd, output;
1954 cmd=_T("git.exe show-ref -d");
1955 int ret = Run(cmd, &output, NULL, CP_UTF8);
1956 if(!ret)
1958 int pos=0;
1959 CString one;
1960 while( pos>=0 )
1962 one=output.Tokenize(_T("\n"),pos);
1963 int start=one.Find(_T(" "),0);
1964 if(start>0)
1966 CString name;
1967 name=one.Right(one.GetLength()-start-1);
1969 CString hash;
1970 hash=one.Left(start);
1972 map[CGitHash(hash)].push_back(name);
1976 else if (ret == 1 && IsInitRepos())
1977 return 0;
1978 return ret;
1982 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
1984 CAutoConfig config(true);
1985 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE) < 0)
1986 return -1;
1987 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
1989 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
1990 CString key = CUnicodeUtils::GetUnicode(entry->name);
1991 key = key.Mid(7, key.GetLength() - 7 - 12); // 7: branch., 12: .description
1992 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
1993 return 0;
1994 }, &map);
1997 static void SetLibGit2SearchPath(int level, const CString &value)
1999 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
2000 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
2003 static void SetLibGit2TemplatePath(const CString &value)
2005 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
2006 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
2009 int CGit::FindAndSetGitExePath(BOOL bFallback)
2011 CRegString msysdir = CRegString(REG_MSYSGIT_PATH, _T(""), FALSE);
2012 CString str = msysdir;
2013 if (!str.IsEmpty() && PathFileExists(str + _T("\\git.exe")))
2015 CGit::ms_LastMsysGitDir = str;
2016 return TRUE;
2019 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2020 if (!bFallback)
2021 return FALSE;
2023 // first, search PATH if git/bin directory is already present
2024 if (FindGitPath())
2026 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2027 msysdir = CGit::ms_LastMsysGitDir;
2028 msysdir.write();
2029 return TRUE;
2032 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2033 str = msyslocalinstalldir;
2034 str.TrimRight(_T("\\"));
2035 #ifdef _WIN64
2036 if (str.IsEmpty())
2038 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2039 str = msysinstalldir;
2040 str.TrimRight(_T("\\"));
2042 #endif
2043 if (str.IsEmpty())
2045 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2046 str = msysinstalldir;
2047 str.TrimRight(_T("\\"));
2049 if (!str.IsEmpty())
2051 if (PathFileExists(str + _T("\\bin\\git.exe")))
2052 str += _T("\\bin");
2053 else if (PathFileExists(str + _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2054 str += _T("\\cmd");
2055 else
2057 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR)str);
2058 return FALSE;
2060 msysdir = str;
2061 CGit::ms_LastMsysGitDir = str;
2062 msysdir.write();
2063 return TRUE;
2066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Found no git.exe\n"));
2067 return FALSE;
2070 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
2072 if (m_bInitialized)
2074 return TRUE;
2077 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
2078 this->m_Environment.clear();
2079 m_Environment.CopyProcessEnvironment();
2080 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2082 // set HOME if not set already
2083 size_t homesize;
2084 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
2085 if (!homesize)
2086 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
2088 //setup ssh client
2089 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
2090 if (sshclient.IsEmpty())
2091 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
2093 if(!sshclient.IsEmpty())
2095 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
2096 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
2098 else
2100 TCHAR sPlink[MAX_PATH] = {0};
2101 GetModuleFileName(NULL, sPlink, _countof(sPlink));
2102 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
2103 if (ptr) {
2104 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPlink.exe"));
2105 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
2106 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2111 TCHAR sAskPass[MAX_PATH] = {0};
2112 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2113 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2114 if (ptr)
2116 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2117 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2118 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2119 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2123 if (!FindAndSetGitExePath(bFallback))
2124 return FALSE;
2126 CString msysGitDir;
2127 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\"));
2128 static const CString prefixes[] = { L"mingw64\\etc", L"mingw32\\etc", L"etc" };
2129 static const int prefixes_len[] = { 8, 8, 0 };
2130 for (int i = 0; i < _countof(prefixes); ++i)
2132 #ifndef _WIN64
2133 if (i == 0)
2134 continue;
2135 #endif
2136 if (PathIsDirectory(msysGitDir + prefixes[i])) {
2137 msysGitDir += prefixes[i].Left(prefixes_len[i]);
2138 break;
2141 if (ms_bMsys2Git) // in Msys2 git.exe is in usr\bin; this also need to be after the check for etc folder, as Msys2 also has mingw64\etc, but uses etc
2142 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\.."));
2143 CGit::ms_MsysGitRootDir = msysGitDir;
2145 if ((CString)CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) != g_Git.GetGitSystemConfig())
2146 CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) = g_Git.GetGitSystemConfig();
2148 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2149 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR)CGit::ms_MsysGitRootDir);
2150 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": System config = %s\n"), (LPCTSTR)g_Git.GetGitSystemConfig());
2152 // Configure libgit2 search paths
2153 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2154 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2155 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2156 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2157 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition = { [](git_smart_subtransport **out, git_transport* owner, void*) -> int { return git_smart_subtransport_ssh_wintunnel(out, owner, FindExecutableOnPath(g_Git.m_Environment.GetEnv(_T("GIT_SSH")), g_Git.m_Environment.GetEnv(_T("PATH"))), g_Git.m_Environment); }, 0 };
2158 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2159 git_libgit2_opts(GIT_OPT_SET_USER_AGENT, "TortoiseGit libgit2");
2160 if (!(ms_bCygwinGit || ms_bMsys2Git))
2161 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("share\\git-core\\templates"));
2162 else
2163 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("usr\\share\\git-core\\templates"));
2165 m_Environment.AddToPath(CGit::ms_LastMsysGitDir);
2166 m_Environment.AddToPath((CString)CRegString(REG_MSYSGIT_EXTRA_PATH, _T(""), FALSE));
2168 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2169 // register filter only once
2170 if (!git_filter_lookup("filter"))
2172 CString sh;
2173 for (const CString& binDirPrefix : { L"\\..\\usr\\bin", L"\\..\\bin", L"" })
2175 CString possibleShExe = CGit::ms_LastMsysGitDir + binDirPrefix + L"\\sh.exe";
2176 if (PathFileExists(possibleShExe))
2178 CString temp;
2179 PathCanonicalize(CStrBuf(temp, MAX_PATH), possibleShExe);
2180 sh.Format(L"\"%s\"", (LPCTSTR)temp);
2181 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2182 m_Environment.AddToPath(temp.Left(temp.GetLength() - 7)); // 7 = len("\\sh.exe")
2183 break;
2187 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2188 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2189 CString gitExecPath = CGit::ms_MsysGitRootDir;
2190 gitExecPath.Append(_T("libexec\\git-core"));
2191 m_Environment.AddToPath(gitExecPath);
2193 if (git_filter_register("filter", git_filter_filter_new(sh, m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2194 return FALSE;
2196 #endif
2198 m_bInitialized = TRUE;
2199 return true;
2202 CString CGit::GetHomeDirectory() const
2204 const wchar_t * homeDir = wget_windows_home_directory();
2205 return CString(homeDir, (int)wcslen(homeDir));
2208 CString CGit::GetGitLocalConfig() const
2210 CString path;
2211 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2212 path += _T("config");
2213 return path;
2216 CStringA CGit::GetGitPathStringA(const CString &path)
2218 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2221 CString CGit::GetGitGlobalConfig() const
2223 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2226 CString CGit::GetGitGlobalXDGConfigPath() const
2228 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2231 CString CGit::GetGitGlobalXDGConfig() const
2233 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2236 CString CGit::GetGitSystemConfig() const
2238 const wchar_t * systemConfig = wget_msysgit_etc();
2239 return CString(systemConfig, (int)wcslen(systemConfig));
2242 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2244 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2246 CAutoRepository repo(GetGitRepository());
2247 if (!repo)
2248 return FALSE;
2250 if (git_repository_head_unborn(repo))
2251 return FALSE;
2253 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2254 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2255 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2257 CAutoStatusList status;
2258 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2259 return FALSE;
2261 return (0 == git_status_list_entrycount(status));
2264 CString out;
2265 CString cmd;
2266 cmd=_T("git.exe rev-parse --verify HEAD");
2268 if(Run(cmd,&out,CP_UTF8))
2269 return FALSE;
2271 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2272 if(Run(cmd,&out,CP_UTF8))
2273 return FALSE;
2275 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2276 if(Run(cmd,&out,CP_UTF8))
2277 return FALSE;
2279 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2280 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2281 return FALSE;
2283 return TRUE;
2285 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2287 int ret;
2288 for (int i = 0; i < list.GetCount(); ++i)
2290 ret = Revert(commit, (CTGitPath&)list[i], err);
2291 if(ret)
2292 return ret;
2294 return 0;
2296 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2298 CString cmd;
2300 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2302 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2304 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2305 return -1;
2307 if (path.Exists())
2309 CString force;
2310 // if the filenames only differ in case, we have to pass "-f"
2311 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2312 force = _T("-f ");
2313 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR)force, (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2314 if (Run(cmd, &err, CP_UTF8))
2315 return -1;
2317 else
2319 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR)path.GetGitPathString());
2320 if (Run(cmd, &err, CP_UTF8))
2321 return -1;
2324 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR)commit, (LPCTSTR)path.GetGitOldPathString());
2325 if (Run(cmd, &err, CP_UTF8))
2326 return -1;
2328 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2329 { //To init git repository, there are not HEAD, so we can use git reset command
2330 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR)path.GetGitPathString());
2332 if (Run(cmd, &err, CP_UTF8))
2333 return -1;
2335 else
2337 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR)commit, (LPCTSTR)path.GetGitPathString());
2338 if (Run(cmd, &err, CP_UTF8))
2339 return -1;
2342 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2344 cmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
2345 if (Run(cmd, &err, CP_UTF8))
2346 return -1;
2349 return 0;
2352 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2354 ATLASSERT(repo);
2356 CAutoIndex index;
2357 if (git_repository_index(index.GetPointer(), repo))
2358 return -1;
2360 return git_index_has_conflicts(index);
2363 int CGit::HasWorkingTreeConflicts()
2365 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2367 CAutoRepository repo(GetGitRepository());
2368 if (!repo)
2369 return -1;
2371 return HasWorkingTreeConflicts(repo);
2374 CString cmd = _T("git.exe ls-files -u -t -z");
2376 CString output;
2377 if (Run(cmd, &output, &gitLastErr, CP_UTF8))
2378 return -1;
2380 return output.IsEmpty() ? 0 : 1;
2383 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2385 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2387 CAutoRepository repo(GetGitRepository());
2388 if (!repo)
2389 return false;
2391 CGitHash fromHash, toHash, baseHash;
2392 if (GetHash(repo, toHash, FixBranchName(to)))
2393 return false;
2395 if (GetHash(repo, fromHash, FixBranchName(from)))
2396 return false;
2398 git_oid baseOid;
2399 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2400 return false;
2402 baseHash = baseOid.id;
2404 if (commonAncestor)
2405 *commonAncestor = baseHash;
2407 return fromHash == baseHash;
2409 // else
2410 CString base;
2411 CGitHash basehash,hash;
2412 CString cmd;
2413 cmd.Format(_T("git.exe merge-base %s %s"), (LPCTSTR)FixBranchName(to), (LPCTSTR)FixBranchName(from));
2415 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2417 return false;
2419 basehash = base.Trim();
2421 GetHash(hash, from);
2423 if (commonAncestor)
2424 *commonAncestor = basehash;
2426 return hash == basehash;
2429 unsigned int CGit::Hash2int(const CGitHash &hash)
2431 int ret=0;
2432 for (int i = 0; i < 4; ++i)
2434 ret = ret << 8;
2435 ret |= hash.m_hash[i];
2437 return ret;
2440 int CGit::RefreshGitIndex()
2442 if(g_Git.m_IsUseGitDLL)
2444 CAutoLocker lock(g_Git.m_critGitDllSec);
2447 int result = [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2448 git_exit_cleanup();
2449 return result;
2451 }catch(...)
2453 git_exit_cleanup();
2454 return -1;
2458 else
2460 CString cmd,output;
2461 cmd=_T("git.exe update-index --refresh");
2462 return Run(cmd, &output, CP_UTF8);
2466 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2468 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2470 CAutoRepository repo(GetGitRepository());
2471 if (!repo)
2472 return -1;
2474 CGitHash hash;
2475 if (GetHash(repo, hash, Refname))
2476 return -1;
2478 CAutoCommit commit;
2479 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2480 return -1;
2482 CAutoTree tree;
2483 if (git_commit_tree(tree.GetPointer(), commit))
2484 return -1;
2486 CAutoTreeEntry entry;
2487 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2488 return -1;
2490 CAutoBlob blob;
2491 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2492 return -1;
2494 CAutoFILE file = _tfsopen(outputfile, _T("wb"), SH_DENYWR);
2495 if (file == nullptr)
2497 giterr_set_str(GITERR_NONE, "Could not create file.");
2498 return -1;
2500 CAutoBuf buf;
2501 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2502 return -1;
2503 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2505 giterr_set_str(GITERR_OS, "Could not write to file.");
2506 return -1;
2509 return 0;
2511 else if (g_Git.m_IsUseGitDLL)
2513 CAutoLocker lock(g_Git.m_critGitDllSec);
2516 g_Git.CheckAndInitDll();
2517 CStringA ref, patha, outa;
2518 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2519 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2520 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2521 ::DeleteFile(outputfile);
2522 int ret = git_checkout_file(ref, patha, outa.GetBuffer());
2523 outa.ReleaseBuffer();
2524 return ret;
2527 catch (const char * msg)
2529 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2530 return -1;
2532 catch (...)
2534 gitLastErr = L"An unknown gitdll.dll error occurred.";
2535 return -1;
2538 else
2540 CString cmd;
2541 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR)Refname, (LPCTSTR)path.GetGitPathString());
2542 return RunLogFile(cmd, outputfile, &gitLastErr);
2546 void CEnvironment::clear()
2548 __super::clear();
2551 bool CEnvironment::empty()
2553 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2556 CEnvironment::operator LPTSTR()
2558 if (empty())
2559 return nullptr;
2560 return &__super::at(0);
2563 void CEnvironment::CopyProcessEnvironment()
2565 if (!empty())
2566 pop_back();
2567 TCHAR *porig = GetEnvironmentStrings();
2568 TCHAR *p = porig;
2569 while(*p !=0 || *(p+1) !=0)
2570 this->push_back(*p++);
2572 push_back(_T('\0'));
2573 push_back(_T('\0'));
2575 FreeEnvironmentStrings(porig);
2578 CString CEnvironment::GetEnv(const TCHAR *name)
2580 CString str;
2581 for (size_t i = 0; i < size(); ++i)
2583 str = &(*this)[i];
2584 int start =0;
2585 CString sname = str.Tokenize(_T("="),start);
2586 if(sname.CompareNoCase(name) == 0)
2588 return &(*this)[i+start];
2590 i+=str.GetLength();
2592 return _T("");
2595 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2597 unsigned int i;
2598 for (i = 0; i < size(); ++i)
2600 CString str = &(*this)[i];
2601 int start =0;
2602 CString sname = str.Tokenize(_T("="),start);
2603 if(sname.CompareNoCase(name) == 0)
2605 break;
2607 i+=str.GetLength();
2610 if(i == size())
2612 if (!value) // as we haven't found the variable we want to remove, just return
2613 return;
2614 if (i == 0) // make inserting into an empty environment work
2616 this->push_back(_T('\0'));
2617 ++i;
2619 i -= 1; // roll back terminate \0\0
2620 this->push_back(_T('\0'));
2623 CEnvironment::iterator it;
2624 it=this->begin();
2625 it += i;
2627 while(*it && i<size())
2629 this->erase(it);
2630 it=this->begin();
2631 it += i;
2634 if (value == nullptr) // remove the variable
2636 this->erase(it);
2637 return;
2640 while(*name)
2642 this->insert(it,*name++);
2643 ++i;
2644 it= begin()+i;
2647 this->insert(it, _T('='));
2648 ++i;
2649 it= begin()+i;
2651 while(*value)
2653 this->insert(it,*value++);
2654 ++i;
2655 it= begin()+i;
2660 void CEnvironment::AddToPath(CString value)
2662 value.TrimRight(L"\\");
2663 if (value.IsEmpty())
2664 return;
2666 CString path = GetEnv(L"PATH").TrimRight(L";") + L";";
2668 // do not double add paths to %PATH%
2669 if (path.Find(value + L";") >= 0 || path.Find(value + L"\\;") >= 0)
2670 return;
2672 path += value;
2674 SetEnv(L"PATH", path);
2677 int CGit::GetGitEncode(TCHAR* configkey)
2679 CString str=GetConfigValue(configkey);
2681 if(str.IsEmpty())
2682 return CP_UTF8;
2684 return CUnicodeUtils::GetCPCode(str);
2688 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2690 GIT_FILE file=0;
2691 int ret=0;
2692 GIT_DIFF diff=0;
2694 CAutoLocker lock(g_Git.m_critGitDllSec);
2698 if(!arg)
2699 diff = GetGitDiff();
2700 else
2701 git_open_diff(&diff, arg);
2703 catch (char* e)
2705 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2706 return -1;
2709 if(diff ==NULL)
2710 return -1;
2712 bool isStat = 0;
2713 if(arg == NULL)
2714 isStat = true;
2715 else
2716 isStat = !!strstr(arg, "stat");
2718 int count=0;
2720 if(hash2 == NULL)
2721 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2722 else
2723 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2725 if(ret)
2726 return -1;
2728 CTGitPath path;
2729 CString strnewname;
2730 CString stroldname;
2732 for (int j = 0; j < count; ++j)
2734 path.Reset();
2735 char *newname;
2736 char *oldname;
2738 strnewname.Empty();
2739 stroldname.Empty();
2741 int mode=0,IsBin=0,inc=0,dec=0;
2742 git_get_diff_file(diff,file,j,&newname,&oldname,
2743 &mode,&IsBin,&inc,&dec);
2745 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2746 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2748 path.SetFromGit(strnewname,&stroldname);
2749 path.ParserAction((BYTE)mode);
2751 if(IsBin)
2753 path.m_StatAdd=_T("-");
2754 path.m_StatDel=_T("-");
2756 else
2758 path.m_StatAdd.Format(_T("%d"),inc);
2759 path.m_StatDel.Format(_T("%d"),dec);
2761 PathList->AddPath(path);
2763 git_diff_flush(diff);
2765 if(arg)
2766 git_close_diff(diff);
2768 return 0;
2771 int CGit::GetShortHASHLength() const
2773 return 7;
2776 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2778 CString str=ref;
2779 CString shortname;
2780 REF_TYPE type = CGit::UNKNOWN;
2782 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2784 type = CGit::LOCAL_BRANCH;
2787 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2789 type = CGit::REMOTE_BRANCH;
2791 else if (str.Right(3) == L"^{}" && CGit::GetShortName(str, shortname, L"refs/tags/"))
2792 type = CGit::ANNOTATED_TAG;
2793 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2795 type = CGit::TAG;
2797 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2799 type = CGit::STASH;
2800 shortname=_T("stash");
2802 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2804 CString bisectGood;
2805 CString bisectBad;
2806 g_Git.GetBisectTerms(&bisectGood, &bisectBad);
2807 TCHAR c;
2808 if (shortname.Find(bisectGood) == 0 && ((c = shortname.GetAt(bisectGood.GetLength())) == '-' || c == '\0'))
2810 type = CGit::BISECT_GOOD;
2811 shortname = bisectGood;
2814 if (shortname.Find(bisectBad) == 0 && ((c = shortname.GetAt(bisectBad.GetLength())) == '-' || c == '\0'))
2816 type = CGit::BISECT_BAD;
2817 shortname = bisectBad;
2820 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2822 type = CGit::NOTES;
2824 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2826 type = CGit::UNKNOWN;
2828 else
2830 type = CGit::UNKNOWN;
2831 shortname = ref;
2834 if(out_type)
2835 *out_type = type;
2837 return shortname;
2840 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2842 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2845 void CGit::SetGit2CredentialCallback(void* callback)
2847 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2850 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2852 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2855 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix)
2857 CString cmd;
2858 if (rev2 == GitRev::GetWorkingCopy())
2859 cmd.Format(_T("git.exe diff --stat%s -p %s --"), bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev1);
2860 else if (rev1 == GitRev::GetWorkingCopy())
2861 cmd.Format(_T("git.exe diff -R --stat%s %s-p %s --"), bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev2);
2862 else
2864 CString merge;
2865 if (bMerge)
2866 merge += _T(" -m");
2868 if (bCombine)
2869 merge += _T(" -c");
2871 CString unified;
2872 if (diffContext >= 0)
2873 unified.Format(_T(" --unified=%d"), diffContext);
2874 cmd.Format(_T("git.exe diff-tree -r -p%s%s --stat%s %s %s --"), (LPCTSTR)merge, (LPCTSTR)unified, bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev1, (LPCTSTR)rev2);
2877 if (!path.IsEmpty())
2879 cmd += _T(" \"");
2880 cmd += path.GetGitPathString();
2881 cmd += _T("\"");
2884 return cmd;
2887 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2889 ATLASSERT(payload && text);
2890 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2891 fwrite("\n", 1, 1, (FILE *)payload);
2894 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2896 ATLASSERT(payload && line);
2897 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2898 fwrite(&line->origin, 1, 1, (FILE *)payload);
2899 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2900 return 0;
2903 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2905 ATLASSERT(repo && identifier && tree);
2907 /* try to resolve identifier */
2908 CAutoObject obj;
2909 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2910 return -1;
2912 if (obj == nullptr)
2913 return GIT_ENOTFOUND;
2915 int err = 0;
2916 switch (git_object_type(obj))
2918 case GIT_OBJ_TREE:
2919 *tree = (git_tree *)obj.Detach();
2920 break;
2921 case GIT_OBJ_COMMIT:
2922 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2923 break;
2924 default:
2925 err = GIT_ENOTFOUND;
2928 return err;
2931 /* use libgit2 get unified diff */
2932 static int GetUnifiedDiffLibGit2(const CTGitPath& path, const git_revnum_t& revOld, const git_revnum_t& revNew, std::function<void(const git_buf*, void*)> statCallback, git_diff_line_cb callback, void* data, bool /* bMerge */, bool bNoPrefix)
2934 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2935 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2937 CAutoRepository repo(g_Git.GetGitRepository());
2938 if (!repo)
2939 return -1;
2941 int isHeadOrphan = git_repository_head_unborn(repo);
2942 if (isHeadOrphan == 1)
2943 return 0;
2944 else if (isHeadOrphan != 0)
2945 return -1;
2947 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2948 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2949 char *buf = pathA.GetBuffer();
2950 if (!pathA.IsEmpty())
2952 opts.pathspec.strings = &buf;
2953 opts.pathspec.count = 1;
2955 if (bNoPrefix)
2957 opts.new_prefix = "";
2958 opts.old_prefix = "";
2960 CAutoDiff diff;
2962 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2964 CAutoTree t1;
2965 CAutoDiff diff2;
2967 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2968 return -1;
2970 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2971 return -1;
2973 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2974 return -1;
2976 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2977 return -1;
2979 if (git_diff_merge(diff, diff2))
2980 return -1;
2982 else
2984 if (tree1.IsEmpty() && tree2.IsEmpty())
2985 return -1;
2987 if (tree1.IsEmpty())
2989 tree1 = tree2;
2990 tree2.Empty();
2993 CAutoTree t1;
2994 CAutoTree t2;
2995 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2996 return -1;
2998 if (tree2.IsEmpty())
3000 /* don't check return value, there are not parent commit at first commit*/
3001 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
3003 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
3004 return -1;
3005 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
3006 return -1;
3009 CAutoDiffStats stats;
3010 if (git_diff_get_stats(stats.GetPointer(), diff))
3011 return -1;
3012 CAutoBuf statBuf;
3013 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
3014 return -1;
3015 statCallback(statBuf, data);
3017 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
3019 CAutoPatch patch;
3020 if (git_patch_from_diff(patch.GetPointer(), diff, i))
3021 return -1;
3023 if (git_patch_print(patch, callback, data))
3024 return -1;
3027 pathA.ReleaseBuffer();
3029 return 0;
3032 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix)
3034 if (UsingLibGit2(GIT_CMD_DIFF))
3036 CAutoFILE file = _tfsopen(patchfile, _T("w"), SH_DENYRW);
3037 if (!file)
3038 return -1;
3039 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge, bNoPrefix);
3041 else
3043 CString cmd;
3044 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext, bNoPrefix);
3045 return RunLogFile(cmd, patchfile, &gitLastErr);
3049 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
3051 ATLASSERT(payload && text);
3052 CStringA *str = (CStringA*) payload;
3053 str->Append(text->ptr, (int)text->size);
3054 str->AppendChar('\n');
3057 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
3059 ATLASSERT(payload && line);
3060 CStringA *str = (CStringA*) payload;
3061 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
3062 str->Append(&line->origin, 1);
3063 str->Append(line->content, (int)line->content_len);
3064 return 0;
3067 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
3069 if (UsingLibGit2(GIT_CMD_DIFF))
3070 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge, false);
3071 else
3073 CString cmd;
3074 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3075 BYTE_VECTOR vector;
3076 int ret = Run(cmd, &vector);
3077 if (!vector.empty())
3079 vector.push_back(0); // vector is not NUL terminated
3080 buffer->Append((char *)&vector[0]);
3082 return ret;
3086 int CGit::GitRevert(int parent, const CGitHash &hash)
3088 if (UsingLibGit2(GIT_CMD_REVERT))
3090 CAutoRepository repo(GetGitRepository());
3091 if (!repo)
3092 return -1;
3094 CAutoCommit commit;
3095 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
3096 return -1;
3098 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3099 revert_opts.mainline = parent;
3100 int result = git_revert(repo, commit, &revert_opts);
3102 return !result ? 0 : -1;
3104 else
3106 CString cmd, merge;
3107 if (parent)
3108 merge.Format(_T("-m %d "), parent);
3109 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR)merge, (LPCTSTR)hash.ToString());
3110 gitLastErr = cmd + _T("\n");
3111 if (Run(cmd, &gitLastErr, CP_UTF8))
3113 return -1;
3115 else
3117 gitLastErr.Empty();
3118 return 0;
3123 int CGit::DeleteRef(const CString& reference)
3125 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3127 CAutoRepository repo(GetGitRepository());
3128 if (!repo)
3129 return -1;
3131 CStringA refA;
3132 if (reference.Right(3) == _T("^{}"))
3133 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3134 else
3135 refA = CUnicodeUtils::GetUTF8(reference);
3137 CAutoReference ref;
3138 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3139 return -1;
3141 int result = -1;
3142 if (git_reference_is_tag(ref))
3143 result = git_tag_delete(repo, git_reference_shorthand(ref));
3144 else if (git_reference_is_branch(ref))
3145 result = git_branch_delete(ref);
3146 else if (git_reference_is_remote(ref))
3147 result = git_branch_delete(ref);
3148 else
3149 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
3151 return result;
3153 else
3155 CString cmd, shortname;
3156 if (GetShortName(reference, shortname, _T("refs/heads/")))
3157 cmd.Format(_T("git.exe branch -D -- %s"), (LPCTSTR)shortname);
3158 else if (GetShortName(reference, shortname, _T("refs/tags/")))
3159 cmd.Format(_T("git.exe tag -d -- %s"), (LPCTSTR)shortname);
3160 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
3161 cmd.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR)shortname);
3162 else
3164 gitLastErr = L"unsupported reference type: " + reference;
3165 return -1;
3168 if (Run(cmd, &gitLastErr, CP_UTF8))
3169 return -1;
3171 gitLastErr.Empty();
3172 return 0;
3176 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3178 if (!PathFileExists(filename))
3179 return false;
3181 CAutoFILE pFile = _tfsopen(filename, _T("r"), SH_DENYWR);
3182 if (!pFile)
3184 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3185 return true; // load no further files
3188 CStringA str;
3191 char s[8196] = { 0 };
3192 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3193 if (read == 0)
3194 break;
3195 str += CStringA(s, read);
3196 } while (true);
3197 msg = CUnicodeUtils::GetUnicode(str);
3198 msg.Replace(_T("\r\n"), _T("\n"));
3199 msg.TrimRight(_T("\n"));
3200 msg += _T("\n");
3202 return true; // load no further files
3205 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, CTGitPathList* filterlist)
3207 if (IsInitRepos())
3208 return GetInitAddList(result);
3210 BYTE_VECTOR out;
3212 int count = 1;
3213 if (filterlist)
3214 count = filterlist->GetCount();
3216 CString head = _T("HEAD");
3217 if (amend)
3218 head = _T("HEAD~1");
3220 for (int i = 0; i < count; ++i)
3222 BYTE_VECTOR cmdout;
3223 CString cmd;
3224 if (ms_bCygwinGit || ms_bMsys2Git)
3226 // Prevent showing all files as modified when using cygwin's git
3227 if (!filterlist)
3228 cmd = _T("git.exe status --");
3229 else
3230 cmd.Format(_T("git.exe status -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3231 Run(cmd, &cmdout);
3232 cmdout.clear();
3235 // also list staged files which will be in the commit
3236 Run(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"), &cmdout);
3238 if (!filterlist)
3239 cmd = (_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3240 else
3241 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3243 BYTE_VECTOR cmdErr;
3244 if (Run(cmd, &cmdout, &cmdErr))
3246 int last = cmdErr.RevertFind(0, -1);
3247 CString str;
3248 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last - 1);
3249 MessageBox(nullptr, str, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3252 out.append(cmdout, 0);
3254 result.ParserFromLog(out);
3256 std::map<CString, int> duplicateMap;
3257 for (int i = 0; i < result.GetCount(); ++i)
3258 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), i));
3260 // handle delete conflict case, when remote : modified, local : deleted.
3261 for (int i = 0; i < count; ++i)
3263 BYTE_VECTOR cmdout;
3264 CString cmd;
3266 if (!filterlist)
3267 cmd = _T("git.exe ls-files -u -t -z");
3268 else
3269 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3271 Run(cmd, &cmdout);
3273 CTGitPathList conflictlist;
3274 conflictlist.ParserFromLog(cmdout);
3275 for (int j = 0; j < conflictlist.GetCount(); ++j)
3277 auto existing = duplicateMap.find(conflictlist[j].GetGitPathString());
3278 if (existing != duplicateMap.end())
3280 CTGitPath& p = const_cast<CTGitPath&>(result[existing->second]);
3281 p.m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3283 else
3285 result.AddPath(conflictlist[j]);
3286 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), result.GetCount() - 1));
3291 // handle source files of file renames/moves (issue #860)
3292 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3293 for (int i = 0; i < count; ++i)
3295 BYTE_VECTOR cmdout;
3296 CString cmd;
3298 if (!filterlist)
3299 cmd = _T("git.exe ls-files -d -z");
3300 else
3301 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3303 Run(cmd, &cmdout);
3305 CTGitPathList deletelist;
3306 deletelist.ParserFromLog(cmdout, true);
3307 for (int j = 0; j < deletelist.GetCount(); ++j)
3309 auto existing = duplicateMap.find(deletelist[j].GetGitPathString());
3310 if (existing == duplicateMap.end())
3312 result.AddPath(deletelist[j]);
3313 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), result.GetCount() - 1));
3315 else
3317 CTGitPath& p = const_cast<CTGitPath&>(result[existing->second]);
3318 p.m_Action |= CTGitPath::LOGACTIONS_MISSING;
3323 return 0;
3326 int CGit::IsRebaseRunning()
3328 CString adminDir;
3329 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3330 return -1;
3332 if (PathIsDirectory(adminDir + L"rebase-apply") || PathIsDirectory(adminDir + L"tgitrebase.active"))
3333 return 1;
3334 return 0;
3337 void CGit::GetBisectTerms(CString* good, CString* bad)
3339 static CString lastGood;
3340 static CString lastBad;
3341 static ULONGLONG lastRead = 0;
3343 SCOPE_EXIT
3345 if (bad)
3346 *bad = lastBad;
3347 if (good)
3348 *good = lastGood;
3351 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3352 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3353 // as we only read a small file the performance effects should be negligible
3354 if (lastRead + 5000 > GetTickCount64())
3355 return;
3356 #endif
3358 lastGood = L"good";
3359 lastBad = L"bad";
3361 CString adminDir;
3362 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir, adminDir))
3363 return;
3365 CString termsFile = adminDir + L"BISECT_TERMS";
3366 CAutoFILE fp;
3367 _tfopen_s(fp.GetPointer(), termsFile, L"rb");
3368 if (!fp)
3369 return;
3370 char badA[MAX_PATH] = { 0 };
3371 fgets(badA, MAX_PATH, fp);
3372 size_t len = strlen(badA);
3373 if (len > 0 && badA[len - 1] == '\n')
3374 badA[len - 1] = '\0';
3375 char goodA[MAX_PATH] = { 0 };
3376 fgets(goodA, MAX_PATH, fp);
3377 len = strlen(goodA);
3378 if (len > 0 && goodA[len - 1] == '\n')
3379 goodA[len - 1] = '\0';
3380 lastGood = CUnicodeUtils::GetUnicode(goodA);
3381 lastBad = CUnicodeUtils::GetUnicode(badA);
3382 lastRead = GetTickCount64();
3385 int CGit::GetGitVersion(CString* versiondebug, CString* errStr)
3387 CString version, err;
3388 if (Run(_T("git.exe --version"), &version, &err, CP_UTF8))
3390 if (errStr)
3391 *errStr = err;
3392 return -1;
3395 int start = 0;
3396 int ver = 0;
3397 if (versiondebug)
3398 *versiondebug = version;
3402 CString str = version.Tokenize(_T("."), start);
3403 int space = str.ReverseFind(_T(' '));
3404 str = str.Mid(space + 1, start);
3405 ver = _ttol(str);
3406 ver <<= 24;
3408 version = version.Mid(start);
3409 start = 0;
3411 str = version.Tokenize(_T("."), start);
3412 ver |= (_ttol(str) & 0xFF) << 16;
3414 str = version.Tokenize(_T("."), start);
3415 ver |= (_ttol(str) & 0xFF) << 8;
3417 str = version.Tokenize(_T("."), start);
3418 ver |= (_ttol(str) & 0xFF);
3420 catch (...)
3422 if (!ver)
3423 return -1;
3426 return ver;