Add support for Git for Windows 2.x and windows-wide system config
[TortoiseGit.git] / src / Git / Git.cpp
blob2519fcb3017740e4ccec588862765aa880de55e7
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 int CGit::m_LogEncode=CP_UTF8;
38 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
40 static LPCTSTR nextpath(const wchar_t* path, wchar_t* buf, size_t buflen)
42 if (path == NULL || buf == NULL || buflen == 0)
43 return NULL;
45 const wchar_t* base = path;
46 wchar_t term = (*path == L'"') ? *path++ : L';';
48 for (buflen--; *path && *path != term && buflen; buflen--)
49 *buf++ = *path++;
51 *buf = L'\0'; /* reserved a byte via initial subtract */
53 while (*path == term || *path == L';')
54 ++path;
56 return (path != base) ? path : NULL;
59 static inline BOOL FileExists(LPCTSTR lpszFileName)
61 struct _stat st;
62 return _tstat(lpszFileName, &st) == 0;
65 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
67 TCHAR buf[MAX_PATH] = { 0 };
69 // search in all paths defined in PATH
70 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
72 TCHAR *pfin = buf + _tcslen(buf) - 1;
74 // ensure trailing slash
75 if (*pfin != _T('/') && *pfin != _T('\\'))
76 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
78 const size_t len = _tcslen(buf);
80 if ((len + filename.GetLength()) < MAX_PATH)
81 _tcscpy_s(pfin + 1, MAX_PATH - len, filename);
82 else
83 break;
85 if (FileExists(buf))
87 if (wantDirectory)
88 pfin[1] = 0;
89 return buf;
93 return _T("");
96 static BOOL FindGitPath()
98 size_t size;
99 _tgetenv_s(&size, NULL, 0, _T("PATH"));
100 if (!size)
101 return FALSE;
103 TCHAR* env = (TCHAR*)alloca(size * sizeof(TCHAR));
104 if (!env)
105 return FALSE;
106 _tgetenv_s(&size, env, size, _T("PATH"));
108 CString gitExeDirectory = FindFileOnPath(_T("git.exe"), env, true);
109 if (!gitExeDirectory.IsEmpty())
111 CGit::ms_LastMsysGitDir = gitExeDirectory;
112 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
113 if (CGit::ms_LastMsysGitDir.GetLength() > 12 && (CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw32\\bin") || CGit::ms_LastMsysGitDir.Right(12) == _T("\\mingw64\\bin")))
115 // prefer cmd directory as early Git for Windows 2.x releases only had this
116 CString installRoot = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd\\git.exe");
117 if (FileExists(installRoot))
118 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 12) + _T("\\cmd");
120 if (CGit::ms_LastMsysGitDir.GetLength() > 4 && CGit::ms_LastMsysGitDir.Right(4) == _T("\\cmd"))
122 // often the msysgit\cmd folder is on the %PATH%, but
123 // that git.exe does not work, so try to guess the bin folder
124 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
125 if (FileExists(binDir))
126 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
128 return TRUE;
131 return FALSE;
134 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
136 CString filename = executable;
138 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
139 filename += _T(".exe");
141 if (FileExists(filename))
142 return filename;
144 filename = FindFileOnPath(filename, env);
145 if (!filename.IsEmpty())
146 return filename;
148 return executable;
151 static bool g_bSortLogical;
152 static bool g_bSortLocalBranchesFirst;
153 static bool g_bSortTagsReversed;
154 static git_cred_acquire_cb g_Git2CredCallback;
155 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
157 static void GetSortOptions()
159 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
160 if (g_bSortLogical)
161 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
162 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
163 if (g_bSortLocalBranchesFirst)
164 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
165 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
166 if (!g_bSortTagsReversed)
167 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
170 static int LogicalComparePredicate(const CString &left, const CString &right)
172 if (g_bSortLogical)
173 return StrCmpLogicalW(left, right) < 0;
174 return StrCmpI(left, right) < 0;
177 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
179 if (g_bSortLogical)
180 return StrCmpLogicalW(left, right) > 0;
181 return StrCmpI(left, right) > 0;
184 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
186 if (g_bSortLocalBranchesFirst)
188 int leftIsRemote = left.Find(_T("remotes/"));
189 int rightIsRemote = right.Find(_T("remotes/"));
191 if (leftIsRemote == 0 && rightIsRemote < 0)
192 return false;
193 else if (leftIsRemote < 0 && rightIsRemote == 0)
194 return true;
196 if (g_bSortLogical)
197 return StrCmpLogicalW(left, right) < 0;
198 return StrCmpI(left, right) < 0;
201 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
203 CString CGit::ms_LastMsysGitDir;
204 CString CGit::ms_MsysGitRootDir;
205 int CGit::ms_LastMsysGitVersion = 0;
206 CGit g_Git;
209 CGit::CGit(void)
211 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
212 m_CurrentDir.ReleaseBuffer();
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"), 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"), 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_bCygwinGit && cmd.Find(_T("git")) == 0)
339 cmd.Replace(_T('\\'), _T('/'));
340 cmd.Replace(_T("\""), _T("\\\""));
341 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
343 else if(cmd.Find(_T("git")) == 0)
345 int firstSpace = cmd.Find(_T(" "));
346 if (firstSpace > 0)
347 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
348 else
349 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
352 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
353 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
355 CString err = CFormatMessageWrapper();
356 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
357 return TGIT_GIT_ERROR_CREATE_PROCESS;
360 m_CurrentGitPi = pi;
362 if(piOut)
363 *piOut=pi;
364 if(hReadOut)
365 *hReadOut = hRead.Detach();
366 if(hErrReadOut)
367 *hErrReadOut = hReadErr.Detach();
368 return 0;
371 //Must use sperate function to convert ANSI str to union code string
372 //Becuase A2W use stack as internal convert buffer.
373 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
375 if(str == NULL)
376 return ;
378 int len ;
379 if(length<0)
380 len = (int)strlen((const char*)p);
381 else
382 len=length;
383 if (len == 0)
384 return;
385 int currentContentLen = str->GetLength();
386 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
387 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
388 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
391 // This method was originally used to check for orphaned branches
392 BOOL CGit::CanParseRev(CString ref)
394 if (ref.IsEmpty())
395 ref = _T("HEAD");
397 CString cmdout;
398 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
400 return FALSE;
402 if(cmdout.IsEmpty())
403 return FALSE;
405 return TRUE;
408 // Checks if we have an orphaned HEAD
409 BOOL CGit::IsInitRepos()
411 CGitHash hash;
412 if (GetHash(hash, _T("HEAD")) != 0)
413 return FALSE;
414 return hash.IsEmpty() ? TRUE : FALSE;
417 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
419 PASYNCREADSTDERRTHREADARGS pDataArray;
420 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
422 DWORD readnumber;
423 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
424 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
426 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
427 break;
430 return 0;
433 int CGit::Run(CGitCall* pcall)
435 PROCESS_INFORMATION pi;
436 CAutoGeneralHandle hRead, hReadErr;
437 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
438 return TGIT_GIT_ERROR_CREATE_PROCESS;
440 CAutoGeneralHandle piThread(pi.hThread);
441 CAutoGeneralHandle piProcess(pi.hProcess);
443 ASYNCREADSTDERRTHREADARGS threadArguments;
444 threadArguments.fileHandle = hReadErr;
445 threadArguments.pcall = pcall;
446 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
448 DWORD readnumber;
449 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
450 bool bAborted=false;
451 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
453 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
454 if(!bAborted)//For now, flush output when command aborted.
455 if(pcall->OnOutputData(data,readnumber))
456 bAborted=true;
458 if(!bAborted)
459 pcall->OnEnd();
461 if (thread)
462 WaitForSingleObject(thread, INFINITE);
464 WaitForSingleObject(pi.hProcess, INFINITE);
465 DWORD exitcode =0;
467 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
469 CString err = CFormatMessageWrapper();
470 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
471 return TGIT_GIT_ERROR_GET_EXIT_CODE;
473 else
474 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
476 return exitcode;
478 class CGitCall_ByteVector : public CGitCall
480 public:
481 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
482 virtual bool OnOutputData(const BYTE* data, size_t size)
484 if (!m_pvector || size == 0)
485 return false;
486 size_t oldsize=m_pvector->size();
487 m_pvector->resize(m_pvector->size()+size);
488 memcpy(&*(m_pvector->begin()+oldsize),data,size);
489 return false;
491 virtual bool OnOutputErrData(const BYTE* data, size_t size)
493 if (!m_pvectorErr || size == 0)
494 return false;
495 size_t oldsize = m_pvectorErr->size();
496 m_pvectorErr->resize(m_pvectorErr->size() + size);
497 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
498 return false;
500 BYTE_VECTOR* m_pvector;
501 BYTE_VECTOR* m_pvectorErr;
504 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
506 CGitCall_ByteVector call(cmd, vector, vectorErr);
507 return Run(&call);
509 int CGit::Run(CString cmd, CString* output, int code)
511 CString err;
512 int ret;
513 ret = Run(cmd, output, &err, code);
515 if (output && !err.IsEmpty())
517 if (!output->IsEmpty())
518 *output += _T("\n");
519 *output += err;
522 return ret;
524 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
526 BYTE_VECTOR vector, vectorErr;
527 int ret;
528 if (outputErr)
529 ret = Run(cmd, &vector, &vectorErr);
530 else
531 ret = Run(cmd, &vector);
533 vector.push_back(0);
534 StringAppend(output, &(vector[0]), code);
536 if (outputErr)
538 vectorErr.push_back(0);
539 StringAppend(outputErr, &(vectorErr[0]), code);
542 return ret;
545 class CGitCallCb : public CGitCall
547 public:
548 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
550 virtual bool OnOutputData(const BYTE* data, size_t size) override
552 // Add data
553 if (size == 0)
554 return false;
555 int oldEndPos = m_buffer.GetLength();
556 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
557 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
559 // Break into lines and feed to m_recv
560 int eolPos;
561 while ((eolPos = m_buffer.Find('\n')) >= 0)
563 m_recv(m_buffer.Left(eolPos));
564 m_buffer = m_buffer.Mid(eolPos + 1);
566 return false;
569 virtual bool OnOutputErrData(const BYTE*, size_t) override
571 return false; // Ignore error output for now
574 virtual void OnEnd() override
576 if (!m_buffer.IsEmpty())
577 m_recv(m_buffer);
578 m_buffer.Empty(); // Just for sure
581 private:
582 GitReceiverFunc m_recv;
583 CStringA m_buffer;
586 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
588 CGitCallCb call(cmd, recv);
589 return Run(&call);
592 CString CGit::GetUserName(void)
594 CEnvironment env;
595 env.CopyProcessEnvironment();
596 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
597 if (!envname.IsEmpty())
598 return envname;
599 return GetConfigValue(L"user.name");
601 CString CGit::GetUserEmail(void)
603 CEnvironment env;
604 env.CopyProcessEnvironment();
605 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
606 if (!envmail.IsEmpty())
607 return envmail;
609 return GetConfigValue(L"user.email");
612 CString CGit::GetConfigValue(const CString& name)
614 CString configValue;
615 if(this->m_IsUseGitDLL)
617 CAutoLocker lock(g_Git.m_critGitDllSec);
621 CheckAndInitDll();
622 }catch(...)
625 CStringA key, value;
626 key = CUnicodeUtils::GetUTF8(name);
630 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
631 return CString();
633 catch (const char *msg)
635 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
636 return CString();
639 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
640 return configValue;
642 else
644 CString cmd;
645 cmd.Format(L"git.exe config %s", name);
646 Run(cmd, &configValue, nullptr, CP_UTF8);
647 if (configValue.IsEmpty())
648 return configValue;
649 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
653 bool CGit::GetConfigValueBool(const CString& name)
655 CString configValue = GetConfigValue(name);
656 configValue.MakeLower();
657 configValue.Trim();
658 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
659 return true;
660 else
661 return false;
664 int CGit::GetConfigValueInt32(const CString& name, int def)
666 CString configValue = GetConfigValue(name);
667 int value = def;
668 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
669 return value;
670 return def;
673 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
675 if(this->m_IsUseGitDLL)
677 CAutoLocker lock(g_Git.m_critGitDllSec);
681 CheckAndInitDll();
683 }catch(...)
686 CStringA keya, valuea;
687 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
688 valuea = CUnicodeUtils::GetUTF8(value);
692 return [=]() { return get_set_config(keya, valuea, type); }();
694 catch (const char *msg)
696 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
697 return -1;
700 else
702 CString cmd;
703 CString option;
704 switch(type)
706 case CONFIG_GLOBAL:
707 option = _T("--global");
708 break;
709 case CONFIG_SYSTEM:
710 option = _T("--system");
711 break;
712 default:
713 break;
715 CString mangledValue = value;
716 mangledValue.Replace(_T("\\\""), _T("\\\\\""));
717 mangledValue.Replace(_T("\""), _T("\\\""));
718 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, mangledValue);
719 CString out;
720 if (Run(cmd, &out, nullptr, CP_UTF8))
722 return -1;
725 return 0;
728 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
730 if(this->m_IsUseGitDLL)
732 CAutoLocker lock(g_Git.m_critGitDllSec);
736 CheckAndInitDll();
737 }catch(...)
740 CStringA keya;
741 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
745 return [=]() { return get_set_config(keya, nullptr, type); }();
747 catch (const char *msg)
749 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
750 return -1;
753 else
755 CString cmd;
756 CString option;
757 switch(type)
759 case CONFIG_GLOBAL:
760 option = _T("--global");
761 break;
762 case CONFIG_SYSTEM:
763 option = _T("--system");
764 break;
765 default:
766 break;
768 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
769 CString out;
770 if (Run(cmd, &out, nullptr, CP_UTF8))
772 return -1;
775 return 0;
778 CString CGit::GetCurrentBranch(bool fallback)
780 CString output;
781 //Run(_T("git.exe branch"),&branch);
783 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
784 if (result != 0 && ((result == 1 && !fallback) || result != 1))
786 return _T("(no branch)");
788 else
789 return output;
793 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
795 if (localBranch.IsEmpty())
796 return;
798 CString configName;
799 configName.Format(L"branch.%s.remote", localBranch);
800 pullRemote = GetConfigValue(configName);
802 //Select pull-branch from current branch
803 configName.Format(L"branch.%s.merge", localBranch);
804 pullBranch = StripRefName(GetConfigValue(configName));
807 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
809 CString refName;
810 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
811 return;
812 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
815 CString CGit::GetFullRefName(const CString& shortRefName)
817 CString refName;
818 CString cmd;
819 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
820 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
821 return CString();//Error
822 int iStart = 0;
823 return refName.Tokenize(L"\n", iStart);
826 CString CGit::StripRefName(CString refName)
828 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
829 refName = refName.Mid(11);
830 else if(wcsncmp(refName, L"refs/", 5) == 0)
831 refName = refName.Mid(5);
832 int start =0;
833 return refName.Tokenize(_T("\n"),start);
836 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
838 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
840 if ( sProjectRoot.IsEmpty() )
841 return -1;
843 CString sDotGitPath;
844 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
845 return -1;
847 CString sHeadFile = sDotGitPath + _T("HEAD");
849 FILE *pFile;
850 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
852 if (!pFile)
854 return -1;
857 char s[256] = {0};
858 fgets(s, sizeof(s), pFile);
860 fclose(pFile);
862 const char *pfx = "ref: refs/heads/";
863 const int len = 16;//strlen(pfx)
865 if ( !strncmp(s, pfx, len) )
867 //# We're on a branch. It might not exist. But
868 //# HEAD looks good enough to be a branch.
869 CStringA utf8Branch(s + len);
870 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
871 sBranchOut.TrimRight(_T(" \r\n\t"));
873 if ( sBranchOut.IsEmpty() )
874 return -1;
876 else if (fallback)
878 CStringA utf8Hash(s);
879 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
880 unicodeHash.TrimRight(_T(" \r\n\t"));
881 if (CGitHash::IsValidSHA1(unicodeHash))
882 sBranchOut = unicodeHash;
883 else
884 //# Assume this is a detached head.
885 sBranchOut = _T("HEAD");
886 return 1;
888 else
890 //# Assume this is a detached head.
891 sBranchOut = "HEAD";
893 return 1;
896 return 0;
899 int CGit::BuildOutputFormat(CString &format,bool IsFull)
901 CString log;
902 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
903 format += log;
904 if(IsFull)
906 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
907 format += log;
908 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
909 format += log;
910 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
911 format += log;
912 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
913 format += log;
914 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
915 format += log;
916 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
917 format += log;
918 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
919 format += log;
922 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
923 format += log;
924 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
925 format += log;
926 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
927 format += log;
929 if(IsFull)
931 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
932 format += log;
934 return 0;
937 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
938 CFilterData *Filter)
940 CString cmd;
941 CString num;
942 CString since;
944 CString file = _T(" --");
946 if(path)
947 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
949 if(count>0)
950 num.Format(_T("-n%d"),count);
952 CString param;
954 if(mask& LOG_INFO_STAT )
955 param += _T(" --numstat ");
956 if(mask& LOG_INFO_FILESTATE)
957 param += _T(" --raw ");
959 if(mask& LOG_INFO_FULLHISTORY)
960 param += _T(" --full-history ");
962 if(mask& LOG_INFO_BOUNDARY)
963 param += _T(" --left-right --boundary ");
965 if(mask& CGit::LOG_INFO_ALL_BRANCH)
966 param += _T(" --all ");
968 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
969 param += _T(" --branches ");
971 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
972 param += _T(" -C ");
974 if(mask& CGit::LOG_INFO_DETECT_RENAME )
975 param += _T(" -M ");
977 if(mask& CGit::LOG_INFO_FIRST_PARENT )
978 param += _T(" --first-parent ");
980 if(mask& CGit::LOG_INFO_NO_MERGE )
981 param += _T(" --no-merges ");
983 if(mask& CGit::LOG_INFO_FOLLOW)
984 param += _T(" --follow ");
986 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
987 param += _T(" -c ");
989 if(mask& CGit::LOG_INFO_FULL_DIFF)
990 param += _T(" --full-diff ");
992 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
993 param += _T(" --simplify-by-decoration ");
995 param += range;
997 CString st1,st2;
999 if( Filter && (Filter->m_From != -1))
1001 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
1002 param += st1;
1005 if( Filter && (Filter->m_To != -1))
1007 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
1008 param += st2;
1011 bool isgrep = false;
1012 if( Filter && (!Filter->m_Author.IsEmpty()))
1014 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
1015 param += st1;
1016 isgrep = true;
1019 if( Filter && (!Filter->m_Committer.IsEmpty()))
1021 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1022 param += st1;
1023 isgrep = true;
1026 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1028 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1029 param += st1;
1030 isgrep = true;
1033 if(Filter && isgrep)
1035 if(!Filter->m_IsRegex)
1036 param += _T(" --fixed-strings ");
1038 param += _T(" --regexp-ignore-case --extended-regexp ");
1041 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1042 if (logOrderBy == LOG_ORDER_TOPOORDER)
1043 param += _T(" --topo-order");
1044 else if (logOrderBy == LOG_ORDER_DATEORDER)
1045 param += _T(" --date-order");
1047 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
1048 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1049 else
1051 CString log;
1052 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1053 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1054 num,param,log);
1057 cmd += file;
1059 return cmd;
1061 #define BUFSIZE 512
1062 void GetTempPath(CString &path)
1064 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1065 DWORD dwRetVal;
1066 DWORD dwBufSize=BUFSIZE;
1067 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1068 lpPathBuffer); // buffer for path
1069 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1071 path=_T("");
1073 path.Format(_T("%s"),lpPathBuffer);
1075 CString GetTempFile()
1077 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1078 DWORD dwRetVal;
1079 DWORD dwBufSize=BUFSIZE;
1080 TCHAR szTempName[BUFSIZE] = { 0 };
1081 UINT uRetVal;
1083 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1084 lpPathBuffer); // buffer for path
1085 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1087 return _T("");
1089 // Create a temporary file.
1090 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1091 TEXT("Patch"), // temp file name prefix
1092 0, // create unique name
1093 szTempName); // buffer for name
1096 if (uRetVal == 0)
1098 return _T("");
1101 return CString(szTempName);
1105 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1107 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1108 if (result == 0) return 0;
1109 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1111 if (lpBuffer)
1112 lpBuffer[0] = '\0';
1113 return result + 13;
1116 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1117 CreateDirectory(lpBuffer, NULL);
1119 return result + 13;
1122 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1124 STARTUPINFO si;
1125 PROCESS_INFORMATION pi;
1126 si.cb=sizeof(STARTUPINFO);
1127 GetStartupInfo(&si);
1129 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1130 psa.bInheritHandle=TRUE;
1132 HANDLE hReadErr, hWriteErr;
1133 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1135 CString err = CFormatMessageWrapper();
1136 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1137 return TGIT_GIT_ERROR_OPEN_PIP;
1140 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1141 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1143 if (houtfile == INVALID_HANDLE_VALUE)
1145 CString err = CFormatMessageWrapper();
1146 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1147 CloseHandle(hReadErr);
1148 CloseHandle(hWriteErr);
1149 return TGIT_GIT_ERROR_OPEN_PIP;
1152 si.wShowWindow = SW_HIDE;
1153 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1154 si.hStdOutput = houtfile;
1155 si.hStdError = hWriteErr;
1157 LPTSTR pEnv = m_Environment;
1158 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1160 if(cmd.Find(_T("git")) == 0)
1161 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1163 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1164 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1166 CString err = CFormatMessageWrapper();
1167 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1168 stdErr = &err;
1169 CloseHandle(hReadErr);
1170 CloseHandle(hWriteErr);
1171 CloseHandle(houtfile);
1172 return TGIT_GIT_ERROR_CREATE_PROCESS;
1175 BYTE_VECTOR stderrVector;
1176 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1177 HANDLE thread;
1178 ASYNCREADSTDERRTHREADARGS threadArguments;
1179 threadArguments.fileHandle = hReadErr;
1180 threadArguments.pcall = &pcall;
1181 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1183 WaitForSingleObject(pi.hProcess,INFINITE);
1185 CloseHandle(hWriteErr);
1186 CloseHandle(hReadErr);
1188 if (thread)
1189 WaitForSingleObject(thread, INFINITE);
1191 stderrVector.push_back(0);
1192 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1194 DWORD exitcode = 0;
1195 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1197 CString err = CFormatMessageWrapper();
1198 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1199 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1201 else
1202 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1204 CloseHandle(pi.hThread);
1205 CloseHandle(pi.hProcess);
1206 CloseHandle(houtfile);
1207 return exitcode;
1210 git_repository * CGit::GetGitRepository() const
1212 git_repository * repo = nullptr;
1213 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1214 return repo;
1217 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1219 ATLASSERT(repo);
1221 // no need to parse a ref if it's already a 40-byte hash
1222 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1224 hash = CGitHash(friendname);
1225 return 0;
1228 int isHeadOrphan = git_repository_head_unborn(repo);
1229 if (isHeadOrphan != 0)
1231 hash.Empty();
1232 if (isHeadOrphan == 1)
1233 return 0;
1234 else
1235 return -1;
1238 CAutoObject gitObject;
1239 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1240 return -1;
1242 const git_oid * oid = git_object_id(gitObject);
1243 if (!oid)
1244 return -1;
1246 hash = CGitHash((char *)oid->id);
1248 return 0;
1251 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1253 // no need to parse a ref if it's already a 40-byte hash
1254 if (CGitHash::IsValidSHA1(friendname))
1256 hash = CGitHash(friendname);
1257 return 0;
1260 if (m_IsUseLibGit2)
1262 CAutoRepository repo(GetGitRepository());
1263 if (!repo)
1264 return -1;
1266 return GetHash(repo, hash, friendname, true);
1268 else
1270 CString branch = FixBranchName(friendname);
1271 if (friendname == _T("FETCH_HEAD") && branch.IsEmpty())
1272 branch = friendname;
1273 CString cmd;
1274 cmd.Format(_T("git.exe rev-parse %s"), branch);
1275 gitLastErr.Empty();
1276 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1277 hash = CGitHash(gitLastErr.Trim());
1278 if (ret == 0)
1279 gitLastErr.Empty();
1280 else if (friendname == _T("HEAD")) // special check for unborn branch
1282 CString currentbranch;
1283 if (GetCurrentBranchFromFile(m_CurrentDir, currentbranch))
1284 return -1;
1285 gitLastErr.Empty();
1286 return 0;
1288 return ret;
1292 int CGit::GetInitAddList(CTGitPathList &outputlist)
1294 CString cmd;
1295 BYTE_VECTOR cmdout;
1297 cmd=_T("git.exe ls-files -s -t -z");
1298 outputlist.Clear();
1299 if (Run(cmd, &cmdout))
1300 return -1;
1302 if (outputlist.ParserFromLsFile(cmdout))
1303 return -1;
1304 for(int i = 0; i < outputlist.GetCount(); ++i)
1305 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1307 return 0;
1309 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1311 CString cmd;
1312 CString ignore;
1313 if (ignoreSpaceAtEol)
1314 ignore += _T(" --ignore-space-at-eol");
1315 if (ignoreSpaceChange)
1316 ignore += _T(" --ignore-space-change");
1317 if (ignoreAllSpace)
1318 ignore += _T(" --ignore-all-space");
1319 if (ignoreBlankLines)
1320 ignore += _T(" --ignore-blank-lines");
1322 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1324 //rev1=+_T("");
1325 if(rev1 == GIT_REV_ZERO)
1326 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1327 else
1328 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1330 else
1332 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1335 BYTE_VECTOR out;
1336 if (Run(cmd, &out))
1337 return -1;
1339 return outputlist.ParserFromLog(out);
1342 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1344 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1345 list->push_back(CUnicodeUtils::GetUnicode(refname));
1346 return 0;
1349 int CGit::GetTagList(STRING_VECTOR &list)
1351 if (this->m_IsUseLibGit2)
1353 CAutoRepository repo(GetGitRepository());
1354 if (!repo)
1355 return -1;
1357 CAutoStrArray tag_names;
1359 if (git_tag_list(tag_names, repo))
1360 return -1;
1362 for (size_t i = 0; i < tag_names->count; ++i)
1364 CStringA tagName(tag_names->strings[i]);
1365 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1368 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1370 return 0;
1372 else
1374 CString cmd, output;
1375 cmd=_T("git.exe tag -l");
1376 int ret = Run(cmd, &output, NULL, CP_UTF8);
1377 if(!ret)
1379 int pos=0;
1380 CString one;
1381 while( pos>=0 )
1383 one=output.Tokenize(_T("\n"),pos);
1384 if (!one.IsEmpty())
1385 list.push_back(one);
1387 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1389 else if (ret == 1 && IsInitRepos())
1390 return 0;
1391 return ret;
1395 CString CGit::GetGitLastErr(const CString& msg)
1397 if (this->m_IsUseLibGit2)
1398 return GetLibGit2LastErr(msg);
1399 else if (gitLastErr.IsEmpty())
1400 return msg + _T("\nUnknown git.exe error.");
1401 else
1403 CString lastError = gitLastErr;
1404 gitLastErr.Empty();
1405 return msg + _T("\n") + lastError;
1409 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1411 if (UsingLibGit2(cmd))
1412 return GetLibGit2LastErr(msg);
1413 else if (gitLastErr.IsEmpty())
1414 return msg + _T("\nUnknown git.exe error.");
1415 else
1417 CString lastError = gitLastErr;
1418 gitLastErr.Empty();
1419 return msg + _T("\n") + lastError;
1423 CString CGit::GetLibGit2LastErr()
1425 const git_error *libgit2err = giterr_last();
1426 if (libgit2err)
1428 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1429 giterr_clear();
1430 return _T("libgit2 returned: ") + lastError;
1432 else
1433 return _T("An error occoured in libgit2, but no message is available.");
1436 CString CGit::GetLibGit2LastErr(const CString& msg)
1438 if (!msg.IsEmpty())
1439 return msg + _T("\n") + GetLibGit2LastErr();
1440 return GetLibGit2LastErr();
1443 CString CGit::FixBranchName_Mod(CString& branchName)
1445 if(branchName == "FETCH_HEAD")
1446 branchName = DerefFetchHead();
1447 return branchName;
1450 CString CGit::FixBranchName(const CString& branchName)
1452 CString tempBranchName = branchName;
1453 FixBranchName_Mod(tempBranchName);
1454 return tempBranchName;
1457 bool CGit::IsBranchTagNameUnique(const CString& name)
1459 if (m_IsUseLibGit2)
1461 CAutoRepository repo(GetGitRepository());
1462 if (!repo)
1463 return true; // TODO: optimize error reporting
1465 CAutoReference tagRef;
1466 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1467 return true;
1469 CAutoReference branchRef;
1470 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1471 return true;
1473 return false;
1475 // else
1476 CString output;
1478 CString cmd;
1479 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1480 int ret = Run(cmd, &output, NULL, CP_UTF8);
1481 if (!ret)
1483 int i = 0, pos = 0;
1484 while (pos >= 0)
1486 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1487 ++i;
1489 if (i >= 2)
1490 return false;
1493 return true;
1496 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1498 if (m_IsUseLibGit2)
1500 CAutoRepository repo(GetGitRepository());
1501 if (!repo)
1502 return false; // TODO: optimize error reporting
1504 CString prefix;
1505 if (isBranch)
1506 prefix = _T("refs/heads/");
1507 else
1508 prefix = _T("refs/tags/");
1510 CAutoReference ref;
1511 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1512 return false;
1514 return true;
1516 // else
1517 CString cmd, output;
1519 cmd = _T("git.exe show-ref ");
1520 if (isBranch)
1521 cmd += _T("--heads ");
1522 else
1523 cmd += _T("--tags ");
1525 cmd += _T("refs/heads/") + name;
1526 cmd += _T(" refs/tags/") + name;
1528 int ret = Run(cmd, &output, NULL, CP_UTF8);
1529 if (!ret)
1531 if (!output.IsEmpty())
1532 return true;
1535 return false;
1538 CString CGit::DerefFetchHead()
1540 CString dotGitPath;
1541 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1542 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1543 int forMergeLineCount = 0;
1544 std::string line;
1545 std::string hashToReturn;
1546 while(getline(fetchHeadFile, line))
1548 //Tokenize this line
1549 std::string::size_type prevPos = 0;
1550 std::string::size_type pos = line.find('\t');
1551 if(pos == std::string::npos) continue; //invalid line
1553 std::string hash = line.substr(0, pos);
1554 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1556 bool forMerge = pos == prevPos;
1557 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1559 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1561 //Process this line
1562 if(forMerge)
1564 hashToReturn = hash;
1565 ++forMergeLineCount;
1566 if(forMergeLineCount > 1)
1567 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1571 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1574 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1576 int ret = 0;
1577 CString cur;
1578 if (m_IsUseLibGit2)
1580 CAutoRepository repo(GetGitRepository());
1581 if (!repo)
1582 return -1;
1584 if (git_repository_head_detached(repo) == 1)
1585 cur = _T("(detached from ");
1587 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1589 git_branch_t flags = GIT_BRANCH_LOCAL;
1590 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1591 flags = GIT_BRANCH_ALL;
1592 else if (type & BRANCH_REMOTE)
1593 flags = GIT_BRANCH_REMOTE;
1595 CAutoBranchIterator it;
1596 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1597 return -1;
1599 git_reference * ref = nullptr;
1600 git_branch_t branchType;
1601 while (git_branch_next(&ref, &branchType, it) == 0)
1603 CAutoReference autoRef(ref);
1604 const char * name = nullptr;
1605 if (git_branch_name(&name, ref))
1606 continue;
1608 CString branchname = CUnicodeUtils::GetUnicode(name);
1609 if (branchType & GIT_BRANCH_REMOTE)
1610 list.push_back(_T("remotes/") + branchname);
1611 else
1613 if (git_branch_is_head(ref))
1614 cur = branchname;
1615 list.push_back(branchname);
1620 else
1622 CString cmd, output;
1623 cmd = _T("git.exe branch --no-color");
1625 if ((type & BRANCH_ALL) == BRANCH_ALL)
1626 cmd += _T(" -a");
1627 else if (type & BRANCH_REMOTE)
1628 cmd += _T(" -r");
1630 ret = Run(cmd, &output, nullptr, CP_UTF8);
1631 if (!ret)
1633 int pos = 0;
1634 CString one;
1635 while (pos >= 0)
1637 one = output.Tokenize(_T("\n"), pos);
1638 one.Trim(L" \r\n\t");
1639 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1640 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1641 if (one[0] == _T('*'))
1643 one = one.Mid(2);
1644 cur = one;
1646 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1648 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1649 one = _T("remotes/") + one;
1650 list.push_back(one);
1654 else if (ret == 1 && IsInitRepos())
1655 return 0;
1658 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1659 list.push_back(L"FETCH_HEAD");
1661 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1663 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1665 for (unsigned int i = 0; i < list.size(); ++i)
1667 if (list[i] == cur)
1669 *current = i;
1670 break;
1675 return ret;
1678 int CGit::GetRemoteList(STRING_VECTOR &list)
1680 if (this->m_IsUseLibGit2)
1682 CAutoRepository repo(GetGitRepository());
1683 if (!repo)
1684 return -1;
1686 CAutoStrArray remotes;
1687 if (git_remote_list(remotes, repo))
1688 return -1;
1690 for (size_t i = 0; i < remotes->count; ++i)
1692 CStringA remote(remotes->strings[i]);
1693 list.push_back(CUnicodeUtils::GetUnicode(remote));
1696 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1698 return 0;
1700 else
1702 int ret;
1703 CString cmd, output;
1704 cmd=_T("git.exe remote");
1705 ret = Run(cmd, &output, NULL, CP_UTF8);
1706 if(!ret)
1708 int pos=0;
1709 CString one;
1710 while( pos>=0 )
1712 one=output.Tokenize(_T("\n"),pos);
1713 if (!one.IsEmpty())
1714 list.push_back(one);
1717 return ret;
1721 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1723 if (UsingLibGit2(GIT_CMD_FETCH))
1725 CAutoRepository repo(GetGitRepository());
1726 if (!repo)
1727 return -1;
1729 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1730 CAutoRemote gitremote;
1731 if (git_remote_lookup(gitremote.GetPointer(), repo, remoteA) < 0)
1732 return -1;
1734 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1735 callbacks.credentials = g_Git2CredCallback;
1736 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1737 git_remote_set_callbacks(gitremote, &callbacks);
1738 if (git_remote_connect(gitremote, GIT_DIRECTION_FETCH) < 0)
1739 return -1;
1741 const git_remote_head** heads = nullptr;
1742 size_t size = 0;
1743 if (git_remote_ls(&heads, &size, gitremote) < 0)
1744 return -1;
1746 for (size_t i = 0; i < size; i++)
1748 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1749 CString shortname;
1750 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1751 continue;
1752 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1753 if (shortname.Find(_T("^{}")) >= 1)
1754 continue;
1755 list.push_back(shortname);
1757 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1758 return 0;
1761 CString cmd, out, err;
1762 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1763 if (Run(cmd, &out, &err, CP_UTF8))
1765 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1766 return -1;
1769 int pos = 0;
1770 while (pos >= 0)
1772 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1773 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1774 if (one.Find(_T("^{}")) >= 1)
1775 continue;
1776 if (!one.IsEmpty())
1777 list.push_back(one);
1779 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1780 return 0;
1783 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1785 if (UsingLibGit2(GIT_CMD_PUSH))
1787 CAutoRepository repo(GetGitRepository());
1788 if (!repo)
1789 return -1;
1791 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1792 CAutoRemote remote;
1793 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1794 return -1;
1796 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1797 callbacks.credentials = g_Git2CredCallback;
1798 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1799 git_remote_set_callbacks(remote, &callbacks);
1800 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1801 return -1;
1803 std::vector<CStringA> refspecs;
1804 for (auto ref : list)
1805 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1807 std::vector<char*> vc;
1808 vc.reserve(refspecs.size());
1809 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1810 git_strarray specs = { &vc[0], vc.size() };
1812 if (git_remote_push(remote, &specs, nullptr) < 0)
1813 return -1;
1815 else
1817 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1818 for (auto ref : list)
1820 CString refspec = _T(":") + ref;
1821 mgtPush.AddFile(refspec);
1824 BOOL cancel = FALSE;
1825 mgtPush.Execute(cancel);
1828 return 0;
1831 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1833 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1834 list->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref)));
1835 return 0;
1838 int CGit::GetRefList(STRING_VECTOR &list)
1840 if (this->m_IsUseLibGit2)
1842 CAutoRepository repo(GetGitRepository());
1843 if (!repo)
1844 return -1;
1846 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1847 return -1;
1849 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1851 return 0;
1853 else
1855 CString cmd, output;
1856 cmd=_T("git.exe show-ref -d");
1857 int ret = Run(cmd, &output, NULL, CP_UTF8);
1858 if(!ret)
1860 int pos=0;
1861 CString one;
1862 while( pos>=0 )
1864 one=output.Tokenize(_T("\n"),pos);
1865 int start=one.Find(_T(" "),0);
1866 if(start>0)
1868 CString name;
1869 name=one.Right(one.GetLength()-start-1);
1870 if (list.empty() || name != *list.crbegin() + _T("^{}"))
1871 list.push_back(name);
1874 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1876 else if (ret == 1 && IsInitRepos())
1877 return 0;
1878 return ret;
1882 typedef struct map_each_ref_payload {
1883 git_repository * repo;
1884 MAP_HASH_NAME * map;
1885 } map_each_ref_payload;
1887 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1889 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1891 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1893 CAutoObject gitObject;
1894 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1895 return 1;
1897 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1899 str += _T("^{}"); // deref tag
1900 CAutoObject derefedTag;
1901 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1902 return 1;
1903 gitObject.Swap(derefedTag);
1906 const git_oid * oid = git_object_id(gitObject);
1907 if (oid == NULL)
1908 return 1;
1910 CGitHash hash((char *)oid->id);
1911 (*payloadContent->map)[hash].push_back(str);
1913 return 0;
1915 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1917 ATLASSERT(repo);
1919 map_each_ref_payload payloadContent = { repo, &map };
1921 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1922 return -1;
1924 for (auto it = map.begin(); it != map.end(); ++it)
1926 std::sort(it->second.begin(), it->second.end());
1929 return 0;
1932 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1934 if (this->m_IsUseLibGit2)
1936 CAutoRepository repo(GetGitRepository());
1937 if (!repo)
1938 return -1;
1940 return GetMapHashToFriendName(repo, map);
1942 else
1944 CString cmd, output;
1945 cmd=_T("git.exe show-ref -d");
1946 int ret = Run(cmd, &output, NULL, CP_UTF8);
1947 if(!ret)
1949 int pos=0;
1950 CString one;
1951 while( pos>=0 )
1953 one=output.Tokenize(_T("\n"),pos);
1954 int start=one.Find(_T(" "),0);
1955 if(start>0)
1957 CString name;
1958 name=one.Right(one.GetLength()-start-1);
1960 CString hash;
1961 hash=one.Left(start);
1963 map[CGitHash(hash)].push_back(name);
1967 else if (ret == 1 && IsInitRepos())
1968 return 0;
1969 return ret;
1973 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
1975 CAutoConfig config(true);
1976 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE) < 0)
1977 return -1;
1978 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
1980 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
1981 CString key = CUnicodeUtils::GetUnicode(entry->name);
1982 key = key.Mid(7, key.GetLength() - 7 - 12); // 7: branch., 12: .description
1983 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
1984 return 0;
1985 }, &map);
1988 static void SetLibGit2SearchPath(int level, const CString &value)
1990 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1991 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1994 static void SetLibGit2TemplatePath(const CString &value)
1996 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1997 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
2000 int CGit::FindAndSetGitExePath(BOOL bFallback)
2002 CRegString msysdir = CRegString(REG_MSYSGIT_PATH, _T(""), FALSE);
2003 CString str = msysdir;
2004 if (!str.IsEmpty() && FileExists(str + _T("\\git.exe")))
2006 CGit::ms_LastMsysGitDir = str;
2007 return TRUE;
2010 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2011 if (!bFallback)
2012 return FALSE;
2014 // first, search PATH if git/bin directory is already present
2015 if (FindGitPath())
2017 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2018 msysdir = CGit::ms_LastMsysGitDir;
2019 msysdir.write();
2020 return TRUE;
2023 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2024 str = msyslocalinstalldir;
2025 str.TrimRight(_T("\\"));
2026 #ifdef _WIN64
2027 if (str.IsEmpty())
2029 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2030 str = msysinstalldir;
2031 str.TrimRight(_T("\\"));
2033 #endif
2034 if (str.IsEmpty())
2036 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2037 str = msysinstalldir;
2038 str.TrimRight(_T("\\"));
2040 if (!str.IsEmpty())
2042 if (FileExists(str + _T("\\bin\\git.exe")))
2043 str += _T("\\bin");
2044 else if (FileExists(str + _T("\\cmd\\git.exe"))) // only needed for older Git for Windows 2.x packages
2045 str += _T("\\cmd");
2046 else
2048 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Git for Windows installation found, but git.exe not exists in %s\n"), str);
2049 return FALSE;
2051 msysdir = str;
2052 CGit::ms_LastMsysGitDir = str;
2053 msysdir.write();
2054 return TRUE;
2057 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": Found no git.exe\n"));
2058 return FALSE;
2061 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
2063 if (m_bInitialized)
2065 return TRUE;
2068 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
2069 this->m_Environment.clear();
2070 m_Environment.CopyProcessEnvironment();
2071 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2073 // set HOME if not set already
2074 size_t homesize;
2075 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
2076 if (!homesize)
2077 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
2079 //setup ssh client
2080 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
2081 if (sshclient.IsEmpty())
2082 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
2084 if(!sshclient.IsEmpty())
2086 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
2087 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
2089 else
2091 TCHAR sPlink[MAX_PATH] = {0};
2092 GetModuleFileName(NULL, sPlink, _countof(sPlink));
2093 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
2094 if (ptr) {
2095 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
2096 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
2097 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2102 TCHAR sAskPass[MAX_PATH] = {0};
2103 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2104 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2105 if (ptr)
2107 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2108 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2109 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2110 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2114 if (!FindAndSetGitExePath(bFallback))
2115 return FALSE;
2117 CString msysGitDir;
2118 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\"));
2119 msysGitDir.ReleaseBuffer();
2120 static CString prefixes[] = { L"mingw64\\etc", L"mingw32\\etc", L"etc" };
2121 static int prefixes_len[] = { 8, 8, 0 };
2122 for (int i = 0; i < _countof(prefixes); ++i)
2124 #ifndef _WIN64
2125 if (i == 0)
2126 continue;
2127 #endif
2128 if (PathIsDirectory(msysGitDir + prefixes[i])) {
2129 msysGitDir += prefixes[i].Left(prefixes_len[i]);
2130 break;
2133 CGit::ms_MsysGitRootDir = msysGitDir;
2135 if ((CString)CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) != g_Git.GetGitSystemConfig())
2136 CRegString(REG_SYSTEM_GITCONFIGPATH, _T(""), FALSE) = g_Git.GetGitSystemConfig();
2138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2139 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_MsysGitRootDir = %s\n"), CGit::ms_MsysGitRootDir);
2140 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": System config = %s\n"), g_Git.GetGitSystemConfig());
2142 // Configure libgit2 search paths
2143 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2144 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2145 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2146 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition = { [](git_smart_subtransport **out, git_transport* owner) -> 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 };
2147 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2148 if (!ms_bCygwinGit)
2149 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("share\\git-core\\templates"));
2150 else
2151 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + _T("usr\\share\\git-core\\templates"));
2153 m_Environment.AddToPath(CGit::ms_LastMsysGitDir);
2154 m_Environment.AddToPath((CString)CRegString(REG_MSYSGIT_EXTRA_PATH, _T(""), FALSE));
2156 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2157 // register filter only once
2158 if (!git_filter_lookup("filter"))
2160 static CString binDirPrefixes[] = { L"", L"\\..\\bin", L"\\..\\usr\\bin" };
2161 CString sh;
2162 for (const CString& binDirPrefix : binDirPrefixes)
2164 CString possibleShExe = CGit::ms_LastMsysGitDir + binDirPrefix + L"\\sh.exe";
2165 if (PathFileExists(possibleShExe))
2167 CString temp;
2168 PathCanonicalize(temp.GetBufferSetLength(MAX_PATH), possibleShExe);
2169 temp.ReleaseBuffer();
2170 sh.Format(L"\"%s\"", temp);
2171 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2172 m_Environment.AddToPath(temp.Left(temp.GetLength() - 7)); // 7 = len("\\sh.exe")
2173 break;
2176 if (git_filter_register("filter", git_filter_filter_new(sh, m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2177 return FALSE;
2179 #endif
2181 m_bInitialized = TRUE;
2182 return true;
2185 CString CGit::GetHomeDirectory() const
2187 const wchar_t * homeDir = wget_windows_home_directory();
2188 return CString(homeDir, (int)wcslen(homeDir));
2191 CString CGit::GetGitLocalConfig() const
2193 CString path;
2194 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2195 path += _T("config");
2196 return path;
2199 CStringA CGit::GetGitPathStringA(const CString &path)
2201 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2204 CString CGit::GetGitGlobalConfig() const
2206 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2209 CString CGit::GetGitGlobalXDGConfigPath() const
2211 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2214 CString CGit::GetGitGlobalXDGConfig() const
2216 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2219 CString CGit::GetGitSystemConfig() const
2221 const wchar_t * systemConfig = wget_msysgit_etc();
2222 return CString(systemConfig, (int)wcslen(systemConfig));
2225 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2227 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2229 CAutoRepository repo = GetGitRepository();
2230 if (!repo)
2231 return FALSE;
2233 if (git_repository_head_unborn(repo))
2234 return FALSE;
2236 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2237 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2238 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2240 CAutoStatusList status;
2241 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2242 return FALSE;
2244 return (0 == git_status_list_entrycount(status));
2247 CString out;
2248 CString cmd;
2249 cmd=_T("git.exe rev-parse --verify HEAD");
2251 if(Run(cmd,&out,CP_UTF8))
2252 return FALSE;
2254 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2255 if(Run(cmd,&out,CP_UTF8))
2256 return FALSE;
2258 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2259 if(Run(cmd,&out,CP_UTF8))
2260 return FALSE;
2262 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2263 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2264 return FALSE;
2266 return TRUE;
2268 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2270 int ret;
2271 for (int i = 0; i < list.GetCount(); ++i)
2273 ret = Revert(commit, (CTGitPath&)list[i], err);
2274 if(ret)
2275 return ret;
2277 return 0;
2279 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2281 CString cmd;
2283 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2285 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2287 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2288 return -1;
2290 CString force;
2291 // if the filenames only differ in case, we have to pass "-f"
2292 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2293 force = _T("-f ");
2294 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2295 if (Run(cmd, &err, CP_UTF8))
2296 return -1;
2298 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2299 if (Run(cmd, &err, CP_UTF8))
2300 return -1;
2302 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2303 { //To init git repository, there are not HEAD, so we can use git reset command
2304 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2306 if (Run(cmd, &err, CP_UTF8))
2307 return -1;
2309 else
2311 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2312 if (Run(cmd, &err, CP_UTF8))
2313 return -1;
2316 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2318 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2319 if (Run(cmd, &err, CP_UTF8))
2320 return -1;
2323 return 0;
2326 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2328 ATLASSERT(repo);
2330 CAutoIndex index;
2331 if (git_repository_index(index.GetPointer(), repo))
2332 return -1;
2334 return git_index_has_conflicts(index);
2337 int CGit::HasWorkingTreeConflicts()
2339 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2341 CAutoRepository repo(GetGitRepository());
2342 if (!repo)
2343 return -1;
2345 return HasWorkingTreeConflicts(repo);
2348 CString cmd = _T("git.exe ls-files -u -t -z");
2350 CString output;
2351 if (Run(cmd, &output, &gitLastErr, CP_UTF8))
2352 return -1;
2354 return output.IsEmpty() ? 0 : 1;
2357 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2359 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2361 CAutoRepository repo(GetGitRepository());
2362 if (!repo)
2363 return false;
2365 CGitHash fromHash, toHash, baseHash;
2366 if (GetHash(repo, toHash, FixBranchName(to)))
2367 return false;
2369 if (GetHash(repo, fromHash, FixBranchName(from)))
2370 return false;
2372 git_oid baseOid;
2373 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2374 return false;
2376 baseHash = baseOid.id;
2378 if (commonAncestor)
2379 *commonAncestor = baseHash;
2381 return fromHash == baseHash;
2383 // else
2384 CString base;
2385 CGitHash basehash,hash;
2386 CString cmd;
2387 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2389 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2391 return false;
2393 basehash = base.Trim();
2395 GetHash(hash, from);
2397 if (commonAncestor)
2398 *commonAncestor = basehash;
2400 return hash == basehash;
2403 unsigned int CGit::Hash2int(const CGitHash &hash)
2405 int ret=0;
2406 for (int i = 0; i < 4; ++i)
2408 ret = ret << 8;
2409 ret |= hash.m_hash[i];
2411 return ret;
2414 int CGit::RefreshGitIndex()
2416 if(g_Git.m_IsUseGitDLL)
2418 CAutoLocker lock(g_Git.m_critGitDllSec);
2421 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2423 }catch(...)
2425 return -1;
2429 else
2431 CString cmd,output;
2432 cmd=_T("git.exe update-index --refresh");
2433 return Run(cmd, &output, CP_UTF8);
2437 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2439 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2441 CAutoRepository repo(GetGitRepository());
2442 if (!repo)
2443 return -1;
2445 CGitHash hash;
2446 if (GetHash(repo, hash, Refname))
2447 return -1;
2449 CAutoCommit commit;
2450 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2451 return -1;
2453 CAutoTree tree;
2454 if (git_commit_tree(tree.GetPointer(), commit))
2455 return -1;
2457 CAutoTreeEntry entry;
2458 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2459 return -1;
2461 CAutoBlob blob;
2462 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2463 return -1;
2465 FILE *file = nullptr;
2466 _tfopen_s(&file, outputfile, _T("wb"));
2467 if (file == nullptr)
2469 giterr_set_str(GITERR_NONE, "Could not create file.");
2470 return -1;
2472 CAutoBuf buf;
2473 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2475 fclose(file);
2476 return -1;
2478 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2480 giterr_set_str(GITERR_OS, "Could not write to file.");
2481 fclose(file);
2483 return -1;
2485 fclose(file);
2487 return 0;
2489 else if (g_Git.m_IsUseGitDLL)
2491 CAutoLocker lock(g_Git.m_critGitDllSec);
2494 g_Git.CheckAndInitDll();
2495 CStringA ref, patha, outa;
2496 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2497 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2498 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2499 ::DeleteFile(outputfile);
2500 int ret = git_checkout_file(ref, patha, outa.GetBuffer());
2501 outa.ReleaseBuffer();
2502 return ret;
2505 catch (const char * msg)
2507 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2508 return -1;
2510 catch (...)
2512 gitLastErr = L"An unknown gitdll.dll error occurred.";
2513 return -1;
2516 else
2518 CString cmd;
2519 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2520 return RunLogFile(cmd, outputfile, &gitLastErr);
2524 void CEnvironment::clear()
2526 __super::clear();
2529 bool CEnvironment::empty()
2531 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2534 CEnvironment::operator LPTSTR()
2536 if (empty())
2537 return nullptr;
2538 return &__super::at(0);
2541 void CEnvironment::CopyProcessEnvironment()
2543 if (!empty())
2544 pop_back();
2545 TCHAR *porig = GetEnvironmentStrings();
2546 TCHAR *p = porig;
2547 while(*p !=0 || *(p+1) !=0)
2548 this->push_back(*p++);
2550 push_back(_T('\0'));
2551 push_back(_T('\0'));
2553 FreeEnvironmentStrings(porig);
2556 CString CEnvironment::GetEnv(const TCHAR *name)
2558 CString str;
2559 for (size_t i = 0; i < size(); ++i)
2561 str = &(*this)[i];
2562 int start =0;
2563 CString sname = str.Tokenize(_T("="),start);
2564 if(sname.CompareNoCase(name) == 0)
2566 return &(*this)[i+start];
2568 i+=str.GetLength();
2570 return _T("");
2573 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2575 unsigned int i;
2576 for (i = 0; i < size(); ++i)
2578 CString str = &(*this)[i];
2579 int start =0;
2580 CString sname = str.Tokenize(_T("="),start);
2581 if(sname.CompareNoCase(name) == 0)
2583 break;
2585 i+=str.GetLength();
2588 if(i == size())
2590 if (!value) // as we haven't found the variable we want to remove, just return
2591 return;
2592 if (i == 0) // make inserting into an empty environment work
2594 this->push_back(_T('\0'));
2595 ++i;
2597 i -= 1; // roll back terminate \0\0
2598 this->push_back(_T('\0'));
2601 CEnvironment::iterator it;
2602 it=this->begin();
2603 it += i;
2605 while(*it && i<size())
2607 this->erase(it);
2608 it=this->begin();
2609 it += i;
2612 if (value == nullptr) // remove the variable
2614 this->erase(it);
2615 return;
2618 while(*name)
2620 this->insert(it,*name++);
2621 ++i;
2622 it= begin()+i;
2625 this->insert(it, _T('='));
2626 ++i;
2627 it= begin()+i;
2629 while(*value)
2631 this->insert(it,*value++);
2632 ++i;
2633 it= begin()+i;
2638 void CEnvironment::AddToPath(CString value)
2640 value.TrimRight(L"\\");
2641 if (value.IsEmpty())
2642 return;
2644 CString path = GetEnv(L"PATH").TrimRight(L";") + L";";
2646 // do not double add paths to %PATH%
2647 if (path.Find(value + L";") >= 0 || path.Find(value + L"\\;") >= 0)
2648 return;
2650 path += value;
2652 SetEnv(L"PATH", path);
2655 int CGit::GetGitEncode(TCHAR* configkey)
2657 CString str=GetConfigValue(configkey);
2659 if(str.IsEmpty())
2660 return CP_UTF8;
2662 return CUnicodeUtils::GetCPCode(str);
2666 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2668 GIT_FILE file=0;
2669 int ret=0;
2670 GIT_DIFF diff=0;
2672 CAutoLocker lock(g_Git.m_critGitDllSec);
2676 if(!arg)
2677 diff = GetGitDiff();
2678 else
2679 git_open_diff(&diff, arg);
2681 catch (char* e)
2683 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2684 return -1;
2687 if(diff ==NULL)
2688 return -1;
2690 bool isStat = 0;
2691 if(arg == NULL)
2692 isStat = true;
2693 else
2694 isStat = !!strstr(arg, "stat");
2696 int count=0;
2698 if(hash2 == NULL)
2699 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2700 else
2701 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2703 if(ret)
2704 return -1;
2706 CTGitPath path;
2707 CString strnewname;
2708 CString stroldname;
2710 for (int j = 0; j < count; ++j)
2712 path.Reset();
2713 char *newname;
2714 char *oldname;
2716 strnewname.Empty();
2717 stroldname.Empty();
2719 int mode=0,IsBin=0,inc=0,dec=0;
2720 git_get_diff_file(diff,file,j,&newname,&oldname,
2721 &mode,&IsBin,&inc,&dec);
2723 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2724 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2726 path.SetFromGit(strnewname,&stroldname);
2727 path.ParserAction((BYTE)mode);
2729 if(IsBin)
2731 path.m_StatAdd=_T("-");
2732 path.m_StatDel=_T("-");
2734 else
2736 path.m_StatAdd.Format(_T("%d"),inc);
2737 path.m_StatDel.Format(_T("%d"),dec);
2739 PathList->AddPath(path);
2741 git_diff_flush(diff);
2743 if(arg)
2744 git_close_diff(diff);
2746 return 0;
2749 int CGit::GetShortHASHLength() const
2751 return 7;
2754 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2756 CString str=ref;
2757 CString shortname;
2758 REF_TYPE type = CGit::UNKNOWN;
2760 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2762 type = CGit::LOCAL_BRANCH;
2765 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2767 type = CGit::REMOTE_BRANCH;
2769 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2771 type = CGit::TAG;
2773 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2775 type = CGit::STASH;
2776 shortname=_T("stash");
2778 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2780 if (shortname.Find(_T("good")) == 0)
2782 type = CGit::BISECT_GOOD;
2783 shortname = _T("good");
2786 if (shortname.Find(_T("bad")) == 0)
2788 type = CGit::BISECT_BAD;
2789 shortname = _T("bad");
2792 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2794 type = CGit::NOTES;
2796 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2798 type = CGit::UNKNOWN;
2800 else
2802 type = CGit::UNKNOWN;
2803 shortname = ref;
2806 if(out_type)
2807 *out_type = type;
2809 return shortname;
2812 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2814 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2817 void CGit::SetGit2CredentialCallback(void* callback)
2819 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2822 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2824 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2827 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2829 CString cmd;
2830 if (rev2 == GitRev::GetWorkingCopy())
2831 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2832 else if (rev1 == GitRev::GetWorkingCopy())
2833 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2834 else
2836 CString merge;
2837 if (bMerge)
2838 merge += _T(" -m");
2840 if (bCombine)
2841 merge += _T(" -c");
2843 CString unified;
2844 if (diffContext >= 0)
2845 unified.Format(_T(" --unified=%d"), diffContext);
2846 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2849 if (!path.IsEmpty())
2851 cmd += _T(" \"");
2852 cmd += path.GetGitPathString();
2853 cmd += _T("\"");
2856 return cmd;
2859 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2861 ATLASSERT(payload && text);
2862 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2863 fwrite("\n", 1, 1, (FILE *)payload);
2866 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2868 ATLASSERT(payload && line);
2869 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2870 fwrite(&line->origin, 1, 1, (FILE *)payload);
2871 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2872 return 0;
2875 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2877 ATLASSERT(repo && identifier && tree);
2879 /* try to resolve identifier */
2880 CAutoObject obj;
2881 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2882 return -1;
2884 if (obj == nullptr)
2885 return GIT_ENOTFOUND;
2887 int err = 0;
2888 switch (git_object_type(obj))
2890 case GIT_OBJ_TREE:
2891 *tree = (git_tree *)obj.Detach();
2892 break;
2893 case GIT_OBJ_COMMIT:
2894 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2895 break;
2896 default:
2897 err = GIT_ENOTFOUND;
2900 return err;
2903 /* use libgit2 get unified diff */
2904 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 */)
2906 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2907 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2909 CAutoRepository repo(g_Git.GetGitRepository());
2910 if (!repo)
2911 return -1;
2913 int isHeadOrphan = git_repository_head_unborn(repo);
2914 if (isHeadOrphan == 1)
2915 return 0;
2916 else if (isHeadOrphan != 0)
2917 return -1;
2919 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2920 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2921 char *buf = pathA.GetBuffer();
2922 if (!pathA.IsEmpty())
2924 opts.pathspec.strings = &buf;
2925 opts.pathspec.count = 1;
2927 CAutoDiff diff;
2929 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2931 CAutoTree t1;
2932 CAutoDiff diff2;
2934 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2935 return -1;
2937 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2938 return -1;
2940 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2941 return -1;
2943 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2944 return -1;
2946 if (git_diff_merge(diff, diff2))
2947 return -1;
2949 else
2951 if (tree1.IsEmpty() && tree2.IsEmpty())
2952 return -1;
2954 if (tree1.IsEmpty())
2956 tree1 = tree2;
2957 tree2.Empty();
2960 CAutoTree t1;
2961 CAutoTree t2;
2962 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2963 return -1;
2965 if (tree2.IsEmpty())
2967 /* don't check return value, there are not parent commit at first commit*/
2968 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2970 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2971 return -1;
2972 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2973 return -1;
2976 CAutoDiffStats stats;
2977 if (git_diff_get_stats(stats.GetPointer(), diff))
2978 return -1;
2979 CAutoBuf statBuf;
2980 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2981 return -1;
2982 statCallback(statBuf, data);
2984 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2986 CAutoPatch patch;
2987 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2988 return -1;
2990 if (git_patch_print(patch, callback, data))
2991 return -1;
2994 pathA.ReleaseBuffer();
2996 return 0;
2999 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
3001 if (UsingLibGit2(GIT_CMD_DIFF))
3003 FILE *file = nullptr;
3004 _tfopen_s(&file, patchfile, _T("w"));
3005 if (file == nullptr)
3006 return -1;
3007 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
3008 fclose(file);
3009 return ret;
3011 else
3013 CString cmd;
3014 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3015 return RunLogFile(cmd, patchfile, &gitLastErr);
3019 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
3021 ATLASSERT(payload && text);
3022 CStringA *str = (CStringA*) payload;
3023 str->Append(text->ptr, (int)text->size);
3024 str->AppendChar('\n');
3027 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
3029 ATLASSERT(payload && line);
3030 CStringA *str = (CStringA*) payload;
3031 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
3032 str->Append(&line->origin, 1);
3033 str->Append(line->content, (int)line->content_len);
3034 return 0;
3037 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
3039 if (UsingLibGit2(GIT_CMD_DIFF))
3040 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
3041 else
3043 CString cmd;
3044 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3045 BYTE_VECTOR vector;
3046 int ret = Run(cmd, &vector);
3047 if (!vector.empty())
3049 vector.push_back(0); // vector is not NUL terminated
3050 buffer->Append((char *)&vector[0]);
3052 return ret;
3056 int CGit::GitRevert(int parent, const CGitHash &hash)
3058 if (UsingLibGit2(GIT_CMD_REVERT))
3060 CAutoRepository repo(GetGitRepository());
3061 if (!repo)
3062 return -1;
3064 CAutoCommit commit;
3065 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
3066 return -1;
3068 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3069 revert_opts.mainline = parent;
3070 int result = git_revert(repo, commit, &revert_opts);
3072 return !result ? 0 : -1;
3074 else
3076 CString cmd, merge;
3077 if (parent)
3078 merge.Format(_T("-m %d "), parent);
3079 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
3080 gitLastErr = cmd + _T("\n");
3081 if (Run(cmd, &gitLastErr, CP_UTF8))
3083 return -1;
3085 else
3087 gitLastErr.Empty();
3088 return 0;
3093 int CGit::DeleteRef(const CString& reference)
3095 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3097 CAutoRepository repo(GetGitRepository());
3098 if (!repo)
3099 return -1;
3101 CStringA refA;
3102 if (reference.Right(3) == _T("^{}"))
3103 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3104 else
3105 refA = CUnicodeUtils::GetUTF8(reference);
3107 CAutoReference ref;
3108 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3109 return -1;
3111 int result = -1;
3112 if (git_reference_is_tag(ref))
3113 result = git_tag_delete(repo, git_reference_shorthand(ref));
3114 else if (git_reference_is_branch(ref))
3115 result = git_branch_delete(ref);
3116 else if (git_reference_is_remote(ref))
3117 result = git_branch_delete(ref);
3118 else
3119 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
3121 return result;
3123 else
3125 CString cmd, shortname;
3126 if (GetShortName(reference, shortname, _T("refs/heads/")))
3127 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
3128 else if (GetShortName(reference, shortname, _T("refs/tags/")))
3129 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
3130 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
3131 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
3132 else
3134 gitLastErr = L"unsupported reference type: " + reference;
3135 return -1;
3138 if (Run(cmd, &gitLastErr, CP_UTF8))
3139 return -1;
3141 gitLastErr.Empty();
3142 return 0;
3146 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3148 if (PathFileExists(filename))
3150 FILE *pFile = nullptr;
3151 _tfopen_s(&pFile, filename, _T("r"));
3152 if (pFile)
3154 CStringA str;
3157 char s[8196] = { 0 };
3158 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3159 if (read == 0)
3160 break;
3161 str += CStringA(s, read);
3162 } while (true);
3163 fclose(pFile);
3164 msg = CUnicodeUtils::GetUnicode(str);
3165 msg.Replace(_T("\r\n"), _T("\n"));
3166 msg.TrimRight(_T("\n"));
3167 msg += _T("\n");
3169 else
3170 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3171 return true; // load no further files
3173 return false;
3176 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, CTGitPathList* filterlist)
3178 if (IsInitRepos())
3179 return GetInitAddList(result);
3181 BYTE_VECTOR out;
3183 int count = 1;
3184 if (filterlist)
3185 count = filterlist->GetCount();
3187 CString head = _T("HEAD");
3188 if (amend)
3189 head = _T("HEAD~1");
3191 for (int i = 0; i < count; ++i)
3193 BYTE_VECTOR cmdout;
3194 CString cmd;
3195 if (ms_bCygwinGit)
3197 // Prevent showing all files as modified when using cygwin's git
3198 if (!filterlist)
3199 cmd = _T("git.exe status --");
3200 else
3201 cmd.Format(_T("git.exe status -- \"%s\""), (*filterlist)[i].GetGitPathString());
3202 Run(cmd, &cmdout);
3203 cmdout.clear();
3206 // also list staged files which will be in the commit
3207 Run(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"), &cmdout);
3209 if (!filterlist)
3210 cmd = (_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3211 else
3212 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3214 BYTE_VECTOR cmdErr;
3215 if (Run(cmd, &cmdout, &cmdErr))
3217 int last = cmdErr.RevertFind(0, -1);
3218 CString str;
3219 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last - 1);
3220 MessageBox(nullptr, str, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3223 out.append(cmdout, 0);
3225 result.ParserFromLog(out);
3227 // handle delete conflict case, when remote : modified, local : deleted.
3228 for (int i = 0; i < count; ++i)
3230 BYTE_VECTOR cmdout;
3231 CString cmd;
3233 if (!filterlist)
3234 cmd = _T("git.exe ls-files -u -t -z");
3235 else
3236 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3238 Run(cmd, &cmdout);
3240 CTGitPathList conflictlist;
3241 conflictlist.ParserFromLog(cmdout);
3242 for (int j = 0; j < conflictlist.GetCount(); ++j)
3244 CTGitPath* p = result.LookForGitPath(conflictlist[j].GetGitPathString());
3245 if (p)
3246 p->m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3247 else
3248 result.AddPath(conflictlist[j]);
3252 // handle source files of file renames/moves (issue #860)
3253 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3254 for (int i = 0; i < count; ++i)
3256 BYTE_VECTOR cmdout;
3257 CString cmd;
3259 if (!filterlist)
3260 cmd = _T("git.exe ls-files -d -z");
3261 else
3262 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3264 Run(cmd, &cmdout);
3266 CTGitPathList deletelist;
3267 deletelist.ParserFromLog(cmdout, true);
3268 for (int j = 0; j < deletelist.GetCount(); ++j)
3270 CTGitPath* p = result.LookForGitPath(deletelist[j].GetGitPathString());
3271 if (!p)
3272 result.AddPath(deletelist[j]);
3276 return 0;