Do not use GitAdminDir objects
[TortoiseGit.git] / src / Git / Git.cpp
blob3ace16d2a16de0d4e919487944263dffec2ed563
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 bool CGit::ms_bCygwinGit = (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE) == TRUE);
38 int CGit::m_LogEncode=CP_UTF8;
39 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
41 static LPCTSTR nextpath(const wchar_t* path, wchar_t* buf, size_t buflen)
43 if (path == NULL || buf == NULL || buflen == 0)
44 return NULL;
46 const wchar_t* base = path;
47 wchar_t term = (*path == L'"') ? *path++ : L';';
49 for (buflen--; *path && *path != term && buflen; buflen--)
50 *buf++ = *path++;
52 *buf = L'\0'; /* reserved a byte via initial subtract */
54 while (*path == term || *path == L';')
55 ++path;
57 return (path != base) ? path : NULL;
60 static inline BOOL FileExists(LPCTSTR lpszFileName)
62 struct _stat st;
63 return _tstat(lpszFileName, &st) == 0;
66 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
68 TCHAR buf[MAX_PATH] = { 0 };
70 // search in all paths defined in PATH
71 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
73 TCHAR *pfin = buf + _tcslen(buf) - 1;
75 // ensure trailing slash
76 if (*pfin != _T('/') && *pfin != _T('\\'))
77 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
79 const size_t len = _tcslen(buf);
81 if ((len + filename.GetLength()) < MAX_PATH)
82 _tcscpy_s(pfin + 1, MAX_PATH - len, filename);
83 else
84 break;
86 if (FileExists(buf))
88 if (wantDirectory)
89 pfin[1] = 0;
90 return buf;
94 return _T("");
97 static BOOL FindGitPath()
99 size_t size;
100 _tgetenv_s(&size, NULL, 0, _T("PATH"));
101 if (!size)
102 return FALSE;
104 TCHAR* env = (TCHAR*)alloca(size * sizeof(TCHAR));
105 if (!env)
106 return FALSE;
107 _tgetenv_s(&size, env, size, _T("PATH"));
109 CString gitExeDirectory = FindFileOnPath(_T("git.exe"), env, true);
110 if (!gitExeDirectory.IsEmpty())
112 CGit::ms_LastMsysGitDir = gitExeDirectory;
113 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
114 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
116 // often the msysgit\cmd folder is on the %PATH%, but
117 // that git.exe does not work, so try to guess the bin folder
118 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
119 if (FileExists(binDir))
120 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
122 return TRUE;
125 return FALSE;
128 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
130 CString filename = executable;
132 if (executable.GetLength() < 4 || executable.Find(_T(".exe"), executable.GetLength() - 4) != executable.GetLength() - 4)
133 filename += _T(".exe");
135 if (FileExists(filename))
136 return filename;
138 filename = FindFileOnPath(filename, env);
139 if (!filename.IsEmpty())
140 return filename;
142 return executable;
145 static bool g_bSortLogical;
146 static bool g_bSortLocalBranchesFirst;
147 static bool g_bSortTagsReversed;
148 static git_cred_acquire_cb g_Git2CredCallback;
149 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
151 static void GetSortOptions()
153 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
154 if (g_bSortLogical)
155 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
156 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
157 if (g_bSortLocalBranchesFirst)
158 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
159 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
160 if (!g_bSortTagsReversed)
161 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
164 static int LogicalComparePredicate(const CString &left, const CString &right)
166 if (g_bSortLogical)
167 return StrCmpLogicalW(left, right) < 0;
168 return StrCmpI(left, right) < 0;
171 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
173 if (g_bSortLogical)
174 return StrCmpLogicalW(left, right) > 0;
175 return StrCmpI(left, right) > 0;
178 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
180 if (g_bSortLocalBranchesFirst)
182 int leftIsRemote = left.Find(_T("remotes/"));
183 int rightIsRemote = right.Find(_T("remotes/"));
185 if (leftIsRemote == 0 && rightIsRemote < 0)
186 return false;
187 else if (leftIsRemote < 0 && rightIsRemote == 0)
188 return true;
190 if (g_bSortLogical)
191 return StrCmpLogicalW(left, right) < 0;
192 return StrCmpI(left, right) < 0;
195 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
197 CString CGit::ms_LastMsysGitDir;
198 int CGit::ms_LastMsysGitVersion = 0;
199 CGit g_Git;
202 CGit::CGit(void)
204 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
205 m_CurrentDir.ReleaseBuffer();
206 m_IsGitDllInited = false;
207 m_GitDiff=0;
208 m_GitSimpleListDiff=0;
209 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
210 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
211 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));
213 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
215 GetSortOptions();
216 this->m_bInitialized =false;
217 CheckMsysGitDir();
218 m_critGitDllSec.Init();
221 CGit::~CGit(void)
223 if(this->m_GitDiff)
225 git_close_diff(m_GitDiff);
226 m_GitDiff=0;
228 if(this->m_GitSimpleListDiff)
230 git_close_diff(m_GitSimpleListDiff);
231 m_GitSimpleListDiff=0;
235 bool CGit::IsBranchNameValid(const CString& branchname)
237 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
238 return false;
239 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
240 return false;
241 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
242 return !!git_reference_is_valid_name(branchA);
245 static bool IsPowerShell(CString cmd)
247 cmd.MakeLower();
248 int powerShellPos = cmd.Find(_T("powershell"));
249 if (powerShellPos < 0)
250 return false;
252 // found the word powershell, check that it is the command and not any parameter
253 int end = cmd.GetLength();
254 if (cmd.Find(_T('"')) == 0)
256 int secondDoubleQuote = cmd.Find(_T('"'), 1);
257 if (secondDoubleQuote > 0)
258 end = secondDoubleQuote;
260 else
262 int firstSpace = cmd.Find(_T(' '));
263 if (firstSpace > 0)
264 end = firstSpace;
267 return (end - 4 - 10 == powerShellPos || end - 10 == powerShellPos); // len(".exe")==4, len("powershell")==10
270 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
272 SECURITY_ATTRIBUTES sa;
273 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
274 CAutoGeneralHandle hStdioFile;
276 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
277 sa.lpSecurityDescriptor=NULL;
278 sa.bInheritHandle=TRUE;
279 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
281 CString err = CFormatMessageWrapper();
282 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
283 return TGIT_GIT_ERROR_OPEN_PIP;
285 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
287 CString err = CFormatMessageWrapper();
288 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
289 return TGIT_GIT_ERROR_OPEN_PIP;
292 if(StdioFile)
294 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
295 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
298 STARTUPINFO si = { 0 };
299 PROCESS_INFORMATION pi;
300 si.cb=sizeof(STARTUPINFO);
302 if (hErrReadOut)
303 si.hStdError = hWriteErr;
304 else
305 si.hStdError = hWrite;
306 if(StdioFile)
307 si.hStdOutput=hStdioFile;
308 else
309 si.hStdOutput=hWrite;
311 si.wShowWindow=SW_HIDE;
312 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
314 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
315 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
317 dwFlags |= CREATE_NEW_PROCESS_GROUP;
319 // 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,
320 // 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)
321 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
322 if (IsPowerShell(cmd))
323 dwFlags |= CREATE_NEW_CONSOLE;
324 else
325 dwFlags |= DETACHED_PROCESS;
327 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
328 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
330 if (ms_bCygwinGit && cmd.Find(_T("git")) == 0)
332 cmd.Replace(_T('\\'), _T('/'));
333 cmd.Replace(_T("\""), _T("\\\""));
334 cmd = _T('"') + CGit::ms_LastMsysGitDir + _T("\\bash.exe\" -c \"/bin/") + cmd + _T('"');
336 else if(cmd.Find(_T("git")) == 0)
338 int firstSpace = cmd.Find(_T(" "));
339 if (firstSpace > 0)
340 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
341 else
342 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
345 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
346 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
348 CString err = CFormatMessageWrapper();
349 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
350 return TGIT_GIT_ERROR_CREATE_PROCESS;
353 m_CurrentGitPi = pi;
355 if(piOut)
356 *piOut=pi;
357 if(hReadOut)
358 *hReadOut = hRead.Detach();
359 if(hErrReadOut)
360 *hErrReadOut = hReadErr.Detach();
361 return 0;
364 //Must use sperate function to convert ANSI str to union code string
365 //Becuase A2W use stack as internal convert buffer.
366 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
368 if(str == NULL)
369 return ;
371 int len ;
372 if(length<0)
373 len = (int)strlen((const char*)p);
374 else
375 len=length;
376 if (len == 0)
377 return;
378 int currentContentLen = str->GetLength();
379 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
380 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
381 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
384 // This method was originally used to check for orphaned branches
385 BOOL CGit::CanParseRev(CString ref)
387 if (ref.IsEmpty())
388 ref = _T("HEAD");
390 CString cmdout;
391 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
393 return FALSE;
395 if(cmdout.IsEmpty())
396 return FALSE;
398 return TRUE;
401 // Checks if we have an orphaned HEAD
402 BOOL CGit::IsInitRepos()
404 CGitHash hash;
405 // handle error on reading HEAD hash as init repo
406 if (GetHash(hash, _T("HEAD")) != 0)
407 return TRUE;
408 return hash.IsEmpty() ? TRUE : FALSE;
411 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
413 PASYNCREADSTDERRTHREADARGS pDataArray;
414 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
416 DWORD readnumber;
417 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
418 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
420 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
421 break;
424 return 0;
427 int CGit::Run(CGitCall* pcall)
429 PROCESS_INFORMATION pi;
430 CAutoGeneralHandle hRead, hReadErr;
431 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
432 return TGIT_GIT_ERROR_CREATE_PROCESS;
434 CAutoGeneralHandle piThread(pi.hThread);
435 CAutoGeneralHandle piProcess(pi.hProcess);
437 ASYNCREADSTDERRTHREADARGS threadArguments;
438 threadArguments.fileHandle = hReadErr;
439 threadArguments.pcall = pcall;
440 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
442 DWORD readnumber;
443 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
444 bool bAborted=false;
445 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
447 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
448 if(!bAborted)//For now, flush output when command aborted.
449 if(pcall->OnOutputData(data,readnumber))
450 bAborted=true;
452 if(!bAborted)
453 pcall->OnEnd();
455 if (thread)
456 WaitForSingleObject(thread, INFINITE);
458 WaitForSingleObject(pi.hProcess, INFINITE);
459 DWORD exitcode =0;
461 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
463 CString err = CFormatMessageWrapper();
464 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
465 return TGIT_GIT_ERROR_GET_EXIT_CODE;
467 else
468 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
470 return exitcode;
472 class CGitCall_ByteVector : public CGitCall
474 public:
475 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
476 virtual bool OnOutputData(const BYTE* data, size_t size)
478 if (!m_pvector || size == 0)
479 return false;
480 size_t oldsize=m_pvector->size();
481 m_pvector->resize(m_pvector->size()+size);
482 memcpy(&*(m_pvector->begin()+oldsize),data,size);
483 return false;
485 virtual bool OnOutputErrData(const BYTE* data, size_t size)
487 if (!m_pvectorErr || size == 0)
488 return false;
489 size_t oldsize = m_pvectorErr->size();
490 m_pvectorErr->resize(m_pvectorErr->size() + size);
491 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
492 return false;
494 BYTE_VECTOR* m_pvector;
495 BYTE_VECTOR* m_pvectorErr;
498 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
500 CGitCall_ByteVector call(cmd, vector, vectorErr);
501 return Run(&call);
503 int CGit::Run(CString cmd, CString* output, int code)
505 CString err;
506 int ret;
507 ret = Run(cmd, output, &err, code);
509 if (output && !err.IsEmpty())
511 if (!output->IsEmpty())
512 *output += _T("\n");
513 *output += err;
516 return ret;
518 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
520 BYTE_VECTOR vector, vectorErr;
521 int ret;
522 if (outputErr)
523 ret = Run(cmd, &vector, &vectorErr);
524 else
525 ret = Run(cmd, &vector);
527 vector.push_back(0);
528 StringAppend(output, &(vector[0]), code);
530 if (outputErr)
532 vectorErr.push_back(0);
533 StringAppend(outputErr, &(vectorErr[0]), code);
536 return ret;
539 class CGitCallCb : public CGitCall
541 public:
542 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
544 virtual bool OnOutputData(const BYTE* data, size_t size) override
546 // Add data
547 if (size == 0)
548 return false;
549 int oldEndPos = m_buffer.GetLength();
550 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
551 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
553 // Break into lines and feed to m_recv
554 int eolPos;
555 while ((eolPos = m_buffer.Find('\n')) >= 0)
557 m_recv(m_buffer.Left(eolPos));
558 m_buffer = m_buffer.Mid(eolPos + 1);
560 return false;
563 virtual bool OnOutputErrData(const BYTE*, size_t) override
565 return false; // Ignore error output for now
568 virtual void OnEnd() override
570 if (!m_buffer.IsEmpty())
571 m_recv(m_buffer);
572 m_buffer.Empty(); // Just for sure
575 private:
576 GitReceiverFunc m_recv;
577 CStringA m_buffer;
580 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
582 CGitCallCb call(cmd, recv);
583 return Run(&call);
586 CString CGit::GetUserName(void)
588 CEnvironment env;
589 env.CopyProcessEnvironment();
590 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
591 if (!envname.IsEmpty())
592 return envname;
593 return GetConfigValue(L"user.name");
595 CString CGit::GetUserEmail(void)
597 CEnvironment env;
598 env.CopyProcessEnvironment();
599 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
600 if (!envmail.IsEmpty())
601 return envmail;
603 return GetConfigValue(L"user.email");
606 CString CGit::GetConfigValue(const CString& name)
608 CString configValue;
609 int start = 0;
610 if(this->m_IsUseGitDLL)
612 CAutoLocker lock(g_Git.m_critGitDllSec);
616 CheckAndInitDll();
617 }catch(...)
620 CStringA key, value;
621 key = CUnicodeUtils::GetUTF8(name);
625 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
626 return CString();
628 catch (const char *msg)
630 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
631 return CString();
634 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
635 return configValue.Tokenize(_T("\n"),start);
637 else
639 CString cmd;
640 cmd.Format(L"git.exe config %s", name);
641 Run(cmd, &configValue, nullptr, CP_UTF8);
642 return configValue.Tokenize(_T("\n"),start);
646 bool CGit::GetConfigValueBool(const CString& name)
648 CString configValue = GetConfigValue(name);
649 configValue.MakeLower();
650 configValue.Trim();
651 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
652 return true;
653 else
654 return false;
657 int CGit::GetConfigValueInt32(const CString& name, int def)
659 CString configValue = GetConfigValue(name);
660 int value = def;
661 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
662 return value;
663 return def;
666 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
668 if(this->m_IsUseGitDLL)
670 CAutoLocker lock(g_Git.m_critGitDllSec);
674 CheckAndInitDll();
676 }catch(...)
679 CStringA keya, valuea;
680 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
681 valuea = CUnicodeUtils::GetUTF8(value);
685 return [=]() { return get_set_config(keya, valuea, type); }();
687 catch (const char *msg)
689 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
690 return -1;
693 else
695 CString cmd;
696 CString option;
697 switch(type)
699 case CONFIG_GLOBAL:
700 option = _T("--global");
701 break;
702 case CONFIG_SYSTEM:
703 option = _T("--system");
704 break;
705 default:
706 break;
708 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
709 CString out;
710 if (Run(cmd, &out, nullptr, CP_UTF8))
712 return -1;
715 return 0;
718 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
720 if(this->m_IsUseGitDLL)
722 CAutoLocker lock(g_Git.m_critGitDllSec);
726 CheckAndInitDll();
727 }catch(...)
730 CStringA keya;
731 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
735 return [=]() { return get_set_config(keya, nullptr, type); }();
737 catch (const char *msg)
739 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
740 return -1;
743 else
745 CString cmd;
746 CString option;
747 switch(type)
749 case CONFIG_GLOBAL:
750 option = _T("--global");
751 break;
752 case CONFIG_SYSTEM:
753 option = _T("--system");
754 break;
755 default:
756 break;
758 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
759 CString out;
760 if (Run(cmd, &out, nullptr, CP_UTF8))
762 return -1;
765 return 0;
768 CString CGit::GetCurrentBranch(bool fallback)
770 CString output;
771 //Run(_T("git.exe branch"),&branch);
773 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
774 if (result != 0 && ((result == 1 && !fallback) || result != 1))
776 return _T("(no branch)");
778 else
779 return output;
783 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
785 if (localBranch.IsEmpty())
786 return;
788 CString configName;
789 configName.Format(L"branch.%s.remote", localBranch);
790 pullRemote = GetConfigValue(configName);
792 //Select pull-branch from current branch
793 configName.Format(L"branch.%s.merge", localBranch);
794 pullBranch = StripRefName(GetConfigValue(configName));
797 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
799 CString refName;
800 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
801 return;
802 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
805 CString CGit::GetFullRefName(const CString& shortRefName)
807 CString refName;
808 CString cmd;
809 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
810 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
811 return CString();//Error
812 int iStart = 0;
813 return refName.Tokenize(L"\n", iStart);
816 CString CGit::StripRefName(CString refName)
818 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
819 refName = refName.Mid(11);
820 else if(wcsncmp(refName, L"refs/", 5) == 0)
821 refName = refName.Mid(5);
822 int start =0;
823 return refName.Tokenize(_T("\n"),start);
826 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
828 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
830 if ( sProjectRoot.IsEmpty() )
831 return -1;
833 CString sDotGitPath;
834 if (!GitAdminDir::GetAdminDirPath(sProjectRoot, sDotGitPath))
835 return -1;
837 CString sHeadFile = sDotGitPath + _T("HEAD");
839 FILE *pFile;
840 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
842 if (!pFile)
844 return -1;
847 char s[256] = {0};
848 fgets(s, sizeof(s), pFile);
850 fclose(pFile);
852 const char *pfx = "ref: refs/heads/";
853 const int len = 16;//strlen(pfx)
855 if ( !strncmp(s, pfx, len) )
857 //# We're on a branch. It might not exist. But
858 //# HEAD looks good enough to be a branch.
859 CStringA utf8Branch(s + len);
860 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
861 sBranchOut.TrimRight(_T(" \r\n\t"));
863 if ( sBranchOut.IsEmpty() )
864 return -1;
866 else if (fallback)
868 CStringA utf8Hash(s);
869 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
870 unicodeHash.TrimRight(_T(" \r\n\t"));
871 if (CGitHash::IsValidSHA1(unicodeHash))
872 sBranchOut = unicodeHash;
873 else
874 //# Assume this is a detached head.
875 sBranchOut = _T("HEAD");
876 return 1;
878 else
880 //# Assume this is a detached head.
881 sBranchOut = "HEAD";
883 return 1;
886 return 0;
889 int CGit::BuildOutputFormat(CString &format,bool IsFull)
891 CString log;
892 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
893 format += log;
894 if(IsFull)
896 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
897 format += log;
898 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
899 format += log;
900 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
901 format += log;
902 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
903 format += log;
904 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
905 format += log;
906 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
907 format += log;
908 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
909 format += log;
912 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
913 format += log;
914 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
915 format += log;
916 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
917 format += log;
919 if(IsFull)
921 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
922 format += log;
924 return 0;
927 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
928 CFilterData *Filter)
930 CString cmd;
931 CString num;
932 CString since;
934 CString file = _T(" --");
936 if(path)
937 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
939 if(count>0)
940 num.Format(_T("-n%d"),count);
942 CString param;
944 if(mask& LOG_INFO_STAT )
945 param += _T(" --numstat ");
946 if(mask& LOG_INFO_FILESTATE)
947 param += _T(" --raw ");
949 if(mask& LOG_INFO_FULLHISTORY)
950 param += _T(" --full-history ");
952 if(mask& LOG_INFO_BOUNDARY)
953 param += _T(" --left-right --boundary ");
955 if(mask& CGit::LOG_INFO_ALL_BRANCH)
956 param += _T(" --all ");
958 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
959 param += _T(" --branches ");
961 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
962 param += _T(" -C ");
964 if(mask& CGit::LOG_INFO_DETECT_RENAME )
965 param += _T(" -M ");
967 if(mask& CGit::LOG_INFO_FIRST_PARENT )
968 param += _T(" --first-parent ");
970 if(mask& CGit::LOG_INFO_NO_MERGE )
971 param += _T(" --no-merges ");
973 if(mask& CGit::LOG_INFO_FOLLOW)
974 param += _T(" --follow ");
976 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
977 param += _T(" -c ");
979 if(mask& CGit::LOG_INFO_FULL_DIFF)
980 param += _T(" --full-diff ");
982 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
983 param += _T(" --simplify-by-decoration ");
985 param += range;
987 CString st1,st2;
989 if( Filter && (Filter->m_From != -1))
991 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
992 param += st1;
995 if( Filter && (Filter->m_To != -1))
997 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
998 param += st2;
1001 bool isgrep = false;
1002 if( Filter && (!Filter->m_Author.IsEmpty()))
1004 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
1005 param += st1;
1006 isgrep = true;
1009 if( Filter && (!Filter->m_Committer.IsEmpty()))
1011 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1012 param += st1;
1013 isgrep = true;
1016 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1018 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1019 param += st1;
1020 isgrep = true;
1023 if(Filter && isgrep)
1025 if(!Filter->m_IsRegex)
1026 param += _T(" --fixed-strings ");
1028 param += _T(" --regexp-ignore-case --extended-regexp ");
1031 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1032 if (logOrderBy == LOG_ORDER_TOPOORDER)
1033 param += _T(" --topo-order");
1034 else if (logOrderBy == LOG_ORDER_DATEORDER)
1035 param += _T(" --date-order");
1037 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
1038 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1039 else
1041 CString log;
1042 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1043 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1044 num,param,log);
1047 cmd += file;
1049 return cmd;
1051 #define BUFSIZE 512
1052 void GetTempPath(CString &path)
1054 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1055 DWORD dwRetVal;
1056 DWORD dwBufSize=BUFSIZE;
1057 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1058 lpPathBuffer); // buffer for path
1059 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1061 path=_T("");
1063 path.Format(_T("%s"),lpPathBuffer);
1065 CString GetTempFile()
1067 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1068 DWORD dwRetVal;
1069 DWORD dwBufSize=BUFSIZE;
1070 TCHAR szTempName[BUFSIZE] = { 0 };
1071 UINT uRetVal;
1073 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1074 lpPathBuffer); // buffer for path
1075 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1077 return _T("");
1079 // Create a temporary file.
1080 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1081 TEXT("Patch"), // temp file name prefix
1082 0, // create unique name
1083 szTempName); // buffer for name
1086 if (uRetVal == 0)
1088 return _T("");
1091 return CString(szTempName);
1095 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1097 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1098 if (result == 0) return 0;
1099 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1101 if (lpBuffer)
1102 lpBuffer[0] = '\0';
1103 return result + 13;
1106 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1107 CreateDirectory(lpBuffer, NULL);
1109 return result + 13;
1112 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1114 STARTUPINFO si;
1115 PROCESS_INFORMATION pi;
1116 si.cb=sizeof(STARTUPINFO);
1117 GetStartupInfo(&si);
1119 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1120 psa.bInheritHandle=TRUE;
1122 HANDLE hReadErr, hWriteErr;
1123 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1125 CString err = CFormatMessageWrapper();
1126 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1127 return TGIT_GIT_ERROR_OPEN_PIP;
1130 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1131 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1133 if (houtfile == INVALID_HANDLE_VALUE)
1135 CString err = CFormatMessageWrapper();
1136 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1137 CloseHandle(hReadErr);
1138 CloseHandle(hWriteErr);
1139 return TGIT_GIT_ERROR_OPEN_PIP;
1142 si.wShowWindow = SW_HIDE;
1143 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1144 si.hStdOutput = houtfile;
1145 si.hStdError = hWriteErr;
1147 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1148 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1150 if(cmd.Find(_T("git")) == 0)
1151 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1153 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1154 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1156 CString err = CFormatMessageWrapper();
1157 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1158 stdErr = &err;
1159 CloseHandle(hReadErr);
1160 CloseHandle(hWriteErr);
1161 CloseHandle(houtfile);
1162 return TGIT_GIT_ERROR_CREATE_PROCESS;
1165 BYTE_VECTOR stderrVector;
1166 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1167 HANDLE thread;
1168 ASYNCREADSTDERRTHREADARGS threadArguments;
1169 threadArguments.fileHandle = hReadErr;
1170 threadArguments.pcall = &pcall;
1171 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1173 WaitForSingleObject(pi.hProcess,INFINITE);
1175 CloseHandle(hWriteErr);
1176 CloseHandle(hReadErr);
1178 if (thread)
1179 WaitForSingleObject(thread, INFINITE);
1181 stderrVector.push_back(0);
1182 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1184 DWORD exitcode = 0;
1185 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1187 CString err = CFormatMessageWrapper();
1188 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1189 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1191 else
1192 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1194 CloseHandle(pi.hThread);
1195 CloseHandle(pi.hProcess);
1196 CloseHandle(houtfile);
1197 return exitcode;
1200 git_repository * CGit::GetGitRepository() const
1202 git_repository * repo = nullptr;
1203 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1204 return repo;
1207 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1209 ATLASSERT(repo);
1211 // no need to parse a ref if it's already a 40-byte hash
1212 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1214 hash = CGitHash(friendname);
1215 return 0;
1218 int isHeadOrphan = git_repository_head_unborn(repo);
1219 if (isHeadOrphan != 0)
1221 hash.Empty();
1222 if (isHeadOrphan == 1)
1223 return 0;
1224 else
1225 return -1;
1228 CAutoObject gitObject;
1229 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1230 return -1;
1232 const git_oid * oid = git_object_id(gitObject);
1233 if (!oid)
1234 return -1;
1236 hash = CGitHash((char *)oid->id);
1238 return 0;
1241 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1243 // no need to parse a ref if it's already a 40-byte hash
1244 if (CGitHash::IsValidSHA1(friendname))
1246 hash = CGitHash(friendname);
1247 return 0;
1250 if (m_IsUseLibGit2)
1252 CAutoRepository repo(GetGitRepository());
1253 if (!repo)
1254 return -1;
1256 return GetHash(repo, hash, friendname, true);
1258 else
1260 CString cmd;
1261 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1262 gitLastErr.Empty();
1263 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1264 hash = CGitHash(gitLastErr.Trim());
1265 if (ret == 0)
1266 gitLastErr.Empty();
1267 return ret;
1271 int CGit::GetInitAddList(CTGitPathList &outputlist)
1273 CString cmd;
1274 BYTE_VECTOR cmdout;
1276 cmd=_T("git.exe ls-files -s -t -z");
1277 outputlist.Clear();
1278 if (Run(cmd, &cmdout))
1279 return -1;
1281 if (outputlist.ParserFromLsFile(cmdout))
1282 return -1;
1283 for(int i = 0; i < outputlist.GetCount(); ++i)
1284 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1286 return 0;
1288 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1290 CString cmd;
1291 CString ignore;
1292 if (ignoreSpaceAtEol)
1293 ignore += _T(" --ignore-space-at-eol");
1294 if (ignoreSpaceChange)
1295 ignore += _T(" --ignore-space-change");
1296 if (ignoreAllSpace)
1297 ignore += _T(" --ignore-all-space");
1298 if (ignoreBlankLines)
1299 ignore += _T(" --ignore-blank-lines");
1301 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1303 //rev1=+_T("");
1304 if(rev1 == GIT_REV_ZERO)
1305 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1306 else
1307 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1309 else
1311 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1314 BYTE_VECTOR out;
1315 if (Run(cmd, &out))
1316 return -1;
1318 outputlist.ParserFromLog(out);
1320 return 0;
1323 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1325 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1326 CString str;
1327 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1328 list->push_back(str);
1329 return 0;
1332 int CGit::GetTagList(STRING_VECTOR &list)
1334 if (this->m_IsUseLibGit2)
1336 CAutoRepository repo(GetGitRepository());
1337 if (!repo)
1338 return -1;
1340 CAutoStrArray tag_names;
1342 if (git_tag_list(tag_names, repo))
1343 return -1;
1345 for (size_t i = 0; i < tag_names->count; ++i)
1347 CStringA tagName(tag_names->strings[i]);
1348 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1351 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1353 return 0;
1355 else
1357 CString cmd, output;
1358 cmd=_T("git.exe tag -l");
1359 int ret = Run(cmd, &output, NULL, CP_UTF8);
1360 if(!ret)
1362 int pos=0;
1363 CString one;
1364 while( pos>=0 )
1366 one=output.Tokenize(_T("\n"),pos);
1367 if (!one.IsEmpty())
1368 list.push_back(one);
1370 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1372 return ret;
1376 CString CGit::GetGitLastErr(const CString& msg)
1378 if (this->m_IsUseLibGit2)
1379 return GetLibGit2LastErr(msg);
1380 else if (gitLastErr.IsEmpty())
1381 return msg + _T("\nUnknown git.exe error.");
1382 else
1384 CString lastError = gitLastErr;
1385 gitLastErr.Empty();
1386 return msg + _T("\n") + lastError;
1390 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1392 if (UsingLibGit2(cmd))
1393 return GetLibGit2LastErr(msg);
1394 else if (gitLastErr.IsEmpty())
1395 return msg + _T("\nUnknown git.exe error.");
1396 else
1398 CString lastError = gitLastErr;
1399 gitLastErr.Empty();
1400 return msg + _T("\n") + lastError;
1404 CString CGit::GetLibGit2LastErr()
1406 const git_error *libgit2err = giterr_last();
1407 if (libgit2err)
1409 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1410 giterr_clear();
1411 return _T("libgit2 returned: ") + lastError;
1413 else
1414 return _T("An error occoured in libgit2, but no message is available.");
1417 CString CGit::GetLibGit2LastErr(const CString& msg)
1419 if (!msg.IsEmpty())
1420 return msg + _T("\n") + GetLibGit2LastErr();
1421 return GetLibGit2LastErr();
1424 CString CGit::FixBranchName_Mod(CString& branchName)
1426 if(branchName == "FETCH_HEAD")
1427 branchName = DerefFetchHead();
1428 return branchName;
1431 CString CGit::FixBranchName(const CString& branchName)
1433 CString tempBranchName = branchName;
1434 FixBranchName_Mod(tempBranchName);
1435 return tempBranchName;
1438 bool CGit::IsBranchTagNameUnique(const CString& name)
1440 if (m_IsUseLibGit2)
1442 CAutoRepository repo(GetGitRepository());
1443 if (!repo)
1444 return true; // TODO: optimize error reporting
1446 CAutoReference tagRef;
1447 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1448 return true;
1450 CAutoReference branchRef;
1451 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1452 return true;
1454 return false;
1456 // else
1457 CString output;
1459 CString cmd;
1460 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1461 int ret = Run(cmd, &output, NULL, CP_UTF8);
1462 if (!ret)
1464 int i = 0, pos = 0;
1465 while (pos >= 0)
1467 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1468 ++i;
1470 if (i >= 2)
1471 return false;
1474 return true;
1477 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1479 if (m_IsUseLibGit2)
1481 CAutoRepository repo(GetGitRepository());
1482 if (!repo)
1483 return false; // TODO: optimize error reporting
1485 CString prefix;
1486 if (isBranch)
1487 prefix = _T("refs/heads/");
1488 else
1489 prefix = _T("refs/tags/");
1491 CAutoReference ref;
1492 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1493 return false;
1495 return true;
1497 // else
1498 CString cmd, output;
1500 cmd = _T("git.exe show-ref ");
1501 if (isBranch)
1502 cmd += _T("--heads ");
1503 else
1504 cmd += _T("--tags ");
1506 cmd += _T("refs/heads/") + name;
1507 cmd += _T(" refs/tags/") + name;
1509 int ret = Run(cmd, &output, NULL, CP_UTF8);
1510 if (!ret)
1512 if (!output.IsEmpty())
1513 return true;
1516 return false;
1519 CString CGit::DerefFetchHead()
1521 CString dotGitPath;
1522 GitAdminDir::GetAdminDirPath(m_CurrentDir, dotGitPath);
1523 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1524 int forMergeLineCount = 0;
1525 std::string line;
1526 std::string hashToReturn;
1527 while(getline(fetchHeadFile, line))
1529 //Tokenize this line
1530 std::string::size_type prevPos = 0;
1531 std::string::size_type pos = line.find('\t');
1532 if(pos == std::string::npos) continue; //invalid line
1534 std::string hash = line.substr(0, pos);
1535 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1537 bool forMerge = pos == prevPos;
1538 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1540 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1542 //Process this line
1543 if(forMerge)
1545 hashToReturn = hash;
1546 ++forMergeLineCount;
1547 if(forMergeLineCount > 1)
1548 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1552 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1555 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1557 int ret = 0;
1558 CString cur;
1559 if (m_IsUseLibGit2)
1561 CAutoRepository repo(GetGitRepository());
1562 if (!repo)
1563 return -1;
1565 if (git_repository_head_detached(repo) == 1)
1566 cur = _T("(detached from ");
1568 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1570 git_branch_t flags = GIT_BRANCH_LOCAL;
1571 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1572 flags = GIT_BRANCH_ALL;
1573 else if (type & BRANCH_REMOTE)
1574 flags = GIT_BRANCH_REMOTE;
1576 CAutoBranchIterator it;
1577 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1578 return -1;
1580 git_reference * ref = nullptr;
1581 git_branch_t branchType;
1582 while (git_branch_next(&ref, &branchType, it) == 0)
1584 CAutoReference autoRef(ref);
1585 const char * name = nullptr;
1586 if (git_branch_name(&name, ref))
1587 continue;
1589 CString branchname = CUnicodeUtils::GetUnicode(name);
1590 if (branchType & GIT_BRANCH_REMOTE)
1591 list.push_back(_T("remotes/") + branchname);
1592 else
1594 if (git_branch_is_head(ref))
1595 cur = branchname;
1596 list.push_back(branchname);
1601 else
1603 CString cmd, output;
1604 cmd = _T("git.exe branch --no-color");
1606 if ((type & BRANCH_ALL) == BRANCH_ALL)
1607 cmd += _T(" -a");
1608 else if (type & BRANCH_REMOTE)
1609 cmd += _T(" -r");
1611 ret = Run(cmd, &output, nullptr, CP_UTF8);
1612 if (!ret)
1614 int pos = 0;
1615 CString one;
1616 while (pos >= 0)
1618 one = output.Tokenize(_T("\n"), pos);
1619 one.Trim(L" \r\n\t");
1620 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1621 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1622 if (one[0] == _T('*'))
1624 one = one.Mid(2);
1625 cur = one;
1627 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1628 list.push_back(one);
1633 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1634 list.push_back(L"FETCH_HEAD");
1636 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1638 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1640 for (unsigned int i = 0; i < list.size(); ++i)
1642 if (list[i] == cur)
1644 *current = i;
1645 break;
1650 return ret;
1653 int CGit::GetRemoteList(STRING_VECTOR &list)
1655 if (this->m_IsUseLibGit2)
1657 CAutoRepository repo(GetGitRepository());
1658 if (!repo)
1659 return -1;
1661 CAutoStrArray remotes;
1662 if (git_remote_list(remotes, repo))
1663 return -1;
1665 for (size_t i = 0; i < remotes->count; ++i)
1667 CStringA remote(remotes->strings[i]);
1668 list.push_back(CUnicodeUtils::GetUnicode(remote));
1671 std::sort(list.begin(), list.end());
1673 return 0;
1675 else
1677 int ret;
1678 CString cmd, output;
1679 cmd=_T("git.exe remote");
1680 ret = Run(cmd, &output, NULL, CP_UTF8);
1681 if(!ret)
1683 int pos=0;
1684 CString one;
1685 while( pos>=0 )
1687 one=output.Tokenize(_T("\n"),pos);
1688 if (!one.IsEmpty())
1689 list.push_back(one);
1692 return ret;
1696 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1698 if (UsingLibGit2(GIT_CMD_FETCH))
1700 CAutoRepository repo(GetGitRepository());
1701 if (!repo)
1702 return -1;
1704 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1705 CAutoRemote remote;
1706 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1707 return -1;
1709 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1710 callbacks.credentials = g_Git2CredCallback;
1711 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1712 git_remote_set_callbacks(remote, &callbacks);
1713 if (git_remote_connect(remote, GIT_DIRECTION_FETCH) < 0)
1714 return -1;
1716 const git_remote_head** heads = nullptr;
1717 size_t size = 0;
1718 if (git_remote_ls(&heads, &size, remote) < 0)
1719 return -1;
1721 for (size_t i = 0; i < size; i++)
1723 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1724 CString shortname;
1725 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1726 continue;
1727 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1728 if (shortname.Find(_T("^{}")) >= 1)
1729 continue;
1730 list.push_back(shortname);
1732 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1733 return 0;
1736 CString cmd, out, err;
1737 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1738 if (Run(cmd, &out, &err, CP_UTF8))
1740 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1741 return -1;
1744 int pos = 0;
1745 while (pos >= 0)
1747 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1748 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1749 if (one.Find(_T("^{}")) >= 1)
1750 continue;
1751 if (!one.IsEmpty())
1752 list.push_back(one);
1754 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1755 return 0;
1758 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1760 if (UsingLibGit2(GIT_CMD_PUSH))
1762 CAutoRepository repo(GetGitRepository());
1763 if (!repo)
1764 return -1;
1766 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1767 CAutoRemote remote;
1768 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1769 return -1;
1771 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1772 callbacks.credentials = g_Git2CredCallback;
1773 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1774 git_remote_set_callbacks(remote, &callbacks);
1775 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1776 return -1;
1778 std::vector<CStringA> refspecs;
1779 for (auto ref : list)
1780 refspecs.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref));
1782 std::vector<char*> vc;
1783 vc.reserve(refspecs.size());
1784 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1785 git_strarray specs = { &vc[0], vc.size() };
1787 if (git_remote_push(remote, &specs, nullptr, nullptr, nullptr) < 0)
1788 return -1;
1790 else
1792 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1793 for (auto ref : list)
1795 CString refspec = _T(":") + ref;
1796 mgtPush.AddFile(refspec);
1799 BOOL cancel = FALSE;
1800 mgtPush.Execute(cancel);
1803 return 0;
1806 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1808 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1809 CString str;
1810 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1811 list->push_back(str);
1812 return 0;
1815 int CGit::GetRefList(STRING_VECTOR &list)
1817 if (this->m_IsUseLibGit2)
1819 CAutoRepository repo(GetGitRepository());
1820 if (!repo)
1821 return -1;
1823 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1824 return -1;
1826 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1828 return 0;
1830 else
1832 CString cmd, output;
1833 cmd=_T("git.exe show-ref -d");
1834 int ret = Run(cmd, &output, NULL, CP_UTF8);
1835 if(!ret)
1837 int pos=0;
1838 CString one;
1839 while( pos>=0 )
1841 one=output.Tokenize(_T("\n"),pos);
1842 int start=one.Find(_T(" "),0);
1843 if(start>0)
1845 CString name;
1846 name=one.Right(one.GetLength()-start-1);
1847 list.push_back(name);
1850 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1852 return ret;
1856 typedef struct map_each_ref_payload {
1857 git_repository * repo;
1858 MAP_HASH_NAME * map;
1859 } map_each_ref_payload;
1861 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1863 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1865 CString str;
1866 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1868 CAutoObject gitObject;
1869 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1870 return 1;
1872 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1874 str += _T("^{}"); // deref tag
1875 CAutoObject derefedTag;
1876 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1877 return 1;
1878 gitObject.Swap(derefedTag);
1881 const git_oid * oid = git_object_id(gitObject);
1882 if (oid == NULL)
1883 return 1;
1885 CGitHash hash((char *)oid->id);
1886 (*payloadContent->map)[hash].push_back(str);
1888 return 0;
1890 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1892 ATLASSERT(repo);
1894 map_each_ref_payload payloadContent = { repo, &map };
1896 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1897 return -1;
1899 for (auto it = map.begin(); it != map.end(); ++it)
1901 std::sort(it->second.begin(), it->second.end());
1904 return 0;
1907 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1909 if (this->m_IsUseLibGit2)
1911 CAutoRepository repo(GetGitRepository());
1912 if (!repo)
1913 return -1;
1915 return GetMapHashToFriendName(repo, map);
1917 else
1919 CString cmd, output;
1920 cmd=_T("git.exe show-ref -d");
1921 int ret = Run(cmd, &output, NULL, CP_UTF8);
1922 if(!ret)
1924 int pos=0;
1925 CString one;
1926 while( pos>=0 )
1928 one=output.Tokenize(_T("\n"),pos);
1929 int start=one.Find(_T(" "),0);
1930 if(start>0)
1932 CString name;
1933 name=one.Right(one.GetLength()-start-1);
1935 CString hash;
1936 hash=one.Left(start);
1938 map[CGitHash(hash)].push_back(name);
1942 return ret;
1946 static void SetLibGit2SearchPath(int level, const CString &value)
1948 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1949 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1952 static void SetLibGit2TemplatePath(const CString &value)
1954 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1955 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1958 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1960 if (m_bInitialized)
1962 return TRUE;
1965 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
1966 this->m_Environment.clear();
1967 m_Environment.CopyProcessEnvironment();
1968 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
1970 TCHAR *oldpath;
1971 size_t homesize,size;
1973 // set HOME if not set already
1974 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1975 if (!homesize)
1976 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1978 //setup ssh client
1979 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1980 if (sshclient.IsEmpty())
1981 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1983 if(!sshclient.IsEmpty())
1985 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1986 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1988 else
1990 TCHAR sPlink[MAX_PATH] = {0};
1991 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1992 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1993 if (ptr) {
1994 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1995 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1996 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2001 TCHAR sAskPass[MAX_PATH] = {0};
2002 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2003 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2004 if (ptr)
2006 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2007 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2008 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2009 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2013 // add git/bin path to PATH
2015 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
2016 CString str = msysdir;
2017 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
2019 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2020 if (!bFallback)
2021 return FALSE;
2023 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2024 str = msyslocalinstalldir;
2025 str.TrimRight(_T("\\"));
2026 if (str.IsEmpty())
2028 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2029 str = msysinstalldir;
2030 str.TrimRight(_T("\\"));
2032 if ( !str.IsEmpty() )
2034 str += "\\bin";
2035 msysdir=str;
2036 CGit::ms_LastMsysGitDir = str;
2037 msysdir.write();
2039 else
2041 // search PATH if git/bin directory is already present
2042 if ( FindGitPath() )
2044 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2045 m_bInitialized = TRUE;
2046 msysdir = CGit::ms_LastMsysGitDir;
2047 msysdir.write();
2048 return TRUE;
2051 return FALSE;
2054 else
2056 CGit::ms_LastMsysGitDir = str;
2059 // check for git.exe existance (maybe it was deinstalled in the meantime)
2060 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
2062 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2063 return FALSE;
2066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2067 // Configure libgit2 search paths
2068 CString msysGitDir;
2069 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
2070 msysGitDir.ReleaseBuffer();
2071 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
2072 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2073 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2074 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 };
2075 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2076 CString msysGitTemplateDir;
2077 if (!ms_bCygwinGit)
2078 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
2079 else
2080 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\usr\\share\\git-core\\templates"));
2081 msysGitTemplateDir.ReleaseBuffer();
2082 SetLibGit2TemplatePath(msysGitTemplateDir);
2084 //set path
2085 _tdupenv_s(&oldpath,&size,_T("PATH"));
2087 CString path;
2088 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
2090 m_Environment.SetEnv(_T("PATH"), path);
2092 CString str1 = m_Environment.GetEnv(_T("PATH"));
2094 CString sOldPath = oldpath;
2095 free(oldpath);
2097 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2098 // register filter only once
2099 if (!git_filter_lookup("filter"))
2101 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir + L"\\sh.exe\"", &m_Environment[0]), GIT_FILTER_DRIVER_PRIORITY))
2102 return FALSE;
2104 #endif
2106 m_bInitialized = TRUE;
2107 return true;
2110 CString CGit::GetHomeDirectory() const
2112 const wchar_t * homeDir = wget_windows_home_directory();
2113 return CString(homeDir, (int)wcslen(homeDir));
2116 CString CGit::GetGitLocalConfig() const
2118 CString path;
2119 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2120 path += _T("config");
2121 return path;
2124 CStringA CGit::GetGitPathStringA(const CString &path)
2126 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2129 CString CGit::GetGitGlobalConfig() const
2131 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2134 CString CGit::GetGitGlobalXDGConfigPath() const
2136 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2139 CString CGit::GetGitGlobalXDGConfig() const
2141 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2144 CString CGit::GetGitSystemConfig() const
2146 const wchar_t * systemConfig = wget_msysgit_etc();
2147 return CString(systemConfig, (int)wcslen(systemConfig));
2150 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2152 CString out;
2153 CString cmd;
2154 cmd=_T("git.exe rev-parse --verify HEAD");
2156 if(Run(cmd,&out,CP_UTF8))
2157 return FALSE;
2159 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2160 if(Run(cmd,&out,CP_UTF8))
2161 return FALSE;
2163 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2164 if(Run(cmd,&out,CP_UTF8))
2165 return FALSE;
2167 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2168 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2169 return FALSE;
2171 return TRUE;
2173 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2175 int ret;
2176 for (int i = 0; i < list.GetCount(); ++i)
2178 ret = Revert(commit, (CTGitPath&)list[i], err);
2179 if(ret)
2180 return ret;
2182 return 0;
2184 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2186 CString cmd;
2188 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2190 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2192 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2193 return -1;
2195 CString force;
2196 // if the filenames only differ in case, we have to pass "-f"
2197 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2198 force = _T("-f ");
2199 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2200 if (Run(cmd, &err, CP_UTF8))
2201 return -1;
2203 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2204 if (Run(cmd, &err, CP_UTF8))
2205 return -1;
2207 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2208 { //To init git repository, there are not HEAD, so we can use git reset command
2209 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2211 if (Run(cmd, &err, CP_UTF8))
2212 return -1;
2214 else
2216 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2217 if (Run(cmd, &err, CP_UTF8))
2218 return -1;
2221 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2223 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2224 if (Run(cmd, &err, CP_UTF8))
2225 return -1;
2228 return 0;
2231 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2233 BYTE_VECTOR vector;
2235 CString cmd;
2236 if(path)
2237 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2238 else
2239 cmd=_T("git.exe ls-files -u -t -z");
2241 if (Run(cmd, &vector))
2243 return -1;
2246 if (list.ParserFromLsFile(vector))
2247 return -1;
2249 return 0;
2252 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2254 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2256 CAutoRepository repo(GetGitRepository());
2257 if (!repo)
2258 return false;
2260 CGitHash fromHash, toHash, baseHash;
2261 if (GetHash(repo, toHash, FixBranchName(to)))
2262 return false;
2264 if (GetHash(repo, fromHash, FixBranchName(from)))
2265 return false;
2267 git_oid baseOid;
2268 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2269 return false;
2271 baseHash = baseOid.id;
2273 if (commonAncestor)
2274 *commonAncestor = baseHash;
2276 return fromHash == baseHash;
2278 // else
2279 CString base;
2280 CGitHash basehash,hash;
2281 CString cmd, err;
2282 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2284 if (Run(cmd, &base, &err, CP_UTF8))
2286 return false;
2288 basehash = base.Trim();
2290 GetHash(hash, from);
2292 if (commonAncestor)
2293 *commonAncestor = basehash;
2295 return hash == basehash;
2298 unsigned int CGit::Hash2int(const CGitHash &hash)
2300 int ret=0;
2301 for (int i = 0; i < 4; ++i)
2303 ret = ret << 8;
2304 ret |= hash.m_hash[i];
2306 return ret;
2309 int CGit::RefreshGitIndex()
2311 if(g_Git.m_IsUseGitDLL)
2313 CAutoLocker lock(g_Git.m_critGitDllSec);
2316 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2318 }catch(...)
2320 return -1;
2324 else
2326 CString cmd,output;
2327 cmd=_T("git.exe update-index --refresh");
2328 return Run(cmd, &output, CP_UTF8);
2332 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2334 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2336 CAutoRepository repo(GetGitRepository());
2337 if (!repo)
2338 return -1;
2340 CGitHash hash;
2341 if (GetHash(repo, hash, Refname))
2342 return -1;
2344 CAutoCommit commit;
2345 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2346 return -1;
2348 CAutoTree tree;
2349 if (git_commit_tree(tree.GetPointer(), commit))
2350 return -1;
2352 CAutoTreeEntry entry;
2353 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2354 return -1;
2356 CAutoBlob blob;
2357 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2358 return -1;
2360 FILE *file = nullptr;
2361 _tfopen_s(&file, outputfile, _T("w"));
2362 if (file == nullptr)
2364 giterr_set_str(GITERR_NONE, "Could not create file.");
2365 return -1;
2367 CAutoBuf buf;
2368 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2370 fclose(file);
2371 return -1;
2373 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2375 giterr_set_str(GITERR_OS, "Could not write to file.");
2376 fclose(file);
2378 return -1;
2380 fclose(file);
2382 return 0;
2384 else if (g_Git.m_IsUseGitDLL)
2386 CAutoLocker lock(g_Git.m_critGitDllSec);
2389 g_Git.CheckAndInitDll();
2390 CStringA ref, patha, outa;
2391 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2392 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2393 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2394 ::DeleteFile(outputfile);
2395 return git_checkout_file(ref, patha, outa);
2398 catch (const char * msg)
2400 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2401 return -1;
2403 catch (...)
2405 gitLastErr = L"An unknown gitdll.dll error occurred.";
2406 return -1;
2409 else
2411 CString cmd;
2412 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2413 return RunLogFile(cmd, outputfile, &gitLastErr);
2416 void CEnvironment::CopyProcessEnvironment()
2418 TCHAR *porig = GetEnvironmentStrings();
2419 TCHAR *p = porig;
2420 while(*p !=0 || *(p+1) !=0)
2421 this->push_back(*p++);
2423 push_back(_T('\0'));
2424 push_back(_T('\0'));
2426 FreeEnvironmentStrings(porig);
2429 CString CEnvironment::GetEnv(const TCHAR *name)
2431 CString str;
2432 for (size_t i = 0; i < size(); ++i)
2434 str = &(*this)[i];
2435 int start =0;
2436 CString sname = str.Tokenize(_T("="),start);
2437 if(sname.CompareNoCase(name) == 0)
2439 return &(*this)[i+start];
2441 i+=str.GetLength();
2443 return _T("");
2446 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2448 unsigned int i;
2449 for (i = 0; i < size(); ++i)
2451 CString str = &(*this)[i];
2452 int start =0;
2453 CString sname = str.Tokenize(_T("="),start);
2454 if(sname.CompareNoCase(name) == 0)
2456 break;
2458 i+=str.GetLength();
2461 if(i == size())
2463 if (!value) // as we haven't found the variable we want to remove, just return
2464 return;
2465 i -= 1; // roll back terminate \0\0
2466 this->push_back(_T('\0'));
2469 CEnvironment::iterator it;
2470 it=this->begin();
2471 it += i;
2473 while(*it && i<size())
2475 this->erase(it);
2476 it=this->begin();
2477 it += i;
2480 if (value == nullptr) // remove the variable
2482 this->erase(it);
2483 return;
2486 while(*name)
2488 this->insert(it,*name++);
2489 ++i;
2490 it= begin()+i;
2493 this->insert(it, _T('='));
2494 ++i;
2495 it= begin()+i;
2497 while(*value)
2499 this->insert(it,*value++);
2500 ++i;
2501 it= begin()+i;
2506 int CGit::GetGitEncode(TCHAR* configkey)
2508 CString str=GetConfigValue(configkey);
2510 if(str.IsEmpty())
2511 return CP_UTF8;
2513 return CUnicodeUtils::GetCPCode(str);
2517 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2519 GIT_FILE file=0;
2520 int ret=0;
2521 GIT_DIFF diff=0;
2523 CAutoLocker lock(g_Git.m_critGitDllSec);
2527 if(!arg)
2528 diff = GetGitDiff();
2529 else
2530 git_open_diff(&diff, arg);
2532 catch (char* e)
2534 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2535 return -1;
2538 if(diff ==NULL)
2539 return -1;
2541 bool isStat = 0;
2542 if(arg == NULL)
2543 isStat = true;
2544 else
2545 isStat = !!strstr(arg, "stat");
2547 int count=0;
2549 if(hash2 == NULL)
2550 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2551 else
2552 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2554 if(ret)
2555 return -1;
2557 CTGitPath path;
2558 CString strnewname;
2559 CString stroldname;
2561 for (int j = 0; j < count; ++j)
2563 path.Reset();
2564 char *newname;
2565 char *oldname;
2567 strnewname.Empty();
2568 stroldname.Empty();
2570 int mode=0,IsBin=0,inc=0,dec=0;
2571 git_get_diff_file(diff,file,j,&newname,&oldname,
2572 &mode,&IsBin,&inc,&dec);
2574 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2575 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2577 path.SetFromGit(strnewname,&stroldname);
2578 path.ParserAction((BYTE)mode);
2580 if(IsBin)
2582 path.m_StatAdd=_T("-");
2583 path.m_StatDel=_T("-");
2585 else
2587 path.m_StatAdd.Format(_T("%d"),inc);
2588 path.m_StatDel.Format(_T("%d"),dec);
2590 PathList->AddPath(path);
2592 git_diff_flush(diff);
2594 if(arg)
2595 git_close_diff(diff);
2597 return 0;
2600 int CGit::GetShortHASHLength() const
2602 return 7;
2605 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2607 CString str=ref;
2608 CString shortname;
2609 REF_TYPE type = CGit::UNKNOWN;
2611 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2613 type = CGit::LOCAL_BRANCH;
2616 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2618 type = CGit::REMOTE_BRANCH;
2620 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2622 type = CGit::TAG;
2624 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2626 type = CGit::STASH;
2627 shortname=_T("stash");
2629 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2631 if (shortname.Find(_T("good")) == 0)
2633 type = CGit::BISECT_GOOD;
2634 shortname = _T("good");
2637 if (shortname.Find(_T("bad")) == 0)
2639 type = CGit::BISECT_BAD;
2640 shortname = _T("bad");
2643 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2645 type = CGit::NOTES;
2647 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2649 type = CGit::UNKNOWN;
2651 else
2653 type = CGit::UNKNOWN;
2654 shortname = ref;
2657 if(out_type)
2658 *out_type = type;
2660 return shortname;
2663 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2665 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2668 void CGit::SetGit2CredentialCallback(void* callback)
2670 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2673 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2675 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2678 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2680 CString cmd;
2681 if (rev2 == GitRev::GetWorkingCopy())
2682 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2683 else if (rev1 == GitRev::GetWorkingCopy())
2684 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2685 else
2687 CString merge;
2688 if (bMerge)
2689 merge += _T(" -m");
2691 if (bCombine)
2692 merge += _T(" -c");
2694 CString unified;
2695 if (diffContext >= 0)
2696 unified.Format(_T(" --unified=%d"), diffContext);
2697 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2700 if (!path.IsEmpty())
2702 cmd += _T(" \"");
2703 cmd += path.GetGitPathString();
2704 cmd += _T("\"");
2707 return cmd;
2710 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2712 ATLASSERT(payload && text);
2713 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2714 fwrite("\n", 1, 1, (FILE *)payload);
2717 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2719 ATLASSERT(payload && line);
2720 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2721 fwrite(&line->origin, 1, 1, (FILE *)payload);
2722 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2723 return 0;
2726 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2728 ATLASSERT(repo && identifier && tree);
2730 /* try to resolve identifier */
2731 CAutoObject obj;
2732 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2733 return -1;
2735 if (obj == nullptr)
2736 return GIT_ENOTFOUND;
2738 int err = 0;
2739 switch (git_object_type(obj))
2741 case GIT_OBJ_TREE:
2742 *tree = (git_tree *)obj.Detach();
2743 break;
2744 case GIT_OBJ_COMMIT:
2745 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2746 break;
2747 default:
2748 err = GIT_ENOTFOUND;
2751 return err;
2754 /* use libgit2 get unified diff */
2755 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 */)
2757 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2758 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2760 CAutoRepository repo(g_Git.GetGitRepository());
2761 if (!repo)
2762 return -1;
2764 int isHeadOrphan = git_repository_head_unborn(repo);
2765 if (isHeadOrphan == 1)
2766 return 0;
2767 else if (isHeadOrphan != 0)
2768 return -1;
2770 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2771 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2772 char *buf = pathA.GetBuffer();
2773 if (!pathA.IsEmpty())
2775 opts.pathspec.strings = &buf;
2776 opts.pathspec.count = 1;
2778 CAutoDiff diff;
2780 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2782 CAutoTree t1;
2783 CAutoDiff diff2;
2785 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2786 return -1;
2788 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2789 return -1;
2791 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2792 return -1;
2794 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2795 return -1;
2797 if (git_diff_merge(diff, diff2))
2798 return -1;
2800 else
2802 if (tree1.IsEmpty() && tree2.IsEmpty())
2803 return -1;
2805 if (tree1.IsEmpty())
2807 tree1 = tree2;
2808 tree2.Empty();
2811 CAutoTree t1;
2812 CAutoTree t2;
2813 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2814 return -1;
2816 if (tree2.IsEmpty())
2818 /* don't check return value, there are not parent commit at first commit*/
2819 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2821 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2822 return -1;
2823 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2824 return -1;
2827 CAutoDiffStats stats;
2828 if (git_diff_get_stats(stats.GetPointer(), diff))
2829 return -1;
2830 CAutoBuf statBuf;
2831 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2832 return -1;
2833 statCallback(statBuf, data);
2835 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2837 CAutoPatch patch;
2838 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2839 return -1;
2841 if (git_patch_print(patch, callback, data))
2842 return -1;
2845 pathA.ReleaseBuffer();
2847 return 0;
2850 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2852 if (UsingLibGit2(GIT_CMD_DIFF))
2854 FILE *file = nullptr;
2855 _tfopen_s(&file, patchfile, _T("w"));
2856 if (file == nullptr)
2857 return -1;
2858 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
2859 fclose(file);
2860 return ret;
2862 else
2864 CString cmd;
2865 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2866 return RunLogFile(cmd, patchfile, &gitLastErr);
2870 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
2872 ATLASSERT(payload && text);
2873 CStringA *str = (CStringA*) payload;
2874 str->Append(text->ptr, (int)text->size);
2875 str->AppendChar('\n');
2878 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2880 ATLASSERT(payload && line);
2881 CStringA *str = (CStringA*) payload;
2882 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2883 str->Append(&line->origin, 1);
2884 str->Append(line->content, (int)line->content_len);
2885 return 0;
2888 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2890 if (UsingLibGit2(GIT_CMD_DIFF))
2891 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
2892 else
2894 CString cmd;
2895 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2896 BYTE_VECTOR vector;
2897 int ret = Run(cmd, &vector);
2898 if (!vector.empty())
2900 vector.push_back(0); // vector is not NUL terminated
2901 buffer->Append((char *)&vector[0]);
2903 return ret;
2907 int CGit::GitRevert(int parent, const CGitHash &hash)
2909 if (UsingLibGit2(GIT_CMD_REVERT))
2911 CAutoRepository repo(GetGitRepository());
2912 if (!repo)
2913 return -1;
2915 CAutoCommit commit;
2916 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2917 return -1;
2919 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2920 revert_opts.mainline = parent;
2921 int result = git_revert(repo, commit, &revert_opts);
2923 return !result ? 0 : -1;
2925 else
2927 CString cmd, merge;
2928 if (parent)
2929 merge.Format(_T("-m %d "), parent);
2930 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2931 gitLastErr = cmd + _T("\n");
2932 if (Run(cmd, &gitLastErr, CP_UTF8))
2934 return -1;
2936 else
2938 gitLastErr.Empty();
2939 return 0;
2944 int CGit::DeleteRef(const CString& reference)
2946 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2948 CAutoRepository repo(GetGitRepository());
2949 if (!repo)
2950 return -1;
2952 CStringA refA;
2953 if (reference.Right(3) == _T("^{}"))
2954 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2955 else
2956 refA = CUnicodeUtils::GetUTF8(reference);
2958 CAutoReference ref;
2959 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2960 return -1;
2962 int result = -1;
2963 if (git_reference_is_tag(ref))
2964 result = git_tag_delete(repo, git_reference_shorthand(ref));
2965 else if (git_reference_is_branch(ref))
2966 result = git_branch_delete(ref);
2967 else if (git_reference_is_remote(ref))
2968 result = git_branch_delete(ref);
2969 else
2970 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2972 return result;
2974 else
2976 CString cmd, shortname;
2977 if (GetShortName(reference, shortname, _T("refs/heads/")))
2978 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2979 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2980 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2981 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2982 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2983 else
2985 gitLastErr = L"unsupported reference type: " + reference;
2986 return -1;
2989 if (Run(cmd, &gitLastErr, CP_UTF8))
2990 return -1;
2992 gitLastErr.Empty();
2993 return 0;
2997 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2999 if (PathFileExists(filename))
3001 FILE *pFile = nullptr;
3002 _tfopen_s(&pFile, filename, _T("r"));
3003 if (pFile)
3005 CStringA str;
3008 char s[8196] = { 0 };
3009 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3010 if (read == 0)
3011 break;
3012 str += CStringA(s, read);
3013 } while (true);
3014 fclose(pFile);
3015 msg = CUnicodeUtils::GetUnicode(str);
3016 msg.Replace(_T("\r\n"), _T("\n"));
3017 msg.TrimRight(_T("\n"));
3018 msg += _T("\n");
3020 else
3021 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3022 return true; // load no further files
3024 return false;