Search for git.exe on %PATH% first
[TortoiseGit.git] / src / Git / Git.cpp
blob0f039741abb3dec3e4e5fe77d79929c6fdf38af9
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() > 4)
115 // often the msysgit\cmd folder is on the %PATH%, but
116 // that git.exe does not work, so try to guess the bin folder
117 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
118 if (FileExists(binDir))
119 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
121 return TRUE;
124 return FALSE;
127 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
129 CString filename = executable;
131 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
132 filename += _T(".exe");
134 if (FileExists(filename))
135 return filename;
137 filename = FindFileOnPath(filename, env);
138 if (!filename.IsEmpty())
139 return filename;
141 return executable;
144 static bool g_bSortLogical;
145 static bool g_bSortLocalBranchesFirst;
146 static bool g_bSortTagsReversed;
147 static git_cred_acquire_cb g_Git2CredCallback;
148 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
150 static void GetSortOptions()
152 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
153 if (g_bSortLogical)
154 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
155 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
156 if (g_bSortLocalBranchesFirst)
157 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
158 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
159 if (!g_bSortTagsReversed)
160 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
163 static int LogicalComparePredicate(const CString &left, const CString &right)
165 if (g_bSortLogical)
166 return StrCmpLogicalW(left, right) < 0;
167 return StrCmpI(left, right) < 0;
170 static int LogicalCompareReversedPredicate(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 LogicalCompareBranchesPredicate(const CString &left, const CString &right)
179 if (g_bSortLocalBranchesFirst)
181 int leftIsRemote = left.Find(_T("remotes/"));
182 int rightIsRemote = right.Find(_T("remotes/"));
184 if (leftIsRemote == 0 && rightIsRemote < 0)
185 return false;
186 else if (leftIsRemote < 0 && rightIsRemote == 0)
187 return true;
189 if (g_bSortLogical)
190 return StrCmpLogicalW(left, right) < 0;
191 return StrCmpI(left, right) < 0;
194 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
196 CString CGit::ms_LastMsysGitDir;
197 int CGit::ms_LastMsysGitVersion = 0;
198 CGit g_Git;
201 CGit::CGit(void)
203 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
204 m_CurrentDir.ReleaseBuffer();
205 m_IsGitDllInited = false;
206 m_GitDiff=0;
207 m_GitSimpleListDiff=0;
208 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
209 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
210 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK);
212 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
214 GetSortOptions();
215 this->m_bInitialized =false;
216 CheckMsysGitDir();
217 m_critGitDllSec.Init();
220 CGit::~CGit(void)
222 if(this->m_GitDiff)
224 git_close_diff(m_GitDiff);
225 m_GitDiff=0;
227 if(this->m_GitSimpleListDiff)
229 git_close_diff(m_GitSimpleListDiff);
230 m_GitSimpleListDiff=0;
234 bool CGit::IsBranchNameValid(const CString& branchname)
236 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
237 return false;
238 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
239 return false;
240 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
241 return !!git_reference_is_valid_name(branchA);
244 static bool IsPowerShell(CString cmd)
246 cmd.MakeLower();
247 int powerShellPos = cmd.Find(_T("powershell"));
248 if (powerShellPos < 0)
249 return false;
251 // found the word powershell, check that it is the command and not any parameter
252 int end = cmd.GetLength();
253 if (cmd.Find(_T('"')) == 0)
255 int secondDoubleQuote = cmd.Find(_T('"'), 1);
256 if (secondDoubleQuote > 0)
257 end = secondDoubleQuote;
259 else
261 int firstSpace = cmd.Find(_T(' '));
262 if (firstSpace > 0)
263 end = firstSpace;
266 return (end - 4 - 10 == powerShellPos || end - 10 == powerShellPos); // len(".exe")==4, len("powershell")==10
269 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
271 SECURITY_ATTRIBUTES sa;
272 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
273 CAutoGeneralHandle hStdioFile;
275 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
276 sa.lpSecurityDescriptor=NULL;
277 sa.bInheritHandle=TRUE;
278 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
280 CString err = CFormatMessageWrapper();
281 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
282 return TGIT_GIT_ERROR_OPEN_PIP;
284 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
286 CString err = CFormatMessageWrapper();
287 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
288 return TGIT_GIT_ERROR_OPEN_PIP;
291 if(StdioFile)
293 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
294 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
297 STARTUPINFO si = { 0 };
298 PROCESS_INFORMATION pi;
299 si.cb=sizeof(STARTUPINFO);
301 if (hErrReadOut)
302 si.hStdError = hWriteErr;
303 else
304 si.hStdError = hWrite;
305 if(StdioFile)
306 si.hStdOutput=hStdioFile;
307 else
308 si.hStdOutput=hWrite;
310 si.wShowWindow=SW_HIDE;
311 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
313 LPTSTR pEnv = m_Environment;
314 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
316 dwFlags |= CREATE_NEW_PROCESS_GROUP;
318 // 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,
319 // 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)
320 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
321 if (IsPowerShell(cmd))
322 dwFlags |= CREATE_NEW_CONSOLE;
323 else
324 dwFlags |= DETACHED_PROCESS;
326 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
327 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
329 if (ms_bCygwinGit && cmd.Find(_T("git")) == 0)
331 cmd.Replace(_T('\\'), _T('/'));
332 cmd.Replace(_T("\""), _T("\\\""));
333 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
335 else if(cmd.Find(_T("git")) == 0)
337 int firstSpace = cmd.Find(_T(" "));
338 if (firstSpace > 0)
339 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
340 else
341 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
344 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
345 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
347 CString err = CFormatMessageWrapper();
348 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
349 return TGIT_GIT_ERROR_CREATE_PROCESS;
352 m_CurrentGitPi = pi;
354 if(piOut)
355 *piOut=pi;
356 if(hReadOut)
357 *hReadOut = hRead.Detach();
358 if(hErrReadOut)
359 *hErrReadOut = hReadErr.Detach();
360 return 0;
363 //Must use sperate function to convert ANSI str to union code string
364 //Becuase A2W use stack as internal convert buffer.
365 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
367 if(str == NULL)
368 return ;
370 int len ;
371 if(length<0)
372 len = (int)strlen((const char*)p);
373 else
374 len=length;
375 if (len == 0)
376 return;
377 int currentContentLen = str->GetLength();
378 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
379 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
380 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
383 // This method was originally used to check for orphaned branches
384 BOOL CGit::CanParseRev(CString ref)
386 if (ref.IsEmpty())
387 ref = _T("HEAD");
389 CString cmdout;
390 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
392 return FALSE;
394 if(cmdout.IsEmpty())
395 return FALSE;
397 return TRUE;
400 // Checks if we have an orphaned HEAD
401 BOOL CGit::IsInitRepos()
403 CGitHash hash;
404 if (GetHash(hash, _T("HEAD")) != 0)
405 return FALSE;
406 return hash.IsEmpty() ? TRUE : FALSE;
409 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
411 PASYNCREADSTDERRTHREADARGS pDataArray;
412 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
414 DWORD readnumber;
415 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
416 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
418 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
419 break;
422 return 0;
425 int CGit::Run(CGitCall* pcall)
427 PROCESS_INFORMATION pi;
428 CAutoGeneralHandle hRead, hReadErr;
429 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
430 return TGIT_GIT_ERROR_CREATE_PROCESS;
432 CAutoGeneralHandle piThread(pi.hThread);
433 CAutoGeneralHandle piProcess(pi.hProcess);
435 ASYNCREADSTDERRTHREADARGS threadArguments;
436 threadArguments.fileHandle = hReadErr;
437 threadArguments.pcall = pcall;
438 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
440 DWORD readnumber;
441 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
442 bool bAborted=false;
443 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
445 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
446 if(!bAborted)//For now, flush output when command aborted.
447 if(pcall->OnOutputData(data,readnumber))
448 bAborted=true;
450 if(!bAborted)
451 pcall->OnEnd();
453 if (thread)
454 WaitForSingleObject(thread, INFINITE);
456 WaitForSingleObject(pi.hProcess, INFINITE);
457 DWORD exitcode =0;
459 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
461 CString err = CFormatMessageWrapper();
462 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
463 return TGIT_GIT_ERROR_GET_EXIT_CODE;
465 else
466 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
468 return exitcode;
470 class CGitCall_ByteVector : public CGitCall
472 public:
473 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
474 virtual bool OnOutputData(const BYTE* data, size_t size)
476 if (!m_pvector || size == 0)
477 return false;
478 size_t oldsize=m_pvector->size();
479 m_pvector->resize(m_pvector->size()+size);
480 memcpy(&*(m_pvector->begin()+oldsize),data,size);
481 return false;
483 virtual bool OnOutputErrData(const BYTE* data, size_t size)
485 if (!m_pvectorErr || size == 0)
486 return false;
487 size_t oldsize = m_pvectorErr->size();
488 m_pvectorErr->resize(m_pvectorErr->size() + size);
489 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
490 return false;
492 BYTE_VECTOR* m_pvector;
493 BYTE_VECTOR* m_pvectorErr;
496 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
498 CGitCall_ByteVector call(cmd, vector, vectorErr);
499 return Run(&call);
501 int CGit::Run(CString cmd, CString* output, int code)
503 CString err;
504 int ret;
505 ret = Run(cmd, output, &err, code);
507 if (output && !err.IsEmpty())
509 if (!output->IsEmpty())
510 *output += _T("\n");
511 *output += err;
514 return ret;
516 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
518 BYTE_VECTOR vector, vectorErr;
519 int ret;
520 if (outputErr)
521 ret = Run(cmd, &vector, &vectorErr);
522 else
523 ret = Run(cmd, &vector);
525 vector.push_back(0);
526 StringAppend(output, &(vector[0]), code);
528 if (outputErr)
530 vectorErr.push_back(0);
531 StringAppend(outputErr, &(vectorErr[0]), code);
534 return ret;
537 class CGitCallCb : public CGitCall
539 public:
540 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
542 virtual bool OnOutputData(const BYTE* data, size_t size) override
544 // Add data
545 if (size == 0)
546 return false;
547 int oldEndPos = m_buffer.GetLength();
548 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
549 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
551 // Break into lines and feed to m_recv
552 int eolPos;
553 while ((eolPos = m_buffer.Find('\n')) >= 0)
555 m_recv(m_buffer.Left(eolPos));
556 m_buffer = m_buffer.Mid(eolPos + 1);
558 return false;
561 virtual bool OnOutputErrData(const BYTE*, size_t) override
563 return false; // Ignore error output for now
566 virtual void OnEnd() override
568 if (!m_buffer.IsEmpty())
569 m_recv(m_buffer);
570 m_buffer.Empty(); // Just for sure
573 private:
574 GitReceiverFunc m_recv;
575 CStringA m_buffer;
578 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
580 CGitCallCb call(cmd, recv);
581 return Run(&call);
584 CString CGit::GetUserName(void)
586 CEnvironment env;
587 env.CopyProcessEnvironment();
588 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
589 if (!envname.IsEmpty())
590 return envname;
591 return GetConfigValue(L"user.name");
593 CString CGit::GetUserEmail(void)
595 CEnvironment env;
596 env.CopyProcessEnvironment();
597 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
598 if (!envmail.IsEmpty())
599 return envmail;
601 return GetConfigValue(L"user.email");
604 CString CGit::GetConfigValue(const CString& name)
606 CString configValue;
607 if(this->m_IsUseGitDLL)
609 CAutoLocker lock(g_Git.m_critGitDllSec);
613 CheckAndInitDll();
614 }catch(...)
617 CStringA key, value;
618 key = CUnicodeUtils::GetUTF8(name);
622 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
623 return CString();
625 catch (const char *msg)
627 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
628 return CString();
631 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
632 return configValue;
634 else
636 CString cmd;
637 cmd.Format(L"git.exe config %s", name);
638 Run(cmd, &configValue, nullptr, CP_UTF8);
639 if (configValue.IsEmpty())
640 return configValue;
641 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
645 bool CGit::GetConfigValueBool(const CString& name)
647 CString configValue = GetConfigValue(name);
648 configValue.MakeLower();
649 configValue.Trim();
650 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
651 return true;
652 else
653 return false;
656 int CGit::GetConfigValueInt32(const CString& name, int def)
658 CString configValue = GetConfigValue(name);
659 int value = def;
660 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
661 return value;
662 return def;
665 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
667 if(this->m_IsUseGitDLL)
669 CAutoLocker lock(g_Git.m_critGitDllSec);
673 CheckAndInitDll();
675 }catch(...)
678 CStringA keya, valuea;
679 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
680 valuea = CUnicodeUtils::GetUTF8(value);
684 return [=]() { return get_set_config(keya, valuea, type); }();
686 catch (const char *msg)
688 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
689 return -1;
692 else
694 CString cmd;
695 CString option;
696 switch(type)
698 case CONFIG_GLOBAL:
699 option = _T("--global");
700 break;
701 case CONFIG_SYSTEM:
702 option = _T("--system");
703 break;
704 default:
705 break;
707 CString mangledValue = value;
708 mangledValue.Replace(_T("\\\""), _T("\\\\\""));
709 mangledValue.Replace(_T("\""), _T("\\\""));
710 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, mangledValue);
711 CString out;
712 if (Run(cmd, &out, nullptr, CP_UTF8))
714 return -1;
717 return 0;
720 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
722 if(this->m_IsUseGitDLL)
724 CAutoLocker lock(g_Git.m_critGitDllSec);
728 CheckAndInitDll();
729 }catch(...)
732 CStringA keya;
733 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
737 return [=]() { return get_set_config(keya, nullptr, type); }();
739 catch (const char *msg)
741 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
742 return -1;
745 else
747 CString cmd;
748 CString option;
749 switch(type)
751 case CONFIG_GLOBAL:
752 option = _T("--global");
753 break;
754 case CONFIG_SYSTEM:
755 option = _T("--system");
756 break;
757 default:
758 break;
760 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
761 CString out;
762 if (Run(cmd, &out, nullptr, CP_UTF8))
764 return -1;
767 return 0;
770 CString CGit::GetCurrentBranch(bool fallback)
772 CString output;
773 //Run(_T("git.exe branch"),&branch);
775 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
776 if (result != 0 && ((result == 1 && !fallback) || result != 1))
778 return _T("(no branch)");
780 else
781 return output;
785 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
787 if (localBranch.IsEmpty())
788 return;
790 CString configName;
791 configName.Format(L"branch.%s.remote", localBranch);
792 pullRemote = GetConfigValue(configName);
794 //Select pull-branch from current branch
795 configName.Format(L"branch.%s.merge", localBranch);
796 pullBranch = StripRefName(GetConfigValue(configName));
799 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
801 CString refName;
802 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
803 return;
804 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
807 CString CGit::GetFullRefName(const CString& shortRefName)
809 CString refName;
810 CString cmd;
811 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
812 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
813 return CString();//Error
814 int iStart = 0;
815 return refName.Tokenize(L"\n", iStart);
818 CString CGit::StripRefName(CString refName)
820 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
821 refName = refName.Mid(11);
822 else if(wcsncmp(refName, L"refs/", 5) == 0)
823 refName = refName.Mid(5);
824 int start =0;
825 return refName.Tokenize(_T("\n"),start);
828 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
830 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
832 if ( sProjectRoot.IsEmpty() )
833 return -1;
835 CString sDotGitPath;
836 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
837 return -1;
839 CString sHeadFile = sDotGitPath + _T("HEAD");
841 FILE *pFile;
842 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
844 if (!pFile)
846 return -1;
849 char s[256] = {0};
850 fgets(s, sizeof(s), pFile);
852 fclose(pFile);
854 const char *pfx = "ref: refs/heads/";
855 const int len = 16;//strlen(pfx)
857 if ( !strncmp(s, pfx, len) )
859 //# We're on a branch. It might not exist. But
860 //# HEAD looks good enough to be a branch.
861 CStringA utf8Branch(s + len);
862 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
863 sBranchOut.TrimRight(_T(" \r\n\t"));
865 if ( sBranchOut.IsEmpty() )
866 return -1;
868 else if (fallback)
870 CStringA utf8Hash(s);
871 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
872 unicodeHash.TrimRight(_T(" \r\n\t"));
873 if (CGitHash::IsValidSHA1(unicodeHash))
874 sBranchOut = unicodeHash;
875 else
876 //# Assume this is a detached head.
877 sBranchOut = _T("HEAD");
878 return 1;
880 else
882 //# Assume this is a detached head.
883 sBranchOut = "HEAD";
885 return 1;
888 return 0;
891 int CGit::BuildOutputFormat(CString &format,bool IsFull)
893 CString log;
894 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
895 format += log;
896 if(IsFull)
898 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
899 format += log;
900 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
901 format += log;
902 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
903 format += log;
904 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
905 format += log;
906 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
907 format += log;
908 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
909 format += log;
910 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
911 format += log;
914 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
915 format += log;
916 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
917 format += log;
918 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
919 format += log;
921 if(IsFull)
923 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
924 format += log;
926 return 0;
929 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
930 CFilterData *Filter)
932 CString cmd;
933 CString num;
934 CString since;
936 CString file = _T(" --");
938 if(path)
939 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
941 if(count>0)
942 num.Format(_T("-n%d"),count);
944 CString param;
946 if(mask& LOG_INFO_STAT )
947 param += _T(" --numstat ");
948 if(mask& LOG_INFO_FILESTATE)
949 param += _T(" --raw ");
951 if(mask& LOG_INFO_FULLHISTORY)
952 param += _T(" --full-history ");
954 if(mask& LOG_INFO_BOUNDARY)
955 param += _T(" --left-right --boundary ");
957 if(mask& CGit::LOG_INFO_ALL_BRANCH)
958 param += _T(" --all ");
960 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
961 param += _T(" --branches ");
963 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
964 param += _T(" -C ");
966 if(mask& CGit::LOG_INFO_DETECT_RENAME )
967 param += _T(" -M ");
969 if(mask& CGit::LOG_INFO_FIRST_PARENT )
970 param += _T(" --first-parent ");
972 if(mask& CGit::LOG_INFO_NO_MERGE )
973 param += _T(" --no-merges ");
975 if(mask& CGit::LOG_INFO_FOLLOW)
976 param += _T(" --follow ");
978 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
979 param += _T(" -c ");
981 if(mask& CGit::LOG_INFO_FULL_DIFF)
982 param += _T(" --full-diff ");
984 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
985 param += _T(" --simplify-by-decoration ");
987 param += range;
989 CString st1,st2;
991 if( Filter && (Filter->m_From != -1))
993 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
994 param += st1;
997 if( Filter && (Filter->m_To != -1))
999 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
1000 param += st2;
1003 bool isgrep = false;
1004 if( Filter && (!Filter->m_Author.IsEmpty()))
1006 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
1007 param += st1;
1008 isgrep = true;
1011 if( Filter && (!Filter->m_Committer.IsEmpty()))
1013 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1014 param += st1;
1015 isgrep = true;
1018 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1020 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1021 param += st1;
1022 isgrep = true;
1025 if(Filter && isgrep)
1027 if(!Filter->m_IsRegex)
1028 param += _T(" --fixed-strings ");
1030 param += _T(" --regexp-ignore-case --extended-regexp ");
1033 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1034 if (logOrderBy == LOG_ORDER_TOPOORDER)
1035 param += _T(" --topo-order");
1036 else if (logOrderBy == LOG_ORDER_DATEORDER)
1037 param += _T(" --date-order");
1039 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
1040 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1041 else
1043 CString log;
1044 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1045 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1046 num,param,log);
1049 cmd += file;
1051 return cmd;
1053 #define BUFSIZE 512
1054 void GetTempPath(CString &path)
1056 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1057 DWORD dwRetVal;
1058 DWORD dwBufSize=BUFSIZE;
1059 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1060 lpPathBuffer); // buffer for path
1061 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1063 path=_T("");
1065 path.Format(_T("%s"),lpPathBuffer);
1067 CString GetTempFile()
1069 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1070 DWORD dwRetVal;
1071 DWORD dwBufSize=BUFSIZE;
1072 TCHAR szTempName[BUFSIZE] = { 0 };
1073 UINT uRetVal;
1075 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1076 lpPathBuffer); // buffer for path
1077 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1079 return _T("");
1081 // Create a temporary file.
1082 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1083 TEXT("Patch"), // temp file name prefix
1084 0, // create unique name
1085 szTempName); // buffer for name
1088 if (uRetVal == 0)
1090 return _T("");
1093 return CString(szTempName);
1097 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1099 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1100 if (result == 0) return 0;
1101 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1103 if (lpBuffer)
1104 lpBuffer[0] = '\0';
1105 return result + 13;
1108 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1109 CreateDirectory(lpBuffer, NULL);
1111 return result + 13;
1114 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1116 STARTUPINFO si;
1117 PROCESS_INFORMATION pi;
1118 si.cb=sizeof(STARTUPINFO);
1119 GetStartupInfo(&si);
1121 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1122 psa.bInheritHandle=TRUE;
1124 HANDLE hReadErr, hWriteErr;
1125 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1127 CString err = CFormatMessageWrapper();
1128 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1129 return TGIT_GIT_ERROR_OPEN_PIP;
1132 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1133 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1135 if (houtfile == INVALID_HANDLE_VALUE)
1137 CString err = CFormatMessageWrapper();
1138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1139 CloseHandle(hReadErr);
1140 CloseHandle(hWriteErr);
1141 return TGIT_GIT_ERROR_OPEN_PIP;
1144 si.wShowWindow = SW_HIDE;
1145 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1146 si.hStdOutput = houtfile;
1147 si.hStdError = hWriteErr;
1149 LPTSTR pEnv = m_Environment;
1150 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1152 if(cmd.Find(_T("git")) == 0)
1153 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1155 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1156 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1158 CString err = CFormatMessageWrapper();
1159 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1160 stdErr = &err;
1161 CloseHandle(hReadErr);
1162 CloseHandle(hWriteErr);
1163 CloseHandle(houtfile);
1164 return TGIT_GIT_ERROR_CREATE_PROCESS;
1167 BYTE_VECTOR stderrVector;
1168 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1169 HANDLE thread;
1170 ASYNCREADSTDERRTHREADARGS threadArguments;
1171 threadArguments.fileHandle = hReadErr;
1172 threadArguments.pcall = &pcall;
1173 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1175 WaitForSingleObject(pi.hProcess,INFINITE);
1177 CloseHandle(hWriteErr);
1178 CloseHandle(hReadErr);
1180 if (thread)
1181 WaitForSingleObject(thread, INFINITE);
1183 stderrVector.push_back(0);
1184 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1186 DWORD exitcode = 0;
1187 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1189 CString err = CFormatMessageWrapper();
1190 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1191 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1193 else
1194 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1196 CloseHandle(pi.hThread);
1197 CloseHandle(pi.hProcess);
1198 CloseHandle(houtfile);
1199 return exitcode;
1202 git_repository * CGit::GetGitRepository() const
1204 git_repository * repo = nullptr;
1205 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1206 return repo;
1209 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1211 ATLASSERT(repo);
1213 // no need to parse a ref if it's already a 40-byte hash
1214 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1216 hash = CGitHash(friendname);
1217 return 0;
1220 int isHeadOrphan = git_repository_head_unborn(repo);
1221 if (isHeadOrphan != 0)
1223 hash.Empty();
1224 if (isHeadOrphan == 1)
1225 return 0;
1226 else
1227 return -1;
1230 CAutoObject gitObject;
1231 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1232 return -1;
1234 const git_oid * oid = git_object_id(gitObject);
1235 if (!oid)
1236 return -1;
1238 hash = CGitHash((char *)oid->id);
1240 return 0;
1243 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1245 // no need to parse a ref if it's already a 40-byte hash
1246 if (CGitHash::IsValidSHA1(friendname))
1248 hash = CGitHash(friendname);
1249 return 0;
1252 if (m_IsUseLibGit2)
1254 CAutoRepository repo(GetGitRepository());
1255 if (!repo)
1256 return -1;
1258 return GetHash(repo, hash, friendname, true);
1260 else
1262 CString branch = FixBranchName(friendname);
1263 if (friendname == _T("FETCH_HEAD") && branch.IsEmpty())
1264 branch = friendname;
1265 CString cmd;
1266 cmd.Format(_T("git.exe rev-parse %s"), branch);
1267 gitLastErr.Empty();
1268 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1269 hash = CGitHash(gitLastErr.Trim());
1270 if (ret == 0)
1271 gitLastErr.Empty();
1272 else if (friendname == _T("HEAD")) // special check for unborn branch
1274 CString currentbranch;
1275 if (GetCurrentBranchFromFile(m_CurrentDir, currentbranch))
1276 return -1;
1277 gitLastErr.Empty();
1278 return 0;
1280 return ret;
1284 int CGit::GetInitAddList(CTGitPathList &outputlist)
1286 CString cmd;
1287 BYTE_VECTOR cmdout;
1289 cmd=_T("git.exe ls-files -s -t -z");
1290 outputlist.Clear();
1291 if (Run(cmd, &cmdout))
1292 return -1;
1294 if (outputlist.ParserFromLsFile(cmdout))
1295 return -1;
1296 for(int i = 0; i < outputlist.GetCount(); ++i)
1297 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1299 return 0;
1301 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1303 CString cmd;
1304 CString ignore;
1305 if (ignoreSpaceAtEol)
1306 ignore += _T(" --ignore-space-at-eol");
1307 if (ignoreSpaceChange)
1308 ignore += _T(" --ignore-space-change");
1309 if (ignoreAllSpace)
1310 ignore += _T(" --ignore-all-space");
1311 if (ignoreBlankLines)
1312 ignore += _T(" --ignore-blank-lines");
1314 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1316 //rev1=+_T("");
1317 if(rev1 == GIT_REV_ZERO)
1318 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1319 else
1320 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1322 else
1324 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1327 BYTE_VECTOR out;
1328 if (Run(cmd, &out))
1329 return -1;
1331 return outputlist.ParserFromLog(out);
1334 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1336 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1337 list->push_back(CUnicodeUtils::GetUnicode(refname));
1338 return 0;
1341 int CGit::GetTagList(STRING_VECTOR &list)
1343 if (this->m_IsUseLibGit2)
1345 CAutoRepository repo(GetGitRepository());
1346 if (!repo)
1347 return -1;
1349 CAutoStrArray tag_names;
1351 if (git_tag_list(tag_names, repo))
1352 return -1;
1354 for (size_t i = 0; i < tag_names->count; ++i)
1356 CStringA tagName(tag_names->strings[i]);
1357 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1360 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1362 return 0;
1364 else
1366 CString cmd, output;
1367 cmd=_T("git.exe tag -l");
1368 int ret = Run(cmd, &output, NULL, CP_UTF8);
1369 if(!ret)
1371 int pos=0;
1372 CString one;
1373 while( pos>=0 )
1375 one=output.Tokenize(_T("\n"),pos);
1376 if (!one.IsEmpty())
1377 list.push_back(one);
1379 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1381 else if (ret == 1 && IsInitRepos())
1382 return 0;
1383 return ret;
1387 CString CGit::GetGitLastErr(const CString& msg)
1389 if (this->m_IsUseLibGit2)
1390 return GetLibGit2LastErr(msg);
1391 else if (gitLastErr.IsEmpty())
1392 return msg + _T("\nUnknown git.exe error.");
1393 else
1395 CString lastError = gitLastErr;
1396 gitLastErr.Empty();
1397 return msg + _T("\n") + lastError;
1401 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1403 if (UsingLibGit2(cmd))
1404 return GetLibGit2LastErr(msg);
1405 else if (gitLastErr.IsEmpty())
1406 return msg + _T("\nUnknown git.exe error.");
1407 else
1409 CString lastError = gitLastErr;
1410 gitLastErr.Empty();
1411 return msg + _T("\n") + lastError;
1415 CString CGit::GetLibGit2LastErr()
1417 const git_error *libgit2err = giterr_last();
1418 if (libgit2err)
1420 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1421 giterr_clear();
1422 return _T("libgit2 returned: ") + lastError;
1424 else
1425 return _T("An error occoured in libgit2, but no message is available.");
1428 CString CGit::GetLibGit2LastErr(const CString& msg)
1430 if (!msg.IsEmpty())
1431 return msg + _T("\n") + GetLibGit2LastErr();
1432 return GetLibGit2LastErr();
1435 CString CGit::FixBranchName_Mod(CString& branchName)
1437 if(branchName == "FETCH_HEAD")
1438 branchName = DerefFetchHead();
1439 return branchName;
1442 CString CGit::FixBranchName(const CString& branchName)
1444 CString tempBranchName = branchName;
1445 FixBranchName_Mod(tempBranchName);
1446 return tempBranchName;
1449 bool CGit::IsBranchTagNameUnique(const CString& name)
1451 if (m_IsUseLibGit2)
1453 CAutoRepository repo(GetGitRepository());
1454 if (!repo)
1455 return true; // TODO: optimize error reporting
1457 CAutoReference tagRef;
1458 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1459 return true;
1461 CAutoReference branchRef;
1462 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1463 return true;
1465 return false;
1467 // else
1468 CString output;
1470 CString cmd;
1471 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1472 int ret = Run(cmd, &output, NULL, CP_UTF8);
1473 if (!ret)
1475 int i = 0, pos = 0;
1476 while (pos >= 0)
1478 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1479 ++i;
1481 if (i >= 2)
1482 return false;
1485 return true;
1488 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1490 if (m_IsUseLibGit2)
1492 CAutoRepository repo(GetGitRepository());
1493 if (!repo)
1494 return false; // TODO: optimize error reporting
1496 CString prefix;
1497 if (isBranch)
1498 prefix = _T("refs/heads/");
1499 else
1500 prefix = _T("refs/tags/");
1502 CAutoReference ref;
1503 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1504 return false;
1506 return true;
1508 // else
1509 CString cmd, output;
1511 cmd = _T("git.exe show-ref ");
1512 if (isBranch)
1513 cmd += _T("--heads ");
1514 else
1515 cmd += _T("--tags ");
1517 cmd += _T("refs/heads/") + name;
1518 cmd += _T(" refs/tags/") + name;
1520 int ret = Run(cmd, &output, NULL, CP_UTF8);
1521 if (!ret)
1523 if (!output.IsEmpty())
1524 return true;
1527 return false;
1530 CString CGit::DerefFetchHead()
1532 CString dotGitPath;
1533 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1534 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1535 int forMergeLineCount = 0;
1536 std::string line;
1537 std::string hashToReturn;
1538 while(getline(fetchHeadFile, line))
1540 //Tokenize this line
1541 std::string::size_type prevPos = 0;
1542 std::string::size_type pos = line.find('\t');
1543 if(pos == std::string::npos) continue; //invalid line
1545 std::string hash = line.substr(0, pos);
1546 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1548 bool forMerge = pos == prevPos;
1549 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1551 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1553 //Process this line
1554 if(forMerge)
1556 hashToReturn = hash;
1557 ++forMergeLineCount;
1558 if(forMergeLineCount > 1)
1559 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1563 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1566 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1568 int ret = 0;
1569 CString cur;
1570 if (m_IsUseLibGit2)
1572 CAutoRepository repo(GetGitRepository());
1573 if (!repo)
1574 return -1;
1576 if (git_repository_head_detached(repo) == 1)
1577 cur = _T("(detached from ");
1579 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1581 git_branch_t flags = GIT_BRANCH_LOCAL;
1582 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1583 flags = GIT_BRANCH_ALL;
1584 else if (type & BRANCH_REMOTE)
1585 flags = GIT_BRANCH_REMOTE;
1587 CAutoBranchIterator it;
1588 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1589 return -1;
1591 git_reference * ref = nullptr;
1592 git_branch_t branchType;
1593 while (git_branch_next(&ref, &branchType, it) == 0)
1595 CAutoReference autoRef(ref);
1596 const char * name = nullptr;
1597 if (git_branch_name(&name, ref))
1598 continue;
1600 CString branchname = CUnicodeUtils::GetUnicode(name);
1601 if (branchType & GIT_BRANCH_REMOTE)
1602 list.push_back(_T("remotes/") + branchname);
1603 else
1605 if (git_branch_is_head(ref))
1606 cur = branchname;
1607 list.push_back(branchname);
1612 else
1614 CString cmd, output;
1615 cmd = _T("git.exe branch --no-color");
1617 if ((type & BRANCH_ALL) == BRANCH_ALL)
1618 cmd += _T(" -a");
1619 else if (type & BRANCH_REMOTE)
1620 cmd += _T(" -r");
1622 ret = Run(cmd, &output, nullptr, CP_UTF8);
1623 if (!ret)
1625 int pos = 0;
1626 CString one;
1627 while (pos >= 0)
1629 one = output.Tokenize(_T("\n"), pos);
1630 one.Trim(L" \r\n\t");
1631 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1632 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1633 if (one[0] == _T('*'))
1635 one = one.Mid(2);
1636 cur = one;
1638 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1640 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1641 one = _T("remotes/") + one;
1642 list.push_back(one);
1646 else if (ret == 1 && IsInitRepos())
1647 return 0;
1650 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1651 list.push_back(L"FETCH_HEAD");
1653 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1655 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1657 for (unsigned int i = 0; i < list.size(); ++i)
1659 if (list[i] == cur)
1661 *current = i;
1662 break;
1667 return ret;
1670 int CGit::GetRemoteList(STRING_VECTOR &list)
1672 if (this->m_IsUseLibGit2)
1674 CAutoRepository repo(GetGitRepository());
1675 if (!repo)
1676 return -1;
1678 CAutoStrArray remotes;
1679 if (git_remote_list(remotes, repo))
1680 return -1;
1682 for (size_t i = 0; i < remotes->count; ++i)
1684 CStringA remote(remotes->strings[i]);
1685 list.push_back(CUnicodeUtils::GetUnicode(remote));
1688 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1690 return 0;
1692 else
1694 int ret;
1695 CString cmd, output;
1696 cmd=_T("git.exe remote");
1697 ret = Run(cmd, &output, NULL, CP_UTF8);
1698 if(!ret)
1700 int pos=0;
1701 CString one;
1702 while( pos>=0 )
1704 one=output.Tokenize(_T("\n"),pos);
1705 if (!one.IsEmpty())
1706 list.push_back(one);
1709 return ret;
1713 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1715 if (UsingLibGit2(GIT_CMD_FETCH))
1717 CAutoRepository repo(GetGitRepository());
1718 if (!repo)
1719 return -1;
1721 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1722 CAutoRemote gitremote;
1723 if (git_remote_lookup(gitremote.GetPointer(), repo, remoteA) < 0)
1724 return -1;
1726 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1727 callbacks.credentials = g_Git2CredCallback;
1728 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1729 git_remote_set_callbacks(gitremote, &callbacks);
1730 if (git_remote_connect(gitremote, GIT_DIRECTION_FETCH) < 0)
1731 return -1;
1733 const git_remote_head** heads = nullptr;
1734 size_t size = 0;
1735 if (git_remote_ls(&heads, &size, gitremote) < 0)
1736 return -1;
1738 for (size_t i = 0; i < size; i++)
1740 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1741 CString shortname;
1742 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1743 continue;
1744 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1745 if (shortname.Find(_T("^{}")) >= 1)
1746 continue;
1747 list.push_back(shortname);
1749 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1750 return 0;
1753 CString cmd, out, err;
1754 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1755 if (Run(cmd, &out, &err, CP_UTF8))
1757 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1758 return -1;
1761 int pos = 0;
1762 while (pos >= 0)
1764 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1765 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1766 if (one.Find(_T("^{}")) >= 1)
1767 continue;
1768 if (!one.IsEmpty())
1769 list.push_back(one);
1771 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1772 return 0;
1775 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1777 if (UsingLibGit2(GIT_CMD_PUSH))
1779 CAutoRepository repo(GetGitRepository());
1780 if (!repo)
1781 return -1;
1783 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1784 CAutoRemote remote;
1785 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1786 return -1;
1788 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1789 callbacks.credentials = g_Git2CredCallback;
1790 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1791 git_remote_set_callbacks(remote, &callbacks);
1792 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1793 return -1;
1795 std::vector<CStringA> refspecs;
1796 for (auto ref : list)
1797 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1799 std::vector<char*> vc;
1800 vc.reserve(refspecs.size());
1801 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1802 git_strarray specs = { &vc[0], vc.size() };
1804 if (git_remote_push(remote, &specs, nullptr) < 0)
1805 return -1;
1807 else
1809 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1810 for (auto ref : list)
1812 CString refspec = _T(":") + ref;
1813 mgtPush.AddFile(refspec);
1816 BOOL cancel = FALSE;
1817 mgtPush.Execute(cancel);
1820 return 0;
1823 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1825 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1826 list->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref)));
1827 return 0;
1830 int CGit::GetRefList(STRING_VECTOR &list)
1832 if (this->m_IsUseLibGit2)
1834 CAutoRepository repo(GetGitRepository());
1835 if (!repo)
1836 return -1;
1838 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1839 return -1;
1841 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1843 return 0;
1845 else
1847 CString cmd, output;
1848 cmd=_T("git.exe show-ref -d");
1849 int ret = Run(cmd, &output, NULL, CP_UTF8);
1850 if(!ret)
1852 int pos=0;
1853 CString one;
1854 while( pos>=0 )
1856 one=output.Tokenize(_T("\n"),pos);
1857 int start=one.Find(_T(" "),0);
1858 if(start>0)
1860 CString name;
1861 name=one.Right(one.GetLength()-start-1);
1862 if (list.empty() || name != *list.crbegin() + _T("^{}"))
1863 list.push_back(name);
1866 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1868 else if (ret == 1 && IsInitRepos())
1869 return 0;
1870 return ret;
1874 typedef struct map_each_ref_payload {
1875 git_repository * repo;
1876 MAP_HASH_NAME * map;
1877 } map_each_ref_payload;
1879 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1881 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1883 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1885 CAutoObject gitObject;
1886 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1887 return 1;
1889 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1891 str += _T("^{}"); // deref tag
1892 CAutoObject derefedTag;
1893 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1894 return 1;
1895 gitObject.Swap(derefedTag);
1898 const git_oid * oid = git_object_id(gitObject);
1899 if (oid == NULL)
1900 return 1;
1902 CGitHash hash((char *)oid->id);
1903 (*payloadContent->map)[hash].push_back(str);
1905 return 0;
1907 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1909 ATLASSERT(repo);
1911 map_each_ref_payload payloadContent = { repo, &map };
1913 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1914 return -1;
1916 for (auto it = map.begin(); it != map.end(); ++it)
1918 std::sort(it->second.begin(), it->second.end());
1921 return 0;
1924 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1926 if (this->m_IsUseLibGit2)
1928 CAutoRepository repo(GetGitRepository());
1929 if (!repo)
1930 return -1;
1932 return GetMapHashToFriendName(repo, map);
1934 else
1936 CString cmd, output;
1937 cmd=_T("git.exe show-ref -d");
1938 int ret = Run(cmd, &output, NULL, CP_UTF8);
1939 if(!ret)
1941 int pos=0;
1942 CString one;
1943 while( pos>=0 )
1945 one=output.Tokenize(_T("\n"),pos);
1946 int start=one.Find(_T(" "),0);
1947 if(start>0)
1949 CString name;
1950 name=one.Right(one.GetLength()-start-1);
1952 CString hash;
1953 hash=one.Left(start);
1955 map[CGitHash(hash)].push_back(name);
1959 else if (ret == 1 && IsInitRepos())
1960 return 0;
1961 return ret;
1965 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
1967 CAutoConfig config(true);
1968 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, FALSE) < 0)
1969 return -1;
1970 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
1972 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
1973 CString key = CUnicodeUtils::GetUnicode(entry->name);
1974 key = key.Mid(7, key.GetLength() - 7 - 12); // 7: branch., 12: .description
1975 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
1976 return 0;
1977 }, &map);
1980 static void SetLibGit2SearchPath(int level, const CString &value)
1982 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1983 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1986 static void SetLibGit2TemplatePath(const CString &value)
1988 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1989 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1992 int CGit::FindAndSetGitExePath(BOOL bFallback)
1994 CRegString msysdir = CRegString(REG_MSYSGIT_PATH, _T(""), FALSE);
1995 CString str = msysdir;
1996 if (str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1998 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
1999 if (!bFallback)
2000 return FALSE;
2002 // first, search PATH if git/bin directory is already present
2003 if (FindGitPath())
2005 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2006 msysdir = CGit::ms_LastMsysGitDir;
2007 msysdir.write();
2008 return TRUE;
2011 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2012 str = msyslocalinstalldir;
2013 str.TrimRight(_T("\\"));
2014 if (str.IsEmpty())
2016 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2017 str = msysinstalldir;
2018 str.TrimRight(_T("\\"));
2020 if (!str.IsEmpty())
2022 str += "\\bin";
2023 msysdir = str;
2024 CGit::ms_LastMsysGitDir = str;
2025 msysdir.write();
2026 return TRUE;
2028 else
2029 return FALSE;
2031 else
2033 CGit::ms_LastMsysGitDir = str;
2034 return TRUE;
2038 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
2040 if (m_bInitialized)
2042 return TRUE;
2045 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
2046 this->m_Environment.clear();
2047 m_Environment.CopyProcessEnvironment();
2048 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2050 TCHAR *oldpath;
2051 size_t homesize,size;
2053 // set HOME if not set already
2054 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
2055 if (!homesize)
2056 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
2058 //setup ssh client
2059 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
2060 if (sshclient.IsEmpty())
2061 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
2063 if(!sshclient.IsEmpty())
2065 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
2066 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
2068 else
2070 TCHAR sPlink[MAX_PATH] = {0};
2071 GetModuleFileName(NULL, sPlink, _countof(sPlink));
2072 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
2073 if (ptr) {
2074 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
2075 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
2076 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2081 TCHAR sAskPass[MAX_PATH] = {0};
2082 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2083 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2084 if (ptr)
2086 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2087 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2088 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2089 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2093 if (!FindAndSetGitExePath(bFallback))
2094 return FALSE;
2096 // check for git.exe existance (maybe it was deinstalled in the meantime)
2097 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
2099 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2100 return FALSE;
2103 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2104 // Configure libgit2 search paths
2105 CString msysGitDir;
2106 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
2107 msysGitDir.ReleaseBuffer();
2108 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
2109 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2110 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2111 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 };
2112 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2113 CString msysGitTemplateDir;
2114 if (!ms_bCygwinGit)
2115 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
2116 else
2117 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\usr\\share\\git-core\\templates"));
2118 msysGitTemplateDir.ReleaseBuffer();
2119 SetLibGit2TemplatePath(msysGitTemplateDir);
2121 //set path
2122 _tdupenv_s(&oldpath,&size,_T("PATH"));
2124 CString path;
2125 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
2127 m_Environment.SetEnv(_T("PATH"), path);
2129 CString str1 = m_Environment.GetEnv(_T("PATH"));
2131 CString sOldPath = oldpath;
2132 free(oldpath);
2134 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2135 // register filter only once
2136 if (!git_filter_lookup("filter"))
2138 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir + L"\\sh.exe\"", m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2139 return FALSE;
2141 #endif
2143 m_bInitialized = TRUE;
2144 return true;
2147 CString CGit::GetHomeDirectory() const
2149 const wchar_t * homeDir = wget_windows_home_directory();
2150 return CString(homeDir, (int)wcslen(homeDir));
2153 CString CGit::GetGitLocalConfig() const
2155 CString path;
2156 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2157 path += _T("config");
2158 return path;
2161 CStringA CGit::GetGitPathStringA(const CString &path)
2163 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2166 CString CGit::GetGitGlobalConfig() const
2168 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2171 CString CGit::GetGitGlobalXDGConfigPath() const
2173 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2176 CString CGit::GetGitGlobalXDGConfig() const
2178 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2181 CString CGit::GetGitSystemConfig() const
2183 const wchar_t * systemConfig = wget_msysgit_etc();
2184 return CString(systemConfig, (int)wcslen(systemConfig));
2187 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2189 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2191 CAutoRepository repo = GetGitRepository();
2192 if (!repo)
2193 return FALSE;
2195 if (git_repository_head_unborn(repo))
2196 return FALSE;
2198 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2199 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2200 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2202 CAutoStatusList status;
2203 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2204 return FALSE;
2206 return (0 == git_status_list_entrycount(status));
2209 CString out;
2210 CString cmd;
2211 cmd=_T("git.exe rev-parse --verify HEAD");
2213 if(Run(cmd,&out,CP_UTF8))
2214 return FALSE;
2216 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2217 if(Run(cmd,&out,CP_UTF8))
2218 return FALSE;
2220 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2221 if(Run(cmd,&out,CP_UTF8))
2222 return FALSE;
2224 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2225 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2226 return FALSE;
2228 return TRUE;
2230 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2232 int ret;
2233 for (int i = 0; i < list.GetCount(); ++i)
2235 ret = Revert(commit, (CTGitPath&)list[i], err);
2236 if(ret)
2237 return ret;
2239 return 0;
2241 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2243 CString cmd;
2245 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2247 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2249 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2250 return -1;
2252 CString force;
2253 // if the filenames only differ in case, we have to pass "-f"
2254 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2255 force = _T("-f ");
2256 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2257 if (Run(cmd, &err, CP_UTF8))
2258 return -1;
2260 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2261 if (Run(cmd, &err, CP_UTF8))
2262 return -1;
2264 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2265 { //To init git repository, there are not HEAD, so we can use git reset command
2266 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2268 if (Run(cmd, &err, CP_UTF8))
2269 return -1;
2271 else
2273 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2274 if (Run(cmd, &err, CP_UTF8))
2275 return -1;
2278 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2280 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2281 if (Run(cmd, &err, CP_UTF8))
2282 return -1;
2285 return 0;
2288 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2290 ATLASSERT(repo);
2292 CAutoIndex index;
2293 if (git_repository_index(index.GetPointer(), repo))
2294 return -1;
2296 return git_index_has_conflicts(index);
2299 int CGit::HasWorkingTreeConflicts()
2301 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2303 CAutoRepository repo(GetGitRepository());
2304 if (!repo)
2305 return -1;
2307 return HasWorkingTreeConflicts(repo);
2310 CString cmd = _T("git.exe ls-files -u -t -z");
2312 CString output;
2313 if (Run(cmd, &output, &gitLastErr, CP_UTF8))
2314 return -1;
2316 return output.IsEmpty() ? 0 : 1;
2319 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2321 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2323 CAutoRepository repo(GetGitRepository());
2324 if (!repo)
2325 return false;
2327 CGitHash fromHash, toHash, baseHash;
2328 if (GetHash(repo, toHash, FixBranchName(to)))
2329 return false;
2331 if (GetHash(repo, fromHash, FixBranchName(from)))
2332 return false;
2334 git_oid baseOid;
2335 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2336 return false;
2338 baseHash = baseOid.id;
2340 if (commonAncestor)
2341 *commonAncestor = baseHash;
2343 return fromHash == baseHash;
2345 // else
2346 CString base;
2347 CGitHash basehash,hash;
2348 CString cmd;
2349 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2351 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2353 return false;
2355 basehash = base.Trim();
2357 GetHash(hash, from);
2359 if (commonAncestor)
2360 *commonAncestor = basehash;
2362 return hash == basehash;
2365 unsigned int CGit::Hash2int(const CGitHash &hash)
2367 int ret=0;
2368 for (int i = 0; i < 4; ++i)
2370 ret = ret << 8;
2371 ret |= hash.m_hash[i];
2373 return ret;
2376 int CGit::RefreshGitIndex()
2378 if(g_Git.m_IsUseGitDLL)
2380 CAutoLocker lock(g_Git.m_critGitDllSec);
2383 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2385 }catch(...)
2387 return -1;
2391 else
2393 CString cmd,output;
2394 cmd=_T("git.exe update-index --refresh");
2395 return Run(cmd, &output, CP_UTF8);
2399 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2401 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2403 CAutoRepository repo(GetGitRepository());
2404 if (!repo)
2405 return -1;
2407 CGitHash hash;
2408 if (GetHash(repo, hash, Refname))
2409 return -1;
2411 CAutoCommit commit;
2412 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2413 return -1;
2415 CAutoTree tree;
2416 if (git_commit_tree(tree.GetPointer(), commit))
2417 return -1;
2419 CAutoTreeEntry entry;
2420 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2421 return -1;
2423 CAutoBlob blob;
2424 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2425 return -1;
2427 FILE *file = nullptr;
2428 _tfopen_s(&file, outputfile, _T("wb"));
2429 if (file == nullptr)
2431 giterr_set_str(GITERR_NONE, "Could not create file.");
2432 return -1;
2434 CAutoBuf buf;
2435 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2437 fclose(file);
2438 return -1;
2440 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2442 giterr_set_str(GITERR_OS, "Could not write to file.");
2443 fclose(file);
2445 return -1;
2447 fclose(file);
2449 return 0;
2451 else if (g_Git.m_IsUseGitDLL)
2453 CAutoLocker lock(g_Git.m_critGitDllSec);
2456 g_Git.CheckAndInitDll();
2457 CStringA ref, patha, outa;
2458 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2459 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2460 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2461 ::DeleteFile(outputfile);
2462 int ret = git_checkout_file(ref, patha, outa.GetBuffer());
2463 outa.ReleaseBuffer();
2464 return ret;
2467 catch (const char * msg)
2469 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2470 return -1;
2472 catch (...)
2474 gitLastErr = L"An unknown gitdll.dll error occurred.";
2475 return -1;
2478 else
2480 CString cmd;
2481 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2482 return RunLogFile(cmd, outputfile, &gitLastErr);
2486 void CEnvironment::clear()
2488 __super::clear();
2491 bool CEnvironment::empty()
2493 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2496 CEnvironment::operator LPTSTR()
2498 if (empty())
2499 return nullptr;
2500 return &__super::at(0);
2503 void CEnvironment::CopyProcessEnvironment()
2505 if (!empty())
2506 pop_back();
2507 TCHAR *porig = GetEnvironmentStrings();
2508 TCHAR *p = porig;
2509 while(*p !=0 || *(p+1) !=0)
2510 this->push_back(*p++);
2512 push_back(_T('\0'));
2513 push_back(_T('\0'));
2515 FreeEnvironmentStrings(porig);
2518 CString CEnvironment::GetEnv(const TCHAR *name)
2520 CString str;
2521 for (size_t i = 0; i < size(); ++i)
2523 str = &(*this)[i];
2524 int start =0;
2525 CString sname = str.Tokenize(_T("="),start);
2526 if(sname.CompareNoCase(name) == 0)
2528 return &(*this)[i+start];
2530 i+=str.GetLength();
2532 return _T("");
2535 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2537 unsigned int i;
2538 for (i = 0; i < size(); ++i)
2540 CString str = &(*this)[i];
2541 int start =0;
2542 CString sname = str.Tokenize(_T("="),start);
2543 if(sname.CompareNoCase(name) == 0)
2545 break;
2547 i+=str.GetLength();
2550 if(i == size())
2552 if (!value) // as we haven't found the variable we want to remove, just return
2553 return;
2554 if (i == 0) // make inserting into an empty environment work
2556 this->push_back(_T('\0'));
2557 ++i;
2559 i -= 1; // roll back terminate \0\0
2560 this->push_back(_T('\0'));
2563 CEnvironment::iterator it;
2564 it=this->begin();
2565 it += i;
2567 while(*it && i<size())
2569 this->erase(it);
2570 it=this->begin();
2571 it += i;
2574 if (value == nullptr) // remove the variable
2576 this->erase(it);
2577 return;
2580 while(*name)
2582 this->insert(it,*name++);
2583 ++i;
2584 it= begin()+i;
2587 this->insert(it, _T('='));
2588 ++i;
2589 it= begin()+i;
2591 while(*value)
2593 this->insert(it,*value++);
2594 ++i;
2595 it= begin()+i;
2600 int CGit::GetGitEncode(TCHAR* configkey)
2602 CString str=GetConfigValue(configkey);
2604 if(str.IsEmpty())
2605 return CP_UTF8;
2607 return CUnicodeUtils::GetCPCode(str);
2611 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2613 GIT_FILE file=0;
2614 int ret=0;
2615 GIT_DIFF diff=0;
2617 CAutoLocker lock(g_Git.m_critGitDllSec);
2621 if(!arg)
2622 diff = GetGitDiff();
2623 else
2624 git_open_diff(&diff, arg);
2626 catch (char* e)
2628 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2629 return -1;
2632 if(diff ==NULL)
2633 return -1;
2635 bool isStat = 0;
2636 if(arg == NULL)
2637 isStat = true;
2638 else
2639 isStat = !!strstr(arg, "stat");
2641 int count=0;
2643 if(hash2 == NULL)
2644 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2645 else
2646 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2648 if(ret)
2649 return -1;
2651 CTGitPath path;
2652 CString strnewname;
2653 CString stroldname;
2655 for (int j = 0; j < count; ++j)
2657 path.Reset();
2658 char *newname;
2659 char *oldname;
2661 strnewname.Empty();
2662 stroldname.Empty();
2664 int mode=0,IsBin=0,inc=0,dec=0;
2665 git_get_diff_file(diff,file,j,&newname,&oldname,
2666 &mode,&IsBin,&inc,&dec);
2668 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2669 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2671 path.SetFromGit(strnewname,&stroldname);
2672 path.ParserAction((BYTE)mode);
2674 if(IsBin)
2676 path.m_StatAdd=_T("-");
2677 path.m_StatDel=_T("-");
2679 else
2681 path.m_StatAdd.Format(_T("%d"),inc);
2682 path.m_StatDel.Format(_T("%d"),dec);
2684 PathList->AddPath(path);
2686 git_diff_flush(diff);
2688 if(arg)
2689 git_close_diff(diff);
2691 return 0;
2694 int CGit::GetShortHASHLength() const
2696 return 7;
2699 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2701 CString str=ref;
2702 CString shortname;
2703 REF_TYPE type = CGit::UNKNOWN;
2705 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2707 type = CGit::LOCAL_BRANCH;
2710 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2712 type = CGit::REMOTE_BRANCH;
2714 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2716 type = CGit::TAG;
2718 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2720 type = CGit::STASH;
2721 shortname=_T("stash");
2723 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2725 if (shortname.Find(_T("good")) == 0)
2727 type = CGit::BISECT_GOOD;
2728 shortname = _T("good");
2731 if (shortname.Find(_T("bad")) == 0)
2733 type = CGit::BISECT_BAD;
2734 shortname = _T("bad");
2737 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2739 type = CGit::NOTES;
2741 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2743 type = CGit::UNKNOWN;
2745 else
2747 type = CGit::UNKNOWN;
2748 shortname = ref;
2751 if(out_type)
2752 *out_type = type;
2754 return shortname;
2757 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2759 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2762 void CGit::SetGit2CredentialCallback(void* callback)
2764 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2767 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2769 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2772 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2774 CString cmd;
2775 if (rev2 == GitRev::GetWorkingCopy())
2776 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2777 else if (rev1 == GitRev::GetWorkingCopy())
2778 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2779 else
2781 CString merge;
2782 if (bMerge)
2783 merge += _T(" -m");
2785 if (bCombine)
2786 merge += _T(" -c");
2788 CString unified;
2789 if (diffContext >= 0)
2790 unified.Format(_T(" --unified=%d"), diffContext);
2791 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2794 if (!path.IsEmpty())
2796 cmd += _T(" \"");
2797 cmd += path.GetGitPathString();
2798 cmd += _T("\"");
2801 return cmd;
2804 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2806 ATLASSERT(payload && text);
2807 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2808 fwrite("\n", 1, 1, (FILE *)payload);
2811 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2813 ATLASSERT(payload && line);
2814 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2815 fwrite(&line->origin, 1, 1, (FILE *)payload);
2816 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2817 return 0;
2820 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2822 ATLASSERT(repo && identifier && tree);
2824 /* try to resolve identifier */
2825 CAutoObject obj;
2826 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2827 return -1;
2829 if (obj == nullptr)
2830 return GIT_ENOTFOUND;
2832 int err = 0;
2833 switch (git_object_type(obj))
2835 case GIT_OBJ_TREE:
2836 *tree = (git_tree *)obj.Detach();
2837 break;
2838 case GIT_OBJ_COMMIT:
2839 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2840 break;
2841 default:
2842 err = GIT_ENOTFOUND;
2845 return err;
2848 /* use libgit2 get unified diff */
2849 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 */)
2851 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2852 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2854 CAutoRepository repo(g_Git.GetGitRepository());
2855 if (!repo)
2856 return -1;
2858 int isHeadOrphan = git_repository_head_unborn(repo);
2859 if (isHeadOrphan == 1)
2860 return 0;
2861 else if (isHeadOrphan != 0)
2862 return -1;
2864 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2865 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2866 char *buf = pathA.GetBuffer();
2867 if (!pathA.IsEmpty())
2869 opts.pathspec.strings = &buf;
2870 opts.pathspec.count = 1;
2872 CAutoDiff diff;
2874 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2876 CAutoTree t1;
2877 CAutoDiff diff2;
2879 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2880 return -1;
2882 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2883 return -1;
2885 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2886 return -1;
2888 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2889 return -1;
2891 if (git_diff_merge(diff, diff2))
2892 return -1;
2894 else
2896 if (tree1.IsEmpty() && tree2.IsEmpty())
2897 return -1;
2899 if (tree1.IsEmpty())
2901 tree1 = tree2;
2902 tree2.Empty();
2905 CAutoTree t1;
2906 CAutoTree t2;
2907 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2908 return -1;
2910 if (tree2.IsEmpty())
2912 /* don't check return value, there are not parent commit at first commit*/
2913 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2915 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2916 return -1;
2917 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2918 return -1;
2921 CAutoDiffStats stats;
2922 if (git_diff_get_stats(stats.GetPointer(), diff))
2923 return -1;
2924 CAutoBuf statBuf;
2925 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2926 return -1;
2927 statCallback(statBuf, data);
2929 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2931 CAutoPatch patch;
2932 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2933 return -1;
2935 if (git_patch_print(patch, callback, data))
2936 return -1;
2939 pathA.ReleaseBuffer();
2941 return 0;
2944 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2946 if (UsingLibGit2(GIT_CMD_DIFF))
2948 FILE *file = nullptr;
2949 _tfopen_s(&file, patchfile, _T("w"));
2950 if (file == nullptr)
2951 return -1;
2952 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
2953 fclose(file);
2954 return ret;
2956 else
2958 CString cmd;
2959 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2960 return RunLogFile(cmd, patchfile, &gitLastErr);
2964 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
2966 ATLASSERT(payload && text);
2967 CStringA *str = (CStringA*) payload;
2968 str->Append(text->ptr, (int)text->size);
2969 str->AppendChar('\n');
2972 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2974 ATLASSERT(payload && line);
2975 CStringA *str = (CStringA*) payload;
2976 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2977 str->Append(&line->origin, 1);
2978 str->Append(line->content, (int)line->content_len);
2979 return 0;
2982 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2984 if (UsingLibGit2(GIT_CMD_DIFF))
2985 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
2986 else
2988 CString cmd;
2989 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2990 BYTE_VECTOR vector;
2991 int ret = Run(cmd, &vector);
2992 if (!vector.empty())
2994 vector.push_back(0); // vector is not NUL terminated
2995 buffer->Append((char *)&vector[0]);
2997 return ret;
3001 int CGit::GitRevert(int parent, const CGitHash &hash)
3003 if (UsingLibGit2(GIT_CMD_REVERT))
3005 CAutoRepository repo(GetGitRepository());
3006 if (!repo)
3007 return -1;
3009 CAutoCommit commit;
3010 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
3011 return -1;
3013 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3014 revert_opts.mainline = parent;
3015 int result = git_revert(repo, commit, &revert_opts);
3017 return !result ? 0 : -1;
3019 else
3021 CString cmd, merge;
3022 if (parent)
3023 merge.Format(_T("-m %d "), parent);
3024 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
3025 gitLastErr = cmd + _T("\n");
3026 if (Run(cmd, &gitLastErr, CP_UTF8))
3028 return -1;
3030 else
3032 gitLastErr.Empty();
3033 return 0;
3038 int CGit::DeleteRef(const CString& reference)
3040 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3042 CAutoRepository repo(GetGitRepository());
3043 if (!repo)
3044 return -1;
3046 CStringA refA;
3047 if (reference.Right(3) == _T("^{}"))
3048 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3049 else
3050 refA = CUnicodeUtils::GetUTF8(reference);
3052 CAutoReference ref;
3053 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3054 return -1;
3056 int result = -1;
3057 if (git_reference_is_tag(ref))
3058 result = git_tag_delete(repo, git_reference_shorthand(ref));
3059 else if (git_reference_is_branch(ref))
3060 result = git_branch_delete(ref);
3061 else if (git_reference_is_remote(ref))
3062 result = git_branch_delete(ref);
3063 else
3064 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
3066 return result;
3068 else
3070 CString cmd, shortname;
3071 if (GetShortName(reference, shortname, _T("refs/heads/")))
3072 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
3073 else if (GetShortName(reference, shortname, _T("refs/tags/")))
3074 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
3075 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
3076 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
3077 else
3079 gitLastErr = L"unsupported reference type: " + reference;
3080 return -1;
3083 if (Run(cmd, &gitLastErr, CP_UTF8))
3084 return -1;
3086 gitLastErr.Empty();
3087 return 0;
3091 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3093 if (PathFileExists(filename))
3095 FILE *pFile = nullptr;
3096 _tfopen_s(&pFile, filename, _T("r"));
3097 if (pFile)
3099 CStringA str;
3102 char s[8196] = { 0 };
3103 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3104 if (read == 0)
3105 break;
3106 str += CStringA(s, read);
3107 } while (true);
3108 fclose(pFile);
3109 msg = CUnicodeUtils::GetUnicode(str);
3110 msg.Replace(_T("\r\n"), _T("\n"));
3111 msg.TrimRight(_T("\n"));
3112 msg += _T("\n");
3114 else
3115 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3116 return true; // load no further files
3118 return false;
3121 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, CTGitPathList* filterlist)
3123 if (IsInitRepos())
3124 return GetInitAddList(result);
3126 BYTE_VECTOR out;
3128 int count = 1;
3129 if (filterlist)
3130 count = filterlist->GetCount();
3132 CString head = _T("HEAD");
3133 if (amend)
3134 head = _T("HEAD~1");
3136 for (int i = 0; i < count; ++i)
3138 BYTE_VECTOR cmdout;
3139 CString cmd;
3140 if (ms_bCygwinGit)
3142 // Prevent showing all files as modified when using cygwin's git
3143 if (!filterlist)
3144 cmd = _T("git.exe status --");
3145 else
3146 cmd.Format(_T("git.exe status -- \"%s\""), (*filterlist)[i].GetGitPathString());
3147 Run(cmd, &cmdout);
3148 cmdout.clear();
3151 // also list staged files which will be in the commit
3152 Run(_T("git.exe diff-index --cached --raw ") + head + _T(" --numstat -C -M -z --"), &cmdout);
3154 if (!filterlist)
3155 cmd = (_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z --"));
3156 else
3157 cmd.Format(_T("git.exe diff-index --raw ") + head + _T(" --numstat -C -M -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3159 BYTE_VECTOR cmdErr;
3160 if (Run(cmd, &cmdout, &cmdErr))
3162 int last = cmdErr.RevertFind(0, -1);
3163 CString str;
3164 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)cmdErr.size() - last - 1);
3165 MessageBox(nullptr, str, _T("TortoiseGit"), MB_OK | MB_ICONERROR);
3168 out.append(cmdout, 0);
3170 result.ParserFromLog(out);
3172 // handle delete conflict case, when remote : modified, local : deleted.
3173 for (int i = 0; i < count; ++i)
3175 BYTE_VECTOR cmdout;
3176 CString cmd;
3178 if (!filterlist)
3179 cmd = _T("git.exe ls-files -u -t -z");
3180 else
3181 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3183 Run(cmd, &cmdout);
3185 CTGitPathList conflictlist;
3186 conflictlist.ParserFromLog(cmdout);
3187 for (int j = 0; j < conflictlist.GetCount(); ++j)
3189 CTGitPath* p = result.LookForGitPath(conflictlist[j].GetGitPathString());
3190 if (p)
3191 p->m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3192 else
3193 result.AddPath(conflictlist[j]);
3197 // handle source files of file renames/moves (issue #860)
3198 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3199 for (int i = 0; i < count; ++i)
3201 BYTE_VECTOR cmdout;
3202 CString cmd;
3204 if (!filterlist)
3205 cmd = _T("git.exe ls-files -d -z");
3206 else
3207 cmd.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist)[i].GetGitPathString());
3209 Run(cmd, &cmdout);
3211 CTGitPathList deletelist;
3212 deletelist.ParserFromLog(cmdout, true);
3213 for (int j = 0; j < deletelist.GetCount(); ++j)
3215 CTGitPath* p = result.LookForGitPath(deletelist[j].GetGitPathString());
3216 if (!p)
3217 result.AddPath(deletelist[j]);
3221 return 0;