Fix reverting to parent for renamed file
[TortoiseGit.git] / src / Git / Git.cpp
blob4285fe6768eed3386cf36d053938e409fdbac0e8
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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;
298 PROCESS_INFORMATION pi;
299 si.cb=sizeof(STARTUPINFO);
300 GetStartupInfo(&si);
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(cmd.Find(_T("git")) == 0)
332 int firstSpace = cmd.Find(_T(" "));
333 if (firstSpace > 0)
334 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
335 else
336 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
339 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
340 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
342 CString err = CFormatMessageWrapper();
343 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
344 return TGIT_GIT_ERROR_CREATE_PROCESS;
347 m_CurrentGitPi = pi;
349 if(piOut)
350 *piOut=pi;
351 if(hReadOut)
352 *hReadOut = hRead.Detach();
353 if(hErrReadOut)
354 *hErrReadOut = hReadErr.Detach();
355 return 0;
358 //Must use sperate function to convert ANSI str to union code string
359 //Becuase A2W use stack as internal convert buffer.
360 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
362 if(str == NULL)
363 return ;
365 int len ;
366 if(length<0)
367 len = (int)strlen((const char*)p);
368 else
369 len=length;
370 if (len == 0)
371 return;
372 int currentContentLen = str->GetLength();
373 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
374 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
375 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
378 // This method was originally used to check for orphaned branches
379 BOOL CGit::CanParseRev(CString ref)
381 if (ref.IsEmpty())
382 ref = _T("HEAD");
384 CString cmdout;
385 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
387 return FALSE;
389 if(cmdout.IsEmpty())
390 return FALSE;
392 return TRUE;
395 // Checks if we have an orphaned HEAD
396 BOOL CGit::IsInitRepos()
398 CGitHash hash;
399 // handle error on reading HEAD hash as init repo
400 if (GetHash(hash, _T("HEAD")) != 0)
401 return TRUE;
402 return hash.IsEmpty() ? TRUE : FALSE;
405 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
407 PASYNCREADSTDERRTHREADARGS pDataArray;
408 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
410 DWORD readnumber;
411 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
412 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
414 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
415 break;
418 return 0;
421 int CGit::Run(CGitCall* pcall)
423 PROCESS_INFORMATION pi;
424 CAutoGeneralHandle hRead, hReadErr;
425 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
426 return TGIT_GIT_ERROR_CREATE_PROCESS;
428 CAutoGeneralHandle piThread(pi.hThread);
429 CAutoGeneralHandle piProcess(pi.hProcess);
431 ASYNCREADSTDERRTHREADARGS threadArguments;
432 threadArguments.fileHandle = hReadErr;
433 threadArguments.pcall = pcall;
434 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
436 DWORD readnumber;
437 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
438 bool bAborted=false;
439 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
441 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
442 if(!bAborted)//For now, flush output when command aborted.
443 if(pcall->OnOutputData(data,readnumber))
444 bAborted=true;
446 if(!bAborted)
447 pcall->OnEnd();
449 if (thread)
450 WaitForSingleObject(thread, INFINITE);
452 WaitForSingleObject(pi.hProcess, INFINITE);
453 DWORD exitcode =0;
455 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
457 CString err = CFormatMessageWrapper();
458 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
459 return TGIT_GIT_ERROR_GET_EXIT_CODE;
461 else
462 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
464 return exitcode;
466 class CGitCall_ByteVector : public CGitCall
468 public:
469 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
470 virtual bool OnOutputData(const BYTE* data, size_t size)
472 if (!m_pvector || size == 0)
473 return false;
474 size_t oldsize=m_pvector->size();
475 m_pvector->resize(m_pvector->size()+size);
476 memcpy(&*(m_pvector->begin()+oldsize),data,size);
477 return false;
479 virtual bool OnOutputErrData(const BYTE* data, size_t size)
481 if (!m_pvectorErr || size == 0)
482 return false;
483 size_t oldsize = m_pvectorErr->size();
484 m_pvectorErr->resize(m_pvectorErr->size() + size);
485 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
486 return false;
488 BYTE_VECTOR* m_pvector;
489 BYTE_VECTOR* m_pvectorErr;
492 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
494 CGitCall_ByteVector call(cmd, vector, vectorErr);
495 return Run(&call);
497 int CGit::Run(CString cmd, CString* output, int code)
499 CString err;
500 int ret;
501 ret = Run(cmd, output, &err, code);
503 if (output && !err.IsEmpty())
505 if (!output->IsEmpty())
506 *output += _T("\n");
507 *output += err;
510 return ret;
512 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
514 BYTE_VECTOR vector, vectorErr;
515 int ret;
516 if (outputErr)
517 ret = Run(cmd, &vector, &vectorErr);
518 else
519 ret = Run(cmd, &vector);
521 vector.push_back(0);
522 StringAppend(output, &(vector[0]), code);
524 if (outputErr)
526 vectorErr.push_back(0);
527 StringAppend(outputErr, &(vectorErr[0]), code);
530 return ret;
533 class CGitCallCb : public CGitCall
535 public:
536 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
538 virtual bool OnOutputData(const BYTE* data, size_t size) override
540 // Add data
541 if (size == 0)
542 return false;
543 int oldEndPos = m_buffer.GetLength();
544 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
545 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
547 // Break into lines and feed to m_recv
548 int eolPos;
549 while ((eolPos = m_buffer.Find('\n')) >= 0)
551 m_recv(m_buffer.Left(eolPos));
552 m_buffer = m_buffer.Mid(eolPos + 1);
554 return false;
557 virtual bool OnOutputErrData(const BYTE*, size_t) override
559 return false; // Ignore error output for now
562 virtual void OnEnd() override
564 if (!m_buffer.IsEmpty())
565 m_recv(m_buffer);
566 m_buffer.Empty(); // Just for sure
569 private:
570 GitReceiverFunc m_recv;
571 CStringA m_buffer;
574 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
576 CGitCallCb call(cmd, recv);
577 return Run(&call);
580 CString CGit::GetUserName(void)
582 CEnvironment env;
583 env.CopyProcessEnvironment();
584 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
585 if (!envname.IsEmpty())
586 return envname;
587 return GetConfigValue(L"user.name");
589 CString CGit::GetUserEmail(void)
591 CEnvironment env;
592 env.CopyProcessEnvironment();
593 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
594 if (!envmail.IsEmpty())
595 return envmail;
597 return GetConfigValue(L"user.email");
600 CString CGit::GetConfigValue(const CString& name)
602 CString configValue;
603 int start = 0;
604 if(this->m_IsUseGitDLL)
606 CAutoLocker lock(g_Git.m_critGitDllSec);
610 CheckAndInitDll();
611 }catch(...)
614 CStringA key, value;
615 key = CUnicodeUtils::GetUTF8(name);
619 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
620 return CString();
622 catch (const char *msg)
624 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
625 return CString();
628 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
629 return configValue.Tokenize(_T("\n"),start);
631 else
633 CString cmd;
634 cmd.Format(L"git.exe config %s", name);
635 Run(cmd, &configValue, nullptr, CP_UTF8);
636 return configValue.Tokenize(_T("\n"),start);
640 bool CGit::GetConfigValueBool(const CString& name)
642 CString configValue = GetConfigValue(name);
643 configValue.MakeLower();
644 configValue.Trim();
645 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
646 return true;
647 else
648 return false;
651 int CGit::GetConfigValueInt32(const CString& name, int def)
653 CString configValue = GetConfigValue(name);
654 int value = def;
655 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
656 return value;
657 return def;
660 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
662 if(this->m_IsUseGitDLL)
664 CAutoLocker lock(g_Git.m_critGitDllSec);
668 CheckAndInitDll();
670 }catch(...)
673 CStringA keya, valuea;
674 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
675 valuea = CUnicodeUtils::GetUTF8(value);
679 return [=]() { return get_set_config(keya, valuea, type); }();
681 catch (const char *msg)
683 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
684 return -1;
687 else
689 CString cmd;
690 CString option;
691 switch(type)
693 case CONFIG_GLOBAL:
694 option = _T("--global");
695 break;
696 case CONFIG_SYSTEM:
697 option = _T("--system");
698 break;
699 default:
700 break;
702 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
703 CString out;
704 if (Run(cmd, &out, nullptr, CP_UTF8))
706 return -1;
709 return 0;
712 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
714 if(this->m_IsUseGitDLL)
716 CAutoLocker lock(g_Git.m_critGitDllSec);
720 CheckAndInitDll();
721 }catch(...)
724 CStringA keya;
725 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
729 return [=]() { return get_set_config(keya, nullptr, type); }();
731 catch (const char *msg)
733 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
734 return -1;
737 else
739 CString cmd;
740 CString option;
741 switch(type)
743 case CONFIG_GLOBAL:
744 option = _T("--global");
745 break;
746 case CONFIG_SYSTEM:
747 option = _T("--system");
748 break;
749 default:
750 break;
752 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
753 CString out;
754 if (Run(cmd, &out, nullptr, CP_UTF8))
756 return -1;
759 return 0;
762 CString CGit::GetCurrentBranch(bool fallback)
764 CString output;
765 //Run(_T("git.exe branch"),&branch);
767 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
768 if (result != 0 && ((result == 1 && !fallback) || result != 1))
770 return _T("(no branch)");
772 else
773 return output;
777 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
779 if (localBranch.IsEmpty())
780 return;
782 CString configName;
783 configName.Format(L"branch.%s.remote", localBranch);
784 pullRemote = GetConfigValue(configName);
786 //Select pull-branch from current branch
787 configName.Format(L"branch.%s.merge", localBranch);
788 pullBranch = StripRefName(GetConfigValue(configName));
791 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
793 CString refName;
794 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
795 return;
796 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
799 CString CGit::GetFullRefName(const CString& shortRefName)
801 CString refName;
802 CString cmd;
803 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
804 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
805 return CString();//Error
806 int iStart = 0;
807 return refName.Tokenize(L"\n", iStart);
810 CString CGit::StripRefName(CString refName)
812 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
813 refName = refName.Mid(11);
814 else if(wcsncmp(refName, L"refs/", 5) == 0)
815 refName = refName.Mid(5);
816 int start =0;
817 return refName.Tokenize(_T("\n"),start);
820 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
822 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
824 if ( sProjectRoot.IsEmpty() )
825 return -1;
827 CString sDotGitPath;
828 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
829 return -1;
831 CString sHeadFile = sDotGitPath + _T("HEAD");
833 FILE *pFile;
834 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
836 if (!pFile)
838 return -1;
841 char s[256] = {0};
842 fgets(s, sizeof(s), pFile);
844 fclose(pFile);
846 const char *pfx = "ref: refs/heads/";
847 const int len = 16;//strlen(pfx)
849 if ( !strncmp(s, pfx, len) )
851 //# We're on a branch. It might not exist. But
852 //# HEAD looks good enough to be a branch.
853 CStringA utf8Branch(s + len);
854 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
855 sBranchOut.TrimRight(_T(" \r\n\t"));
857 if ( sBranchOut.IsEmpty() )
858 return -1;
860 else if (fallback)
862 CStringA utf8Hash(s);
863 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
864 unicodeHash.TrimRight(_T(" \r\n\t"));
865 if (CGitHash::IsValidSHA1(unicodeHash))
866 sBranchOut = unicodeHash;
867 else
868 //# Assume this is a detached head.
869 sBranchOut = _T("HEAD");
870 return 1;
872 else
874 //# Assume this is a detached head.
875 sBranchOut = "HEAD";
877 return 1;
880 return 0;
883 int CGit::BuildOutputFormat(CString &format,bool IsFull)
885 CString log;
886 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
887 format += log;
888 if(IsFull)
890 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
891 format += log;
892 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
893 format += log;
894 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
895 format += log;
896 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
897 format += log;
898 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
899 format += log;
900 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
901 format += log;
902 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
903 format += log;
906 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
907 format += log;
908 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
909 format += log;
910 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
911 format += log;
913 if(IsFull)
915 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
916 format += log;
918 return 0;
921 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
922 CFilterData *Filter)
924 CString cmd;
925 CString num;
926 CString since;
928 CString file = _T(" --");
930 if(path)
931 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
933 if(count>0)
934 num.Format(_T("-n%d"),count);
936 CString param;
938 if(mask& LOG_INFO_STAT )
939 param += _T(" --numstat ");
940 if(mask& LOG_INFO_FILESTATE)
941 param += _T(" --raw ");
943 if(mask& LOG_INFO_FULLHISTORY)
944 param += _T(" --full-history ");
946 if(mask& LOG_INFO_BOUNDARY)
947 param += _T(" --left-right --boundary ");
949 if(mask& CGit::LOG_INFO_ALL_BRANCH)
950 param += _T(" --all ");
952 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
953 param += _T(" --branches ");
955 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
956 param += _T(" -C ");
958 if(mask& CGit::LOG_INFO_DETECT_RENAME )
959 param += _T(" -M ");
961 if(mask& CGit::LOG_INFO_FIRST_PARENT )
962 param += _T(" --first-parent ");
964 if(mask& CGit::LOG_INFO_NO_MERGE )
965 param += _T(" --no-merges ");
967 if(mask& CGit::LOG_INFO_FOLLOW)
968 param += _T(" --follow ");
970 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
971 param += _T(" -c ");
973 if(mask& CGit::LOG_INFO_FULL_DIFF)
974 param += _T(" --full-diff ");
976 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
977 param += _T(" --simplify-by-decoration ");
979 param += range;
981 CString st1,st2;
983 if( Filter && (Filter->m_From != -1))
985 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
986 param += st1;
989 if( Filter && (Filter->m_To != -1))
991 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
992 param += st2;
995 bool isgrep = false;
996 if( Filter && (!Filter->m_Author.IsEmpty()))
998 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
999 param += st1;
1000 isgrep = true;
1003 if( Filter && (!Filter->m_Committer.IsEmpty()))
1005 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
1006 param += st1;
1007 isgrep = true;
1010 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
1012 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
1013 param += st1;
1014 isgrep = true;
1017 if(Filter && isgrep)
1019 if(!Filter->m_IsRegex)
1020 param += _T(" --fixed-strings ");
1022 param += _T(" --regexp-ignore-case --extended-regexp ");
1025 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
1026 if (logOrderBy == LOG_ORDER_TOPOORDER)
1027 param += _T(" --topo-order");
1028 else if (logOrderBy == LOG_ORDER_DATEORDER)
1029 param += _T(" --date-order");
1031 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
1032 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
1033 else
1035 CString log;
1036 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
1037 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1038 num,param,log);
1041 cmd += file;
1043 return cmd;
1045 #define BUFSIZE 512
1046 void GetTempPath(CString &path)
1048 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1049 DWORD dwRetVal;
1050 DWORD dwBufSize=BUFSIZE;
1051 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1052 lpPathBuffer); // buffer for path
1053 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1055 path=_T("");
1057 path.Format(_T("%s"),lpPathBuffer);
1059 CString GetTempFile()
1061 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1062 DWORD dwRetVal;
1063 DWORD dwBufSize=BUFSIZE;
1064 TCHAR szTempName[BUFSIZE] = { 0 };
1065 UINT uRetVal;
1067 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1068 lpPathBuffer); // buffer for path
1069 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1071 return _T("");
1073 // Create a temporary file.
1074 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1075 TEXT("Patch"), // temp file name prefix
1076 0, // create unique name
1077 szTempName); // buffer for name
1080 if (uRetVal == 0)
1082 return _T("");
1085 return CString(szTempName);
1089 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1091 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1092 if (result == 0) return 0;
1093 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1095 if (lpBuffer)
1096 lpBuffer[0] = '\0';
1097 return result + 13;
1100 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1101 CreateDirectory(lpBuffer, NULL);
1103 return result + 13;
1106 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1108 STARTUPINFO si;
1109 PROCESS_INFORMATION pi;
1110 si.cb=sizeof(STARTUPINFO);
1111 GetStartupInfo(&si);
1113 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1114 psa.bInheritHandle=TRUE;
1116 HANDLE hReadErr, hWriteErr;
1117 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1119 CString err = CFormatMessageWrapper();
1120 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1121 return TGIT_GIT_ERROR_OPEN_PIP;
1124 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1125 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1127 if (houtfile == INVALID_HANDLE_VALUE)
1129 CString err = CFormatMessageWrapper();
1130 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1131 CloseHandle(hReadErr);
1132 CloseHandle(hWriteErr);
1133 return TGIT_GIT_ERROR_OPEN_PIP;
1136 si.wShowWindow = SW_HIDE;
1137 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1138 si.hStdOutput = houtfile;
1139 si.hStdError = hWriteErr;
1141 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1142 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1144 if(cmd.Find(_T("git")) == 0)
1145 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1147 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1148 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1150 CString err = CFormatMessageWrapper();
1151 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1152 stdErr = &err;
1153 CloseHandle(hReadErr);
1154 CloseHandle(hWriteErr);
1155 CloseHandle(houtfile);
1156 return TGIT_GIT_ERROR_CREATE_PROCESS;
1159 BYTE_VECTOR stderrVector;
1160 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1161 HANDLE thread;
1162 ASYNCREADSTDERRTHREADARGS threadArguments;
1163 threadArguments.fileHandle = hReadErr;
1164 threadArguments.pcall = &pcall;
1165 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1167 WaitForSingleObject(pi.hProcess,INFINITE);
1169 CloseHandle(hWriteErr);
1170 CloseHandle(hReadErr);
1172 if (thread)
1173 WaitForSingleObject(thread, INFINITE);
1175 stderrVector.push_back(0);
1176 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1178 DWORD exitcode = 0;
1179 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1181 CString err = CFormatMessageWrapper();
1182 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1183 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1185 else
1186 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1188 CloseHandle(pi.hThread);
1189 CloseHandle(pi.hProcess);
1190 CloseHandle(houtfile);
1191 return exitcode;
1194 git_repository * CGit::GetGitRepository() const
1196 git_repository * repo = nullptr;
1197 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1198 return repo;
1201 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1203 ATLASSERT(repo);
1205 // no need to parse a ref if it's already a 40-byte hash
1206 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1208 hash = CGitHash(friendname);
1209 return 0;
1212 int isHeadOrphan = git_repository_head_unborn(repo);
1213 if (isHeadOrphan != 0)
1215 hash.Empty();
1216 if (isHeadOrphan == 1)
1217 return 0;
1218 else
1219 return -1;
1222 CAutoObject gitObject;
1223 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1224 return -1;
1226 const git_oid * oid = git_object_id(gitObject);
1227 if (!oid)
1228 return -1;
1230 hash = CGitHash((char *)oid->id);
1232 return 0;
1235 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1237 // no need to parse a ref if it's already a 40-byte hash
1238 if (CGitHash::IsValidSHA1(friendname))
1240 hash = CGitHash(friendname);
1241 return 0;
1244 if (m_IsUseLibGit2)
1246 CAutoRepository repo(GetGitRepository());
1247 if (!repo)
1248 return -1;
1250 return GetHash(repo, hash, friendname, true);
1252 else
1254 CString cmd;
1255 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1256 gitLastErr.Empty();
1257 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1258 hash = CGitHash(gitLastErr.Trim());
1259 if (ret == 0)
1260 gitLastErr.Empty();
1261 return ret;
1265 int CGit::GetInitAddList(CTGitPathList &outputlist)
1267 CString cmd;
1268 BYTE_VECTOR cmdout;
1270 cmd=_T("git.exe ls-files -s -t -z");
1271 outputlist.Clear();
1272 if (Run(cmd, &cmdout))
1273 return -1;
1275 if (outputlist.ParserFromLsFile(cmdout))
1276 return -1;
1277 for(int i = 0; i < outputlist.GetCount(); ++i)
1278 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1280 return 0;
1282 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1284 CString cmd;
1285 CString ignore;
1286 if (ignoreSpaceAtEol)
1287 ignore += _T(" --ignore-space-at-eol");
1288 if (ignoreSpaceChange)
1289 ignore += _T(" --ignore-space-change");
1290 if (ignoreAllSpace)
1291 ignore += _T(" --ignore-all-space");
1292 if (ignoreBlankLines)
1293 ignore += _T(" --ignore-blank-lines");
1295 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1297 //rev1=+_T("");
1298 if(rev1 == GIT_REV_ZERO)
1299 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1300 else
1301 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1303 else
1305 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1308 BYTE_VECTOR out;
1309 if (Run(cmd, &out))
1310 return -1;
1312 outputlist.ParserFromLog(out);
1314 return 0;
1317 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1319 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1320 CString str;
1321 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1322 list->push_back(str);
1323 return 0;
1326 int CGit::GetTagList(STRING_VECTOR &list)
1328 if (this->m_IsUseLibGit2)
1330 CAutoRepository repo(GetGitRepository());
1331 if (!repo)
1332 return -1;
1334 CAutoStrArray tag_names;
1336 if (git_tag_list(tag_names, repo))
1337 return -1;
1339 for (size_t i = 0; i < tag_names->count; ++i)
1341 CStringA tagName(tag_names->strings[i]);
1342 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1345 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1347 return 0;
1349 else
1351 CString cmd, output;
1352 cmd=_T("git.exe tag -l");
1353 int ret = Run(cmd, &output, NULL, CP_UTF8);
1354 if(!ret)
1356 int pos=0;
1357 CString one;
1358 while( pos>=0 )
1360 one=output.Tokenize(_T("\n"),pos);
1361 if (!one.IsEmpty())
1362 list.push_back(one);
1364 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1366 return ret;
1370 CString CGit::GetGitLastErr(const CString& msg)
1372 if (this->m_IsUseLibGit2)
1373 return GetLibGit2LastErr(msg);
1374 else if (gitLastErr.IsEmpty())
1375 return msg + _T("\nUnknown git.exe error.");
1376 else
1378 CString lastError = gitLastErr;
1379 gitLastErr.Empty();
1380 return msg + _T("\n") + lastError;
1384 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1386 if (UsingLibGit2(cmd))
1387 return GetLibGit2LastErr(msg);
1388 else if (gitLastErr.IsEmpty())
1389 return msg + _T("\nUnknown git.exe error.");
1390 else
1392 CString lastError = gitLastErr;
1393 gitLastErr.Empty();
1394 return msg + _T("\n") + lastError;
1398 CString CGit::GetLibGit2LastErr()
1400 const git_error *libgit2err = giterr_last();
1401 if (libgit2err)
1403 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1404 giterr_clear();
1405 return _T("libgit2 returned: ") + lastError;
1407 else
1408 return _T("An error occoured in libgit2, but no message is available.");
1411 CString CGit::GetLibGit2LastErr(const CString& msg)
1413 if (!msg.IsEmpty())
1414 return msg + _T("\n") + GetLibGit2LastErr();
1415 return GetLibGit2LastErr();
1418 CString CGit::FixBranchName_Mod(CString& branchName)
1420 if(branchName == "FETCH_HEAD")
1421 branchName = DerefFetchHead();
1422 return branchName;
1425 CString CGit::FixBranchName(const CString& branchName)
1427 CString tempBranchName = branchName;
1428 FixBranchName_Mod(tempBranchName);
1429 return tempBranchName;
1432 bool CGit::IsBranchTagNameUnique(const CString& name)
1434 if (m_IsUseLibGit2)
1436 CAutoRepository repo(GetGitRepository());
1437 if (!repo)
1438 return true; // TODO: optimize error reporting
1440 CAutoReference tagRef;
1441 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1442 return true;
1444 CAutoReference branchRef;
1445 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1446 return true;
1448 return false;
1450 // else
1451 CString output;
1453 CString cmd;
1454 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1455 int ret = Run(cmd, &output, NULL, CP_UTF8);
1456 if (!ret)
1458 int i = 0, pos = 0;
1459 while (pos >= 0)
1461 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1462 ++i;
1464 if (i >= 2)
1465 return false;
1468 return true;
1471 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1473 if (m_IsUseLibGit2)
1475 CAutoRepository repo(GetGitRepository());
1476 if (!repo)
1477 return false; // TODO: optimize error reporting
1479 CString prefix;
1480 if (isBranch)
1481 prefix = _T("refs/heads/");
1482 else
1483 prefix = _T("refs/tags/");
1485 CAutoReference ref;
1486 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1487 return false;
1489 return true;
1491 // else
1492 CString cmd, output;
1494 cmd = _T("git.exe show-ref ");
1495 if (isBranch)
1496 cmd += _T("--heads ");
1497 else
1498 cmd += _T("--tags ");
1500 cmd += _T("refs/heads/") + name;
1501 cmd += _T(" refs/tags/") + name;
1503 int ret = Run(cmd, &output, NULL, CP_UTF8);
1504 if (!ret)
1506 if (!output.IsEmpty())
1507 return true;
1510 return false;
1513 CString CGit::DerefFetchHead()
1515 CString dotGitPath;
1516 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1517 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1518 int forMergeLineCount = 0;
1519 std::string line;
1520 std::string hashToReturn;
1521 while(getline(fetchHeadFile, line))
1523 //Tokenize this line
1524 std::string::size_type prevPos = 0;
1525 std::string::size_type pos = line.find('\t');
1526 if(pos == std::string::npos) continue; //invalid line
1528 std::string hash = line.substr(0, pos);
1529 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1531 bool forMerge = pos == prevPos;
1532 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1534 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1536 //Process this line
1537 if(forMerge)
1539 hashToReturn = hash;
1540 ++forMergeLineCount;
1541 if(forMergeLineCount > 1)
1542 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1546 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1549 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1551 int ret = 0;
1552 CString cur;
1553 if (m_IsUseLibGit2)
1555 CAutoRepository repo(GetGitRepository());
1556 if (!repo)
1557 return -1;
1559 if (git_repository_head_detached(repo) == 1)
1560 cur = _T("(detached from ");
1562 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1564 git_branch_t flags = GIT_BRANCH_LOCAL;
1565 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1566 flags = GIT_BRANCH_ALL;
1567 else if (type & BRANCH_REMOTE)
1568 flags = GIT_BRANCH_REMOTE;
1570 CAutoBranchIterator it;
1571 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1572 return -1;
1574 git_reference * ref = nullptr;
1575 git_branch_t branchType;
1576 while (git_branch_next(&ref, &branchType, it) == 0)
1578 CAutoReference autoRef(ref);
1579 const char * name = nullptr;
1580 if (git_branch_name(&name, ref))
1581 continue;
1583 CString branchname = CUnicodeUtils::GetUnicode(name);
1584 if (branchType & GIT_BRANCH_REMOTE)
1585 list.push_back(_T("remotes/") + branchname);
1586 else
1588 if (git_branch_is_head(ref))
1589 cur = branchname;
1590 list.push_back(branchname);
1595 else
1597 CString cmd, output;
1598 cmd = _T("git.exe branch --no-color");
1600 if ((type & BRANCH_ALL) == BRANCH_ALL)
1601 cmd += _T(" -a");
1602 else if (type & BRANCH_REMOTE)
1603 cmd += _T(" -r");
1605 ret = Run(cmd, &output, nullptr, CP_UTF8);
1606 if (!ret)
1608 int pos = 0;
1609 CString one;
1610 while (pos >= 0)
1612 one = output.Tokenize(_T("\n"), pos);
1613 one.Trim(L" \r\n\t");
1614 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1615 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1616 if (one[0] == _T('*'))
1618 one = one.Mid(2);
1619 cur = one;
1621 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1622 list.push_back(one);
1627 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1628 list.push_back(L"FETCH_HEAD");
1630 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1632 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1634 for (unsigned int i = 0; i < list.size(); ++i)
1636 if (list[i] == cur)
1638 *current = i;
1639 break;
1644 return ret;
1647 int CGit::GetRemoteList(STRING_VECTOR &list)
1649 if (this->m_IsUseLibGit2)
1651 CAutoRepository repo(GetGitRepository());
1652 if (!repo)
1653 return -1;
1655 CAutoStrArray remotes;
1656 if (git_remote_list(remotes, repo))
1657 return -1;
1659 for (size_t i = 0; i < remotes->count; ++i)
1661 CStringA remote(remotes->strings[i]);
1662 list.push_back(CUnicodeUtils::GetUnicode(remote));
1665 std::sort(list.begin(), list.end());
1667 return 0;
1669 else
1671 int ret;
1672 CString cmd, output;
1673 cmd=_T("git.exe remote");
1674 ret = Run(cmd, &output, NULL, CP_UTF8);
1675 if(!ret)
1677 int pos=0;
1678 CString one;
1679 while( pos>=0 )
1681 one=output.Tokenize(_T("\n"),pos);
1682 if (!one.IsEmpty())
1683 list.push_back(one);
1686 return ret;
1690 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR& list)
1692 if (UsingLibGit2(GIT_CMD_FETCH))
1694 CAutoRepository repo(GetGitRepository());
1695 if (!repo)
1696 return -1;
1698 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1699 CAutoRemote remote;
1700 if (git_remote_load(remote.GetPointer(), repo, remoteA) < 0)
1701 return -1;
1703 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1704 callbacks.credentials = g_Git2CredCallback;
1705 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1706 git_remote_set_callbacks(remote, &callbacks);
1707 if (git_remote_connect(remote, GIT_DIRECTION_FETCH) < 0)
1708 return -1;
1710 const git_remote_head** heads = nullptr;
1711 size_t size = 0;
1712 if (git_remote_ls(&heads, &size, remote) < 0)
1713 return -1;
1715 for (int i = 0; i < size; i++)
1717 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1718 CString shortname;
1719 if (!GetShortName(ref, shortname, _T("refs/tags/")))
1720 continue;
1721 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1722 if (shortname.Find(_T("^{}")) >= 1)
1723 continue;
1724 list.push_back(shortname);
1726 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1727 return 0;
1730 CString cmd, out, err;
1731 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1732 if (Run(cmd, &out, &err, CP_UTF8))
1734 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1735 return -1;
1738 int pos = 0;
1739 while (pos >= 0)
1741 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1742 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1743 if (one.Find(_T("^{}")) >= 1)
1744 continue;
1745 if (!one.IsEmpty())
1746 list.push_back(one);
1748 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1749 return 0;
1752 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1754 if (UsingLibGit2(GIT_CMD_PUSH))
1756 CAutoRepository repo(GetGitRepository());
1757 if (!repo)
1758 return -1;
1760 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1761 CAutoRemote remote;
1762 if (git_remote_load(remote.GetPointer(), repo, remoteA) < 0)
1763 return -1;
1765 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1766 callbacks.credentials = g_Git2CredCallback;
1767 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1768 git_remote_set_callbacks(remote, &callbacks);
1769 if (git_remote_connect(remote, GIT_DIRECTION_PUSH) < 0)
1770 return -1;
1772 CAutoPush push;
1773 if (git_push_new(push.GetPointer(), remote) < 0)
1774 return -1;
1776 for (auto ref : list)
1778 CString refspec = _T(":") + ref;
1779 if (git_push_add_refspec(push, CUnicodeUtils::GetUTF8(refspec)) < 0)
1780 return -1;
1783 if (git_push_finish(push) < 0)
1784 return -1;
1786 if (git_push_update_tips(push, nullptr, nullptr) < 0)
1787 return -1;
1789 else
1791 CMassiveGitTaskBase mgtPush(_T("push ") + sRemote, FALSE);
1792 for (auto ref : list)
1794 CString refspec = _T(":") + ref;
1795 mgtPush.AddFile(refspec);
1798 BOOL cancel = FALSE;
1799 mgtPush.Execute(cancel);
1802 return 0;
1805 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1807 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1808 CString str;
1809 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1810 list->push_back(str);
1811 return 0;
1814 int CGit::GetRefList(STRING_VECTOR &list)
1816 if (this->m_IsUseLibGit2)
1818 CAutoRepository repo(GetGitRepository());
1819 if (!repo)
1820 return -1;
1822 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1823 return -1;
1825 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1827 return 0;
1829 else
1831 CString cmd, output;
1832 cmd=_T("git.exe show-ref -d");
1833 int ret = Run(cmd, &output, NULL, CP_UTF8);
1834 if(!ret)
1836 int pos=0;
1837 CString one;
1838 while( pos>=0 )
1840 one=output.Tokenize(_T("\n"),pos);
1841 int start=one.Find(_T(" "),0);
1842 if(start>0)
1844 CString name;
1845 name=one.Right(one.GetLength()-start-1);
1846 list.push_back(name);
1849 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1851 return ret;
1855 typedef struct map_each_ref_payload {
1856 git_repository * repo;
1857 MAP_HASH_NAME * map;
1858 } map_each_ref_payload;
1860 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1862 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1864 CString str;
1865 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1867 CAutoObject gitObject;
1868 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1869 return 1;
1871 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1873 str += _T("^{}"); // deref tag
1874 CAutoObject derefedTag;
1875 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1876 return 1;
1877 gitObject.Swap(derefedTag);
1880 const git_oid * oid = git_object_id(gitObject);
1881 if (oid == NULL)
1882 return 1;
1884 CGitHash hash((char *)oid->id);
1885 (*payloadContent->map)[hash].push_back(str);
1887 return 0;
1889 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1891 ATLASSERT(repo);
1893 map_each_ref_payload payloadContent = { repo, &map };
1895 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1896 return -1;
1898 for (auto it = map.begin(); it != map.end(); ++it)
1900 std::sort(it->second.begin(), it->second.end());
1903 return 0;
1906 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1908 if (this->m_IsUseLibGit2)
1910 CAutoRepository repo(GetGitRepository());
1911 if (!repo)
1912 return -1;
1914 return GetMapHashToFriendName(repo, map);
1916 else
1918 CString cmd, output;
1919 cmd=_T("git.exe show-ref -d");
1920 int ret = Run(cmd, &output, NULL, CP_UTF8);
1921 if(!ret)
1923 int pos=0;
1924 CString one;
1925 while( pos>=0 )
1927 one=output.Tokenize(_T("\n"),pos);
1928 int start=one.Find(_T(" "),0);
1929 if(start>0)
1931 CString name;
1932 name=one.Right(one.GetLength()-start-1);
1934 CString hash;
1935 hash=one.Left(start);
1937 map[CGitHash(hash)].push_back(name);
1941 return ret;
1945 static void SetLibGit2SearchPath(int level, const CString &value)
1947 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1948 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1951 static void SetLibGit2TemplatePath(const CString &value)
1953 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1954 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1957 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1959 if (m_bInitialized)
1961 return TRUE;
1964 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": CheckMsysGitDir(%d)\n"), bFallback);
1965 this->m_Environment.clear();
1966 m_Environment.CopyProcessEnvironment();
1967 m_Environment.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
1969 TCHAR *oldpath;
1970 size_t homesize,size;
1972 // set HOME if not set already
1973 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1974 if (!homesize)
1975 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1977 //setup ssh client
1978 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1979 if (sshclient.IsEmpty())
1980 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1982 if(!sshclient.IsEmpty())
1984 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1985 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1987 else
1989 TCHAR sPlink[MAX_PATH] = {0};
1990 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1991 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1992 if (ptr) {
1993 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1994 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1995 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
2000 TCHAR sAskPass[MAX_PATH] = {0};
2001 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
2002 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
2003 if (ptr)
2005 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
2006 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
2007 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
2008 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
2012 // add git/bin path to PATH
2014 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
2015 CString str = msysdir;
2016 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
2018 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2019 if (!bFallback)
2020 return FALSE;
2022 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
2023 str = msyslocalinstalldir;
2024 str.TrimRight(_T("\\"));
2025 if (str.IsEmpty())
2027 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
2028 str = msysinstalldir;
2029 str.TrimRight(_T("\\"));
2031 if ( !str.IsEmpty() )
2033 str += "\\bin";
2034 msysdir=str;
2035 CGit::ms_LastMsysGitDir = str;
2036 msysdir.write();
2038 else
2040 // search PATH if git/bin directory is already present
2041 if ( FindGitPath() )
2043 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir);
2044 m_bInitialized = TRUE;
2045 msysdir = CGit::ms_LastMsysGitDir;
2046 msysdir.write();
2047 return TRUE;
2050 return FALSE;
2053 else
2055 CGit::ms_LastMsysGitDir = str;
2058 // check for git.exe existance (maybe it was deinstalled in the meantime)
2059 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
2061 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir);
2062 return FALSE;
2065 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir);
2066 // Configure libgit2 search paths
2067 CString msysGitDir;
2068 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
2069 msysGitDir.ReleaseBuffer();
2070 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
2071 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2072 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2073 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 };
2074 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2075 CString msysGitTemplateDir;
2076 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
2077 msysGitTemplateDir.ReleaseBuffer();
2078 SetLibGit2TemplatePath(msysGitTemplateDir);
2080 //set path
2081 _tdupenv_s(&oldpath,&size,_T("PATH"));
2083 CString path;
2084 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
2086 m_Environment.SetEnv(_T("PATH"), path);
2088 CString str1 = m_Environment.GetEnv(_T("PATH"));
2090 CString sOldPath = oldpath;
2091 free(oldpath);
2093 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2094 // register filter only once
2095 if (!git_filter_lookup("filter"))
2097 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir + L"\\sh.exe\"", &m_Environment[0]), GIT_FILTER_DRIVER_PRIORITY))
2098 return FALSE;
2100 #endif
2102 m_bInitialized = TRUE;
2103 return true;
2106 CString CGit::GetHomeDirectory() const
2108 const wchar_t * homeDir = wget_windows_home_directory();
2109 return CString(homeDir, (int)wcslen(homeDir));
2112 CString CGit::GetGitLocalConfig() const
2114 CString path;
2115 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
2116 path += _T("config");
2117 return path;
2120 CStringA CGit::GetGitPathStringA(const CString &path)
2122 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2125 CString CGit::GetGitGlobalConfig() const
2127 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
2130 CString CGit::GetGitGlobalXDGConfigPath() const
2132 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
2135 CString CGit::GetGitGlobalXDGConfig() const
2137 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
2140 CString CGit::GetGitSystemConfig() const
2142 const wchar_t * systemConfig = wget_msysgit_etc();
2143 return CString(systemConfig, (int)wcslen(systemConfig));
2146 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2148 CString out;
2149 CString cmd;
2150 cmd=_T("git.exe rev-parse --verify HEAD");
2152 if(Run(cmd,&out,CP_UTF8))
2153 return FALSE;
2155 cmd=_T("git.exe update-index --ignore-submodules --refresh");
2156 if(Run(cmd,&out,CP_UTF8))
2157 return FALSE;
2159 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
2160 if(Run(cmd,&out,CP_UTF8))
2161 return FALSE;
2163 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2164 if (!stagedOk && Run(cmd, &out, CP_UTF8))
2165 return FALSE;
2167 return TRUE;
2169 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2171 int ret;
2172 for (int i = 0; i < list.GetCount(); ++i)
2174 ret = Revert(commit, (CTGitPath&)list[i], err);
2175 if(ret)
2176 return ret;
2178 return 0;
2180 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2182 CString cmd;
2184 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2186 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2188 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2189 return -1;
2191 CString force;
2192 // if the filenames only differ in case, we have to pass "-f"
2193 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2194 force = _T("-f ");
2195 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2196 if (Run(cmd, &err, CP_UTF8))
2197 return -1;
2199 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2200 if (Run(cmd, &err, CP_UTF8))
2201 return -1;
2203 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2204 { //To init git repository, there are not HEAD, so we can use git reset command
2205 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2207 if (Run(cmd, &err, CP_UTF8))
2208 return -1;
2210 else
2212 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2213 if (Run(cmd, &err, CP_UTF8))
2214 return -1;
2217 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2219 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2220 if (Run(cmd, &err, CP_UTF8))
2221 return -1;
2224 return 0;
2227 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2229 BYTE_VECTOR vector;
2231 CString cmd;
2232 if(path)
2233 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2234 else
2235 cmd=_T("git.exe ls-files -u -t -z");
2237 if (Run(cmd, &vector))
2239 return -1;
2242 if (list.ParserFromLsFile(vector))
2243 return -1;
2245 return 0;
2248 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2250 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2252 CAutoRepository repo(GetGitRepository());
2253 if (!repo)
2254 return false;
2256 CGitHash fromHash, toHash, baseHash;
2257 if (GetHash(repo, toHash, FixBranchName(to)))
2258 return false;
2260 if (GetHash(repo, fromHash, FixBranchName(from)))
2261 return false;
2263 git_oid baseOid;
2264 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2265 return false;
2267 baseHash = baseOid.id;
2269 if (commonAncestor)
2270 *commonAncestor = baseHash;
2272 return fromHash == baseHash;
2274 // else
2275 CString base;
2276 CGitHash basehash,hash;
2277 CString cmd, err;
2278 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2280 if (Run(cmd, &base, &err, CP_UTF8))
2282 return false;
2284 basehash = base.Trim();
2286 GetHash(hash, from);
2288 if (commonAncestor)
2289 *commonAncestor = basehash;
2291 return hash == basehash;
2294 unsigned int CGit::Hash2int(const CGitHash &hash)
2296 int ret=0;
2297 for (int i = 0; i < 4; ++i)
2299 ret = ret << 8;
2300 ret |= hash.m_hash[i];
2302 return ret;
2305 int CGit::RefreshGitIndex()
2307 if(g_Git.m_IsUseGitDLL)
2309 CAutoLocker lock(g_Git.m_critGitDllSec);
2312 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2314 }catch(...)
2316 return -1;
2320 else
2322 CString cmd,output;
2323 cmd=_T("git.exe update-index --refresh");
2324 return Run(cmd, &output, CP_UTF8);
2328 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2330 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2332 CAutoRepository repo(GetGitRepository());
2333 if (!repo)
2334 return -1;
2336 CGitHash hash;
2337 if (GetHash(repo, hash, Refname))
2338 return -1;
2340 CAutoCommit commit;
2341 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2342 return -1;
2344 CAutoTree tree;
2345 if (git_commit_tree(tree.GetPointer(), commit))
2346 return -1;
2348 CAutoTreeEntry entry;
2349 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2350 return -1;
2352 CAutoBlob blob;
2353 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2354 return -1;
2356 FILE *file = nullptr;
2357 _tfopen_s(&file, outputfile, _T("w"));
2358 if (file == nullptr)
2360 giterr_set_str(GITERR_NONE, "Could not create file.");
2361 return -1;
2363 CAutoBuf buf;
2364 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2366 fclose(file);
2367 return -1;
2369 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2371 giterr_set_str(GITERR_OS, "Could not write to file.");
2372 fclose(file);
2374 return -1;
2376 fclose(file);
2378 return 0;
2380 else if (g_Git.m_IsUseGitDLL)
2382 CAutoLocker lock(g_Git.m_critGitDllSec);
2385 g_Git.CheckAndInitDll();
2386 CStringA ref, patha, outa;
2387 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2388 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2389 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2390 ::DeleteFile(outputfile);
2391 return git_checkout_file(ref, patha, outa);
2394 catch (const char * msg)
2396 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2397 return -1;
2399 catch (...)
2401 gitLastErr = L"An unknown gitdll.dll error occurred.";
2402 return -1;
2405 else
2407 CString cmd;
2408 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2409 return RunLogFile(cmd, outputfile, &gitLastErr);
2412 void CEnvironment::CopyProcessEnvironment()
2414 TCHAR *porig = GetEnvironmentStrings();
2415 TCHAR *p = porig;
2416 while(*p !=0 || *(p+1) !=0)
2417 this->push_back(*p++);
2419 push_back(_T('\0'));
2420 push_back(_T('\0'));
2422 FreeEnvironmentStrings(porig);
2425 CString CEnvironment::GetEnv(const TCHAR *name)
2427 CString str;
2428 for (size_t i = 0; i < size(); ++i)
2430 str = &(*this)[i];
2431 int start =0;
2432 CString sname = str.Tokenize(_T("="),start);
2433 if(sname.CompareNoCase(name) == 0)
2435 return &(*this)[i+start];
2437 i+=str.GetLength();
2439 return _T("");
2442 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2444 unsigned int i;
2445 for (i = 0; i < size(); ++i)
2447 CString str = &(*this)[i];
2448 int start =0;
2449 CString sname = str.Tokenize(_T("="),start);
2450 if(sname.CompareNoCase(name) == 0)
2452 break;
2454 i+=str.GetLength();
2457 if(i == size())
2459 if (!value) // as we haven't found the variable we want to remove, just return
2460 return;
2461 i -= 1; // roll back terminate \0\0
2462 this->push_back(_T('\0'));
2465 CEnvironment::iterator it;
2466 it=this->begin();
2467 it += i;
2469 while(*it && i<size())
2471 this->erase(it);
2472 it=this->begin();
2473 it += i;
2476 if (value == nullptr) // remove the variable
2478 this->erase(it);
2479 return;
2482 while(*name)
2484 this->insert(it,*name++);
2485 ++i;
2486 it= begin()+i;
2489 this->insert(it, _T('='));
2490 ++i;
2491 it= begin()+i;
2493 while(*value)
2495 this->insert(it,*value++);
2496 ++i;
2497 it= begin()+i;
2502 int CGit::GetGitEncode(TCHAR* configkey)
2504 CString str=GetConfigValue(configkey);
2506 if(str.IsEmpty())
2507 return CP_UTF8;
2509 return CUnicodeUtils::GetCPCode(str);
2513 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2515 GIT_FILE file=0;
2516 int ret=0;
2517 GIT_DIFF diff=0;
2519 CAutoLocker lock(g_Git.m_critGitDllSec);
2523 if(!arg)
2524 diff = GetGitDiff();
2525 else
2526 git_open_diff(&diff, arg);
2528 catch (char* e)
2530 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e), _T("TortoiseGit"), MB_OK);
2531 return -1;
2534 if(diff ==NULL)
2535 return -1;
2537 bool isStat = 0;
2538 if(arg == NULL)
2539 isStat = true;
2540 else
2541 isStat = !!strstr(arg, "stat");
2543 int count=0;
2545 if(hash2 == NULL)
2546 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2547 else
2548 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2550 if(ret)
2551 return -1;
2553 CTGitPath path;
2554 CString strnewname;
2555 CString stroldname;
2557 for (int j = 0; j < count; ++j)
2559 path.Reset();
2560 char *newname;
2561 char *oldname;
2563 strnewname.Empty();
2564 stroldname.Empty();
2566 int mode=0,IsBin=0,inc=0,dec=0;
2567 git_get_diff_file(diff,file,j,&newname,&oldname,
2568 &mode,&IsBin,&inc,&dec);
2570 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2571 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2573 path.SetFromGit(strnewname,&stroldname);
2574 path.ParserAction((BYTE)mode);
2576 if(IsBin)
2578 path.m_StatAdd=_T("-");
2579 path.m_StatDel=_T("-");
2581 else
2583 path.m_StatAdd.Format(_T("%d"),inc);
2584 path.m_StatDel.Format(_T("%d"),dec);
2586 PathList->AddPath(path);
2588 git_diff_flush(diff);
2590 if(arg)
2591 git_close_diff(diff);
2593 return 0;
2596 int CGit::GetShortHASHLength() const
2598 return 7;
2601 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2603 CString str=ref;
2604 CString shortname;
2605 REF_TYPE type = CGit::UNKNOWN;
2607 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2609 type = CGit::LOCAL_BRANCH;
2612 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2614 type = CGit::REMOTE_BRANCH;
2616 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2618 type = CGit::TAG;
2620 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2622 type = CGit::STASH;
2623 shortname=_T("stash");
2625 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2627 if (shortname.Find(_T("good")) == 0)
2629 type = CGit::BISECT_GOOD;
2630 shortname = _T("good");
2633 if (shortname.Find(_T("bad")) == 0)
2635 type = CGit::BISECT_BAD;
2636 shortname = _T("bad");
2639 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2641 type = CGit::NOTES;
2643 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2645 type = CGit::UNKNOWN;
2647 else
2649 type = CGit::UNKNOWN;
2650 shortname = ref;
2653 if(out_type)
2654 *out_type = type;
2656 return shortname;
2659 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2661 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2664 void CGit::SetGit2CredentialCallback(void* callback)
2666 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2669 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2671 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2674 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2676 CString cmd;
2677 if (rev2 == GitRev::GetWorkingCopy())
2678 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2679 else if (rev1 == GitRev::GetWorkingCopy())
2680 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2681 else
2683 CString merge;
2684 if (bMerge)
2685 merge += _T(" -m");
2687 if (bCombine)
2688 merge += _T(" -c");
2690 CString unified;
2691 if (diffContext >= 0)
2692 unified.Format(_T(" --unified=%d"), diffContext);
2693 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2696 if (!path.IsEmpty())
2698 cmd += _T(" \"");
2699 cmd += path.GetGitPathString();
2700 cmd += _T("\"");
2703 return cmd;
2706 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2708 ATLASSERT(payload && text);
2709 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2710 fwrite("\n", 1, 1, (FILE *)payload);
2713 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2715 ATLASSERT(payload && line);
2716 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2717 fwrite(&line->origin, 1, 1, (FILE *)payload);
2718 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2719 return 0;
2722 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2724 ATLASSERT(repo && identifier && tree);
2726 /* try to resolve identifier */
2727 CAutoObject obj;
2728 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2729 return -1;
2731 if (obj == nullptr)
2732 return GIT_ENOTFOUND;
2734 int err = 0;
2735 switch (git_object_type(obj))
2737 case GIT_OBJ_TREE:
2738 *tree = (git_tree *)obj.Detach();
2739 break;
2740 case GIT_OBJ_COMMIT:
2741 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2742 break;
2743 default:
2744 err = GIT_ENOTFOUND;
2747 return err;
2750 /* use libgit2 get unified diff */
2751 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 */)
2753 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2754 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2756 CAutoRepository repo(g_Git.GetGitRepository());
2757 if (!repo)
2758 return -1;
2760 int isHeadOrphan = git_repository_head_unborn(repo);
2761 if (isHeadOrphan == 1)
2762 return 0;
2763 else if (isHeadOrphan != 0)
2764 return -1;
2766 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2767 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2768 char *buf = pathA.GetBuffer();
2769 if (!pathA.IsEmpty())
2771 opts.pathspec.strings = &buf;
2772 opts.pathspec.count = 1;
2774 CAutoDiff diff;
2776 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2778 CAutoTree t1;
2779 CAutoDiff diff2;
2781 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2782 return -1;
2784 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2785 return -1;
2787 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2788 return -1;
2790 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2791 return -1;
2793 if (git_diff_merge(diff, diff2))
2794 return -1;
2796 else
2798 if (tree1.IsEmpty() && tree2.IsEmpty())
2799 return -1;
2801 if (tree1.IsEmpty())
2803 tree1 = tree2;
2804 tree2.Empty();
2807 CAutoTree t1;
2808 CAutoTree t2;
2809 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2810 return -1;
2812 if (tree2.IsEmpty())
2814 /* don't check return value, there are not parent commit at first commit*/
2815 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2817 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2818 return -1;
2819 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2820 return -1;
2823 CAutoDiffStats stats;
2824 if (git_diff_get_stats(stats.GetPointer(), diff))
2825 return -1;
2826 CAutoBuf statBuf;
2827 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2828 return -1;
2829 statCallback(statBuf, data);
2831 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2833 CAutoPatch patch;
2834 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2835 return -1;
2837 if (git_patch_print(patch, callback, data))
2838 return -1;
2841 pathA.ReleaseBuffer();
2843 return 0;
2846 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2848 if (UsingLibGit2(GIT_CMD_DIFF))
2850 FILE *file = nullptr;
2851 _tfopen_s(&file, patchfile, _T("w"));
2852 if (file == nullptr)
2853 return -1;
2854 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge);
2855 fclose(file);
2856 return ret;
2858 else
2860 CString cmd;
2861 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2862 return RunLogFile(cmd, patchfile, &gitLastErr);
2866 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
2868 ATLASSERT(payload && text);
2869 CStringA *str = (CStringA*) payload;
2870 str->Append(text->ptr, (int)text->size);
2871 str->AppendChar('\n');
2874 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2876 ATLASSERT(payload && line);
2877 CStringA *str = (CStringA*) payload;
2878 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2879 str->Append(&line->origin, 1);
2880 str->Append(line->content, (int)line->content_len);
2881 return 0;
2884 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2886 if (UsingLibGit2(GIT_CMD_DIFF))
2887 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge);
2888 else
2890 CString cmd;
2891 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2892 BYTE_VECTOR vector;
2893 int ret = Run(cmd, &vector);
2894 if (!vector.empty())
2896 vector.push_back(0); // vector is not NUL terminated
2897 buffer->Append((char *)&vector[0]);
2899 return ret;
2903 int CGit::GitRevert(int parent, const CGitHash &hash)
2905 if (UsingLibGit2(GIT_CMD_REVERT))
2907 CAutoRepository repo(GetGitRepository());
2908 if (!repo)
2909 return -1;
2911 CAutoCommit commit;
2912 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2913 return -1;
2915 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2916 revert_opts.mainline = parent;
2917 int result = git_revert(repo, commit, &revert_opts);
2919 return !result ? 0 : -1;
2921 else
2923 CString cmd, merge;
2924 if (parent)
2925 merge.Format(_T("-m %d "), parent);
2926 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2927 gitLastErr = cmd + _T("\n");
2928 if (Run(cmd, &gitLastErr, CP_UTF8))
2930 return -1;
2932 else
2934 gitLastErr.Empty();
2935 return 0;
2940 int CGit::DeleteRef(const CString& reference)
2942 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2944 CAutoRepository repo(GetGitRepository());
2945 if (!repo)
2946 return -1;
2948 CStringA refA;
2949 if (reference.Right(3) == _T("^{}"))
2950 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2951 else
2952 refA = CUnicodeUtils::GetUTF8(reference);
2954 CAutoReference ref;
2955 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2956 return -1;
2958 int result = -1;
2959 if (git_reference_is_tag(ref))
2960 result = git_tag_delete(repo, git_reference_shorthand(ref));
2961 else if (git_reference_is_branch(ref))
2962 result = git_branch_delete(ref);
2963 else if (git_reference_is_remote(ref))
2964 result = git_branch_delete(ref);
2965 else
2966 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2968 return result;
2970 else
2972 CString cmd, shortname;
2973 if (GetShortName(reference, shortname, _T("refs/heads/")))
2974 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2975 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2976 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2977 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2978 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2979 else
2981 gitLastErr = L"unsupported reference type: " + reference;
2982 return -1;
2985 if (Run(cmd, &gitLastErr, CP_UTF8))
2986 return -1;
2988 gitLastErr.Empty();
2989 return 0;
2993 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2995 if (PathFileExists(filename))
2997 FILE *pFile = nullptr;
2998 _tfopen_s(&pFile, filename, _T("r"));
2999 if (pFile)
3001 CStringA str;
3004 char s[8196] = { 0 };
3005 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3006 if (read == 0)
3007 break;
3008 str += CStringA(s, read);
3009 } while (true);
3010 fclose(pFile);
3011 msg = CUnicodeUtils::GetUnicode(str);
3012 msg.Replace(_T("\r\n"), _T("\n"));
3013 msg.TrimRight(_T("\n"));
3014 msg += _T("\n");
3016 else
3017 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
3018 return true; // load no further files
3020 return false;