Update libgit2
[TortoiseGit.git] / src / Git / Git.cpp
blob763ad5b4b4c270f9227c1f698fa050a722bd7ebe
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 "GitRev.h"
23 #include "registry.h"
24 #include "GitForWindows.h"
25 #include <map>
26 #include "UnicodeUtils.h"
27 #include "gitdll.h"
28 #include <fstream>
29 #include "FormatMessageWrapper.h"
30 #include "SmartHandle.h"
31 #include "MassiveGitTaskBase.h"
32 #include "git2/sys/filter.h"
33 #include "git2/sys/transport.h"
34 #include "../libgit2/filter-filter.h"
35 #include "../libgit2/ssh-wintunnel.h"
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"), (1 << GIT_CMD_MERGE_BASE) | (1 << GIT_CMD_DELETETAGBRANCH) | (1 << GIT_CMD_GETONEFILE) | (1 << GIT_CMD_ADD));
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.empty()) ? &m_Environment[0]: NULL;
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(cmd.Find(_T("git")) == 0)
331 int firstSpace = cmd.Find(_T(" "));
332 if (firstSpace > 0)
333 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
334 else
335 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
338 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
339 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
341 CString err = CFormatMessageWrapper();
342 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
343 return TGIT_GIT_ERROR_CREATE_PROCESS;
346 m_CurrentGitPi = pi;
348 if(piOut)
349 *piOut=pi;
350 if(hReadOut)
351 *hReadOut = hRead.Detach();
352 if(hErrReadOut)
353 *hErrReadOut = hReadErr.Detach();
354 return 0;
357 //Must use sperate function to convert ANSI str to union code string
358 //Becuase A2W use stack as internal convert buffer.
359 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
361 if(str == NULL)
362 return ;
364 int len ;
365 if(length<0)
366 len = (int)strlen((const char*)p);
367 else
368 len=length;
369 if (len == 0)
370 return;
371 int currentContentLen = str->GetLength();
372 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
373 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
374 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
377 // This method was originally used to check for orphaned branches
378 BOOL CGit::CanParseRev(CString ref)
380 if (ref.IsEmpty())
381 ref = _T("HEAD");
383 CString cmdout;
384 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
386 return FALSE;
388 if(cmdout.IsEmpty())
389 return FALSE;
391 return TRUE;
394 // Checks if we have an orphaned HEAD
395 BOOL CGit::IsInitRepos()
397 CGitHash hash;
398 // handle error on reading HEAD hash as init repo
399 if (GetHash(hash, _T("HEAD")) != 0)
400 return TRUE;
401 return hash.IsEmpty() ? TRUE : FALSE;
404 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
406 PASYNCREADSTDERRTHREADARGS pDataArray;
407 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
409 DWORD readnumber;
410 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
411 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
413 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
414 break;
417 return 0;
420 int CGit::Run(CGitCall* pcall)
422 PROCESS_INFORMATION pi;
423 CAutoGeneralHandle hRead, hReadErr;
424 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
425 return TGIT_GIT_ERROR_CREATE_PROCESS;
427 CAutoGeneralHandle piThread(pi.hThread);
428 CAutoGeneralHandle piProcess(pi.hProcess);
430 ASYNCREADSTDERRTHREADARGS threadArguments;
431 threadArguments.fileHandle = hReadErr;
432 threadArguments.pcall = pcall;
433 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
435 DWORD readnumber;
436 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
437 bool bAborted=false;
438 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
440 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
441 if(!bAborted)//For now, flush output when command aborted.
442 if(pcall->OnOutputData(data,readnumber))
443 bAborted=true;
445 if(!bAborted)
446 pcall->OnEnd();
448 if (thread)
449 WaitForSingleObject(thread, INFINITE);
451 WaitForSingleObject(pi.hProcess, INFINITE);
452 DWORD exitcode =0;
454 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
456 CString err = CFormatMessageWrapper();
457 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
458 return TGIT_GIT_ERROR_GET_EXIT_CODE;
460 else
461 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
463 return exitcode;
465 class CGitCall_ByteVector : public CGitCall
467 public:
468 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
469 virtual bool OnOutputData(const BYTE* data, size_t size)
471 if (!m_pvector || size == 0)
472 return false;
473 size_t oldsize=m_pvector->size();
474 m_pvector->resize(m_pvector->size()+size);
475 memcpy(&*(m_pvector->begin()+oldsize),data,size);
476 return false;
478 virtual bool OnOutputErrData(const BYTE* data, size_t size)
480 if (!m_pvectorErr || size == 0)
481 return false;
482 size_t oldsize = m_pvectorErr->size();
483 m_pvectorErr->resize(m_pvectorErr->size() + size);
484 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
485 return false;
487 BYTE_VECTOR* m_pvector;
488 BYTE_VECTOR* m_pvectorErr;
491 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
493 CGitCall_ByteVector call(cmd, vector, vectorErr);
494 return Run(&call);
496 int CGit::Run(CString cmd, CString* output, int code)
498 CString err;
499 int ret;
500 ret = Run(cmd, output, &err, code);
502 if (output && !err.IsEmpty())
504 if (!output->IsEmpty())
505 *output += _T("\n");
506 *output += err;
509 return ret;
511 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
513 BYTE_VECTOR vector, vectorErr;
514 int ret;
515 if (outputErr)
516 ret = Run(cmd, &vector, &vectorErr);
517 else
518 ret = Run(cmd, &vector);
520 vector.push_back(0);
521 StringAppend(output, &(vector[0]), code);
523 if (outputErr)
525 vectorErr.push_back(0);
526 StringAppend(outputErr, &(vectorErr[0]), code);
529 return ret;
532 class CGitCallCb : public CGitCall
534 public:
535 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
537 virtual bool OnOutputData(const BYTE* data, size_t size) override
539 // Add data
540 if (size == 0)
541 return false;
542 int oldEndPos = m_buffer.GetLength();
543 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
544 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
546 // Break into lines and feed to m_recv
547 int eolPos;
548 while ((eolPos = m_buffer.Find('\n')) >= 0)
550 m_recv(m_buffer.Left(eolPos));
551 m_buffer = m_buffer.Mid(eolPos + 1);
553 return false;
556 virtual bool OnOutputErrData(const BYTE*, size_t) override
558 return false; // Ignore error output for now
561 virtual void OnEnd() override
563 if (!m_buffer.IsEmpty())
564 m_recv(m_buffer);
565 m_buffer.Empty(); // Just for sure
568 private:
569 GitReceiverFunc m_recv;
570 CStringA m_buffer;
573 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
575 CGitCallCb call(cmd, recv);
576 return Run(&call);
579 CString CGit::GetUserName(void)
581 CEnvironment env;
582 env.CopyProcessEnvironment();
583 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
584 if (!envname.IsEmpty())
585 return envname;
586 return GetConfigValue(L"user.name");
588 CString CGit::GetUserEmail(void)
590 CEnvironment env;
591 env.CopyProcessEnvironment();
592 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
593 if (!envmail.IsEmpty())
594 return envmail;
596 return GetConfigValue(L"user.email");
599 CString CGit::GetConfigValue(const CString& name)
601 CString configValue;
602 int start = 0;
603 if(this->m_IsUseGitDLL)
605 CAutoLocker lock(g_Git.m_critGitDllSec);
609 CheckAndInitDll();
610 }catch(...)
613 CStringA key, value;
614 key = CUnicodeUtils::GetUTF8(name);
618 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
619 return CString();
621 catch (const char *msg)
623 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
624 return CString();
627 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
628 return configValue.Tokenize(_T("\n"),start);
630 else
632 CString cmd;
633 cmd.Format(L"git.exe config %s", name);
634 Run(cmd, &configValue, nullptr, CP_UTF8);
635 return configValue.Tokenize(_T("\n"),start);
639 bool CGit::GetConfigValueBool(const CString& name)
641 CString configValue = GetConfigValue(name);
642 configValue.MakeLower();
643 configValue.Trim();
644 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
645 return true;
646 else
647 return false;
650 int CGit::GetConfigValueInt32(const CString& name, int def)
652 CString configValue = GetConfigValue(name);
653 int value = def;
654 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
655 return value;
656 return def;
659 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
661 if(this->m_IsUseGitDLL)
663 CAutoLocker lock(g_Git.m_critGitDllSec);
667 CheckAndInitDll();
669 }catch(...)
672 CStringA keya, valuea;
673 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
674 valuea = CUnicodeUtils::GetUTF8(value);
678 return [=]() { return get_set_config(keya, valuea, type); }();
680 catch (const char *msg)
682 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
683 return -1;
686 else
688 CString cmd;
689 CString option;
690 switch(type)
692 case CONFIG_GLOBAL:
693 option = _T("--global");
694 break;
695 case CONFIG_SYSTEM:
696 option = _T("--system");
697 break;
698 default:
699 break;
701 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
702 CString out;
703 if (Run(cmd, &out, nullptr, CP_UTF8))
705 return -1;
708 return 0;
711 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
713 if(this->m_IsUseGitDLL)
715 CAutoLocker lock(g_Git.m_critGitDllSec);
719 CheckAndInitDll();
720 }catch(...)
723 CStringA keya;
724 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
728 return [=]() { return get_set_config(keya, nullptr, type); }();
730 catch (const char *msg)
732 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
733 return -1;
736 else
738 CString cmd;
739 CString option;
740 switch(type)
742 case CONFIG_GLOBAL:
743 option = _T("--global");
744 break;
745 case CONFIG_SYSTEM:
746 option = _T("--system");
747 break;
748 default:
749 break;
751 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
752 CString out;
753 if (Run(cmd, &out, nullptr, CP_UTF8))
755 return -1;
758 return 0;
761 CString CGit::GetCurrentBranch(bool fallback)
763 CString output;
764 //Run(_T("git.exe branch"),&branch);
766 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
767 if (result != 0 && ((result == 1 && !fallback) || result != 1))
769 return _T("(no branch)");
771 else
772 return output;
776 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
778 if (localBranch.IsEmpty())
779 return;
781 CString configName;
782 configName.Format(L"branch.%s.remote", localBranch);
783 pullRemote = GetConfigValue(configName);
785 //Select pull-branch from current branch
786 configName.Format(L"branch.%s.merge", localBranch);
787 pullBranch = StripRefName(GetConfigValue(configName));
790 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
792 CString refName;
793 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
794 return;
795 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
798 CString CGit::GetFullRefName(const CString& shortRefName)
800 CString refName;
801 CString cmd;
802 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
803 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
804 return CString();//Error
805 int iStart = 0;
806 return refName.Tokenize(L"\n", iStart);
809 CString CGit::StripRefName(CString refName)
811 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
812 refName = refName.Mid(11);
813 else if(wcsncmp(refName, L"refs/", 5) == 0)
814 refName = refName.Mid(5);
815 int start =0;
816 return refName.Tokenize(_T("\n"),start);
819 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
821 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
823 if ( sProjectRoot.IsEmpty() )
824 return -1;
826 CString sDotGitPath;
827 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
828 return -1;
830 CString sHeadFile = sDotGitPath + _T("HEAD");
832 FILE *pFile;
833 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
835 if (!pFile)
837 return -1;
840 char s[256] = {0};
841 fgets(s, sizeof(s), pFile);
843 fclose(pFile);
845 const char *pfx = "ref: refs/heads/";
846 const int len = 16;//strlen(pfx)
848 if ( !strncmp(s, pfx, len) )
850 //# We're on a branch. It might not exist. But
851 //# HEAD looks good enough to be a branch.
852 CStringA utf8Branch(s + len);
853 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
854 sBranchOut.TrimRight(_T(" \r\n\t"));
856 if ( sBranchOut.IsEmpty() )
857 return -1;
859 else if (fallback)
861 CStringA utf8Hash(s);
862 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
863 unicodeHash.TrimRight(_T(" \r\n\t"));
864 if (CGitHash::IsValidSHA1(unicodeHash))
865 sBranchOut = unicodeHash;
866 else
867 //# Assume this is a detached head.
868 sBranchOut = _T("HEAD");
869 return 1;
871 else
873 //# Assume this is a detached head.
874 sBranchOut = "HEAD";
876 return 1;
879 return 0;
882 int CGit::BuildOutputFormat(CString &format,bool IsFull)
884 CString log;
885 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
886 format += log;
887 if(IsFull)
889 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
890 format += log;
891 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
892 format += log;
893 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
894 format += log;
895 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
896 format += log;
897 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
898 format += log;
899 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
900 format += log;
901 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
902 format += log;
905 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
906 format += log;
907 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
908 format += log;
909 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
910 format += log;
912 if(IsFull)
914 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
915 format += log;
917 return 0;
920 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
921 CFilterData *Filter)
923 CString cmd;
924 CString num;
925 CString since;
927 CString file = _T(" --");
929 if(path)
930 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
932 if(count>0)
933 num.Format(_T("-n%d"),count);
935 CString param;
937 if(mask& LOG_INFO_STAT )
938 param += _T(" --numstat ");
939 if(mask& LOG_INFO_FILESTATE)
940 param += _T(" --raw ");
942 if(mask& LOG_INFO_FULLHISTORY)
943 param += _T(" --full-history ");
945 if(mask& LOG_INFO_BOUNDARY)
946 param += _T(" --left-right --boundary ");
948 if(mask& CGit::LOG_INFO_ALL_BRANCH)
949 param += _T(" --all ");
951 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
952 param += _T(" --branches ");
954 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
955 param += _T(" -C ");
957 if(mask& CGit::LOG_INFO_DETECT_RENAME )
958 param += _T(" -M ");
960 if(mask& CGit::LOG_INFO_FIRST_PARENT )
961 param += _T(" --first-parent ");
963 if(mask& CGit::LOG_INFO_NO_MERGE )
964 param += _T(" --no-merges ");
966 if(mask& CGit::LOG_INFO_FOLLOW)
967 param += _T(" --follow ");
969 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
970 param += _T(" -c ");
972 if(mask& CGit::LOG_INFO_FULL_DIFF)
973 param += _T(" --full-diff ");
975 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
976 param += _T(" --simplify-by-decoration ");
978 param += range;
980 CString st1,st2;
982 if( Filter && (Filter->m_From != -1))
984 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
985 param += st1;
988 if( Filter && (Filter->m_To != -1))
990 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
991 param += st2;
994 bool isgrep = false;
995 if( Filter && (!Filter->m_Author.IsEmpty()))
997 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
998 param += st1;
999 isgrep = true;
1002 if( Filter && (!Filter->m_Committer.IsEmpty()))
1004 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1005 param += st1;
1006 isgrep = true;
1009 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1011 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1012 param += st1;
1013 isgrep = true;
1016 if(Filter && isgrep)
1018 if(!Filter->m_IsRegex)
1019 param += _T(" --fixed-strings ");
1021 param += _T(" --regexp-ignore-case --extended-regexp ");
1024 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1025 if (logOrderBy == LOG_ORDER_TOPOORDER)
1026 param += _T(" --topo-order");
1027 else if (logOrderBy == LOG_ORDER_DATEORDER)
1028 param += _T(" --date-order");
1030 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
1031 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1032 else
1034 CString log;
1035 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1036 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1037 num,param,log);
1040 cmd += file;
1042 return cmd;
1044 #define BUFSIZE 512
1045 void GetTempPath(CString &path)
1047 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1048 DWORD dwRetVal;
1049 DWORD dwBufSize=BUFSIZE;
1050 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1051 lpPathBuffer); // buffer for path
1052 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1054 path=_T("");
1056 path.Format(_T("%s"),lpPathBuffer);
1058 CString GetTempFile()
1060 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1061 DWORD dwRetVal;
1062 DWORD dwBufSize=BUFSIZE;
1063 TCHAR szTempName[BUFSIZE] = { 0 };
1064 UINT uRetVal;
1066 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1067 lpPathBuffer); // buffer for path
1068 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1070 return _T("");
1072 // Create a temporary file.
1073 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1074 TEXT("Patch"), // temp file name prefix
1075 0, // create unique name
1076 szTempName); // buffer for name
1079 if (uRetVal == 0)
1081 return _T("");
1084 return CString(szTempName);
1088 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1090 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1091 if (result == 0) return 0;
1092 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1094 if (lpBuffer)
1095 lpBuffer[0] = '\0';
1096 return result + 13;
1099 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1100 CreateDirectory(lpBuffer, NULL);
1102 return result + 13;
1105 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1107 STARTUPINFO si;
1108 PROCESS_INFORMATION pi;
1109 si.cb=sizeof(STARTUPINFO);
1110 GetStartupInfo(&si);
1112 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1113 psa.bInheritHandle=TRUE;
1115 HANDLE hReadErr, hWriteErr;
1116 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1118 CString err = CFormatMessageWrapper();
1119 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1120 return TGIT_GIT_ERROR_OPEN_PIP;
1123 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1124 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1126 if (houtfile == INVALID_HANDLE_VALUE)
1128 CString err = CFormatMessageWrapper();
1129 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1130 CloseHandle(hReadErr);
1131 CloseHandle(hWriteErr);
1132 return TGIT_GIT_ERROR_OPEN_PIP;
1135 si.wShowWindow = SW_HIDE;
1136 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1137 si.hStdOutput = houtfile;
1138 si.hStdError = hWriteErr;
1140 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1141 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1143 if(cmd.Find(_T("git")) == 0)
1144 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1146 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1147 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1149 CString err = CFormatMessageWrapper();
1150 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1151 stdErr = &err;
1152 CloseHandle(hReadErr);
1153 CloseHandle(hWriteErr);
1154 CloseHandle(houtfile);
1155 return TGIT_GIT_ERROR_CREATE_PROCESS;
1158 BYTE_VECTOR stderrVector;
1159 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1160 HANDLE thread;
1161 ASYNCREADSTDERRTHREADARGS threadArguments;
1162 threadArguments.fileHandle = hReadErr;
1163 threadArguments.pcall = &pcall;
1164 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1166 WaitForSingleObject(pi.hProcess,INFINITE);
1168 CloseHandle(hWriteErr);
1169 CloseHandle(hReadErr);
1171 if (thread)
1172 WaitForSingleObject(thread, INFINITE);
1174 stderrVector.push_back(0);
1175 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1177 DWORD exitcode = 0;
1178 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1180 CString err = CFormatMessageWrapper();
1181 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1182 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1184 else
1185 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1187 CloseHandle(pi.hThread);
1188 CloseHandle(pi.hProcess);
1189 CloseHandle(houtfile);
1190 return exitcode;
1193 git_repository * CGit::GetGitRepository() const
1195 git_repository * repo = nullptr;
1196 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1197 return repo;
1200 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1202 ATLASSERT(repo);
1204 // no need to parse a ref if it's already a 40-byte hash
1205 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1207 hash = CGitHash(friendname);
1208 return 0;
1211 int isHeadOrphan = git_repository_head_unborn(repo);
1212 if (isHeadOrphan != 0)
1214 hash.Empty();
1215 if (isHeadOrphan == 1)
1216 return 0;
1217 else
1218 return -1;
1221 CAutoObject gitObject;
1222 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1223 return -1;
1225 const git_oid * oid = git_object_id(gitObject);
1226 if (!oid)
1227 return -1;
1229 hash = CGitHash((char *)oid->id);
1231 return 0;
1234 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1236 // no need to parse a ref if it's already a 40-byte hash
1237 if (CGitHash::IsValidSHA1(friendname))
1239 hash = CGitHash(friendname);
1240 return 0;
1243 if (m_IsUseLibGit2)
1245 CAutoRepository repo(GetGitRepository());
1246 if (!repo)
1247 return -1;
1249 return GetHash(repo, hash, friendname, true);
1251 else
1253 CString cmd;
1254 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1255 gitLastErr.Empty();
1256 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1257 hash = CGitHash(gitLastErr.Trim());
1258 if (ret == 0)
1259 gitLastErr.Empty();
1260 return ret;
1264 int CGit::GetInitAddList(CTGitPathList &outputlist)
1266 CString cmd;
1267 BYTE_VECTOR cmdout;
1269 cmd=_T("git.exe ls-files -s -t -z");
1270 outputlist.Clear();
1271 if (Run(cmd, &cmdout))
1272 return -1;
1274 if (outputlist.ParserFromLsFile(cmdout))
1275 return -1;
1276 for(int i = 0; i < outputlist.GetCount(); ++i)
1277 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1279 return 0;
1281 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1283 CString cmd;
1284 CString ignore;
1285 if (ignoreSpaceAtEol)
1286 ignore += _T(" --ignore-space-at-eol");
1287 if (ignoreSpaceChange)
1288 ignore += _T(" --ignore-space-change");
1289 if (ignoreAllSpace)
1290 ignore += _T(" --ignore-all-space");
1291 if (ignoreBlankLines)
1292 ignore += _T(" --ignore-blank-lines");
1294 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1296 //rev1=+_T("");
1297 if(rev1 == GIT_REV_ZERO)
1298 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1299 else
1300 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1302 else
1304 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1307 BYTE_VECTOR out;
1308 if (Run(cmd, &out))
1309 return -1;
1311 outputlist.ParserFromLog(out);
1313 return 0;
1316 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1318 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1319 CString str;
1320 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1321 list->push_back(str);
1322 return 0;
1325 int CGit::GetTagList(STRING_VECTOR &list)
1327 if (this->m_IsUseLibGit2)
1329 CAutoRepository repo(GetGitRepository());
1330 if (!repo)
1331 return -1;
1333 CAutoStrArray tag_names;
1335 if (git_tag_list(tag_names, repo))
1336 return -1;
1338 for (size_t i = 0; i < tag_names->count; ++i)
1340 CStringA tagName(tag_names->strings[i]);
1341 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1344 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1346 return 0;
1348 else
1350 CString cmd, output;
1351 cmd=_T("git.exe tag -l");
1352 int ret = Run(cmd, &output, NULL, CP_UTF8);
1353 if(!ret)
1355 int pos=0;
1356 CString one;
1357 while( pos>=0 )
1359 one=output.Tokenize(_T("\n"),pos);
1360 if (!one.IsEmpty())
1361 list.push_back(one);
1363 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1365 return ret;
1369 CString CGit::GetGitLastErr(const CString& msg)
1371 if (this->m_IsUseLibGit2)
1372 return GetLibGit2LastErr(msg);
1373 else if (gitLastErr.IsEmpty())
1374 return msg + _T("\nUnknown git.exe error.");
1375 else
1377 CString lastError = gitLastErr;
1378 gitLastErr.Empty();
1379 return msg + _T("\n") + lastError;
1383 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1385 if (UsingLibGit2(cmd))
1386 return GetLibGit2LastErr(msg);
1387 else if (gitLastErr.IsEmpty())
1388 return msg + _T("\nUnknown git.exe error.");
1389 else
1391 CString lastError = gitLastErr;
1392 gitLastErr.Empty();
1393 return msg + _T("\n") + lastError;
1397 CString CGit::GetLibGit2LastErr()
1399 const git_error *libgit2err = giterr_last();
1400 if (libgit2err)
1402 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1403 giterr_clear();
1404 return _T("libgit2 returned: ") + lastError;
1406 else
1407 return _T("An error occoured in libgit2, but no message is available.");
1410 CString CGit::GetLibGit2LastErr(const CString& msg)
1412 if (!msg.IsEmpty())
1413 return msg + _T("\n") + GetLibGit2LastErr();
1414 return GetLibGit2LastErr();
1417 CString CGit::FixBranchName_Mod(CString& branchName)
1419 if(branchName == "FETCH_HEAD")
1420 branchName = DerefFetchHead();
1421 return branchName;
1424 CString CGit::FixBranchName(const CString& branchName)
1426 CString tempBranchName = branchName;
1427 FixBranchName_Mod(tempBranchName);
1428 return tempBranchName;
1431 bool CGit::IsBranchTagNameUnique(const CString& name)
1433 if (m_IsUseLibGit2)
1435 CAutoRepository repo(GetGitRepository());
1436 if (!repo)
1437 return true; // TODO: optimize error reporting
1439 CAutoReference tagRef;
1440 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1441 return true;
1443 CAutoReference branchRef;
1444 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1445 return true;
1447 return false;
1449 // else
1450 CString output;
1452 CString cmd;
1453 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1454 int ret = Run(cmd, &output, NULL, CP_UTF8);
1455 if (!ret)
1457 int i = 0, pos = 0;
1458 while (pos >= 0)
1460 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1461 ++i;
1463 if (i >= 2)
1464 return false;
1467 return true;
1470 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1472 if (m_IsUseLibGit2)
1474 CAutoRepository repo(GetGitRepository());
1475 if (!repo)
1476 return false; // TODO: optimize error reporting
1478 CString prefix;
1479 if (isBranch)
1480 prefix = _T("refs/heads/");
1481 else
1482 prefix = _T("refs/tags/");
1484 CAutoReference ref;
1485 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1486 return false;
1488 return true;
1490 // else
1491 CString cmd, output;
1493 cmd = _T("git.exe show-ref ");
1494 if (isBranch)
1495 cmd += _T("--heads ");
1496 else
1497 cmd += _T("--tags ");
1499 cmd += _T("refs/heads/") + name;
1500 cmd += _T(" refs/tags/") + name;
1502 int ret = Run(cmd, &output, NULL, CP_UTF8);
1503 if (!ret)
1505 if (!output.IsEmpty())
1506 return true;
1509 return false;
1512 CString CGit::DerefFetchHead()
1514 CString dotGitPath;
1515 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1516 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1517 int forMergeLineCount = 0;
1518 std::string line;
1519 std::string hashToReturn;
1520 while(getline(fetchHeadFile, line))
1522 //Tokenize this line
1523 std::string::size_type prevPos = 0;
1524 std::string::size_type pos = line.find('\t');
1525 if(pos == std::string::npos) continue; //invalid line
1527 std::string hash = line.substr(0, pos);
1528 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1530 bool forMerge = pos == prevPos;
1531 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1533 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1535 //Process this line
1536 if(forMerge)
1538 hashToReturn = hash;
1539 ++forMergeLineCount;
1540 if(forMergeLineCount > 1)
1541 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1545 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1548 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1550 int ret = 0;
1551 CString cur;
1552 if (m_IsUseLibGit2)
1554 CAutoRepository repo(GetGitRepository());
1555 if (!repo)
1556 return -1;
1558 if (git_repository_head_detached(repo) == 1)
1559 cur = _T("(detached from ");
1561 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1563 git_branch_t flags = GIT_BRANCH_LOCAL;
1564 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1565 flags = GIT_BRANCH_ALL;
1566 else if (type & BRANCH_REMOTE)
1567 flags = GIT_BRANCH_REMOTE;
1569 CAutoBranchIterator it;
1570 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1571 return -1;
1573 git_reference * ref = nullptr;
1574 git_branch_t branchType;
1575 while (git_branch_next(&ref, &branchType, it) == 0)
1577 CAutoReference autoRef(ref);
1578 const char * name = nullptr;
1579 if (git_branch_name(&name, ref))
1580 continue;
1582 CString branchname = CUnicodeUtils::GetUnicode(name);
1583 if (branchType & GIT_BRANCH_REMOTE)
1584 list.push_back(_T("remotes/") + branchname);
1585 else
1587 if (git_branch_is_head(ref))
1588 cur = branchname;
1589 list.push_back(branchname);
1594 else
1596 CString cmd, output;
1597 cmd = _T("git.exe branch --no-color");
1599 if ((type & BRANCH_ALL) == BRANCH_ALL)
1600 cmd += _T(" -a");
1601 else if (type & BRANCH_REMOTE)
1602 cmd += _T(" -r");
1604 ret = Run(cmd, &output, nullptr, CP_UTF8);
1605 if (!ret)
1607 int pos = 0;
1608 CString one;
1609 while (pos >= 0)
1611 one = output.Tokenize(_T("\n"), pos);
1612 one.Trim(L" \r\n\t");
1613 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1614 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1615 if (one[0] == _T('*'))
1617 one = one.Mid(2);
1618 cur = one;
1620 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1621 list.push_back(one);
1626 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1627 list.push_back(L"FETCH_HEAD");
1629 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1631 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1633 for (unsigned int i = 0; i < list.size(); ++i)
1635 if (list[i] == cur)
1637 *current = i;
1638 break;
1643 return ret;
1646 int CGit::GetRemoteList(STRING_VECTOR &list)
1648 if (this->m_IsUseLibGit2)
1650 CAutoRepository repo(GetGitRepository());
1651 if (!repo)
1652 return -1;
1654 CAutoStrArray remotes;
1655 if (git_remote_list(remotes, repo))
1656 return -1;
1658 for (size_t i = 0; i < remotes->count; ++i)
1660 CStringA remote(remotes->strings[i]);
1661 list.push_back(CUnicodeUtils::GetUnicode(remote));
1664 std::sort(list.begin(), list.end());
1666 return 0;
1668 else
1670 int ret;
1671 CString cmd, output;
1672 cmd=_T("git.exe remote");
1673 ret = Run(cmd, &output, NULL, CP_UTF8);
1674 if(!ret)
1676 int pos=0;
1677 CString one;
1678 while( pos>=0 )
1680 one=output.Tokenize(_T("\n"),pos);
1681 if (!one.IsEmpty())
1682 list.push_back(one);
1685 return ret;
1689 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1691 if (UsingLibGit2(GIT_CMD_FETCH))
1693 CAutoRepository repo(GetGitRepository());
1694 if (!repo)
1695 return -1;
1697 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1698 CAutoRemote remote;
1699 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1700 return -1;
1702 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1703 callbacks.credentials = g_Git2CredCallback;
1704 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1705 git_remote_set_callbacks(remote, &callbacks);
1706 if (git_remote_connect(remote, GIT_DIRECTION_FETCH) < 0)
1707 return -1;
1709 const git_remote_head** heads = nullptr;
1710 size_t size = 0;
1711 if (git_remote_ls(&heads, &size, remote) < 0)
1712 return -1;
1714 for (int i = 0; i < size; i++)
1716 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1717 CString shortname;
1718 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1719 continue;
1720 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1721 if (shortname.Find(_T("^{}")) >= 1)
1722 continue;
1723 list.push_back(shortname);
1725 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1726 return 0;
1729 CString cmd, out, err;
1730 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1731 if (Run(cmd, &out, &err, CP_UTF8))
1733 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1734 return -1;
1737 int pos = 0;
1738 while (pos >= 0)
1740 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1741 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1742 if (one.Find(_T("^{}")) >= 1)
1743 continue;
1744 if (!one.IsEmpty())
1745 list.push_back(one);
1747 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1748 return 0;
1751 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1753 if (UsingLibGit2(GIT_CMD_PUSH))
1755 CAutoRepository repo(GetGitRepository());
1756 if (!repo)
1757 return -1;
1759 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1760 CAutoRemote remote;
1761 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1762 return -1;
1764 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1765 callbacks.credentials = g_Git2CredCallback;
1766 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1767 git_remote_set_callbacks(remote, &callbacks);
1768 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1769 return -1;
1771 std::vector<CStringA> refspecs;
1772 for (auto ref : list)
1773 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1775 std::vector<char*> vc;
1776 vc.reserve(refspecs.size());
1777 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1778 git_strarray specs = { &vc[0], vc.size() };
1780 if (git_remote_push(remote, &specs, nullptr, nullptr, nullptr) < 0)
1781 return -1;
1783 else
1785 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1786 for (auto ref : list)
1788 CString refspec = _T(":") + ref;
1789 mgtPush.AddFile(refspec);
1792 BOOL cancel = FALSE;
1793 mgtPush.Execute(cancel);
1796 return 0;
1799 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1801 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1802 CString str;
1803 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1804 list->push_back(str);
1805 return 0;
1808 int CGit::GetRefList(STRING_VECTOR &list)
1810 if (this->m_IsUseLibGit2)
1812 CAutoRepository repo(GetGitRepository());
1813 if (!repo)
1814 return -1;
1816 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1817 return -1;
1819 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1821 return 0;
1823 else
1825 CString cmd, output;
1826 cmd=_T("git.exe show-ref -d");
1827 int ret = Run(cmd, &output, NULL, CP_UTF8);
1828 if(!ret)
1830 int pos=0;
1831 CString one;
1832 while( pos>=0 )
1834 one=output.Tokenize(_T("\n"),pos);
1835 int start=one.Find(_T(" "),0);
1836 if(start>0)
1838 CString name;
1839 name=one.Right(one.GetLength()-start-1);
1840 list.push_back(name);
1843 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1845 return ret;
1849 typedef struct map_each_ref_payload {
1850 git_repository * repo;
1851 MAP_HASH_NAME * map;
1852 } map_each_ref_payload;
1854 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1856 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1858 CString str;
1859 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1861 CAutoObject gitObject;
1862 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1863 return 1;
1865 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1867 str += _T("^{}"); // deref tag
1868 CAutoObject derefedTag;
1869 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1870 return 1;
1871 gitObject.Swap(derefedTag);
1874 const git_oid * oid = git_object_id(gitObject);
1875 if (oid == NULL)
1876 return 1;
1878 CGitHash hash((char *)oid->id);
1879 (*payloadContent->map)[hash].push_back(str);
1881 return 0;
1883 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1885 ATLASSERT(repo);
1887 map_each_ref_payload payloadContent = { repo, &map };
1889 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1890 return -1;
1892 for (auto it = map.begin(); it != map.end(); ++it)
1894 std::sort(it->second.begin(), it->second.end());
1897 return 0;
1900 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1902 if (this->m_IsUseLibGit2)
1904 CAutoRepository repo(GetGitRepository());
1905 if (!repo)
1906 return -1;
1908 return GetMapHashToFriendName(repo, map);
1910 else
1912 CString cmd, output;
1913 cmd=_T("git.exe show-ref -d");
1914 int ret = Run(cmd, &output, NULL, CP_UTF8);
1915 if(!ret)
1917 int pos=0;
1918 CString one;
1919 while( pos>=0 )
1921 one=output.Tokenize(_T("\n"),pos);
1922 int start=one.Find(_T(" "),0);
1923 if(start>0)
1925 CString name;
1926 name=one.Right(one.GetLength()-start-1);
1928 CString hash;
1929 hash=one.Left(start);
1931 map[CGitHash(hash)].push_back(name);
1935 return ret;
1939 static void SetLibGit2SearchPath(int level, const CString &value)
1941 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1942 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1945 static void SetLibGit2TemplatePath(const CString &value)
1947 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1948 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1951 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1953 if (m_bInitialized)
1955 return TRUE;
1958 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
1959 this->m_Environment.clear();
1960 m_Environment.CopyProcessEnvironment();
1961 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
1963 TCHAR *oldpath;
1964 size_t homesize,size;
1966 // set HOME if not set already
1967 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1968 if (!homesize)
1969 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1971 //setup ssh client
1972 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1973 if (sshclient.IsEmpty())
1974 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1976 if(!sshclient.IsEmpty())
1978 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1979 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1981 else
1983 TCHAR sPlink[MAX_PATH] = {0};
1984 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1985 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1986 if (ptr) {
1987 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1988 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1989 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1994 TCHAR sAskPass[MAX_PATH] = {0};
1995 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1996 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1997 if (ptr)
1999 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2000 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2001 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2002 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2006 // add git/bin path to PATH
2008 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
2009 CString str = msysdir;
2010 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
2012 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2013 if (!bFallback)
2014 return FALSE;
2016 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2017 str = msyslocalinstalldir;
2018 str.TrimRight(_T("\\"));
2019 if (str.IsEmpty())
2021 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2022 str = msysinstalldir;
2023 str.TrimRight(_T("\\"));
2025 if ( !str.IsEmpty() )
2027 str += "\\bin";
2028 msysdir=str;
2029 CGit::ms_LastMsysGitDir = str;
2030 msysdir.write();
2032 else
2034 // search PATH if git/bin directory is already present
2035 if ( FindGitPath() )
2037 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2038 m_bInitialized = TRUE;
2039 msysdir = CGit::ms_LastMsysGitDir;
2040 msysdir.write();
2041 return TRUE;
2044 return FALSE;
2047 else
2049 CGit::ms_LastMsysGitDir = str;
2052 // check for git.exe existance (maybe it was deinstalled in the meantime)
2053 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
2055 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2056 return FALSE;
2059 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2060 // Configure libgit2 search paths
2061 CString msysGitDir;
2062 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
2063 msysGitDir.ReleaseBuffer();
2064 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
2065 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2066 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2067 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]); }, 0 };
2068 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2069 CString msysGitTemplateDir;
2070 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
2071 msysGitTemplateDir.ReleaseBuffer();
2072 SetLibGit2TemplatePath(msysGitTemplateDir);
2074 //set path
2075 _tdupenv_s(&oldpath,&size,_T("PATH"));
2077 CString path;
2078 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
2080 m_Environment.SetEnv(_T("PATH"), path);
2082 CString str1 = m_Environment.GetEnv(_T("PATH"));
2084 CString sOldPath = oldpath;
2085 free(oldpath);
2087 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2088 // register filter only once
2089 if (!git_filter_lookup("filter"))
2091 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir + L"\\sh.exe\"", &m_Environment[0]), GIT_FILTER_DRIVER_PRIORITY))
2092 return FALSE;
2094 #endif
2096 m_bInitialized = TRUE;
2097 return true;
2100 CString CGit::GetHomeDirectory() const
2102 const wchar_t * homeDir = wget_windows_home_directory();
2103 return CString(homeDir, (int)wcslen(homeDir));
2106 CString CGit::GetGitLocalConfig() const
2108 CString path;
2109 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
2110 path += _T("config");
2111 return path;
2114 CStringA CGit::GetGitPathStringA(const CString &path)
2116 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2119 CString CGit::GetGitGlobalConfig() const
2121 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2124 CString CGit::GetGitGlobalXDGConfigPath() const
2126 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2129 CString CGit::GetGitGlobalXDGConfig() const
2131 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2134 CString CGit::GetGitSystemConfig() const
2136 const wchar_t * systemConfig = wget_msysgit_etc();
2137 return CString(systemConfig, (int)wcslen(systemConfig));
2140 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2142 CString out;
2143 CString cmd;
2144 cmd=_T("git.exe rev-parse --verify HEAD");
2146 if(Run(cmd,&out,CP_UTF8))
2147 return FALSE;
2149 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2150 if(Run(cmd,&out,CP_UTF8))
2151 return FALSE;
2153 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2154 if(Run(cmd,&out,CP_UTF8))
2155 return FALSE;
2157 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2158 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2159 return FALSE;
2161 return TRUE;
2163 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2165 int ret;
2166 for (int i = 0; i < list.GetCount(); ++i)
2168 ret = Revert(commit, (CTGitPath&)list[i], err);
2169 if(ret)
2170 return ret;
2172 return 0;
2174 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2176 CString cmd;
2178 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2180 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2182 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2183 return -1;
2185 CString force;
2186 // if the filenames only differ in case, we have to pass "-f"
2187 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2188 force = _T("-f ");
2189 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2190 if (Run(cmd, &err, CP_UTF8))
2191 return -1;
2193 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2194 if (Run(cmd, &err, CP_UTF8))
2195 return -1;
2197 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2198 { //To init git repository, there are not HEAD, so we can use git reset command
2199 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2201 if (Run(cmd, &err, CP_UTF8))
2202 return -1;
2204 else
2206 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2207 if (Run(cmd, &err, CP_UTF8))
2208 return -1;
2211 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2213 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2214 if (Run(cmd, &err, CP_UTF8))
2215 return -1;
2218 return 0;
2221 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2223 BYTE_VECTOR vector;
2225 CString cmd;
2226 if(path)
2227 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2228 else
2229 cmd=_T("git.exe ls-files -u -t -z");
2231 if (Run(cmd, &vector))
2233 return -1;
2236 if (list.ParserFromLsFile(vector))
2237 return -1;
2239 return 0;
2242 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2244 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2246 CAutoRepository repo(GetGitRepository());
2247 if (!repo)
2248 return false;
2250 CGitHash fromHash, toHash, baseHash;
2251 if (GetHash(repo, toHash, FixBranchName(to)))
2252 return false;
2254 if (GetHash(repo, fromHash, FixBranchName(from)))
2255 return false;
2257 git_oid baseOid;
2258 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2259 return false;
2261 baseHash = baseOid.id;
2263 if (commonAncestor)
2264 *commonAncestor = baseHash;
2266 return fromHash == baseHash;
2268 // else
2269 CString base;
2270 CGitHash basehash,hash;
2271 CString cmd, err;
2272 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2274 if (Run(cmd, &base, &err, CP_UTF8))
2276 return false;
2278 basehash = base.Trim();
2280 GetHash(hash, from);
2282 if (commonAncestor)
2283 *commonAncestor = basehash;
2285 return hash == basehash;
2288 unsigned int CGit::Hash2int(const CGitHash &hash)
2290 int ret=0;
2291 for (int i = 0; i < 4; ++i)
2293 ret = ret << 8;
2294 ret |= hash.m_hash[i];
2296 return ret;
2299 int CGit::RefreshGitIndex()
2301 if(g_Git.m_IsUseGitDLL)
2303 CAutoLocker lock(g_Git.m_critGitDllSec);
2306 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2308 }catch(...)
2310 return -1;
2314 else
2316 CString cmd,output;
2317 cmd=_T("git.exe update-index --refresh");
2318 return Run(cmd, &output, CP_UTF8);
2322 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2324 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2326 CAutoRepository repo(GetGitRepository());
2327 if (!repo)
2328 return -1;
2330 CGitHash hash;
2331 if (GetHash(repo, hash, Refname))
2332 return -1;
2334 CAutoCommit commit;
2335 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2336 return -1;
2338 CAutoTree tree;
2339 if (git_commit_tree(tree.GetPointer(), commit))
2340 return -1;
2342 CAutoTreeEntry entry;
2343 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2344 return -1;
2346 CAutoBlob blob;
2347 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2348 return -1;
2350 FILE *file = nullptr;
2351 _tfopen_s(&file, outputfile, _T("w"));
2352 if (file == nullptr)
2354 giterr_set_str(GITERR_NONE, "Could not create file.");
2355 return -1;
2357 CAutoBuf buf;
2358 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2360 fclose(file);
2361 return -1;
2363 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2365 giterr_set_str(GITERR_OS, "Could not write to file.");
2366 fclose(file);
2368 return -1;
2370 fclose(file);
2372 return 0;
2374 else if (g_Git.m_IsUseGitDLL)
2376 CAutoLocker lock(g_Git.m_critGitDllSec);
2379 g_Git.CheckAndInitDll();
2380 CStringA ref, patha, outa;
2381 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2382 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2383 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2384 ::DeleteFile(outputfile);
2385 return git_checkout_file(ref, patha, outa);
2388 catch (const char * msg)
2390 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2391 return -1;
2393 catch (...)
2395 gitLastErr = L"An unknown gitdll.dll error occurred.";
2396 return -1;
2399 else
2401 CString cmd;
2402 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2403 return RunLogFile(cmd, outputfile, &gitLastErr);
2406 void CEnvironment::CopyProcessEnvironment()
2408 TCHAR *porig = GetEnvironmentStrings();
2409 TCHAR *p = porig;
2410 while(*p !=0 || *(p+1) !=0)
2411 this->push_back(*p++);
2413 push_back(_T('\0'));
2414 push_back(_T('\0'));
2416 FreeEnvironmentStrings(porig);
2419 CString CEnvironment::GetEnv(const TCHAR *name)
2421 CString str;
2422 for (size_t i = 0; i < size(); ++i)
2424 str = &(*this)[i];
2425 int start =0;
2426 CString sname = str.Tokenize(_T("="),start);
2427 if(sname.CompareNoCase(name) == 0)
2429 return &(*this)[i+start];
2431 i+=str.GetLength();
2433 return _T("");
2436 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2438 unsigned int i;
2439 for (i = 0; i < size(); ++i)
2441 CString str = &(*this)[i];
2442 int start =0;
2443 CString sname = str.Tokenize(_T("="),start);
2444 if(sname.CompareNoCase(name) == 0)
2446 break;
2448 i+=str.GetLength();
2451 if(i == size())
2453 if (!value) // as we haven't found the variable we want to remove, just return
2454 return;
2455 i -= 1; // roll back terminate \0\0
2456 this->push_back(_T('\0'));
2459 CEnvironment::iterator it;
2460 it=this->begin();
2461 it += i;
2463 while(*it && i<size())
2465 this->erase(it);
2466 it=this->begin();
2467 it += i;
2470 if (value == nullptr) // remove the variable
2472 this->erase(it);
2473 return;
2476 while(*name)
2478 this->insert(it,*name++);
2479 ++i;
2480 it= begin()+i;
2483 this->insert(it, _T('='));
2484 ++i;
2485 it= begin()+i;
2487 while(*value)
2489 this->insert(it,*value++);
2490 ++i;
2491 it= begin()+i;
2496 int CGit::GetGitEncode(TCHAR* configkey)
2498 CString str=GetConfigValue(configkey);
2500 if(str.IsEmpty())
2501 return CP_UTF8;
2503 return CUnicodeUtils::GetCPCode(str);
2507 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2509 GIT_FILE file=0;
2510 int ret=0;
2511 GIT_DIFF diff=0;
2513 CAutoLocker lock(g_Git.m_critGitDllSec);
2517 if(!arg)
2518 diff = GetGitDiff();
2519 else
2520 git_open_diff(&diff, arg);
2522 catch (char* e)
2524 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2525 return -1;
2528 if(diff ==NULL)
2529 return -1;
2531 bool isStat = 0;
2532 if(arg == NULL)
2533 isStat = true;
2534 else
2535 isStat = !!strstr(arg, "stat");
2537 int count=0;
2539 if(hash2 == NULL)
2540 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2541 else
2542 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2544 if(ret)
2545 return -1;
2547 CTGitPath path;
2548 CString strnewname;
2549 CString stroldname;
2551 for (int j = 0; j < count; ++j)
2553 path.Reset();
2554 char *newname;
2555 char *oldname;
2557 strnewname.Empty();
2558 stroldname.Empty();
2560 int mode=0,IsBin=0,inc=0,dec=0;
2561 git_get_diff_file(diff,file,j,&newname,&oldname,
2562 &mode,&IsBin,&inc,&dec);
2564 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2565 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2567 path.SetFromGit(strnewname,&stroldname);
2568 path.ParserAction((BYTE)mode);
2570 if(IsBin)
2572 path.m_StatAdd=_T("-");
2573 path.m_StatDel=_T("-");
2575 else
2577 path.m_StatAdd.Format(_T("%d"),inc);
2578 path.m_StatDel.Format(_T("%d"),dec);
2580 PathList->AddPath(path);
2582 git_diff_flush(diff);
2584 if(arg)
2585 git_close_diff(diff);
2587 return 0;
2590 int CGit::GetShortHASHLength() const
2592 return 7;
2595 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2597 CString str=ref;
2598 CString shortname;
2599 REF_TYPE type = CGit::UNKNOWN;
2601 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2603 type = CGit::LOCAL_BRANCH;
2606 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2608 type = CGit::REMOTE_BRANCH;
2610 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2612 type = CGit::TAG;
2614 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2616 type = CGit::STASH;
2617 shortname=_T("stash");
2619 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2621 if (shortname.Find(_T("good")) == 0)
2623 type = CGit::BISECT_GOOD;
2624 shortname = _T("good");
2627 if (shortname.Find(_T("bad")) == 0)
2629 type = CGit::BISECT_BAD;
2630 shortname = _T("bad");
2633 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2635 type = CGit::NOTES;
2637 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2639 type = CGit::UNKNOWN;
2641 else
2643 type = CGit::UNKNOWN;
2644 shortname = ref;
2647 if(out_type)
2648 *out_type = type;
2650 return shortname;
2653 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2655 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2658 void CGit::SetGit2CredentialCallback(void* callback)
2660 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2663 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2665 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2668 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2670 CString cmd;
2671 if (rev2 == GitRev::GetWorkingCopy())
2672 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2673 else if (rev1 == GitRev::GetWorkingCopy())
2674 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2675 else
2677 CString merge;
2678 if (bMerge)
2679 merge += _T(" -m");
2681 if (bCombine)
2682 merge += _T(" -c");
2684 CString unified;
2685 if (diffContext >= 0)
2686 unified.Format(_T(" --unified=%d"), diffContext);
2687 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2690 if (!path.IsEmpty())
2692 cmd += _T(" \"");
2693 cmd += path.GetGitPathString();
2694 cmd += _T("\"");
2697 return cmd;
2700 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2702 ATLASSERT(payload && text);
2703 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2704 fwrite("\n", 1, 1, (FILE *)payload);
2707 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2709 ATLASSERT(payload && line);
2710 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2711 fwrite(&line->origin, 1, 1, (FILE *)payload);
2712 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2713 return 0;
2716 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2718 ATLASSERT(repo && identifier && tree);
2720 /* try to resolve identifier */
2721 CAutoObject obj;
2722 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2723 return -1;
2725 if (obj == nullptr)
2726 return GIT_ENOTFOUND;
2728 int err = 0;
2729 switch (git_object_type(obj))
2731 case GIT_OBJ_TREE:
2732 *tree = (git_tree *)obj.Detach();
2733 break;
2734 case GIT_OBJ_COMMIT:
2735 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2736 break;
2737 default:
2738 err = GIT_ENOTFOUND;
2741 return err;
2744 /* use libgit2 get unified diff */
2745 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 */)
2747 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2748 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2750 CAutoRepository repo(g_Git.GetGitRepository());
2751 if (!repo)
2752 return -1;
2754 int isHeadOrphan = git_repository_head_unborn(repo);
2755 if (isHeadOrphan == 1)
2756 return 0;
2757 else if (isHeadOrphan != 0)
2758 return -1;
2760 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2761 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2762 char *buf = pathA.GetBuffer();
2763 if (!pathA.IsEmpty())
2765 opts.pathspec.strings = &buf;
2766 opts.pathspec.count = 1;
2768 CAutoDiff diff;
2770 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2772 CAutoTree t1;
2773 CAutoDiff diff2;
2775 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2776 return -1;
2778 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2779 return -1;
2781 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2782 return -1;
2784 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2785 return -1;
2787 if (git_diff_merge(diff, diff2))
2788 return -1;
2790 else
2792 if (tree1.IsEmpty() && tree2.IsEmpty())
2793 return -1;
2795 if (tree1.IsEmpty())
2797 tree1 = tree2;
2798 tree2.Empty();
2801 CAutoTree t1;
2802 CAutoTree t2;
2803 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2804 return -1;
2806 if (tree2.IsEmpty())
2808 /* don't check return value, there are not parent commit at first commit*/
2809 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2811 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2812 return -1;
2813 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2814 return -1;
2817 CAutoDiffStats stats;
2818 if (git_diff_get_stats(stats.GetPointer(), diff))
2819 return -1;
2820 CAutoBuf statBuf;
2821 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2822 return -1;
2823 statCallback(statBuf, data);
2825 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2827 CAutoPatch patch;
2828 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2829 return -1;
2831 if (git_patch_print(patch, callback, data))
2832 return -1;
2835 pathA.ReleaseBuffer();
2837 return 0;
2840 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2842 if (UsingLibGit2(GIT_CMD_DIFF))
2844 FILE *file = nullptr;
2845 _tfopen_s(&file, patchfile, _T("w"));
2846 if (file == nullptr)
2847 return -1;
2848 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
2849 fclose(file);
2850 return ret;
2852 else
2854 CString cmd;
2855 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2856 return RunLogFile(cmd, patchfile, &gitLastErr);
2860 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
2862 ATLASSERT(payload && text);
2863 CStringA *str = (CStringA*) payload;
2864 str->Append(text->ptr, (int)text->size);
2865 str->AppendChar('\n');
2868 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2870 ATLASSERT(payload && line);
2871 CStringA *str = (CStringA*) payload;
2872 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2873 str->Append(&line->origin, 1);
2874 str->Append(line->content, (int)line->content_len);
2875 return 0;
2878 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2880 if (UsingLibGit2(GIT_CMD_DIFF))
2881 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
2882 else
2884 CString cmd;
2885 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2886 BYTE_VECTOR vector;
2887 int ret = Run(cmd, &vector);
2888 if (!vector.empty())
2890 vector.push_back(0); // vector is not NUL terminated
2891 buffer->Append((char *)&vector[0]);
2893 return ret;
2897 int CGit::GitRevert(int parent, const CGitHash &hash)
2899 if (UsingLibGit2(GIT_CMD_REVERT))
2901 CAutoRepository repo(GetGitRepository());
2902 if (!repo)
2903 return -1;
2905 CAutoCommit commit;
2906 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2907 return -1;
2909 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2910 revert_opts.mainline = parent;
2911 int result = git_revert(repo, commit, &revert_opts);
2913 return !result ? 0 : -1;
2915 else
2917 CString cmd, merge;
2918 if (parent)
2919 merge.Format(_T("-m %d "), parent);
2920 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2921 gitLastErr = cmd + _T("\n");
2922 if (Run(cmd, &gitLastErr, CP_UTF8))
2924 return -1;
2926 else
2928 gitLastErr.Empty();
2929 return 0;
2934 int CGit::DeleteRef(const CString& reference)
2936 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2938 CAutoRepository repo(GetGitRepository());
2939 if (!repo)
2940 return -1;
2942 CStringA refA;
2943 if (reference.Right(3) == _T("^{}"))
2944 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2945 else
2946 refA = CUnicodeUtils::GetUTF8(reference);
2948 CAutoReference ref;
2949 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2950 return -1;
2952 int result = -1;
2953 if (git_reference_is_tag(ref))
2954 result = git_tag_delete(repo, git_reference_shorthand(ref));
2955 else if (git_reference_is_branch(ref))
2956 result = git_branch_delete(ref);
2957 else if (git_reference_is_remote(ref))
2958 result = git_branch_delete(ref);
2959 else
2960 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2962 return result;
2964 else
2966 CString cmd, shortname;
2967 if (GetShortName(reference, shortname, _T("refs/heads/")))
2968 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2969 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2970 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2971 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2972 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2973 else
2975 gitLastErr = L"unsupported reference type: " + reference;
2976 return -1;
2979 if (Run(cmd, &gitLastErr, CP_UTF8))
2980 return -1;
2982 gitLastErr.Empty();
2983 return 0;
2987 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2989 if (PathFileExists(filename))
2991 FILE *pFile = nullptr;
2992 _tfopen_s(&pFile, filename, _T("r"));
2993 if (pFile)
2995 CStringA str;
2998 char s[8196] = { 0 };
2999 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3000 if (read == 0)
3001 break;
3002 str += CStringA(s, read);
3003 } while (true);
3004 fclose(pFile);
3005 msg = CUnicodeUtils::GetUnicode(str);
3006 msg.Replace(_T("\r\n"), _T("\n"));
3007 msg.TrimRight(_T("\n"));
3008 msg += _T("\n");
3010 else
3011 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3012 return true; // load no further files
3014 return false;