Refactored: Replace 'count' parameter of CGit::GetLogCmd() with CFilterData::m_Number...
[TortoiseGit.git] / src / Git / Git.cpp
blobd7c8dc53c213e1ac5e202d3c64502ff91d6be802
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - 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 inline BOOL FileExists(LPCTSTR lpszFileName)
62 struct _stat st;
63 return _tstat(lpszFileName, &st) == 0;
66 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
68 TCHAR buf[MAX_PATH] = { 0 };
70 // search in all paths defined in PATH
71 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
73 TCHAR *pfin = buf + _tcslen(buf) - 1;
75 // ensure trailing slash
76 if (*pfin != _T('/') && *pfin != _T('\\'))
77 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
79 const size_t len = _tcslen(buf);
81 if ((len + filename.GetLength()) < MAX_PATH)
82 _tcscpy_s(pfin + 1, MAX_PATH - len, filename);
83 else
84 break;
86 if (FileExists(buf))
88 if (wantDirectory)
89 pfin[1] = 0;
90 return buf;
94 return _T("");
97 static BOOL FindGitPath()
99 size_t size;
100 _tgetenv_s(&size, NULL, 0, _T("PATH"));
101 if (!size)
102 return FALSE;
104 TCHAR* env = (TCHAR*)alloca(size * sizeof(TCHAR));
105 if (!env)
106 return FALSE;
107 _tgetenv_s(&size, env, size, _T("PATH"));
109 CString gitExeDirectory = FindFileOnPath(_T("git.exe"), env, true);
110 if (!gitExeDirectory.IsEmpty())
112 CGit::ms_LastMsysGitDir = gitExeDirectory;
113 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
114 if (CGit::ms_LastMsysGitDir.GetLength() > 12 && (CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw64\\bin")))
116 // prefer cmd directory as early Git for Windows 2.x releases only had this
117 CString installRoot = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd\\git.exe");
118 if (FileExists(installRoot))
119 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd");
121 if (CGit::ms_LastMsysGitDir.GetLength() > 4 && CGit::ms_LastMsysGitDir.Right(4) == _T("\\cmd"))
123 // often the msysgit\cmd folder is on the %PATH%, but
124 // that git.exe does not work, so try to guess the bin folder
125 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
126 if (FileExists(binDir))
127 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
129 return TRUE;
132 return FALSE;
135 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
137 CString filename = executable;
139 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
140 filename += _T(".exe");
142 if (FileExists(filename))
143 return filename;
145 filename = FindFileOnPath(filename, env);
146 if (!filename.IsEmpty())
147 return filename;
149 return executable;
152 static bool g_bSortLogical;
153 static bool g_bSortLocalBranchesFirst;
154 static bool g_bSortTagsReversed;
155 static git_cred_acquire_cb g_Git2CredCallback;
156 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
158 static void GetSortOptions()
160 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
161 if (g_bSortLogical)
162 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
163 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
164 if (g_bSortLocalBranchesFirst)
165 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
166 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
167 if (!g_bSortTagsReversed)
168 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
171 static int LogicalComparePredicate(const CString &left, const CString &right)
173 if (g_bSortLogical)
174 return StrCmpLogicalW(left, right) < 0;
175 return StrCmpI(left, right) < 0;
178 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
180 if (g_bSortLogical)
181 return StrCmpLogicalW(left, right) > 0;
182 return StrCmpI(left, right) > 0;
185 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
187 if (g_bSortLocalBranchesFirst)
189 int leftIsRemote = left.Find(_T("remotes/"));
190 int rightIsRemote = right.Find(_T("remotes/"));
192 if (leftIsRemote == 0 && rightIsRemote < 0)
193 return false;
194 else if (leftIsRemote < 0 && rightIsRemote == 0)
195 return true;
197 if (g_bSortLogical)
198 return StrCmpLogicalW(left, right) < 0;
199 return StrCmpI(left, right) < 0;
202 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
204 CString CGit::ms_LastMsysGitDir;
205 CString CGit::ms_MsysGitRootDir;
206 int CGit::ms_LastMsysGitVersion = 0;
207 CGit g_Git;
210 CGit::CGit(void)
212 GetCurrentDirectory(MAX_PATH, CStrBuf(m_CurrentDir, MAX_PATH));
213 m_IsGitDllInited = false;
214 m_GitDiff=0;
215 m_GitSimpleListDiff=0;
216 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
217 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
218 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK);
220 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
222 GetSortOptions();
223 this->m_bInitialized =false;
224 CheckMsysGitDir();
225 m_critGitDllSec.Init();
228 CGit::~CGit(void)
230 if(this->m_GitDiff)
232 git_close_diff(m_GitDiff);
233 m_GitDiff=0;
235 if(this->m_GitSimpleListDiff)
237 git_close_diff(m_GitSimpleListDiff);
238 m_GitSimpleListDiff=0;
242 bool CGit::IsBranchNameValid(const CString& branchname)
244 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
245 return false;
246 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
247 return false;
248 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
249 return !!git_reference_is_valid_name(branchA);
252 static bool IsPowerShell(CString cmd)
254 cmd.MakeLower();
255 int powerShellPos = cmd.Find(_T("powershell"));
256 if (powerShellPos < 0)
257 return false;
259 // found the word powershell, check that it is the command and not any parameter
260 int end = cmd.GetLength();
261 if (cmd.Find(_T('"')) == 0)
263 int secondDoubleQuote = cmd.Find(_T('"'), 1);
264 if (secondDoubleQuote > 0)
265 end = secondDoubleQuote;
267 else
269 int firstSpace = cmd.Find(_T(' '));
270 if (firstSpace > 0)
271 end = firstSpace;
274 return (end - 4 - 10 == powerShellPos || end - 10 == powerShellPos); // len(".exe")==4, len("powershell")==10
277 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
279 SECURITY_ATTRIBUTES sa;
280 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
281 CAutoGeneralHandle hStdioFile;
283 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
284 sa.lpSecurityDescriptor=NULL;
285 sa.bInheritHandle=TRUE;
286 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
288 CString err = CFormatMessageWrapper();
289 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), (LPCTSTR)err.Trim());
290 return TGIT_GIT_ERROR_OPEN_PIP;
292 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
294 CString err = CFormatMessageWrapper();
295 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), (LPCTSTR)err.Trim());
296 return TGIT_GIT_ERROR_OPEN_PIP;
299 if(StdioFile)
301 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
302 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
305 STARTUPINFO si = { 0 };
306 PROCESS_INFORMATION pi;
307 si.cb=sizeof(STARTUPINFO);
309 if (hErrReadOut)
310 si.hStdError = hWriteErr;
311 else
312 si.hStdError = hWrite;
313 if(StdioFile)
314 si.hStdOutput=hStdioFile;
315 else
316 si.hStdOutput=hWrite;
318 si.wShowWindow=SW_HIDE;
319 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
321 LPTSTR pEnv = m_Environment;
322 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
324 dwFlags |= CREATE_NEW_PROCESS_GROUP;
326 // 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,
327 // 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)
328 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
329 if (IsPowerShell(cmd))
330 dwFlags |= CREATE_NEW_CONSOLE;
331 else
332 dwFlags |= DETACHED_PROCESS;
334 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
335 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
337 if (ms_bMsys2Git && cmd.Find(_T("git")) == 0 && cmd.Find(L"git.exe config ") == -1)
339 cmd.Replace(_T("\\"), _T("\\\\\\\\"));
340 cmd.Replace(_T("\""), _T("\\\""));
341 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/usr/bin/") + cmd + _T('"');
343 else if (ms_bCygwinGit && cmd.Find(_T("git")) == 0 && cmd.Find(L"git.exe config ") == -1)
345 cmd.Replace(_T('\\'), _T('/'));
346 cmd.Replace(_T("\""), _T("\\\""));
347 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
349 else if(cmd.Find(_T("git")) == 0)
351 int firstSpace = cmd.Find(_T(" "));
352 if (firstSpace > 0)
353 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
354 else
355 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
358 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), (LPCTSTR)cmd);
359 if(!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, TRUE, dwFlags, pEnv, m_CurrentDir.GetBuffer(), &si, &pi))
361 CString err = CFormatMessageWrapper();
362 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), (LPCTSTR)err.Trim());
363 return TGIT_GIT_ERROR_CREATE_PROCESS;
366 m_CurrentGitPi = pi;
368 if(piOut)
369 *piOut=pi;
370 if(hReadOut)
371 *hReadOut = hRead.Detach();
372 if(hErrReadOut)
373 *hErrReadOut = hReadErr.Detach();
374 return 0;
377 //Must use sperate function to convert ANSI str to union code string
378 //Becuase A2W use stack as internal convert buffer.
379 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
381 if(str == NULL)
382 return ;
384 int len ;
385 if(length<0)
386 len = (int)strlen((const char*)p);
387 else
388 len=length;
389 if (len == 0)
390 return;
391 int currentContentLen = str->GetLength();
392 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
393 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
394 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
397 // This method was originally used to check for orphaned branches
398 BOOL CGit::CanParseRev(CString ref)
400 if (ref.IsEmpty())
401 ref = _T("HEAD");
403 CString cmdout;
404 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
406 return FALSE;
408 if(cmdout.IsEmpty())
409 return FALSE;
411 return TRUE;
414 // Checks if we have an orphaned HEAD
415 BOOL CGit::IsInitRepos()
417 CGitHash hash;
418 if (GetHash(hash, _T("HEAD")) != 0)
419 return FALSE;
420 return hash.IsEmpty() ? TRUE : FALSE;
423 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
425 PASYNCREADSTDERRTHREADARGS pDataArray;
426 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
428 DWORD readnumber;
429 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
430 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
432 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
433 break;
436 return 0;
439 int CGit::Run(CGitCall* pcall)
441 PROCESS_INFORMATION pi;
442 CAutoGeneralHandle hRead, hReadErr;
443 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
444 return TGIT_GIT_ERROR_CREATE_PROCESS;
446 CAutoGeneralHandle piThread(pi.hThread);
447 CAutoGeneralHandle piProcess(pi.hProcess);
449 ASYNCREADSTDERRTHREADARGS threadArguments;
450 threadArguments.fileHandle = hReadErr;
451 threadArguments.pcall = pcall;
452 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
454 DWORD readnumber;
455 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
456 bool bAborted=false;
457 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
459 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
460 if(!bAborted)//For now, flush output when command aborted.
461 if(pcall->OnOutputData(data,readnumber))
462 bAborted=true;
464 if(!bAborted)
465 pcall->OnEnd();
467 if (thread)
468 WaitForSingleObject(thread, INFINITE);
470 WaitForSingleObject(pi.hProcess, INFINITE);
471 DWORD exitcode =0;
473 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
475 CString err = CFormatMessageWrapper();
476 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), (LPCTSTR)err.Trim());
477 return TGIT_GIT_ERROR_GET_EXIT_CODE;
479 else
480 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
482 return exitcode;
484 class CGitCall_ByteVector : public CGitCall
486 public:
487 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
488 virtual bool OnOutputData(const BYTE* data, size_t size)
490 if (!m_pvector || size == 0)
491 return false;
492 size_t oldsize=m_pvector->size();
493 m_pvector->resize(m_pvector->size()+size);
494 memcpy(&*(m_pvector->begin()+oldsize),data,size);
495 return false;
497 virtual bool OnOutputErrData(const BYTE* data, size_t size)
499 if (!m_pvectorErr || size == 0)
500 return false;
501 size_t oldsize = m_pvectorErr->size();
502 m_pvectorErr->resize(m_pvectorErr->size() + size);
503 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
504 return false;
506 BYTE_VECTOR* m_pvector;
507 BYTE_VECTOR* m_pvectorErr;
510 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
512 CGitCall_ByteVector call(cmd, vector, vectorErr);
513 return Run(&call);
515 int CGit::Run(CString cmd, CString* output, int code)
517 CString err;
518 int ret;
519 ret = Run(cmd, output, &err, code);
521 if (output && !err.IsEmpty())
523 if (!output->IsEmpty())
524 *output += _T("\n");
525 *output += err;
528 return ret;
530 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
532 BYTE_VECTOR vector, vectorErr;
533 int ret;
534 if (outputErr)
535 ret = Run(cmd, &vector, &vectorErr);
536 else
537 ret = Run(cmd, &vector);
539 vector.push_back(0);
540 StringAppend(output, &(vector[0]), code);
542 if (outputErr)
544 vectorErr.push_back(0);
545 StringAppend(outputErr, &(vectorErr[0]), code);
548 return ret;
551 class CGitCallCb : public CGitCall
553 public:
554 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
556 virtual bool OnOutputData(const BYTE* data, size_t size) override
558 // Add data
559 if (size == 0)
560 return false;
561 int oldEndPos = m_buffer.GetLength();
562 memcpy(m_buffer.GetBuffer(oldEndPos + (int)size) + oldEndPos, data, size);
563 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
565 // Break into lines and feed to m_recv
566 int eolPos;
567 while ((eolPos = m_buffer.Find('\n')) >= 0)
569 m_recv(m_buffer.Left(eolPos));
570 m_buffer = m_buffer.Mid(eolPos + 1);
572 return false;
575 virtual bool OnOutputErrData(const BYTE*, size_t) override
577 return false; // Ignore error output for now
580 virtual void OnEnd() override
582 if (!m_buffer.IsEmpty())
583 m_recv(m_buffer);
584 m_buffer.Empty(); // Just for sure
587 private:
588 GitReceiverFunc m_recv;
589 CStringA m_buffer;
592 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
594 CGitCallCb call(cmd, recv);
595 return Run(&call);
598 CString CGit::GetUserName(void)
600 CEnvironment env;
601 env.CopyProcessEnvironment();
602 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
603 if (!envname.IsEmpty())
604 return envname;
605 return GetConfigValue(L"user.name");
607 CString CGit::GetUserEmail(void)
609 CEnvironment env;
610 env.CopyProcessEnvironment();
611 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
612 if (!envmail.IsEmpty())
613 return envmail;
615 return GetConfigValue(L"user.email");
618 CString CGit::GetConfigValue(const CString& name)
620 CString configValue;
621 if(this->m_IsUseGitDLL)
623 CAutoLocker lock(g_Git.m_critGitDllSec);
627 CheckAndInitDll();
628 }catch(...)
631 CStringA key, value;
632 key = CUnicodeUtils::GetUTF8(name);
636 if (git_get_config(key, CStrBufA(value, 4096), 4096))
637 return CString();
639 catch (const char *msg)
641 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
642 return CString();
645 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
646 return configValue;
648 else
650 CString cmd;
651 cmd.Format(L"git.exe config %s", (LPCTSTR)name);
652 Run(cmd, &configValue, nullptr, CP_UTF8);
653 if (configValue.IsEmpty())
654 return configValue;
655 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
659 bool CGit::GetConfigValueBool(const CString& name)
661 CString configValue = GetConfigValue(name);
662 configValue.MakeLower();
663 configValue.Trim();
664 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
665 return true;
666 else
667 return false;
670 int CGit::GetConfigValueInt32(const CString& name, int def)
672 CString configValue = GetConfigValue(name);
673 int value = def;
674 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
675 return value;
676 return def;
679 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
681 if(this->m_IsUseGitDLL)
683 CAutoLocker lock(g_Git.m_critGitDllSec);
687 CheckAndInitDll();
689 }catch(...)
692 CStringA keya, valuea;
693 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
694 valuea = CUnicodeUtils::GetUTF8(value);
698 return [=]() { return get_set_config(keya, valuea, type); }();
700 catch (const char *msg)
702 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
703 return -1;
706 else
708 CString cmd;
709 CString option;
710 switch(type)
712 case CONFIG_GLOBAL:
713 option = _T("--global");
714 break;
715 case CONFIG_SYSTEM:
716 option = _T("--system");
717 break;
718 default:
719 break;
721 CString mangledValue = value;
722 mangledValue.Replace(_T("\\\""), _T("\\\\\""));
723 mangledValue.Replace(_T("\""), _T("\\\""));
724 cmd.Format(_T("git.exe config %s %s \"%s\""), (LPCTSTR)option, (LPCTSTR)key, (LPCTSTR)mangledValue);
725 CString out;
726 if (Run(cmd, &out, nullptr, CP_UTF8))
728 return -1;
731 return 0;
734 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
736 if(this->m_IsUseGitDLL)
738 CAutoLocker lock(g_Git.m_critGitDllSec);
742 CheckAndInitDll();
743 }catch(...)
746 CStringA keya;
747 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
751 return [=]() { return get_set_config(keya, nullptr, type); }();
753 catch (const char *msg)
755 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
756 return -1;
759 else
761 CString cmd;
762 CString option;
763 switch(type)
765 case CONFIG_GLOBAL:
766 option = _T("--global");
767 break;
768 case CONFIG_SYSTEM:
769 option = _T("--system");
770 break;
771 default:
772 break;
774 cmd.Format(_T("git.exe config %s --unset %s"), (LPCTSTR)option, (LPCTSTR)key);
775 CString out;
776 if (Run(cmd, &out, nullptr, CP_UTF8))
778 return -1;
781 return 0;
784 CString CGit::GetCurrentBranch(bool fallback)
786 CString output;
787 //Run(_T("git.exe branch"),&branch);
789 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
790 if (result != 0 && ((result == 1 && !fallback) || result != 1))
792 return _T("(no branch)");
794 else
795 return output;
799 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
801 if (localBranch.IsEmpty())
802 return;
804 CString configName;
805 configName.Format(L"branch.%s.remote", (LPCTSTR)localBranch);
806 pullRemote = GetConfigValue(configName);
808 //Select pull-branch from current branch
809 configName.Format(L"branch.%s.merge", (LPCTSTR)localBranch);
810 pullBranch = StripRefName(GetConfigValue(configName));
813 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
815 CString refName;
816 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
817 return;
818 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
821 CString CGit::GetFullRefName(const CString& shortRefName)
823 CString refName;
824 CString cmd;
825 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR)shortRefName);
826 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
827 return CString();//Error
828 int iStart = 0;
829 return refName.Tokenize(L"\n", iStart);
832 CString CGit::StripRefName(CString refName)
834 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
835 refName = refName.Mid(11);
836 else if(wcsncmp(refName, L"refs/", 5) == 0)
837 refName = refName.Mid(5);
838 int start =0;
839 return refName.Tokenize(_T("\n"),start);
842 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
844 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
846 if ( sProjectRoot.IsEmpty() )
847 return -1;
849 CString sDotGitPath;
850 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
851 return -1;
853 CString sHeadFile = sDotGitPath + _T("HEAD");
855 FILE *pFile;
856 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
858 if (!pFile)
860 return -1;
863 char s[256] = {0};
864 fgets(s, sizeof(s), pFile);
866 fclose(pFile);
868 const char *pfx = "ref: refs/heads/";
869 const int len = 16;//strlen(pfx)
871 if ( !strncmp(s, pfx, len) )
873 //# We're on a branch. It might not exist. But
874 //# HEAD looks good enough to be a branch.
875 CStringA utf8Branch(s + len);
876 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
877 sBranchOut.TrimRight(_T(" \r\n\t"));
879 if ( sBranchOut.IsEmpty() )
880 return -1;
882 else if (fallback)
884 CStringA utf8Hash(s);
885 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
886 unicodeHash.TrimRight(_T(" \r\n\t"));
887 if (CGitHash::IsValidSHA1(unicodeHash))
888 sBranchOut = unicodeHash;
889 else
890 //# Assume this is a detached head.
891 sBranchOut = _T("HEAD");
892 return 1;
894 else
896 //# Assume this is a detached head.
897 sBranchOut = "HEAD";
899 return 1;
902 return 0;
905 int CGit::BuildOutputFormat(CString &format,bool IsFull)
907 CString log;
908 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
909 format += log;
910 if(IsFull)
912 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
913 format += log;
914 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
915 format += log;
916 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
917 format += log;
918 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
919 format += log;
920 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
921 format += log;
922 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
923 format += log;
924 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
925 format += log;
928 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
929 format += log;
930 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
931 format += log;
932 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
933 format += log;
935 if(IsFull)
937 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
938 format += log;
940 return 0;
943 CString CGit::GetLogCmd(const CString& range, const CTGitPath* path, int mask, bool paramonly,
944 CFilterData *Filter)
946 CString cmd;
947 CString num;
948 CString since;
950 CString file = _T(" --");
952 if(path)
953 file.Format(_T(" -- \"%s\""), (LPCTSTR)path->GetGitPathString());
955 CString param;
957 if(mask& LOG_INFO_STAT )
958 param += _T(" --numstat ");
959 if(mask& LOG_INFO_FILESTATE)
960 param += _T(" --raw ");
962 if(mask& LOG_INFO_FULLHISTORY)
963 param += _T(" --full-history ");
965 if(mask& LOG_INFO_BOUNDARY)
966 param += _T(" --left-right --boundary ");
968 if(mask& CGit::LOG_INFO_ALL_BRANCH)
969 param += _T(" --all ");
971 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
972 param += _T(" --branches ");
974 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
975 param += _T(" -C ");
977 if(mask& CGit::LOG_INFO_DETECT_RENAME )
978 param += _T(" -M ");
980 if(mask& CGit::LOG_INFO_FIRST_PARENT )
981 param += _T(" --first-parent ");
983 if(mask& CGit::LOG_INFO_NO_MERGE )
984 param += _T(" --no-merges ");
986 if(mask& CGit::LOG_INFO_FOLLOW)
987 param += _T(" --follow ");
989 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
990 param += _T(" -c ");
992 if(mask& CGit::LOG_INFO_FULL_DIFF)
993 param += _T(" --full-diff ");
995 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
996 param += _T(" --simplify-by-decoration ");
998 param += range;
1000 CString st1,st2;
1002 if (Filter && Filter->m_NumberOfLogs > 0)
1003 num.Format(_T("-n%d"), Filter->m_NumberOfLogs);
1005 if( Filter && (Filter->m_From != -1))
1007 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
1008 param += st1;
1011 if( Filter && (Filter->m_To != -1))
1013 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
1014 param += st2;
1017 bool isgrep = false;
1018 if( Filter && (!Filter->m_Author.IsEmpty()))
1020 st1.Format(_T(" --author=\"%s\"" ), (LPCTSTR)Filter->m_Author);
1021 param += st1;
1022 isgrep = true;
1025 if( Filter && (!Filter->m_Committer.IsEmpty()))
1027 st1.Format(_T(" --committer=\"%s\"" ), (LPCTSTR)Filter->m_Author);
1028 param += st1;
1029 isgrep = true;
1032 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1034 st1.Format(_T(" --grep=\"%s\"" ), (LPCTSTR)Filter->m_MessageFilter);
1035 param += st1;
1036 isgrep = true;
1039 if(Filter && isgrep)
1041 if(!Filter->m_IsRegex)
1042 param += _T(" --fixed-strings ");
1044 param += _T(" --regexp-ignore-case --extended-regexp ");
1047 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1048 if (logOrderBy == LOG_ORDER_TOPOORDER)
1049 param += _T(" --topo-order");
1050 else if (logOrderBy == LOG_ORDER_DATEORDER)
1051 param += _T(" --date-order");
1053 if(paramonly) //tgit.dll.Git.cpp:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1054 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), (LPCTSTR)num, (LPCTSTR)param);
1055 else
1057 CString log;
1058 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1059 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1060 (LPCTSTR)num, (LPCTSTR)param, (LPCTSTR)log);
1063 cmd += file;
1065 return cmd;
1067 #define BUFSIZE 512
1068 void GetTempPath(CString &path)
1070 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1071 DWORD dwRetVal;
1072 DWORD dwBufSize=BUFSIZE;
1073 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1074 lpPathBuffer); // buffer for path
1075 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1077 path=_T("");
1079 path.Format(_T("%s"),lpPathBuffer);
1081 CString GetTempFile()
1083 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1084 DWORD dwRetVal;
1085 DWORD dwBufSize=BUFSIZE;
1086 TCHAR szTempName[BUFSIZE] = { 0 };
1087 UINT uRetVal;
1089 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1090 lpPathBuffer); // buffer for path
1091 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1093 return _T("");
1095 // Create a temporary file.
1096 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1097 TEXT("Patch"), // temp file name prefix
1098 0, // create unique name
1099 szTempName); // buffer for name
1102 if (uRetVal == 0)
1104 return _T("");
1107 return CString(szTempName);
1111 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1113 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1114 if (result == 0) return 0;
1115 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1117 if (lpBuffer)
1118 lpBuffer[0] = '\0';
1119 return result + 13;
1122 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1123 CreateDirectory(lpBuffer, NULL);
1125 return result + 13;
1128 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1130 STARTUPINFO si;
1131 PROCESS_INFORMATION pi;
1132 si.cb=sizeof(STARTUPINFO);
1133 GetStartupInfo(&si);
1135 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1136 psa.bInheritHandle=TRUE;
1138 HANDLE hReadErr, hWriteErr;
1139 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1141 CString err = CFormatMessageWrapper();
1142 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), (LPCTSTR)err.Trim());
1143 return TGIT_GIT_ERROR_OPEN_PIP;
1146 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1147 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1149 if (houtfile == INVALID_HANDLE_VALUE)
1151 CString err = CFormatMessageWrapper();
1152 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), (LPCTSTR)err.Trim());
1153 CloseHandle(hReadErr);
1154 CloseHandle(hWriteErr);
1155 return TGIT_GIT_ERROR_OPEN_PIP;
1158 si.wShowWindow = SW_HIDE;
1159 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1160 si.hStdOutput = houtfile;
1161 si.hStdError = hWriteErr;
1163 LPTSTR pEnv = m_Environment;
1164 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1166 if(cmd.Find(_T("git")) == 0)
1167 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1169 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), (LPCTSTR)cmd);
1170 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1172 CString err = CFormatMessageWrapper();
1173 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), (LPCTSTR)err.Trim());
1174 stdErr = &err;
1175 CloseHandle(hReadErr);
1176 CloseHandle(hWriteErr);
1177 CloseHandle(houtfile);
1178 return TGIT_GIT_ERROR_CREATE_PROCESS;
1181 BYTE_VECTOR stderrVector;
1182 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1183 HANDLE thread;
1184 ASYNCREADSTDERRTHREADARGS threadArguments;
1185 threadArguments.fileHandle = hReadErr;
1186 threadArguments.pcall = &pcall;
1187 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1189 WaitForSingleObject(pi.hProcess,INFINITE);
1191 CloseHandle(hWriteErr);
1192 CloseHandle(hReadErr);
1194 if (thread)
1195 WaitForSingleObject(thread, INFINITE);
1197 stderrVector.push_back(0);
1198 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1200 DWORD exitcode = 0;
1201 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1203 CString err = CFormatMessageWrapper();
1204 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), (LPCTSTR)err.Trim());
1205 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1207 else
1208 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1210 CloseHandle(pi.hThread);
1211 CloseHandle(pi.hProcess);
1212 CloseHandle(houtfile);
1213 return exitcode;
1216 git_repository * CGit::GetGitRepository() const
1218 git_repository * repo = nullptr;
1219 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1220 return repo;
1223 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1225 ATLASSERT(repo);
1227 // no need to parse a ref if it's already a 40-byte hash
1228 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1230 hash = CGitHash(friendname);
1231 return 0;
1234 int isHeadOrphan = git_repository_head_unborn(repo);
1235 if (isHeadOrphan != 0)
1237 hash.Empty();
1238 if (isHeadOrphan == 1)
1239 return 0;
1240 else
1241 return -1;
1244 CAutoObject gitObject;
1245 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1246 return -1;
1248 const git_oid * oid = git_object_id(gitObject);
1249 if (!oid)
1250 return -1;
1252 hash = CGitHash((char *)oid->id);
1254 return 0;
1257 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1259 // no need to parse a ref if it's already a 40-byte hash
1260 if (CGitHash::IsValidSHA1(friendname))
1262 hash = CGitHash(friendname);
1263 return 0;
1266 if (m_IsUseLibGit2)
1268 CAutoRepository repo(GetGitRepository());
1269 if (!repo)
1270 return -1;
1272 return GetHash(repo, hash, friendname, true);
1274 else
1276 CString branch = FixBranchName(friendname);
1277 if (friendname == _T("FETCH_HEAD") && branch.IsEmpty())
1278 branch = friendname;
1279 CString cmd;
1280 cmd.Format(_T("git.exe rev-parse %s"), (LPCTSTR)branch);
1281 gitLastErr.Empty();
1282 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1283 hash = CGitHash(gitLastErr.Trim());
1284 if (ret == 0)
1285 gitLastErr.Empty();
1286 else if (friendname == _T("HEAD")) // special check for unborn branch
1288 CString currentbranch;
1289 if (GetCurrentBranchFromFile(m_CurrentDir, currentbranch))
1290 return -1;
1291 gitLastErr.Empty();
1292 return 0;
1294 return ret;
1298 int CGit::GetInitAddList(CTGitPathList &outputlist)
1300 CString cmd;
1301 BYTE_VECTOR cmdout;
1303 cmd=_T("git.exe ls-files -s -t -z");
1304 outputlist.Clear();
1305 if (Run(cmd, &cmdout))
1306 return -1;
1308 if (outputlist.ParserFromLsFile(cmdout))
1309 return -1;
1310 for(int i = 0; i < outputlist.GetCount(); ++i)
1311 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1313 return 0;
1315 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1317 CString cmd;
1318 CString ignore;
1319 if (ignoreSpaceAtEol)
1320 ignore += _T(" --ignore-space-at-eol");
1321 if (ignoreSpaceChange)
1322 ignore += _T(" --ignore-space-change");
1323 if (ignoreAllSpace)
1324 ignore += _T(" --ignore-all-space");
1325 if (ignoreBlankLines)
1326 ignore += _T(" --ignore-blank-lines");
1328 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1330 //rev1=+_T("");
1331 if(rev1 == GIT_REV_ZERO)
1332 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev2);
1333 else
1334 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev1);
1336 else
1338 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), (LPCTSTR)ignore, (LPCTSTR)rev2, (LPCTSTR)rev1);
1341 BYTE_VECTOR out;
1342 if (Run(cmd, &out))
1343 return -1;
1345 return outputlist.ParserFromLog(out);
1348 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1350 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1351 list->push_back(CUnicodeUtils::GetUnicode(refname));
1352 return 0;
1355 int CGit::GetTagList(STRING_VECTOR &list)
1357 if (this->m_IsUseLibGit2)
1359 CAutoRepository repo(GetGitRepository());
1360 if (!repo)
1361 return -1;
1363 CAutoStrArray tag_names;
1365 if (git_tag_list(tag_names, repo))
1366 return -1;
1368 for (size_t i = 0; i < tag_names->count; ++i)
1370 CStringA tagName(tag_names->strings[i]);
1371 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1374 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1376 return 0;
1378 else
1380 CString cmd, output;
1381 cmd=_T("git.exe tag -l");
1382 int ret = Run(cmd, &output, NULL, CP_UTF8);
1383 if(!ret)
1385 int pos=0;
1386 CString one;
1387 while( pos>=0 )
1389 one=output.Tokenize(_T("\n"),pos);
1390 if (!one.IsEmpty())
1391 list.push_back(one);
1393 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1395 else if (ret == 1 && IsInitRepos())
1396 return 0;
1397 return ret;
1401 CString CGit::GetGitLastErr(const CString& msg)
1403 if (this->m_IsUseLibGit2)
1404 return GetLibGit2LastErr(msg);
1405 else if (gitLastErr.IsEmpty())
1406 return msg + _T("\nUnknown git.exe error.");
1407 else
1409 CString lastError = gitLastErr;
1410 gitLastErr.Empty();
1411 return msg + _T("\n") + lastError;
1415 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1417 if (UsingLibGit2(cmd))
1418 return GetLibGit2LastErr(msg);
1419 else if (gitLastErr.IsEmpty())
1420 return msg + _T("\nUnknown git.exe error.");
1421 else
1423 CString lastError = gitLastErr;
1424 gitLastErr.Empty();
1425 return msg + _T("\n") + lastError;
1429 CString CGit::GetLibGit2LastErr()
1431 const git_error *libgit2err = giterr_last();
1432 if (libgit2err)
1434 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1435 giterr_clear();
1436 return _T("libgit2 returned: ") + lastError;
1438 else
1439 return _T("An error occoured in libgit2, but no message is available.");
1442 CString CGit::GetLibGit2LastErr(const CString& msg)
1444 if (!msg.IsEmpty())
1445 return msg + _T("\n") + GetLibGit2LastErr();
1446 return GetLibGit2LastErr();
1449 CString CGit::FixBranchName_Mod(CString& branchName)
1451 if(branchName == "FETCH_HEAD")
1452 branchName = DerefFetchHead();
1453 return branchName;
1456 CString CGit::FixBranchName(const CString& branchName)
1458 CString tempBranchName = branchName;
1459 FixBranchName_Mod(tempBranchName);
1460 return tempBranchName;
1463 bool CGit::IsBranchTagNameUnique(const CString& name)
1465 if (m_IsUseLibGit2)
1467 CAutoRepository repo(GetGitRepository());
1468 if (!repo)
1469 return true; // TODO: optimize error reporting
1471 CAutoReference tagRef;
1472 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1473 return true;
1475 CAutoReference branchRef;
1476 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1477 return true;
1479 return false;
1481 // else
1482 CString output;
1484 CString cmd;
1485 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), (LPCTSTR)name, (LPCTSTR)name);
1486 int ret = Run(cmd, &output, NULL, CP_UTF8);
1487 if (!ret)
1489 int i = 0, pos = 0;
1490 while (pos >= 0)
1492 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1493 ++i;
1495 if (i >= 2)
1496 return false;
1499 return true;
1502 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1504 if (m_IsUseLibGit2)
1506 CAutoRepository repo(GetGitRepository());
1507 if (!repo)
1508 return false; // TODO: optimize error reporting
1510 CString prefix;
1511 if (isBranch)
1512 prefix = _T("refs/heads/");
1513 else
1514 prefix = _T("refs/tags/");
1516 CAutoReference ref;
1517 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1518 return false;
1520 return true;
1522 // else
1523 CString cmd, output;
1525 cmd = _T("git.exe show-ref ");
1526 if (isBranch)
1527 cmd += _T("--heads ");
1528 else
1529 cmd += _T("--tags ");
1531 cmd += _T("refs/heads/") + name;
1532 cmd += _T(" refs/tags/") + name;
1534 int ret = Run(cmd, &output, NULL, CP_UTF8);
1535 if (!ret)
1537 if (!output.IsEmpty())
1538 return true;
1541 return false;
1544 CString CGit::DerefFetchHead()
1546 CString dotGitPath;
1547 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1548 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1549 int forMergeLineCount = 0;
1550 std::string line;
1551 std::string hashToReturn;
1552 while(getline(fetchHeadFile, line))
1554 //Tokenize this line
1555 std::string::size_type prevPos = 0;
1556 std::string::size_type pos = line.find('\t');
1557 if(pos == std::string::npos) continue; //invalid line
1559 std::string hash = line.substr(0, pos);
1560 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1562 bool forMerge = pos == prevPos;
1563 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1565 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1567 //Process this line
1568 if(forMerge)
1570 hashToReturn = hash;
1571 ++forMergeLineCount;
1572 if(forMergeLineCount > 1)
1573 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1577 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1580 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1582 int ret = 0;
1583 CString cur;
1584 bool headIsDetached = false;
1585 if (m_IsUseLibGit2)
1587 CAutoRepository repo(GetGitRepository());
1588 if (!repo)
1589 return -1;
1591 if (git_repository_head_detached(repo) == 1)
1592 headIsDetached = true;
1594 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1596 git_branch_t flags = GIT_BRANCH_LOCAL;
1597 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1598 flags = GIT_BRANCH_ALL;
1599 else if (type & BRANCH_REMOTE)
1600 flags = GIT_BRANCH_REMOTE;
1602 CAutoBranchIterator it;
1603 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1604 return -1;
1606 git_reference * ref = nullptr;
1607 git_branch_t branchType;
1608 while (git_branch_next(&ref, &branchType, it) == 0)
1610 CAutoReference autoRef(ref);
1611 const char * name = nullptr;
1612 if (git_branch_name(&name, ref))
1613 continue;
1615 CString branchname = CUnicodeUtils::GetUnicode(name);
1616 if (branchType & GIT_BRANCH_REMOTE)
1617 list.push_back(_T("remotes/") + branchname);
1618 else
1620 if (git_branch_is_head(ref))
1621 cur = branchname;
1622 list.push_back(branchname);
1627 else
1629 CString cmd, output;
1630 cmd = _T("git.exe branch --no-color");
1632 if ((type & BRANCH_ALL) == BRANCH_ALL)
1633 cmd += _T(" -a");
1634 else if (type & BRANCH_REMOTE)
1635 cmd += _T(" -r");
1637 ret = Run(cmd, &output, nullptr, CP_UTF8);
1638 if (!ret)
1640 int pos = 0;
1641 CString one;
1642 while (pos >= 0)
1644 one = output.Tokenize(_T("\n"), pos);
1645 one.Trim(L" \r\n\t");
1646 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1647 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1648 if (one[0] == _T('*'))
1650 one = one.Mid(2);
1651 cur = one;
1653 // check whether HEAD is detached
1654 CString currentHead;
1655 if (one.Left(1) == _T("(") && GetCurrentBranchFromFile(g_Git.m_CurrentDir, currentHead) == 1)
1657 headIsDetached = true;
1658 continue;
1661 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1662 one = _T("remotes/") + one;
1663 list.push_back(one);
1666 else if (ret == 1 && IsInitRepos())
1667 return 0;
1670 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1671 list.push_back(L"FETCH_HEAD");
1673 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1675 if (current && !headIsDetached)
1677 for (unsigned int i = 0; i < list.size(); ++i)
1679 if (list[i] == cur)
1681 *current = i;
1682 break;
1687 return ret;
1690 int CGit::GetRemoteList(STRING_VECTOR &list)
1692 if (this->m_IsUseLibGit2)
1694 CAutoRepository repo(GetGitRepository());
1695 if (!repo)
1696 return -1;
1698 CAutoStrArray remotes;
1699 if (git_remote_list(remotes, repo))
1700 return -1;
1702 for (size_t i = 0; i < remotes->count; ++i)
1704 CStringA remote(remotes->strings[i]);
1705 list.push_back(CUnicodeUtils::GetUnicode(remote));
1708 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1710 return 0;
1712 else
1714 int ret;
1715 CString cmd, output;
1716 cmd=_T("git.exe remote");
1717 ret = Run(cmd, &output, NULL, CP_UTF8);
1718 if(!ret)
1720 int pos=0;
1721 CString one;
1722 while( pos>=0 )
1724 one=output.Tokenize(_T("\n"),pos);
1725 if (!one.IsEmpty())
1726 list.push_back(one);
1729 return ret;
1733 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
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) < 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(), 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(), 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 (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 (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 if (this->m_IsUseLibGit2)
1850 CAutoRepository repo(GetGitRepository());
1851 if (!repo)
1852 return -1;
1854 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1855 return -1;
1857 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1859 return 0;
1861 else
1863 CString cmd, output;
1864 cmd=_T("git.exe show-ref -d");
1865 int ret = Run(cmd, &output, NULL, CP_UTF8);
1866 if(!ret)
1868 int pos=0;
1869 CString one;
1870 while( pos>=0 )
1872 one=output.Tokenize(_T("\n"),pos);
1873 int start=one.Find(_T(" "),0);
1874 if(start>0)
1876 CString name;
1877 name=one.Right(one.GetLength()-start-1);
1878 if (list.empty() || name != *list.crbegin() + _T("^{}"))
1879 list.push_back(name);
1882 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1884 else if (ret == 1 && IsInitRepos())
1885 return 0;
1886 return ret;
1890 typedef struct map_each_ref_payload {
1891 git_repository * repo;
1892 MAP_HASH_NAME * map;
1893 } map_each_ref_payload;
1895 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1897 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1899 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1901 CAutoObject gitObject;
1902 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1903 return 1;
1905 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1907 str += _T("^{}"); // deref tag
1908 CAutoObject derefedTag;
1909 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1910 return 1;
1911 gitObject.Swap(derefedTag);
1914 const git_oid * oid = git_object_id(gitObject);
1915 if (oid == NULL)
1916 return 1;
1918 CGitHash hash((char *)oid->id);
1919 (*payloadContent->map)[hash].push_back(str);
1921 return 0;
1923 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1925 ATLASSERT(repo);
1927 map_each_ref_payload payloadContent = { repo, &map };
1929 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1930 return -1;
1932 for (auto it = map.begin(); it != map.end(); ++it)
1934 std::sort(it->second.begin(), it->second.end());
1937 return 0;
1940 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1942 if (this->m_IsUseLibGit2)
1944 CAutoRepository repo(GetGitRepository());
1945 if (!repo)
1946 return -1;
1948 return GetMapHashToFriendName(repo, map);
1950 else
1952 CString cmd, output;
1953 cmd=_T("git.exe show-ref -d");
1954 int ret = Run(cmd, &output, NULL, CP_UTF8);
1955 if(!ret)
1957 int pos=0;
1958 CString one;
1959 while( pos>=0 )
1961 one=output.Tokenize(_T("\n"),pos);
1962 int start=one.Find(_T(" "),0);
1963 if(start>0)
1965 CString name;
1966 name=one.Right(one.GetLength()-start-1);
1968 CString hash;
1969 hash=one.Left(start);
1971 map[CGitHash(hash)].push_back(name);
1975 else if (ret == 1 && IsInitRepos())
1976 return 0;
1977 return ret;
1981 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
1983 CAutoConfig config(true);
1984 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE) < 0)
1985 return -1;
1986 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
1988 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
1989 CString key = CUnicodeUtils::GetUnicode(entry->name);
1990 key = key.Mid(7, key.GetLength() - 7 - 12); // 7: branch., 12: .description
1991 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
1992 return 0;
1993 }, &map);
1996 static void SetLibGit2SearchPath(int level, const CString &value)
1998 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1999 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
2002 static void SetLibGit2TemplatePath(const CString &value)
2004 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
2005 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
2008 int CGit::FindAndSetGitExePath(BOOL bFallback)
2010 CRegString msysdir = CRegString(REG_MSYSGIT_PATH, _T(""), FALSE);
2011 CString str = msysdir;
2012 if (!str.IsEmpty() && FileExists(str + _T("\\git.exe")))
2014 CGit::ms_LastMsysGitDir = str;
2015 return TRUE;
2018 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2019 if (!bFallback)
2020 return FALSE;
2022 // first, search PATH if git/bin directory is already present
2023 if (FindGitPath())
2025 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2026 msysdir = CGit::ms_LastMsysGitDir;
2027 msysdir.write();
2028 return TRUE;
2031 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2032 str = msyslocalinstalldir;
2033 str.TrimRight(_T("\\"));
2034 #ifdef _WIN64
2035 if (str.IsEmpty())
2037 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2038 str = msysinstalldir;
2039 str.TrimRight(_T("\\"));
2041 #endif
2042 if (str.IsEmpty())
2044 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2045 str = msysinstalldir;
2046 str.TrimRight(_T("\\"));
2048 if (!str.IsEmpty())
2050 if (FileExists(str + _T("\\bin\\git.exe")))
2051 str += _T("\\bin");
2052 else if (FileExists(str + _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2053 str += _T("\\cmd");
2054 else
2056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), (LPCTSTR)str);
2057 return FALSE;
2059 msysdir = str;
2060 CGit::ms_LastMsysGitDir = str;
2061 msysdir.write();
2062 return TRUE;
2065 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Found no git.exe\n"));
2066 return FALSE;
2069 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
2071 if (m_bInitialized)
2073 return TRUE;
2076 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
2077 this->m_Environment.clear();
2078 m_Environment.CopyProcessEnvironment();
2079 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2081 // set HOME if not set already
2082 size_t homesize;
2083 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
2084 if (!homesize)
2085 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
2087 //setup ssh client
2088 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
2089 if (sshclient.IsEmpty())
2090 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
2092 if(!sshclient.IsEmpty())
2094 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
2095 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
2097 else
2099 TCHAR sPlink[MAX_PATH] = {0};
2100 GetModuleFileName(NULL, sPlink, _countof(sPlink));
2101 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
2102 if (ptr) {
2103 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPlink.exe"));
2104 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
2105 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2110 TCHAR sAskPass[MAX_PATH] = {0};
2111 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2112 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2113 if (ptr)
2115 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2116 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2117 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2118 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2122 if (!FindAndSetGitExePath(bFallback))
2123 return FALSE;
2125 CString msysGitDir;
2126 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\"));
2127 static CString prefixes[] = { L"mingw64\\etc", L"mingw32\\etc", L"etc" };
2128 static int prefixes_len[] = { 8, 8, 0 };
2129 for (int i = 0; i < _countof(prefixes); ++i)
2131 #ifndef _WIN64
2132 if (i == 0)
2133 continue;
2134 #endif
2135 if (PathIsDirectory(msysGitDir + prefixes[i])) {
2136 msysGitDir += prefixes[i].Left(prefixes_len[i]);
2137 break;
2140 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
2141 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\.."));
2142 CGit::ms_MsysGitRootDir = msysGitDir;
2144 if ((CString)CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) != g_Git.GetGitSystemConfig())
2145 CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) = g_Git.GetGitSystemConfig();
2147 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), (LPCTSTR)CGit::ms_LastMsysGitDir);
2148 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_MsysGitRootDir = %s\n"), (LPCTSTR)CGit::ms_MsysGitRootDir);
2149 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": System config = %s\n"), (LPCTSTR)g_Git.GetGitSystemConfig());
2151 // Configure libgit2 search paths
2152 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2153 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2154 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2155 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 };
2156 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2157 if (!(ms_bCygwinGit || ms_bMsys2Git))
2158 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("share\\git-core\\templates"));
2159 else
2160 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("usr\\share\\git-core\\templates"));
2162 m_Environment.AddToPath(CGit::ms_LastMsysGitDir);
2163 m_Environment.AddToPath((CString)CRegString(REG_MSYSGIT_EXTRA_PATH, _T(""), FALSE));
2165 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2166 // register filter only once
2167 if (!git_filter_lookup("filter"))
2169 static CString binDirPrefixes[] = { L"\\..\\usr\\bin", L"\\..\\bin", L"" };
2170 CString sh;
2171 for (const CString& binDirPrefix : binDirPrefixes)
2173 CString possibleShExe = CGit::ms_LastMsysGitDir + binDirPrefix + L"\\sh.exe";
2174 if (PathFileExists(possibleShExe))
2176 CString temp;
2177 PathCanonicalize(CStrBuf(temp, MAX_PATH), possibleShExe);
2178 sh.Format(L"\"%s\"", (LPCTSTR)temp);
2179 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2180 m_Environment.AddToPath(temp.Left(temp.GetLength() - 7)); // 7 = len("\\sh.exe")
2181 break;
2184 if (git_filter_register("filter", git_filter_filter_new(sh, m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2185 return FALSE;
2187 #endif
2189 m_bInitialized = TRUE;
2190 return true;
2193 CString CGit::GetHomeDirectory() const
2195 const wchar_t * homeDir = wget_windows_home_directory();
2196 return CString(homeDir, (int)wcslen(homeDir));
2199 CString CGit::GetGitLocalConfig() const
2201 CString path;
2202 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2203 path += _T("config");
2204 return path;
2207 CStringA CGit::GetGitPathStringA(const CString &path)
2209 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2212 CString CGit::GetGitGlobalConfig() const
2214 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2217 CString CGit::GetGitGlobalXDGConfigPath() const
2219 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2222 CString CGit::GetGitGlobalXDGConfig() const
2224 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2227 CString CGit::GetGitSystemConfig() const
2229 const wchar_t * systemConfig = wget_msysgit_etc();
2230 return CString(systemConfig, (int)wcslen(systemConfig));
2233 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2235 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2237 CAutoRepository repo = GetGitRepository();
2238 if (!repo)
2239 return FALSE;
2241 if (git_repository_head_unborn(repo))
2242 return FALSE;
2244 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2245 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2246 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2248 CAutoStatusList status;
2249 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2250 return FALSE;
2252 return (0 == git_status_list_entrycount(status));
2255 CString out;
2256 CString cmd;
2257 cmd=_T("git.exe rev-parse --verify HEAD");
2259 if(Run(cmd,&out,CP_UTF8))
2260 return FALSE;
2262 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2263 if(Run(cmd,&out,CP_UTF8))
2264 return FALSE;
2266 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2267 if(Run(cmd,&out,CP_UTF8))
2268 return FALSE;
2270 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2271 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2272 return FALSE;
2274 return TRUE;
2276 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2278 int ret;
2279 for (int i = 0; i < list.GetCount(); ++i)
2281 ret = Revert(commit, (CTGitPath&)list[i], err);
2282 if(ret)
2283 return ret;
2285 return 0;
2287 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2289 CString cmd;
2291 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2293 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2295 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2296 return -1;
2298 CString force;
2299 // if the filenames only differ in case, we have to pass "-f"
2300 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2301 force = _T("-f ");
2302 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), (LPCTSTR)force, (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2303 if (Run(cmd, &err, CP_UTF8))
2304 return -1;
2306 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR)commit, (LPCTSTR)path.GetGitOldPathString());
2307 if (Run(cmd, &err, CP_UTF8))
2308 return -1;
2310 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2311 { //To init git repository, there are not HEAD, so we can use git reset command
2312 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""), (LPCTSTR)path.GetGitPathString());
2314 if (Run(cmd, &err, CP_UTF8))
2315 return -1;
2317 else
2319 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), (LPCTSTR)commit, (LPCTSTR)path.GetGitPathString());
2320 if (Run(cmd, &err, CP_UTF8))
2321 return -1;
2324 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2326 cmd.Format(_T("git.exe add -f -- \"%s\""), (LPCTSTR)path.GetGitPathString());
2327 if (Run(cmd, &err, CP_UTF8))
2328 return -1;
2331 return 0;
2334 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2336 ATLASSERT(repo);
2338 CAutoIndex index;
2339 if (git_repository_index(index.GetPointer(), repo))
2340 return -1;
2342 return git_index_has_conflicts(index);
2345 int CGit::HasWorkingTreeConflicts()
2347 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2349 CAutoRepository repo(GetGitRepository());
2350 if (!repo)
2351 return -1;
2353 return HasWorkingTreeConflicts(repo);
2356 CString cmd = _T("git.exe ls-files -u -t -z");
2358 CString output;
2359 if (Run(cmd, &output, &gitLastErr, CP_UTF8))
2360 return -1;
2362 return output.IsEmpty() ? 0 : 1;
2365 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2367 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2369 CAutoRepository repo(GetGitRepository());
2370 if (!repo)
2371 return false;
2373 CGitHash fromHash, toHash, baseHash;
2374 if (GetHash(repo, toHash, FixBranchName(to)))
2375 return false;
2377 if (GetHash(repo, fromHash, FixBranchName(from)))
2378 return false;
2380 git_oid baseOid;
2381 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2382 return false;
2384 baseHash = baseOid.id;
2386 if (commonAncestor)
2387 *commonAncestor = baseHash;
2389 return fromHash == baseHash;
2391 // else
2392 CString base;
2393 CGitHash basehash,hash;
2394 CString cmd;
2395 cmd.Format(_T("git.exe merge-base %s %s"), (LPCTSTR)FixBranchName(to), (LPCTSTR)FixBranchName(from));
2397 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2399 return false;
2401 basehash = base.Trim();
2403 GetHash(hash, from);
2405 if (commonAncestor)
2406 *commonAncestor = basehash;
2408 return hash == basehash;
2411 unsigned int CGit::Hash2int(const CGitHash &hash)
2413 int ret=0;
2414 for (int i = 0; i < 4; ++i)
2416 ret = ret << 8;
2417 ret |= hash.m_hash[i];
2419 return ret;
2422 int CGit::RefreshGitIndex()
2424 if(g_Git.m_IsUseGitDLL)
2426 CAutoLocker lock(g_Git.m_critGitDllSec);
2429 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2431 }catch(...)
2433 return -1;
2437 else
2439 CString cmd,output;
2440 cmd=_T("git.exe update-index --refresh");
2441 return Run(cmd, &output, CP_UTF8);
2445 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2447 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2449 CAutoRepository repo(GetGitRepository());
2450 if (!repo)
2451 return -1;
2453 CGitHash hash;
2454 if (GetHash(repo, hash, Refname))
2455 return -1;
2457 CAutoCommit commit;
2458 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2459 return -1;
2461 CAutoTree tree;
2462 if (git_commit_tree(tree.GetPointer(), commit))
2463 return -1;
2465 CAutoTreeEntry entry;
2466 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2467 return -1;
2469 CAutoBlob blob;
2470 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2471 return -1;
2473 FILE *file = nullptr;
2474 _tfopen_s(&file, outputfile, _T("wb"));
2475 if (file == nullptr)
2477 giterr_set_str(GITERR_NONE, "Could not create file.");
2478 return -1;
2480 CAutoBuf buf;
2481 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2483 fclose(file);
2484 return -1;
2486 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2488 giterr_set_str(GITERR_OS, "Could not write to file.");
2489 fclose(file);
2491 return -1;
2493 fclose(file);
2495 return 0;
2497 else if (g_Git.m_IsUseGitDLL)
2499 CAutoLocker lock(g_Git.m_critGitDllSec);
2502 g_Git.CheckAndInitDll();
2503 CStringA ref, patha, outa;
2504 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2505 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2506 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2507 ::DeleteFile(outputfile);
2508 int ret = git_checkout_file(ref, patha, outa.GetBuffer());
2509 outa.ReleaseBuffer();
2510 return ret;
2513 catch (const char * msg)
2515 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2516 return -1;
2518 catch (...)
2520 gitLastErr = L"An unknown gitdll.dll error occurred.";
2521 return -1;
2524 else
2526 CString cmd;
2527 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), (LPCTSTR)Refname, (LPCTSTR)path.GetGitPathString());
2528 return RunLogFile(cmd, outputfile, &gitLastErr);
2532 void CEnvironment::clear()
2534 __super::clear();
2537 bool CEnvironment::empty()
2539 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2542 CEnvironment::operator LPTSTR()
2544 if (empty())
2545 return nullptr;
2546 return &__super::at(0);
2549 void CEnvironment::CopyProcessEnvironment()
2551 if (!empty())
2552 pop_back();
2553 TCHAR *porig = GetEnvironmentStrings();
2554 TCHAR *p = porig;
2555 while(*p !=0 || *(p+1) !=0)
2556 this->push_back(*p++);
2558 push_back(_T('\0'));
2559 push_back(_T('\0'));
2561 FreeEnvironmentStrings(porig);
2564 CString CEnvironment::GetEnv(const TCHAR *name)
2566 CString str;
2567 for (size_t i = 0; i < size(); ++i)
2569 str = &(*this)[i];
2570 int start =0;
2571 CString sname = str.Tokenize(_T("="),start);
2572 if(sname.CompareNoCase(name) == 0)
2574 return &(*this)[i+start];
2576 i+=str.GetLength();
2578 return _T("");
2581 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2583 unsigned int i;
2584 for (i = 0; i < size(); ++i)
2586 CString str = &(*this)[i];
2587 int start =0;
2588 CString sname = str.Tokenize(_T("="),start);
2589 if(sname.CompareNoCase(name) == 0)
2591 break;
2593 i+=str.GetLength();
2596 if(i == size())
2598 if (!value) // as we haven't found the variable we want to remove, just return
2599 return;
2600 if (i == 0) // make inserting into an empty environment work
2602 this->push_back(_T('\0'));
2603 ++i;
2605 i -= 1; // roll back terminate \0\0
2606 this->push_back(_T('\0'));
2609 CEnvironment::iterator it;
2610 it=this->begin();
2611 it += i;
2613 while(*it && i<size())
2615 this->erase(it);
2616 it=this->begin();
2617 it += i;
2620 if (value == nullptr) // remove the variable
2622 this->erase(it);
2623 return;
2626 while(*name)
2628 this->insert(it,*name++);
2629 ++i;
2630 it= begin()+i;
2633 this->insert(it, _T('='));
2634 ++i;
2635 it= begin()+i;
2637 while(*value)
2639 this->insert(it,*value++);
2640 ++i;
2641 it= begin()+i;
2646 void CEnvironment::AddToPath(CString value)
2648 value.TrimRight(L"\\");
2649 if (value.IsEmpty())
2650 return;
2652 CString path = GetEnv(L"PATH").TrimRight(L";") + L";";
2654 // do not double add paths to %PATH%
2655 if (path.Find(value + L";") >= 0 || path.Find(value + L"\\;") >= 0)
2656 return;
2658 path += value;
2660 SetEnv(L"PATH", path);
2663 int CGit::GetGitEncode(TCHAR* configkey)
2665 CString str=GetConfigValue(configkey);
2667 if(str.IsEmpty())
2668 return CP_UTF8;
2670 return CUnicodeUtils::GetCPCode(str);
2674 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2676 GIT_FILE file=0;
2677 int ret=0;
2678 GIT_DIFF diff=0;
2680 CAutoLocker lock(g_Git.m_critGitDllSec);
2684 if(!arg)
2685 diff = GetGitDiff();
2686 else
2687 git_open_diff(&diff, arg);
2689 catch (char* e)
2691 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2692 return -1;
2695 if(diff ==NULL)
2696 return -1;
2698 bool isStat = 0;
2699 if(arg == NULL)
2700 isStat = true;
2701 else
2702 isStat = !!strstr(arg, "stat");
2704 int count=0;
2706 if(hash2 == NULL)
2707 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2708 else
2709 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2711 if(ret)
2712 return -1;
2714 CTGitPath path;
2715 CString strnewname;
2716 CString stroldname;
2718 for (int j = 0; j < count; ++j)
2720 path.Reset();
2721 char *newname;
2722 char *oldname;
2724 strnewname.Empty();
2725 stroldname.Empty();
2727 int mode=0,IsBin=0,inc=0,dec=0;
2728 git_get_diff_file(diff,file,j,&newname,&oldname,
2729 &mode,&IsBin,&inc,&dec);
2731 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2732 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2734 path.SetFromGit(strnewname,&stroldname);
2735 path.ParserAction((BYTE)mode);
2737 if(IsBin)
2739 path.m_StatAdd=_T("-");
2740 path.m_StatDel=_T("-");
2742 else
2744 path.m_StatAdd.Format(_T("%d"),inc);
2745 path.m_StatDel.Format(_T("%d"),dec);
2747 PathList->AddPath(path);
2749 git_diff_flush(diff);
2751 if(arg)
2752 git_close_diff(diff);
2754 return 0;
2757 int CGit::GetShortHASHLength() const
2759 return 7;
2762 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2764 CString str=ref;
2765 CString shortname;
2766 REF_TYPE type = CGit::UNKNOWN;
2768 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2770 type = CGit::LOCAL_BRANCH;
2773 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2775 type = CGit::REMOTE_BRANCH;
2777 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2779 type = CGit::TAG;
2781 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2783 type = CGit::STASH;
2784 shortname=_T("stash");
2786 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2788 if (shortname.Find(_T("good")) == 0)
2790 type = CGit::BISECT_GOOD;
2791 shortname = _T("good");
2794 if (shortname.Find(_T("bad")) == 0)
2796 type = CGit::BISECT_BAD;
2797 shortname = _T("bad");
2800 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2802 type = CGit::NOTES;
2804 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2806 type = CGit::UNKNOWN;
2808 else
2810 type = CGit::UNKNOWN;
2811 shortname = ref;
2814 if(out_type)
2815 *out_type = type;
2817 return shortname;
2820 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2822 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2825 void CGit::SetGit2CredentialCallback(void* callback)
2827 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2830 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2832 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2835 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2837 CString cmd;
2838 if (rev2 == GitRev::GetWorkingCopy())
2839 cmd.Format(_T("git.exe diff --stat -p %s --"), (LPCTSTR)rev1);
2840 else if (rev1 == GitRev::GetWorkingCopy())
2841 cmd.Format(_T("git.exe diff -R --stat -p %s --"), (LPCTSTR)rev2);
2842 else
2844 CString merge;
2845 if (bMerge)
2846 merge += _T(" -m");
2848 if (bCombine)
2849 merge += _T(" -c");
2851 CString unified;
2852 if (diffContext >= 0)
2853 unified.Format(_T(" --unified=%d"), diffContext);
2854 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), (LPCTSTR)merge, (LPCTSTR)unified, (LPCTSTR)rev1, (LPCTSTR)rev2);
2857 if (!path.IsEmpty())
2859 cmd += _T(" \"");
2860 cmd += path.GetGitPathString();
2861 cmd += _T("\"");
2864 return cmd;
2867 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2869 ATLASSERT(payload && text);
2870 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2871 fwrite("\n", 1, 1, (FILE *)payload);
2874 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2876 ATLASSERT(payload && line);
2877 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2878 fwrite(&line->origin, 1, 1, (FILE *)payload);
2879 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2880 return 0;
2883 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2885 ATLASSERT(repo && identifier && tree);
2887 /* try to resolve identifier */
2888 CAutoObject obj;
2889 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2890 return -1;
2892 if (obj == nullptr)
2893 return GIT_ENOTFOUND;
2895 int err = 0;
2896 switch (git_object_type(obj))
2898 case GIT_OBJ_TREE:
2899 *tree = (git_tree *)obj.Detach();
2900 break;
2901 case GIT_OBJ_COMMIT:
2902 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2903 break;
2904 default:
2905 err = GIT_ENOTFOUND;
2908 return err;
2911 /* use libgit2 get unified diff */
2912 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 */)
2914 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2915 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2917 CAutoRepository repo(g_Git.GetGitRepository());
2918 if (!repo)
2919 return -1;
2921 int isHeadOrphan = git_repository_head_unborn(repo);
2922 if (isHeadOrphan == 1)
2923 return 0;
2924 else if (isHeadOrphan != 0)
2925 return -1;
2927 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2928 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2929 char *buf = pathA.GetBuffer();
2930 if (!pathA.IsEmpty())
2932 opts.pathspec.strings = &buf;
2933 opts.pathspec.count = 1;
2935 CAutoDiff diff;
2937 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2939 CAutoTree t1;
2940 CAutoDiff diff2;
2942 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2943 return -1;
2945 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2946 return -1;
2948 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2949 return -1;
2951 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2952 return -1;
2954 if (git_diff_merge(diff, diff2))
2955 return -1;
2957 else
2959 if (tree1.IsEmpty() && tree2.IsEmpty())
2960 return -1;
2962 if (tree1.IsEmpty())
2964 tree1 = tree2;
2965 tree2.Empty();
2968 CAutoTree t1;
2969 CAutoTree t2;
2970 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2971 return -1;
2973 if (tree2.IsEmpty())
2975 /* don't check return value, there are not parent commit at first commit*/
2976 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2978 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2979 return -1;
2980 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2981 return -1;
2984 CAutoDiffStats stats;
2985 if (git_diff_get_stats(stats.GetPointer(), diff))
2986 return -1;
2987 CAutoBuf statBuf;
2988 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2989 return -1;
2990 statCallback(statBuf, data);
2992 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2994 CAutoPatch patch;
2995 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2996 return -1;
2998 if (git_patch_print(patch, callback, data))
2999 return -1;
3002 pathA.ReleaseBuffer();
3004 return 0;
3007 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
3009 if (UsingLibGit2(GIT_CMD_DIFF))
3011 FILE *file = nullptr;
3012 _tfopen_s(&file, patchfile, _T("w"));
3013 if (file == nullptr)
3014 return -1;
3015 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
3016 fclose(file);
3017 return ret;
3019 else
3021 CString cmd;
3022 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3023 return RunLogFile(cmd, patchfile, &gitLastErr);
3027 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
3029 ATLASSERT(payload && text);
3030 CStringA *str = (CStringA*) payload;
3031 str->Append(text->ptr, (int)text->size);
3032 str->AppendChar('\n');
3035 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
3037 ATLASSERT(payload && line);
3038 CStringA *str = (CStringA*) payload;
3039 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
3040 str->Append(&line->origin, 1);
3041 str->Append(line->content, (int)line->content_len);
3042 return 0;
3045 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
3047 if (UsingLibGit2(GIT_CMD_DIFF))
3048 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
3049 else
3051 CString cmd;
3052 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3053 BYTE_VECTOR vector;
3054 int ret = Run(cmd, &vector);
3055 if (!vector.empty())
3057 vector.push_back(0); // vector is not NUL terminated
3058 buffer->Append((char *)&vector[0]);
3060 return ret;
3064 int CGit::GitRevert(int parent, const CGitHash &hash)
3066 if (UsingLibGit2(GIT_CMD_REVERT))
3068 CAutoRepository repo(GetGitRepository());
3069 if (!repo)
3070 return -1;
3072 CAutoCommit commit;
3073 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
3074 return -1;
3076 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3077 revert_opts.mainline = parent;
3078 int result = git_revert(repo, commit, &revert_opts);
3080 return !result ? 0 : -1;
3082 else
3084 CString cmd, merge;
3085 if (parent)
3086 merge.Format(_T("-m %d "), parent);
3087 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), (LPCTSTR)merge, (LPCTSTR)hash.ToString());
3088 gitLastErr = cmd + _T("\n");
3089 if (Run(cmd, &gitLastErr, CP_UTF8))
3091 return -1;
3093 else
3095 gitLastErr.Empty();
3096 return 0;
3101 int CGit::DeleteRef(const CString& reference)
3103 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3105 CAutoRepository repo(GetGitRepository());
3106 if (!repo)
3107 return -1;
3109 CStringA refA;
3110 if (reference.Right(3) == _T("^{}"))
3111 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3112 else
3113 refA = CUnicodeUtils::GetUTF8(reference);
3115 CAutoReference ref;
3116 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3117 return -1;
3119 int result = -1;
3120 if (git_reference_is_tag(ref))
3121 result = git_tag_delete(repo, git_reference_shorthand(ref));
3122 else if (git_reference_is_branch(ref))
3123 result = git_branch_delete(ref);
3124 else if (git_reference_is_remote(ref))
3125 result = git_branch_delete(ref);
3126 else
3127 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
3129 return result;
3131 else
3133 CString cmd, shortname;
3134 if (GetShortName(reference, shortname, _T("refs/heads/")))
3135 cmd.Format(_T("git.exe branch -D -- %s"), (LPCTSTR)shortname);
3136 else if (GetShortName(reference, shortname, _T("refs/tags/")))
3137 cmd.Format(_T("git.exe tag -d -- %s"), (LPCTSTR)shortname);
3138 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
3139 cmd.Format(_T("git.exe branch -r -D -- %s"), (LPCTSTR)shortname);
3140 else
3142 gitLastErr = L"unsupported reference type: " + reference;
3143 return -1;
3146 if (Run(cmd, &gitLastErr, CP_UTF8))
3147 return -1;
3149 gitLastErr.Empty();
3150 return 0;
3154 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3156 if (PathFileExists(filename))
3158 FILE *pFile = nullptr;
3159 _tfopen_s(&pFile, filename, _T("r"));
3160 if (pFile)
3162 CStringA str;
3165 char s[8196] = { 0 };
3166 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3167 if (read == 0)
3168 break;
3169 str += CStringA(s, read);
3170 } while (true);
3171 fclose(pFile);
3172 msg = CUnicodeUtils::GetUnicode(str);
3173 msg.Replace(_T("\r\n"), _T("\n"));
3174 msg.TrimRight(_T("\n"));
3175 msg += _T("\n");
3177 else
3178 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3179 return true; // load no further files
3181 return false;
3184 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, CTGitPathList* filterlist)
3186 if (IsInitRepos())
3187 return GetInitAddList(result);
3189 BYTE_VECTOR out;
3191 int count = 1;
3192 if (filterlist)
3193 count = filterlist->GetCount();
3195 CString head = _T("HEAD");
3196 if (amend)
3197 head = _T("HEAD~1");
3199 for (int i = 0; i < count; ++i)
3201 BYTE_VECTOR cmdout;
3202 CString cmd;
3203 if (ms_bCygwinGit || ms_bMsys2Git)
3205 // Prevent showing all files as modified when using cygwin's git
3206 if (!filterlist)
3207 cmd = _T("git.exe status --");
3208 else
3209 cmd.Format(_T("git.exe status -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3210 Run(cmd, &cmdout);
3211 cmdout.clear();
3214 // also list staged files which will be in the commit
3215 Run(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"), &cmdout);
3217 if (!filterlist)
3218 cmd = (_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3219 else
3220 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3222 BYTE_VECTOR cmdErr;
3223 if (Run(cmd, &cmdout, &cmdErr))
3225 int last = cmdErr.RevertFind(0, -1);
3226 CString str;
3227 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last - 1);
3228 MessageBox(nullptr, str, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3231 out.append(cmdout, 0);
3233 result.ParserFromLog(out);
3235 // handle delete conflict case, when remote : modified, local : deleted.
3236 for (int i = 0; i < count; ++i)
3238 BYTE_VECTOR cmdout;
3239 CString cmd;
3241 if (!filterlist)
3242 cmd = _T("git.exe ls-files -u -t -z");
3243 else
3244 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3246 Run(cmd, &cmdout);
3248 CTGitPathList conflictlist;
3249 conflictlist.ParserFromLog(cmdout);
3250 for (int j = 0; j < conflictlist.GetCount(); ++j)
3252 CTGitPath* p = result.LookForGitPath(conflictlist[j].GetGitPathString());
3253 if (p)
3254 p->m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3255 else
3256 result.AddPath(conflictlist[j]);
3260 // handle source files of file renames/moves (issue #860)
3261 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3262 for (int i = 0; i < count; ++i)
3264 BYTE_VECTOR cmdout;
3265 CString cmd;
3267 if (!filterlist)
3268 cmd = _T("git.exe ls-files -d -z");
3269 else
3270 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""), (LPCTSTR)(*filterlist)[i].GetGitPathString());
3272 Run(cmd, &cmdout);
3274 CTGitPathList deletelist;
3275 deletelist.ParserFromLog(cmdout, true);
3276 for (int j = 0; j < deletelist.GetCount(); ++j)
3278 CTGitPath* p = result.LookForGitPath(deletelist[j].GetGitPathString());
3279 if (!p)
3280 result.AddPath(deletelist[j]);
3284 return 0;