GetOneFile() should write file in binary mode
[TortoiseGit.git] / src / Git / Git.cpp
blob00851aaffc7bec24177e6e83868b58f3fad6bf0e
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 "FormatMessageWrapper.h"
28 #include "SmartHandle.h"
29 #include "MassiveGitTaskBase.h"
30 #include "git2/sys/filter.h"
31 #include "git2/sys/transport.h"
32 #include "../libgit2/filter-filter.h"
33 #include "../libgit2/ssh-wintunnel.h"
35 bool CGit::ms_bCygwinGit = (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE) == TRUE);
36 int CGit::m_LogEncode=CP_UTF8;
37 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
39 static LPCTSTR nextpath(const wchar_t* path, wchar_t* buf, size_t buflen)
41 if (path == NULL || buf == NULL || buflen == 0)
42 return NULL;
44 const wchar_t* base = path;
45 wchar_t term = (*path == L'"') ? *path++ : L';';
47 for (buflen--; *path && *path != term && buflen; buflen--)
48 *buf++ = *path++;
50 *buf = L'\0'; /* reserved a byte via initial subtract */
52 while (*path == term || *path == L';')
53 ++path;
55 return (path != base) ? path : NULL;
58 static inline BOOL FileExists(LPCTSTR lpszFileName)
60 struct _stat st;
61 return _tstat(lpszFileName, &st) == 0;
64 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
66 TCHAR buf[MAX_PATH] = { 0 };
68 // search in all paths defined in PATH
69 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
71 TCHAR *pfin = buf + _tcslen(buf) - 1;
73 // ensure trailing slash
74 if (*pfin != _T('/') && *pfin != _T('\\'))
75 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
77 const size_t len = _tcslen(buf);
79 if ((len + filename.GetLength()) < MAX_PATH)
80 _tcscpy_s(pfin + 1, MAX_PATH - len, filename);
81 else
82 break;
84 if (FileExists(buf))
86 if (wantDirectory)
87 pfin[1] = 0;
88 return buf;
92 return _T("");
95 static BOOL FindGitPath()
97 size_t size;
98 _tgetenv_s(&size, NULL, 0, _T("PATH"));
99 if (!size)
100 return FALSE;
102 TCHAR* env = (TCHAR*)alloca(size * sizeof(TCHAR));
103 if (!env)
104 return FALSE;
105 _tgetenv_s(&size, env, size, _T("PATH"));
107 CString gitExeDirectory = FindFileOnPath(_T("git.exe"), env, true);
108 if (!gitExeDirectory.IsEmpty())
110 CGit::ms_LastMsysGitDir = gitExeDirectory;
111 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
112 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
114 // often the msysgit\cmd folder is on the %PATH%, but
115 // that git.exe does not work, so try to guess the bin folder
116 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
117 if (FileExists(binDir))
118 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
120 return TRUE;
123 return FALSE;
126 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
128 CString filename = executable;
130 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
131 filename += _T(".exe");
133 if (FileExists(filename))
134 return filename;
136 filename = FindFileOnPath(filename, env);
137 if (!filename.IsEmpty())
138 return filename;
140 return executable;
143 static bool g_bSortLogical;
144 static bool g_bSortLocalBranchesFirst;
145 static bool g_bSortTagsReversed;
146 static git_cred_acquire_cb g_Git2CredCallback;
147 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
149 static void GetSortOptions()
151 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
152 if (g_bSortLogical)
153 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
154 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
155 if (g_bSortLocalBranchesFirst)
156 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
157 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
158 if (!g_bSortTagsReversed)
159 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
162 static int LogicalComparePredicate(const CString &left, const CString &right)
164 if (g_bSortLogical)
165 return StrCmpLogicalW(left, right) < 0;
166 return StrCmpI(left, right) < 0;
169 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
171 if (g_bSortLogical)
172 return StrCmpLogicalW(left, right) > 0;
173 return StrCmpI(left, right) > 0;
176 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
178 if (g_bSortLocalBranchesFirst)
180 int leftIsRemote = left.Find(_T("remotes/"));
181 int rightIsRemote = right.Find(_T("remotes/"));
183 if (leftIsRemote == 0 && rightIsRemote < 0)
184 return false;
185 else if (leftIsRemote < 0 && rightIsRemote == 0)
186 return true;
188 if (g_bSortLogical)
189 return StrCmpLogicalW(left, right) < 0;
190 return StrCmpI(left, right) < 0;
193 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
195 CString CGit::ms_LastMsysGitDir;
196 int CGit::ms_LastMsysGitVersion = 0;
197 CGit g_Git;
200 CGit::CGit(void)
202 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
203 m_CurrentDir.ReleaseBuffer();
204 m_IsGitDllInited = false;
205 m_GitDiff=0;
206 m_GitSimpleListDiff=0;
207 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
208 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
209 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK);
211 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
213 GetSortOptions();
214 this->m_bInitialized =false;
215 CheckMsysGitDir();
216 m_critGitDllSec.Init();
219 CGit::~CGit(void)
221 if(this->m_GitDiff)
223 git_close_diff(m_GitDiff);
224 m_GitDiff=0;
226 if(this->m_GitSimpleListDiff)
228 git_close_diff(m_GitSimpleListDiff);
229 m_GitSimpleListDiff=0;
233 bool CGit::IsBranchNameValid(const CString& branchname)
235 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
236 return false;
237 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
238 return false;
239 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
240 return !!git_reference_is_valid_name(branchA);
243 static bool IsPowerShell(CString cmd)
245 cmd.MakeLower();
246 int powerShellPos = cmd.Find(_T("powershell"));
247 if (powerShellPos < 0)
248 return false;
250 // found the word powershell, check that it is the command and not any parameter
251 int end = cmd.GetLength();
252 if (cmd.Find(_T('"')) == 0)
254 int secondDoubleQuote = cmd.Find(_T('"'), 1);
255 if (secondDoubleQuote > 0)
256 end = secondDoubleQuote;
258 else
260 int firstSpace = cmd.Find(_T(' '));
261 if (firstSpace > 0)
262 end = firstSpace;
265 return (end - 4 - 10 == powerShellPos || end - 10 == powerShellPos); // len(".exe")==4, len("powershell")==10
268 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
270 SECURITY_ATTRIBUTES sa;
271 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
272 CAutoGeneralHandle hStdioFile;
274 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
275 sa.lpSecurityDescriptor=NULL;
276 sa.bInheritHandle=TRUE;
277 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
279 CString err = CFormatMessageWrapper();
280 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
281 return TGIT_GIT_ERROR_OPEN_PIP;
283 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
285 CString err = CFormatMessageWrapper();
286 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
287 return TGIT_GIT_ERROR_OPEN_PIP;
290 if(StdioFile)
292 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
293 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
296 STARTUPINFO si = { 0 };
297 PROCESS_INFORMATION pi;
298 si.cb=sizeof(STARTUPINFO);
300 if (hErrReadOut)
301 si.hStdError = hWriteErr;
302 else
303 si.hStdError = hWrite;
304 if(StdioFile)
305 si.hStdOutput=hStdioFile;
306 else
307 si.hStdOutput=hWrite;
309 si.wShowWindow=SW_HIDE;
310 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
312 LPTSTR pEnv = m_Environment;
313 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
315 dwFlags |= CREATE_NEW_PROCESS_GROUP;
317 // 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,
318 // 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)
319 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
320 if (IsPowerShell(cmd))
321 dwFlags |= CREATE_NEW_CONSOLE;
322 else
323 dwFlags |= DETACHED_PROCESS;
325 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
326 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
328 if (ms_bCygwinGit && cmd.Find(_T("git")) == 0)
330 cmd.Replace(_T('\\'), _T('/'));
331 cmd.Replace(_T("\""), _T("\\\""));
332 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
334 else if(cmd.Find(_T("git")) == 0)
336 int firstSpace = cmd.Find(_T(" "));
337 if (firstSpace > 0)
338 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
339 else
340 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
343 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
344 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
346 CString err = CFormatMessageWrapper();
347 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
348 return TGIT_GIT_ERROR_CREATE_PROCESS;
351 m_CurrentGitPi = pi;
353 if(piOut)
354 *piOut=pi;
355 if(hReadOut)
356 *hReadOut = hRead.Detach();
357 if(hErrReadOut)
358 *hErrReadOut = hReadErr.Detach();
359 return 0;
362 //Must use sperate function to convert ANSI str to union code string
363 //Becuase A2W use stack as internal convert buffer.
364 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
366 if(str == NULL)
367 return ;
369 int len ;
370 if(length<0)
371 len = (int)strlen((const char*)p);
372 else
373 len=length;
374 if (len == 0)
375 return;
376 int currentContentLen = str->GetLength();
377 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
378 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
379 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
382 // This method was originally used to check for orphaned branches
383 BOOL CGit::CanParseRev(CString ref)
385 if (ref.IsEmpty())
386 ref = _T("HEAD");
388 CString cmdout;
389 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
391 return FALSE;
393 if(cmdout.IsEmpty())
394 return FALSE;
396 return TRUE;
399 // Checks if we have an orphaned HEAD
400 BOOL CGit::IsInitRepos()
402 CGitHash hash;
403 if (GetHash(hash, _T("HEAD")) != 0)
404 return FALSE;
405 return hash.IsEmpty() ? TRUE : FALSE;
408 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
410 PASYNCREADSTDERRTHREADARGS pDataArray;
411 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
413 DWORD readnumber;
414 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
415 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
417 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
418 break;
421 return 0;
424 int CGit::Run(CGitCall* pcall)
426 PROCESS_INFORMATION pi;
427 CAutoGeneralHandle hRead, hReadErr;
428 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
429 return TGIT_GIT_ERROR_CREATE_PROCESS;
431 CAutoGeneralHandle piThread(pi.hThread);
432 CAutoGeneralHandle piProcess(pi.hProcess);
434 ASYNCREADSTDERRTHREADARGS threadArguments;
435 threadArguments.fileHandle = hReadErr;
436 threadArguments.pcall = pcall;
437 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
439 DWORD readnumber;
440 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
441 bool bAborted=false;
442 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
444 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
445 if(!bAborted)//For now, flush output when command aborted.
446 if(pcall->OnOutputData(data,readnumber))
447 bAborted=true;
449 if(!bAborted)
450 pcall->OnEnd();
452 if (thread)
453 WaitForSingleObject(thread, INFINITE);
455 WaitForSingleObject(pi.hProcess, INFINITE);
456 DWORD exitcode =0;
458 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
460 CString err = CFormatMessageWrapper();
461 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
462 return TGIT_GIT_ERROR_GET_EXIT_CODE;
464 else
465 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
467 return exitcode;
469 class CGitCall_ByteVector : public CGitCall
471 public:
472 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
473 virtual bool OnOutputData(const BYTE* data, size_t size)
475 if (!m_pvector || size == 0)
476 return false;
477 size_t oldsize=m_pvector->size();
478 m_pvector->resize(m_pvector->size()+size);
479 memcpy(&*(m_pvector->begin()+oldsize),data,size);
480 return false;
482 virtual bool OnOutputErrData(const BYTE* data, size_t size)
484 if (!m_pvectorErr || size == 0)
485 return false;
486 size_t oldsize = m_pvectorErr->size();
487 m_pvectorErr->resize(m_pvectorErr->size() + size);
488 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
489 return false;
491 BYTE_VECTOR* m_pvector;
492 BYTE_VECTOR* m_pvectorErr;
495 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
497 CGitCall_ByteVector call(cmd, vector, vectorErr);
498 return Run(&call);
500 int CGit::Run(CString cmd, CString* output, int code)
502 CString err;
503 int ret;
504 ret = Run(cmd, output, &err, code);
506 if (output && !err.IsEmpty())
508 if (!output->IsEmpty())
509 *output += _T("\n");
510 *output += err;
513 return ret;
515 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
517 BYTE_VECTOR vector, vectorErr;
518 int ret;
519 if (outputErr)
520 ret = Run(cmd, &vector, &vectorErr);
521 else
522 ret = Run(cmd, &vector);
524 vector.push_back(0);
525 StringAppend(output, &(vector[0]), code);
527 if (outputErr)
529 vectorErr.push_back(0);
530 StringAppend(outputErr, &(vectorErr[0]), code);
533 return ret;
536 class CGitCallCb : public CGitCall
538 public:
539 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
541 virtual bool OnOutputData(const BYTE* data, size_t size) override
543 // Add data
544 if (size == 0)
545 return false;
546 int oldEndPos = m_buffer.GetLength();
547 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
548 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
550 // Break into lines and feed to m_recv
551 int eolPos;
552 while ((eolPos = m_buffer.Find('\n')) >= 0)
554 m_recv(m_buffer.Left(eolPos));
555 m_buffer = m_buffer.Mid(eolPos + 1);
557 return false;
560 virtual bool OnOutputErrData(const BYTE*, size_t) override
562 return false; // Ignore error output for now
565 virtual void OnEnd() override
567 if (!m_buffer.IsEmpty())
568 m_recv(m_buffer);
569 m_buffer.Empty(); // Just for sure
572 private:
573 GitReceiverFunc m_recv;
574 CStringA m_buffer;
577 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
579 CGitCallCb call(cmd, recv);
580 return Run(&call);
583 CString CGit::GetUserName(void)
585 CEnvironment env;
586 env.CopyProcessEnvironment();
587 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
588 if (!envname.IsEmpty())
589 return envname;
590 return GetConfigValue(L"user.name");
592 CString CGit::GetUserEmail(void)
594 CEnvironment env;
595 env.CopyProcessEnvironment();
596 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
597 if (!envmail.IsEmpty())
598 return envmail;
600 return GetConfigValue(L"user.email");
603 CString CGit::GetConfigValue(const CString& name)
605 CString configValue;
606 if(this->m_IsUseGitDLL)
608 CAutoLocker lock(g_Git.m_critGitDllSec);
612 CheckAndInitDll();
613 }catch(...)
616 CStringA key, value;
617 key = CUnicodeUtils::GetUTF8(name);
621 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
622 return CString();
624 catch (const char *msg)
626 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
627 return CString();
630 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
631 return configValue;
633 else
635 CString cmd;
636 cmd.Format(L"git.exe config %s", name);
637 Run(cmd, &configValue, nullptr, CP_UTF8);
638 if (configValue.IsEmpty())
639 return configValue;
640 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
644 bool CGit::GetConfigValueBool(const CString& name)
646 CString configValue = GetConfigValue(name);
647 configValue.MakeLower();
648 configValue.Trim();
649 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
650 return true;
651 else
652 return false;
655 int CGit::GetConfigValueInt32(const CString& name, int def)
657 CString configValue = GetConfigValue(name);
658 int value = def;
659 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
660 return value;
661 return def;
664 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
666 if(this->m_IsUseGitDLL)
668 CAutoLocker lock(g_Git.m_critGitDllSec);
672 CheckAndInitDll();
674 }catch(...)
677 CStringA keya, valuea;
678 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
679 valuea = CUnicodeUtils::GetUTF8(value);
683 return [=]() { return get_set_config(keya, valuea, type); }();
685 catch (const char *msg)
687 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
688 return -1;
691 else
693 CString cmd;
694 CString option;
695 switch(type)
697 case CONFIG_GLOBAL:
698 option = _T("--global");
699 break;
700 case CONFIG_SYSTEM:
701 option = _T("--system");
702 break;
703 default:
704 break;
706 CString mangledValue = value;
707 mangledValue.Replace(_T("\\\""), _T("\\\\\""));
708 mangledValue.Replace(_T("\""), _T("\\\""));
709 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, mangledValue);
710 CString out;
711 if (Run(cmd, &out, nullptr, CP_UTF8))
713 return -1;
716 return 0;
719 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
721 if(this->m_IsUseGitDLL)
723 CAutoLocker lock(g_Git.m_critGitDllSec);
727 CheckAndInitDll();
728 }catch(...)
731 CStringA keya;
732 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
736 return [=]() { return get_set_config(keya, nullptr, type); }();
738 catch (const char *msg)
740 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
741 return -1;
744 else
746 CString cmd;
747 CString option;
748 switch(type)
750 case CONFIG_GLOBAL:
751 option = _T("--global");
752 break;
753 case CONFIG_SYSTEM:
754 option = _T("--system");
755 break;
756 default:
757 break;
759 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
760 CString out;
761 if (Run(cmd, &out, nullptr, CP_UTF8))
763 return -1;
766 return 0;
769 CString CGit::GetCurrentBranch(bool fallback)
771 CString output;
772 //Run(_T("git.exe branch"),&branch);
774 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
775 if (result != 0 && ((result == 1 && !fallback) || result != 1))
777 return _T("(no branch)");
779 else
780 return output;
784 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
786 if (localBranch.IsEmpty())
787 return;
789 CString configName;
790 configName.Format(L"branch.%s.remote", localBranch);
791 pullRemote = GetConfigValue(configName);
793 //Select pull-branch from current branch
794 configName.Format(L"branch.%s.merge", localBranch);
795 pullBranch = StripRefName(GetConfigValue(configName));
798 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
800 CString refName;
801 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
802 return;
803 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
806 CString CGit::GetFullRefName(const CString& shortRefName)
808 CString refName;
809 CString cmd;
810 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
811 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
812 return CString();//Error
813 int iStart = 0;
814 return refName.Tokenize(L"\n", iStart);
817 CString CGit::StripRefName(CString refName)
819 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
820 refName = refName.Mid(11);
821 else if(wcsncmp(refName, L"refs/", 5) == 0)
822 refName = refName.Mid(5);
823 int start =0;
824 return refName.Tokenize(_T("\n"),start);
827 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
829 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
831 if ( sProjectRoot.IsEmpty() )
832 return -1;
834 CString sDotGitPath;
835 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
836 return -1;
838 CString sHeadFile = sDotGitPath + _T("HEAD");
840 FILE *pFile;
841 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
843 if (!pFile)
845 return -1;
848 char s[256] = {0};
849 fgets(s, sizeof(s), pFile);
851 fclose(pFile);
853 const char *pfx = "ref: refs/heads/";
854 const int len = 16;//strlen(pfx)
856 if ( !strncmp(s, pfx, len) )
858 //# We're on a branch. It might not exist. But
859 //# HEAD looks good enough to be a branch.
860 CStringA utf8Branch(s + len);
861 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
862 sBranchOut.TrimRight(_T(" \r\n\t"));
864 if ( sBranchOut.IsEmpty() )
865 return -1;
867 else if (fallback)
869 CStringA utf8Hash(s);
870 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
871 unicodeHash.TrimRight(_T(" \r\n\t"));
872 if (CGitHash::IsValidSHA1(unicodeHash))
873 sBranchOut = unicodeHash;
874 else
875 //# Assume this is a detached head.
876 sBranchOut = _T("HEAD");
877 return 1;
879 else
881 //# Assume this is a detached head.
882 sBranchOut = "HEAD";
884 return 1;
887 return 0;
890 int CGit::BuildOutputFormat(CString &format,bool IsFull)
892 CString log;
893 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
894 format += log;
895 if(IsFull)
897 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
898 format += log;
899 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
900 format += log;
901 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
902 format += log;
903 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
904 format += log;
905 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
906 format += log;
907 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
908 format += log;
909 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
910 format += log;
913 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
914 format += log;
915 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
916 format += log;
917 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
918 format += log;
920 if(IsFull)
922 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
923 format += log;
925 return 0;
928 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
929 CFilterData *Filter)
931 CString cmd;
932 CString num;
933 CString since;
935 CString file = _T(" --");
937 if(path)
938 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
940 if(count>0)
941 num.Format(_T("-n%d"),count);
943 CString param;
945 if(mask& LOG_INFO_STAT )
946 param += _T(" --numstat ");
947 if(mask& LOG_INFO_FILESTATE)
948 param += _T(" --raw ");
950 if(mask& LOG_INFO_FULLHISTORY)
951 param += _T(" --full-history ");
953 if(mask& LOG_INFO_BOUNDARY)
954 param += _T(" --left-right --boundary ");
956 if(mask& CGit::LOG_INFO_ALL_BRANCH)
957 param += _T(" --all ");
959 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
960 param += _T(" --branches ");
962 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
963 param += _T(" -C ");
965 if(mask& CGit::LOG_INFO_DETECT_RENAME )
966 param += _T(" -M ");
968 if(mask& CGit::LOG_INFO_FIRST_PARENT )
969 param += _T(" --first-parent ");
971 if(mask& CGit::LOG_INFO_NO_MERGE )
972 param += _T(" --no-merges ");
974 if(mask& CGit::LOG_INFO_FOLLOW)
975 param += _T(" --follow ");
977 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
978 param += _T(" -c ");
980 if(mask& CGit::LOG_INFO_FULL_DIFF)
981 param += _T(" --full-diff ");
983 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
984 param += _T(" --simplify-by-decoration ");
986 param += range;
988 CString st1,st2;
990 if( Filter && (Filter->m_From != -1))
992 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
993 param += st1;
996 if( Filter && (Filter->m_To != -1))
998 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
999 param += st2;
1002 bool isgrep = false;
1003 if( Filter && (!Filter->m_Author.IsEmpty()))
1005 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
1006 param += st1;
1007 isgrep = true;
1010 if( Filter && (!Filter->m_Committer.IsEmpty()))
1012 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1013 param += st1;
1014 isgrep = true;
1017 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1019 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1020 param += st1;
1021 isgrep = true;
1024 if(Filter && isgrep)
1026 if(!Filter->m_IsRegex)
1027 param += _T(" --fixed-strings ");
1029 param += _T(" --regexp-ignore-case --extended-regexp ");
1032 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1033 if (logOrderBy == LOG_ORDER_TOPOORDER)
1034 param += _T(" --topo-order");
1035 else if (logOrderBy == LOG_ORDER_DATEORDER)
1036 param += _T(" --date-order");
1038 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
1039 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1040 else
1042 CString log;
1043 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1044 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1045 num,param,log);
1048 cmd += file;
1050 return cmd;
1052 #define BUFSIZE 512
1053 void GetTempPath(CString &path)
1055 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1056 DWORD dwRetVal;
1057 DWORD dwBufSize=BUFSIZE;
1058 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1059 lpPathBuffer); // buffer for path
1060 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1062 path=_T("");
1064 path.Format(_T("%s"),lpPathBuffer);
1066 CString GetTempFile()
1068 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1069 DWORD dwRetVal;
1070 DWORD dwBufSize=BUFSIZE;
1071 TCHAR szTempName[BUFSIZE] = { 0 };
1072 UINT uRetVal;
1074 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1075 lpPathBuffer); // buffer for path
1076 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1078 return _T("");
1080 // Create a temporary file.
1081 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1082 TEXT("Patch"), // temp file name prefix
1083 0, // create unique name
1084 szTempName); // buffer for name
1087 if (uRetVal == 0)
1089 return _T("");
1092 return CString(szTempName);
1096 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1098 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1099 if (result == 0) return 0;
1100 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1102 if (lpBuffer)
1103 lpBuffer[0] = '\0';
1104 return result + 13;
1107 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1108 CreateDirectory(lpBuffer, NULL);
1110 return result + 13;
1113 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1115 STARTUPINFO si;
1116 PROCESS_INFORMATION pi;
1117 si.cb=sizeof(STARTUPINFO);
1118 GetStartupInfo(&si);
1120 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1121 psa.bInheritHandle=TRUE;
1123 HANDLE hReadErr, hWriteErr;
1124 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1126 CString err = CFormatMessageWrapper();
1127 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1128 return TGIT_GIT_ERROR_OPEN_PIP;
1131 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1132 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1134 if (houtfile == INVALID_HANDLE_VALUE)
1136 CString err = CFormatMessageWrapper();
1137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1138 CloseHandle(hReadErr);
1139 CloseHandle(hWriteErr);
1140 return TGIT_GIT_ERROR_OPEN_PIP;
1143 si.wShowWindow = SW_HIDE;
1144 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1145 si.hStdOutput = houtfile;
1146 si.hStdError = hWriteErr;
1148 LPTSTR pEnv = m_Environment;
1149 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1151 if(cmd.Find(_T("git")) == 0)
1152 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1154 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1155 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1157 CString err = CFormatMessageWrapper();
1158 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1159 stdErr = &err;
1160 CloseHandle(hReadErr);
1161 CloseHandle(hWriteErr);
1162 CloseHandle(houtfile);
1163 return TGIT_GIT_ERROR_CREATE_PROCESS;
1166 BYTE_VECTOR stderrVector;
1167 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1168 HANDLE thread;
1169 ASYNCREADSTDERRTHREADARGS threadArguments;
1170 threadArguments.fileHandle = hReadErr;
1171 threadArguments.pcall = &pcall;
1172 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1174 WaitForSingleObject(pi.hProcess,INFINITE);
1176 CloseHandle(hWriteErr);
1177 CloseHandle(hReadErr);
1179 if (thread)
1180 WaitForSingleObject(thread, INFINITE);
1182 stderrVector.push_back(0);
1183 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1185 DWORD exitcode = 0;
1186 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1188 CString err = CFormatMessageWrapper();
1189 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1190 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1192 else
1193 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1195 CloseHandle(pi.hThread);
1196 CloseHandle(pi.hProcess);
1197 CloseHandle(houtfile);
1198 return exitcode;
1201 git_repository * CGit::GetGitRepository() const
1203 git_repository * repo = nullptr;
1204 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1205 return repo;
1208 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1210 ATLASSERT(repo);
1212 // no need to parse a ref if it's already a 40-byte hash
1213 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1215 hash = CGitHash(friendname);
1216 return 0;
1219 int isHeadOrphan = git_repository_head_unborn(repo);
1220 if (isHeadOrphan != 0)
1222 hash.Empty();
1223 if (isHeadOrphan == 1)
1224 return 0;
1225 else
1226 return -1;
1229 CAutoObject gitObject;
1230 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1231 return -1;
1233 const git_oid * oid = git_object_id(gitObject);
1234 if (!oid)
1235 return -1;
1237 hash = CGitHash((char *)oid->id);
1239 return 0;
1242 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1244 // no need to parse a ref if it's already a 40-byte hash
1245 if (CGitHash::IsValidSHA1(friendname))
1247 hash = CGitHash(friendname);
1248 return 0;
1251 if (m_IsUseLibGit2)
1253 CAutoRepository repo(GetGitRepository());
1254 if (!repo)
1255 return -1;
1257 return GetHash(repo, hash, friendname, true);
1259 else
1261 CString branch = FixBranchName(friendname);
1262 if (friendname == _T("FETCH_HEAD") && branch.IsEmpty())
1263 branch = friendname;
1264 CString cmd;
1265 cmd.Format(_T("git.exe rev-parse %s"), branch);
1266 gitLastErr.Empty();
1267 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1268 hash = CGitHash(gitLastErr.Trim());
1269 if (ret == 0)
1270 gitLastErr.Empty();
1271 else if (friendname == _T("HEAD")) // special check for unborn branch
1273 CString branch;
1274 if (GetCurrentBranchFromFile(m_CurrentDir, branch))
1275 return -1;
1276 gitLastErr.Empty();
1277 return 0;
1279 return ret;
1283 int CGit::GetInitAddList(CTGitPathList &outputlist)
1285 CString cmd;
1286 BYTE_VECTOR cmdout;
1288 cmd=_T("git.exe ls-files -s -t -z");
1289 outputlist.Clear();
1290 if (Run(cmd, &cmdout))
1291 return -1;
1293 if (outputlist.ParserFromLsFile(cmdout))
1294 return -1;
1295 for(int i = 0; i < outputlist.GetCount(); ++i)
1296 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1298 return 0;
1300 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1302 CString cmd;
1303 CString ignore;
1304 if (ignoreSpaceAtEol)
1305 ignore += _T(" --ignore-space-at-eol");
1306 if (ignoreSpaceChange)
1307 ignore += _T(" --ignore-space-change");
1308 if (ignoreAllSpace)
1309 ignore += _T(" --ignore-all-space");
1310 if (ignoreBlankLines)
1311 ignore += _T(" --ignore-blank-lines");
1313 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1315 //rev1=+_T("");
1316 if(rev1 == GIT_REV_ZERO)
1317 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1318 else
1319 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1321 else
1323 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1326 BYTE_VECTOR out;
1327 if (Run(cmd, &out))
1328 return -1;
1330 return outputlist.ParserFromLog(out);
1333 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1335 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1336 list->push_back(CUnicodeUtils::GetUnicode(refname));
1337 return 0;
1340 int CGit::GetTagList(STRING_VECTOR &list)
1342 if (this->m_IsUseLibGit2)
1344 CAutoRepository repo(GetGitRepository());
1345 if (!repo)
1346 return -1;
1348 CAutoStrArray tag_names;
1350 if (git_tag_list(tag_names, repo))
1351 return -1;
1353 for (size_t i = 0; i < tag_names->count; ++i)
1355 CStringA tagName(tag_names->strings[i]);
1356 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1359 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1361 return 0;
1363 else
1365 CString cmd, output;
1366 cmd=_T("git.exe tag -l");
1367 int ret = Run(cmd, &output, NULL, CP_UTF8);
1368 if(!ret)
1370 int pos=0;
1371 CString one;
1372 while( pos>=0 )
1374 one=output.Tokenize(_T("\n"),pos);
1375 if (!one.IsEmpty())
1376 list.push_back(one);
1378 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1380 else if (ret == 1 && IsInitRepos())
1381 return 0;
1382 return ret;
1386 CString CGit::GetGitLastErr(const CString& msg)
1388 if (this->m_IsUseLibGit2)
1389 return GetLibGit2LastErr(msg);
1390 else if (gitLastErr.IsEmpty())
1391 return msg + _T("\nUnknown git.exe error.");
1392 else
1394 CString lastError = gitLastErr;
1395 gitLastErr.Empty();
1396 return msg + _T("\n") + lastError;
1400 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1402 if (UsingLibGit2(cmd))
1403 return GetLibGit2LastErr(msg);
1404 else if (gitLastErr.IsEmpty())
1405 return msg + _T("\nUnknown git.exe error.");
1406 else
1408 CString lastError = gitLastErr;
1409 gitLastErr.Empty();
1410 return msg + _T("\n") + lastError;
1414 CString CGit::GetLibGit2LastErr()
1416 const git_error *libgit2err = giterr_last();
1417 if (libgit2err)
1419 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1420 giterr_clear();
1421 return _T("libgit2 returned: ") + lastError;
1423 else
1424 return _T("An error occoured in libgit2, but no message is available.");
1427 CString CGit::GetLibGit2LastErr(const CString& msg)
1429 if (!msg.IsEmpty())
1430 return msg + _T("\n") + GetLibGit2LastErr();
1431 return GetLibGit2LastErr();
1434 CString CGit::FixBranchName_Mod(CString& branchName)
1436 if(branchName == "FETCH_HEAD")
1437 branchName = DerefFetchHead();
1438 return branchName;
1441 CString CGit::FixBranchName(const CString& branchName)
1443 CString tempBranchName = branchName;
1444 FixBranchName_Mod(tempBranchName);
1445 return tempBranchName;
1448 bool CGit::IsBranchTagNameUnique(const CString& name)
1450 if (m_IsUseLibGit2)
1452 CAutoRepository repo(GetGitRepository());
1453 if (!repo)
1454 return true; // TODO: optimize error reporting
1456 CAutoReference tagRef;
1457 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1458 return true;
1460 CAutoReference branchRef;
1461 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1462 return true;
1464 return false;
1466 // else
1467 CString output;
1469 CString cmd;
1470 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1471 int ret = Run(cmd, &output, NULL, CP_UTF8);
1472 if (!ret)
1474 int i = 0, pos = 0;
1475 while (pos >= 0)
1477 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1478 ++i;
1480 if (i >= 2)
1481 return false;
1484 return true;
1487 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1489 if (m_IsUseLibGit2)
1491 CAutoRepository repo(GetGitRepository());
1492 if (!repo)
1493 return false; // TODO: optimize error reporting
1495 CString prefix;
1496 if (isBranch)
1497 prefix = _T("refs/heads/");
1498 else
1499 prefix = _T("refs/tags/");
1501 CAutoReference ref;
1502 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1503 return false;
1505 return true;
1507 // else
1508 CString cmd, output;
1510 cmd = _T("git.exe show-ref ");
1511 if (isBranch)
1512 cmd += _T("--heads ");
1513 else
1514 cmd += _T("--tags ");
1516 cmd += _T("refs/heads/") + name;
1517 cmd += _T(" refs/tags/") + name;
1519 int ret = Run(cmd, &output, NULL, CP_UTF8);
1520 if (!ret)
1522 if (!output.IsEmpty())
1523 return true;
1526 return false;
1529 CString CGit::DerefFetchHead()
1531 CString dotGitPath;
1532 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1533 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1534 int forMergeLineCount = 0;
1535 std::string line;
1536 std::string hashToReturn;
1537 while(getline(fetchHeadFile, line))
1539 //Tokenize this line
1540 std::string::size_type prevPos = 0;
1541 std::string::size_type pos = line.find('\t');
1542 if(pos == std::string::npos) continue; //invalid line
1544 std::string hash = line.substr(0, pos);
1545 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1547 bool forMerge = pos == prevPos;
1548 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1550 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1552 //Process this line
1553 if(forMerge)
1555 hashToReturn = hash;
1556 ++forMergeLineCount;
1557 if(forMergeLineCount > 1)
1558 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1562 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1565 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1567 int ret = 0;
1568 CString cur;
1569 if (m_IsUseLibGit2)
1571 CAutoRepository repo(GetGitRepository());
1572 if (!repo)
1573 return -1;
1575 if (git_repository_head_detached(repo) == 1)
1576 cur = _T("(detached from ");
1578 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1580 git_branch_t flags = GIT_BRANCH_LOCAL;
1581 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1582 flags = GIT_BRANCH_ALL;
1583 else if (type & BRANCH_REMOTE)
1584 flags = GIT_BRANCH_REMOTE;
1586 CAutoBranchIterator it;
1587 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1588 return -1;
1590 git_reference * ref = nullptr;
1591 git_branch_t branchType;
1592 while (git_branch_next(&ref, &branchType, it) == 0)
1594 CAutoReference autoRef(ref);
1595 const char * name = nullptr;
1596 if (git_branch_name(&name, ref))
1597 continue;
1599 CString branchname = CUnicodeUtils::GetUnicode(name);
1600 if (branchType & GIT_BRANCH_REMOTE)
1601 list.push_back(_T("remotes/") + branchname);
1602 else
1604 if (git_branch_is_head(ref))
1605 cur = branchname;
1606 list.push_back(branchname);
1611 else
1613 CString cmd, output;
1614 cmd = _T("git.exe branch --no-color");
1616 if ((type & BRANCH_ALL) == BRANCH_ALL)
1617 cmd += _T(" -a");
1618 else if (type & BRANCH_REMOTE)
1619 cmd += _T(" -r");
1621 ret = Run(cmd, &output, nullptr, CP_UTF8);
1622 if (!ret)
1624 int pos = 0;
1625 CString one;
1626 while (pos >= 0)
1628 one = output.Tokenize(_T("\n"), pos);
1629 one.Trim(L" \r\n\t");
1630 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1631 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1632 if (one[0] == _T('*'))
1634 one = one.Mid(2);
1635 cur = one;
1637 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1639 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1640 one = _T("remotes/") + one;
1641 list.push_back(one);
1645 else if (ret == 1 && IsInitRepos())
1646 return 0;
1649 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1650 list.push_back(L"FETCH_HEAD");
1652 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1654 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1656 for (unsigned int i = 0; i < list.size(); ++i)
1658 if (list[i] == cur)
1660 *current = i;
1661 break;
1666 return ret;
1669 int CGit::GetRemoteList(STRING_VECTOR &list)
1671 if (this->m_IsUseLibGit2)
1673 CAutoRepository repo(GetGitRepository());
1674 if (!repo)
1675 return -1;
1677 CAutoStrArray remotes;
1678 if (git_remote_list(remotes, repo))
1679 return -1;
1681 for (size_t i = 0; i < remotes->count; ++i)
1683 CStringA remote(remotes->strings[i]);
1684 list.push_back(CUnicodeUtils::GetUnicode(remote));
1687 std::sort(list.begin(), list.end());
1689 return 0;
1691 else
1693 int ret;
1694 CString cmd, output;
1695 cmd=_T("git.exe remote");
1696 ret = Run(cmd, &output, NULL, CP_UTF8);
1697 if(!ret)
1699 int pos=0;
1700 CString one;
1701 while( pos>=0 )
1703 one=output.Tokenize(_T("\n"),pos);
1704 if (!one.IsEmpty())
1705 list.push_back(one);
1708 return ret;
1712 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1714 if (UsingLibGit2(GIT_CMD_FETCH))
1716 CAutoRepository repo(GetGitRepository());
1717 if (!repo)
1718 return -1;
1720 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1721 CAutoRemote remote;
1722 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1723 return -1;
1725 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1726 callbacks.credentials = g_Git2CredCallback;
1727 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1728 git_remote_set_callbacks(remote, &callbacks);
1729 if (git_remote_connect(remote, GIT_DIRECTION_FETCH) < 0)
1730 return -1;
1732 const git_remote_head** heads = nullptr;
1733 size_t size = 0;
1734 if (git_remote_ls(&heads, &size, remote) < 0)
1735 return -1;
1737 for (size_t i = 0; i < size; i++)
1739 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1740 CString shortname;
1741 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1742 continue;
1743 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1744 if (shortname.Find(_T("^{}")) >= 1)
1745 continue;
1746 list.push_back(shortname);
1748 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1749 return 0;
1752 CString cmd, out, err;
1753 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1754 if (Run(cmd, &out, &err, CP_UTF8))
1756 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1757 return -1;
1760 int pos = 0;
1761 while (pos >= 0)
1763 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1764 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1765 if (one.Find(_T("^{}")) >= 1)
1766 continue;
1767 if (!one.IsEmpty())
1768 list.push_back(one);
1770 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1771 return 0;
1774 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1776 if (UsingLibGit2(GIT_CMD_PUSH))
1778 CAutoRepository repo(GetGitRepository());
1779 if (!repo)
1780 return -1;
1782 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1783 CAutoRemote remote;
1784 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1785 return -1;
1787 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1788 callbacks.credentials = g_Git2CredCallback;
1789 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1790 git_remote_set_callbacks(remote, &callbacks);
1791 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1792 return -1;
1794 std::vector<CStringA> refspecs;
1795 for (auto ref : list)
1796 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1798 std::vector<char*> vc;
1799 vc.reserve(refspecs.size());
1800 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1801 git_strarray specs = { &vc[0], vc.size() };
1803 if (git_remote_push(remote, &specs, nullptr) < 0)
1804 return -1;
1806 else
1808 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1809 for (auto ref : list)
1811 CString refspec = _T(":") + ref;
1812 mgtPush.AddFile(refspec);
1815 BOOL cancel = FALSE;
1816 mgtPush.Execute(cancel);
1819 return 0;
1822 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1824 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1825 list->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref)));
1826 return 0;
1829 int CGit::GetRefList(STRING_VECTOR &list)
1831 if (this->m_IsUseLibGit2)
1833 CAutoRepository repo(GetGitRepository());
1834 if (!repo)
1835 return -1;
1837 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1838 return -1;
1840 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1842 return 0;
1844 else
1846 CString cmd, output;
1847 cmd=_T("git.exe show-ref -d");
1848 int ret = Run(cmd, &output, NULL, CP_UTF8);
1849 if(!ret)
1851 int pos=0;
1852 CString one;
1853 while( pos>=0 )
1855 one=output.Tokenize(_T("\n"),pos);
1856 int start=one.Find(_T(" "),0);
1857 if(start>0)
1859 CString name;
1860 name=one.Right(one.GetLength()-start-1);
1861 if (list.empty() || name != *list.crbegin() + _T("^{}"))
1862 list.push_back(name);
1865 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1867 else if (ret == 1 && IsInitRepos())
1868 return 0;
1869 return ret;
1873 typedef struct map_each_ref_payload {
1874 git_repository * repo;
1875 MAP_HASH_NAME * map;
1876 } map_each_ref_payload;
1878 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1880 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1882 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1884 CAutoObject gitObject;
1885 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1886 return 1;
1888 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1890 str += _T("^{}"); // deref tag
1891 CAutoObject derefedTag;
1892 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1893 return 1;
1894 gitObject.Swap(derefedTag);
1897 const git_oid * oid = git_object_id(gitObject);
1898 if (oid == NULL)
1899 return 1;
1901 CGitHash hash((char *)oid->id);
1902 (*payloadContent->map)[hash].push_back(str);
1904 return 0;
1906 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1908 ATLASSERT(repo);
1910 map_each_ref_payload payloadContent = { repo, &map };
1912 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1913 return -1;
1915 for (auto it = map.begin(); it != map.end(); ++it)
1917 std::sort(it->second.begin(), it->second.end());
1920 return 0;
1923 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1925 if (this->m_IsUseLibGit2)
1927 CAutoRepository repo(GetGitRepository());
1928 if (!repo)
1929 return -1;
1931 return GetMapHashToFriendName(repo, map);
1933 else
1935 CString cmd, output;
1936 cmd=_T("git.exe show-ref -d");
1937 int ret = Run(cmd, &output, NULL, CP_UTF8);
1938 if(!ret)
1940 int pos=0;
1941 CString one;
1942 while( pos>=0 )
1944 one=output.Tokenize(_T("\n"),pos);
1945 int start=one.Find(_T(" "),0);
1946 if(start>0)
1948 CString name;
1949 name=one.Right(one.GetLength()-start-1);
1951 CString hash;
1952 hash=one.Left(start);
1954 map[CGitHash(hash)].push_back(name);
1958 else if (ret == 1 && IsInitRepos())
1959 return 0;
1960 return ret;
1964 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
1966 CAutoConfig config(true);
1967 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE) < 0)
1968 return -1;
1969 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
1971 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
1972 CString key = CUnicodeUtils::GetUnicode(entry->name);
1973 key = key.Mid(7, key.GetLength() - 7 - 12); // 7: branch., 12: .description
1974 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
1975 return 0;
1976 }, &map);
1979 static void SetLibGit2SearchPath(int level, const CString &value)
1981 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1982 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1985 static void SetLibGit2TemplatePath(const CString &value)
1987 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1988 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1991 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1993 if (m_bInitialized)
1995 return TRUE;
1998 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
1999 this->m_Environment.clear();
2000 m_Environment.CopyProcessEnvironment();
2001 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2003 TCHAR *oldpath;
2004 size_t homesize,size;
2006 // set HOME if not set already
2007 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
2008 if (!homesize)
2009 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
2011 //setup ssh client
2012 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
2013 if (sshclient.IsEmpty())
2014 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
2016 if(!sshclient.IsEmpty())
2018 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
2019 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
2021 else
2023 TCHAR sPlink[MAX_PATH] = {0};
2024 GetModuleFileName(NULL, sPlink, _countof(sPlink));
2025 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
2026 if (ptr) {
2027 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
2028 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
2029 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2034 TCHAR sAskPass[MAX_PATH] = {0};
2035 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2036 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2037 if (ptr)
2039 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2040 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2041 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2042 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2046 // add git/bin path to PATH
2048 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
2049 CString str = msysdir;
2050 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
2052 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2053 if (!bFallback)
2054 return FALSE;
2056 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2057 str = msyslocalinstalldir;
2058 str.TrimRight(_T("\\"));
2059 if (str.IsEmpty())
2061 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2062 str = msysinstalldir;
2063 str.TrimRight(_T("\\"));
2065 if ( !str.IsEmpty() )
2067 str += "\\bin";
2068 msysdir=str;
2069 CGit::ms_LastMsysGitDir = str;
2070 msysdir.write();
2072 else
2074 // search PATH if git/bin directory is already present
2075 if ( FindGitPath() )
2077 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2078 m_bInitialized = TRUE;
2079 msysdir = CGit::ms_LastMsysGitDir;
2080 msysdir.write();
2081 return TRUE;
2084 return FALSE;
2087 else
2089 CGit::ms_LastMsysGitDir = str;
2092 // check for git.exe existance (maybe it was deinstalled in the meantime)
2093 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
2095 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2096 return FALSE;
2099 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2100 // Configure libgit2 search paths
2101 CString msysGitDir;
2102 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
2103 msysGitDir.ReleaseBuffer();
2104 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
2105 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2106 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2107 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 };
2108 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2109 CString msysGitTemplateDir;
2110 if (!ms_bCygwinGit)
2111 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
2112 else
2113 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\usr\\share\\git-core\\templates"));
2114 msysGitTemplateDir.ReleaseBuffer();
2115 SetLibGit2TemplatePath(msysGitTemplateDir);
2117 //set path
2118 _tdupenv_s(&oldpath,&size,_T("PATH"));
2120 CString path;
2121 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
2123 m_Environment.SetEnv(_T("PATH"), path);
2125 CString str1 = m_Environment.GetEnv(_T("PATH"));
2127 CString sOldPath = oldpath;
2128 free(oldpath);
2130 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2131 // register filter only once
2132 if (!git_filter_lookup("filter"))
2134 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir + L"\\sh.exe\"", m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2135 return FALSE;
2137 #endif
2139 m_bInitialized = TRUE;
2140 return true;
2143 CString CGit::GetHomeDirectory() const
2145 const wchar_t * homeDir = wget_windows_home_directory();
2146 return CString(homeDir, (int)wcslen(homeDir));
2149 CString CGit::GetGitLocalConfig() const
2151 CString path;
2152 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2153 path += _T("config");
2154 return path;
2157 CStringA CGit::GetGitPathStringA(const CString &path)
2159 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2162 CString CGit::GetGitGlobalConfig() const
2164 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2167 CString CGit::GetGitGlobalXDGConfigPath() const
2169 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2172 CString CGit::GetGitGlobalXDGConfig() const
2174 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2177 CString CGit::GetGitSystemConfig() const
2179 const wchar_t * systemConfig = wget_msysgit_etc();
2180 return CString(systemConfig, (int)wcslen(systemConfig));
2183 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2185 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2187 CAutoRepository repo = GetGitRepository();
2188 if (!repo)
2189 return FALSE;
2191 if (git_repository_head_unborn(repo))
2192 return FALSE;
2194 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2195 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2196 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2198 CAutoStatusList status;
2199 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2200 return FALSE;
2202 return (0 == git_status_list_entrycount(status));
2205 CString out;
2206 CString cmd;
2207 cmd=_T("git.exe rev-parse --verify HEAD");
2209 if(Run(cmd,&out,CP_UTF8))
2210 return FALSE;
2212 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2213 if(Run(cmd,&out,CP_UTF8))
2214 return FALSE;
2216 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2217 if(Run(cmd,&out,CP_UTF8))
2218 return FALSE;
2220 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2221 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2222 return FALSE;
2224 return TRUE;
2226 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2228 int ret;
2229 for (int i = 0; i < list.GetCount(); ++i)
2231 ret = Revert(commit, (CTGitPath&)list[i], err);
2232 if(ret)
2233 return ret;
2235 return 0;
2237 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2239 CString cmd;
2241 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2243 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2245 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2246 return -1;
2248 CString force;
2249 // if the filenames only differ in case, we have to pass "-f"
2250 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2251 force = _T("-f ");
2252 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2253 if (Run(cmd, &err, CP_UTF8))
2254 return -1;
2256 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2257 if (Run(cmd, &err, CP_UTF8))
2258 return -1;
2260 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2261 { //To init git repository, there are not HEAD, so we can use git reset command
2262 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2264 if (Run(cmd, &err, CP_UTF8))
2265 return -1;
2267 else
2269 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2270 if (Run(cmd, &err, CP_UTF8))
2271 return -1;
2274 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2276 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2277 if (Run(cmd, &err, CP_UTF8))
2278 return -1;
2281 return 0;
2284 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2286 ATLASSERT(repo);
2288 CAutoIndex index;
2289 if (git_repository_index(index.GetPointer(), repo))
2290 return -1;
2292 return git_index_has_conflicts(index);
2295 int CGit::HasWorkingTreeConflicts()
2297 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2299 CAutoRepository repo(GetGitRepository());
2300 if (!repo)
2301 return -1;
2303 return HasWorkingTreeConflicts(repo);
2306 CString cmd = _T("git.exe ls-files -u -t -z");
2308 CString output;
2309 if (Run(cmd, &output, &gitLastErr, CP_UTF8))
2310 return -1;
2312 return output.IsEmpty() ? 0 : 1;
2315 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2317 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2319 CAutoRepository repo(GetGitRepository());
2320 if (!repo)
2321 return false;
2323 CGitHash fromHash, toHash, baseHash;
2324 if (GetHash(repo, toHash, FixBranchName(to)))
2325 return false;
2327 if (GetHash(repo, fromHash, FixBranchName(from)))
2328 return false;
2330 git_oid baseOid;
2331 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2332 return false;
2334 baseHash = baseOid.id;
2336 if (commonAncestor)
2337 *commonAncestor = baseHash;
2339 return fromHash == baseHash;
2341 // else
2342 CString base;
2343 CGitHash basehash,hash;
2344 CString cmd;
2345 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2347 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2349 return false;
2351 basehash = base.Trim();
2353 GetHash(hash, from);
2355 if (commonAncestor)
2356 *commonAncestor = basehash;
2358 return hash == basehash;
2361 unsigned int CGit::Hash2int(const CGitHash &hash)
2363 int ret=0;
2364 for (int i = 0; i < 4; ++i)
2366 ret = ret << 8;
2367 ret |= hash.m_hash[i];
2369 return ret;
2372 int CGit::RefreshGitIndex()
2374 if(g_Git.m_IsUseGitDLL)
2376 CAutoLocker lock(g_Git.m_critGitDllSec);
2379 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2381 }catch(...)
2383 return -1;
2387 else
2389 CString cmd,output;
2390 cmd=_T("git.exe update-index --refresh");
2391 return Run(cmd, &output, CP_UTF8);
2395 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2397 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2399 CAutoRepository repo(GetGitRepository());
2400 if (!repo)
2401 return -1;
2403 CGitHash hash;
2404 if (GetHash(repo, hash, Refname))
2405 return -1;
2407 CAutoCommit commit;
2408 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2409 return -1;
2411 CAutoTree tree;
2412 if (git_commit_tree(tree.GetPointer(), commit))
2413 return -1;
2415 CAutoTreeEntry entry;
2416 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2417 return -1;
2419 CAutoBlob blob;
2420 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2421 return -1;
2423 FILE *file = nullptr;
2424 _tfopen_s(&file, outputfile, _T("wb"));
2425 if (file == nullptr)
2427 giterr_set_str(GITERR_NONE, "Could not create file.");
2428 return -1;
2430 CAutoBuf buf;
2431 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2433 fclose(file);
2434 return -1;
2436 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2438 giterr_set_str(GITERR_OS, "Could not write to file.");
2439 fclose(file);
2441 return -1;
2443 fclose(file);
2445 return 0;
2447 else if (g_Git.m_IsUseGitDLL)
2449 CAutoLocker lock(g_Git.m_critGitDllSec);
2452 g_Git.CheckAndInitDll();
2453 CStringA ref, patha, outa;
2454 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2455 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2456 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2457 ::DeleteFile(outputfile);
2458 return git_checkout_file(ref, patha, outa);
2461 catch (const char * msg)
2463 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2464 return -1;
2466 catch (...)
2468 gitLastErr = L"An unknown gitdll.dll error occurred.";
2469 return -1;
2472 else
2474 CString cmd;
2475 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2476 return RunLogFile(cmd, outputfile, &gitLastErr);
2480 void CEnvironment::clear()
2482 __super::clear();
2485 bool CEnvironment::empty()
2487 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2490 CEnvironment::operator LPTSTR()
2492 if (empty())
2493 return nullptr;
2494 return &__super::at(0);
2497 void CEnvironment::CopyProcessEnvironment()
2499 if (!empty())
2500 pop_back();
2501 TCHAR *porig = GetEnvironmentStrings();
2502 TCHAR *p = porig;
2503 while(*p !=0 || *(p+1) !=0)
2504 this->push_back(*p++);
2506 push_back(_T('\0'));
2507 push_back(_T('\0'));
2509 FreeEnvironmentStrings(porig);
2512 CString CEnvironment::GetEnv(const TCHAR *name)
2514 CString str;
2515 for (size_t i = 0; i < size(); ++i)
2517 str = &(*this)[i];
2518 int start =0;
2519 CString sname = str.Tokenize(_T("="),start);
2520 if(sname.CompareNoCase(name) == 0)
2522 return &(*this)[i+start];
2524 i+=str.GetLength();
2526 return _T("");
2529 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2531 unsigned int i;
2532 for (i = 0; i < size(); ++i)
2534 CString str = &(*this)[i];
2535 int start =0;
2536 CString sname = str.Tokenize(_T("="),start);
2537 if(sname.CompareNoCase(name) == 0)
2539 break;
2541 i+=str.GetLength();
2544 if(i == size())
2546 if (!value) // as we haven't found the variable we want to remove, just return
2547 return;
2548 if (i == 0) // make inserting into an empty environment work
2550 this->push_back(_T('\0'));
2551 ++i;
2553 i -= 1; // roll back terminate \0\0
2554 this->push_back(_T('\0'));
2557 CEnvironment::iterator it;
2558 it=this->begin();
2559 it += i;
2561 while(*it && i<size())
2563 this->erase(it);
2564 it=this->begin();
2565 it += i;
2568 if (value == nullptr) // remove the variable
2570 this->erase(it);
2571 return;
2574 while(*name)
2576 this->insert(it,*name++);
2577 ++i;
2578 it= begin()+i;
2581 this->insert(it, _T('='));
2582 ++i;
2583 it= begin()+i;
2585 while(*value)
2587 this->insert(it,*value++);
2588 ++i;
2589 it= begin()+i;
2594 int CGit::GetGitEncode(TCHAR* configkey)
2596 CString str=GetConfigValue(configkey);
2598 if(str.IsEmpty())
2599 return CP_UTF8;
2601 return CUnicodeUtils::GetCPCode(str);
2605 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2607 GIT_FILE file=0;
2608 int ret=0;
2609 GIT_DIFF diff=0;
2611 CAutoLocker lock(g_Git.m_critGitDllSec);
2615 if(!arg)
2616 diff = GetGitDiff();
2617 else
2618 git_open_diff(&diff, arg);
2620 catch (char* e)
2622 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2623 return -1;
2626 if(diff ==NULL)
2627 return -1;
2629 bool isStat = 0;
2630 if(arg == NULL)
2631 isStat = true;
2632 else
2633 isStat = !!strstr(arg, "stat");
2635 int count=0;
2637 if(hash2 == NULL)
2638 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2639 else
2640 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2642 if(ret)
2643 return -1;
2645 CTGitPath path;
2646 CString strnewname;
2647 CString stroldname;
2649 for (int j = 0; j < count; ++j)
2651 path.Reset();
2652 char *newname;
2653 char *oldname;
2655 strnewname.Empty();
2656 stroldname.Empty();
2658 int mode=0,IsBin=0,inc=0,dec=0;
2659 git_get_diff_file(diff,file,j,&newname,&oldname,
2660 &mode,&IsBin,&inc,&dec);
2662 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2663 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2665 path.SetFromGit(strnewname,&stroldname);
2666 path.ParserAction((BYTE)mode);
2668 if(IsBin)
2670 path.m_StatAdd=_T("-");
2671 path.m_StatDel=_T("-");
2673 else
2675 path.m_StatAdd.Format(_T("%d"),inc);
2676 path.m_StatDel.Format(_T("%d"),dec);
2678 PathList->AddPath(path);
2680 git_diff_flush(diff);
2682 if(arg)
2683 git_close_diff(diff);
2685 return 0;
2688 int CGit::GetShortHASHLength() const
2690 return 7;
2693 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2695 CString str=ref;
2696 CString shortname;
2697 REF_TYPE type = CGit::UNKNOWN;
2699 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2701 type = CGit::LOCAL_BRANCH;
2704 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2706 type = CGit::REMOTE_BRANCH;
2708 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2710 type = CGit::TAG;
2712 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2714 type = CGit::STASH;
2715 shortname=_T("stash");
2717 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2719 if (shortname.Find(_T("good")) == 0)
2721 type = CGit::BISECT_GOOD;
2722 shortname = _T("good");
2725 if (shortname.Find(_T("bad")) == 0)
2727 type = CGit::BISECT_BAD;
2728 shortname = _T("bad");
2731 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2733 type = CGit::NOTES;
2735 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2737 type = CGit::UNKNOWN;
2739 else
2741 type = CGit::UNKNOWN;
2742 shortname = ref;
2745 if(out_type)
2746 *out_type = type;
2748 return shortname;
2751 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2753 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2756 void CGit::SetGit2CredentialCallback(void* callback)
2758 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2761 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2763 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2766 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2768 CString cmd;
2769 if (rev2 == GitRev::GetWorkingCopy())
2770 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2771 else if (rev1 == GitRev::GetWorkingCopy())
2772 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2773 else
2775 CString merge;
2776 if (bMerge)
2777 merge += _T(" -m");
2779 if (bCombine)
2780 merge += _T(" -c");
2782 CString unified;
2783 if (diffContext >= 0)
2784 unified.Format(_T(" --unified=%d"), diffContext);
2785 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2788 if (!path.IsEmpty())
2790 cmd += _T(" \"");
2791 cmd += path.GetGitPathString();
2792 cmd += _T("\"");
2795 return cmd;
2798 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2800 ATLASSERT(payload && text);
2801 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2802 fwrite("\n", 1, 1, (FILE *)payload);
2805 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2807 ATLASSERT(payload && line);
2808 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2809 fwrite(&line->origin, 1, 1, (FILE *)payload);
2810 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2811 return 0;
2814 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2816 ATLASSERT(repo && identifier && tree);
2818 /* try to resolve identifier */
2819 CAutoObject obj;
2820 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2821 return -1;
2823 if (obj == nullptr)
2824 return GIT_ENOTFOUND;
2826 int err = 0;
2827 switch (git_object_type(obj))
2829 case GIT_OBJ_TREE:
2830 *tree = (git_tree *)obj.Detach();
2831 break;
2832 case GIT_OBJ_COMMIT:
2833 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2834 break;
2835 default:
2836 err = GIT_ENOTFOUND;
2839 return err;
2842 /* use libgit2 get unified diff */
2843 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 */)
2845 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2846 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2848 CAutoRepository repo(g_Git.GetGitRepository());
2849 if (!repo)
2850 return -1;
2852 int isHeadOrphan = git_repository_head_unborn(repo);
2853 if (isHeadOrphan == 1)
2854 return 0;
2855 else if (isHeadOrphan != 0)
2856 return -1;
2858 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2859 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2860 char *buf = pathA.GetBuffer();
2861 if (!pathA.IsEmpty())
2863 opts.pathspec.strings = &buf;
2864 opts.pathspec.count = 1;
2866 CAutoDiff diff;
2868 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2870 CAutoTree t1;
2871 CAutoDiff diff2;
2873 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2874 return -1;
2876 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2877 return -1;
2879 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2880 return -1;
2882 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2883 return -1;
2885 if (git_diff_merge(diff, diff2))
2886 return -1;
2888 else
2890 if (tree1.IsEmpty() && tree2.IsEmpty())
2891 return -1;
2893 if (tree1.IsEmpty())
2895 tree1 = tree2;
2896 tree2.Empty();
2899 CAutoTree t1;
2900 CAutoTree t2;
2901 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2902 return -1;
2904 if (tree2.IsEmpty())
2906 /* don't check return value, there are not parent commit at first commit*/
2907 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2909 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2910 return -1;
2911 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2912 return -1;
2915 CAutoDiffStats stats;
2916 if (git_diff_get_stats(stats.GetPointer(), diff))
2917 return -1;
2918 CAutoBuf statBuf;
2919 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2920 return -1;
2921 statCallback(statBuf, data);
2923 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2925 CAutoPatch patch;
2926 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2927 return -1;
2929 if (git_patch_print(patch, callback, data))
2930 return -1;
2933 pathA.ReleaseBuffer();
2935 return 0;
2938 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2940 if (UsingLibGit2(GIT_CMD_DIFF))
2942 FILE *file = nullptr;
2943 _tfopen_s(&file, patchfile, _T("w"));
2944 if (file == nullptr)
2945 return -1;
2946 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
2947 fclose(file);
2948 return ret;
2950 else
2952 CString cmd;
2953 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2954 return RunLogFile(cmd, patchfile, &gitLastErr);
2958 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
2960 ATLASSERT(payload && text);
2961 CStringA *str = (CStringA*) payload;
2962 str->Append(text->ptr, (int)text->size);
2963 str->AppendChar('\n');
2966 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2968 ATLASSERT(payload && line);
2969 CStringA *str = (CStringA*) payload;
2970 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2971 str->Append(&line->origin, 1);
2972 str->Append(line->content, (int)line->content_len);
2973 return 0;
2976 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2978 if (UsingLibGit2(GIT_CMD_DIFF))
2979 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
2980 else
2982 CString cmd;
2983 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2984 BYTE_VECTOR vector;
2985 int ret = Run(cmd, &vector);
2986 if (!vector.empty())
2988 vector.push_back(0); // vector is not NUL terminated
2989 buffer->Append((char *)&vector[0]);
2991 return ret;
2995 int CGit::GitRevert(int parent, const CGitHash &hash)
2997 if (UsingLibGit2(GIT_CMD_REVERT))
2999 CAutoRepository repo(GetGitRepository());
3000 if (!repo)
3001 return -1;
3003 CAutoCommit commit;
3004 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
3005 return -1;
3007 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3008 revert_opts.mainline = parent;
3009 int result = git_revert(repo, commit, &revert_opts);
3011 return !result ? 0 : -1;
3013 else
3015 CString cmd, merge;
3016 if (parent)
3017 merge.Format(_T("-m %d "), parent);
3018 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
3019 gitLastErr = cmd + _T("\n");
3020 if (Run(cmd, &gitLastErr, CP_UTF8))
3022 return -1;
3024 else
3026 gitLastErr.Empty();
3027 return 0;
3032 int CGit::DeleteRef(const CString& reference)
3034 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3036 CAutoRepository repo(GetGitRepository());
3037 if (!repo)
3038 return -1;
3040 CStringA refA;
3041 if (reference.Right(3) == _T("^{}"))
3042 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3043 else
3044 refA = CUnicodeUtils::GetUTF8(reference);
3046 CAutoReference ref;
3047 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3048 return -1;
3050 int result = -1;
3051 if (git_reference_is_tag(ref))
3052 result = git_tag_delete(repo, git_reference_shorthand(ref));
3053 else if (git_reference_is_branch(ref))
3054 result = git_branch_delete(ref);
3055 else if (git_reference_is_remote(ref))
3056 result = git_branch_delete(ref);
3057 else
3058 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
3060 return result;
3062 else
3064 CString cmd, shortname;
3065 if (GetShortName(reference, shortname, _T("refs/heads/")))
3066 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
3067 else if (GetShortName(reference, shortname, _T("refs/tags/")))
3068 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
3069 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
3070 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
3071 else
3073 gitLastErr = L"unsupported reference type: " + reference;
3074 return -1;
3077 if (Run(cmd, &gitLastErr, CP_UTF8))
3078 return -1;
3080 gitLastErr.Empty();
3081 return 0;
3085 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3087 if (PathFileExists(filename))
3089 FILE *pFile = nullptr;
3090 _tfopen_s(&pFile, filename, _T("r"));
3091 if (pFile)
3093 CStringA str;
3096 char s[8196] = { 0 };
3097 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3098 if (read == 0)
3099 break;
3100 str += CStringA(s, read);
3101 } while (true);
3102 fclose(pFile);
3103 msg = CUnicodeUtils::GetUnicode(str);
3104 msg.Replace(_T("\r\n"), _T("\n"));
3105 msg.TrimRight(_T("\n"));
3106 msg += _T("\n");
3108 else
3109 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3110 return true; // load no further files
3112 return false;
3115 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, CTGitPathList* filterlist)
3117 if (IsInitRepos())
3118 return GetInitAddList(result);
3120 BYTE_VECTOR out;
3122 int count = 1;
3123 if (filterlist)
3124 count = filterlist->GetCount();
3126 CString head = _T("HEAD");
3127 if (amend)
3128 head = _T("HEAD~1");
3130 for (int i = 0; i < count; ++i)
3132 BYTE_VECTOR cmdout;
3133 CString cmd;
3134 if (ms_bCygwinGit)
3136 // Prevent showing all files as modified when using cygwin's git
3137 if (!filterlist)
3138 cmd = _T("git.exe status --");
3139 else
3140 cmd.Format(_T("git.exe status -- \"%s\""), (*filterlist)[i].GetGitPathString());
3141 Run(cmd, &cmdout);
3142 cmdout.clear();
3145 // also list staged files which will be in the commit
3146 Run(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"), &cmdout);
3148 if (!filterlist)
3149 cmd = (_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3150 else
3151 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3153 BYTE_VECTOR cmdErr;
3154 if (Run(cmd, &cmdout, &cmdErr))
3156 int last = cmdErr.RevertFind(0, -1);
3157 CString str;
3158 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last - 1);
3159 MessageBox(nullptr, str, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3162 out.append(cmdout, 0);
3164 result.ParserFromLog(out);
3166 // handle delete conflict case, when remote : modified, local : deleted.
3167 for (int i = 0; i < count; ++i)
3169 BYTE_VECTOR cmdout;
3170 CString cmd;
3172 if (!filterlist)
3173 cmd = _T("git.exe ls-files -u -t -z");
3174 else
3175 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3177 Run(cmd, &cmdout);
3179 CTGitPathList conflictlist;
3180 conflictlist.ParserFromLog(cmdout);
3181 for (int j = 0; j < conflictlist.GetCount(); ++j)
3183 CTGitPath* p = result.LookForGitPath(conflictlist[j].GetGitPathString());
3184 if (p)
3185 p->m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3186 else
3187 result.AddPath(conflictlist[j]);
3191 // handle source files of file renames/moves (issue #860)
3192 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3193 for (int i = 0; i < count; ++i)
3195 BYTE_VECTOR cmdout;
3196 CString cmd;
3198 if (!filterlist)
3199 cmd = _T("git.exe ls-files -d -z");
3200 else
3201 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3203 Run(cmd, &cmdout);
3205 CTGitPathList deletelist;
3206 deletelist.ParserFromLog(cmdout, true);
3207 for (int j = 0; j < deletelist.GetCount(); ++j)
3209 CTGitPath* p = result.LookForGitPath(deletelist[j].GetGitPathString());
3210 if (!p)
3211 result.AddPath(deletelist[j]);
3215 return 0;