Use "Left" instead of "Mid(0,"
[TortoiseGit.git] / src / Git / Git.cpp
blob5096ea95dac19222f8610c966ad7a0053d6863f2
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2018 - 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 "UnicodeUtils.h"
26 #include "gitdll.h"
27 #include <fstream>
28 #include <iterator>
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 static int CalculateDiffSimilarityIndexThreshold(DWORD index)
39 if (index < 0 || index > 100)
40 return 50;
41 return index;
44 bool CGit::ms_bCygwinGit = (CRegDWORD(L"Software\\TortoiseGit\\CygwinHack", FALSE) == TRUE);
45 bool CGit::ms_bMsys2Git = (CRegDWORD(L"Software\\TortoiseGit\\Msys2Hack", FALSE) == TRUE);
46 int CGit::ms_iSimilarityIndexThreshold = CalculateDiffSimilarityIndexThreshold(CRegDWORD(L"Software\\TortoiseGit\\DiffSimilarityIndexThreshold", 50));
47 int CGit::m_LogEncode=CP_UTF8;
48 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
50 static LPCTSTR nextpath(const wchar_t* path, wchar_t* buf, size_t buflen)
52 if (!path || !buf || buflen == 0)
53 return nullptr;
55 const wchar_t* base = path;
56 wchar_t term = (*path == L'"') ? *path++ : L';';
58 for (buflen--; *path && *path != term && buflen; buflen--)
59 *buf++ = *path++;
61 *buf = L'\0'; /* reserved a byte via initial subtract */
63 while (*path == term || *path == L';')
64 ++path;
66 return (path != base) ? path : nullptr;
69 static CString FindFileOnPath(const CString& filename, LPCTSTR env, bool wantDirectory = false)
71 TCHAR buf[MAX_PATH] = { 0 };
73 // search in all paths defined in PATH
74 while ((env = nextpath(env, buf, _countof(buf) - 1)) != nullptr && *buf)
76 TCHAR* pfin = buf + wcslen(buf) - 1;
78 // ensure trailing slash
79 if (*pfin != L'/' && *pfin != L'\\')
80 wcscpy_s(++pfin, 2, L"\\"); // we have enough space left, MAX_PATH-1 is used in nextpath above
82 const size_t len = wcslen(buf);
84 if ((len + filename.GetLength()) < _countof(buf))
85 wcscpy_s(pfin + 1, _countof(buf) - len, filename);
86 else
87 break;
89 if (PathFileExists(buf))
91 if (wantDirectory)
92 pfin[1] = L'\0';
93 return buf;
97 return L"";
100 static BOOL FindGitPath()
102 size_t size;
103 _wgetenv_s(&size, nullptr, 0, L"PATH");
104 if (!size)
105 return FALSE;
107 auto env = std::make_unique<TCHAR[]>(size);
108 if (!env)
109 return FALSE;
110 _wgetenv_s(&size, env.get(), size, L"PATH");
112 CString gitExeDirectory = FindFileOnPath(L"git.exe", env.get(), true);
113 if (!gitExeDirectory.IsEmpty())
115 CGit::ms_LastMsysGitDir = gitExeDirectory;
116 CGit::ms_LastMsysGitDir.TrimRight(L'\\');
117 if (CStringUtils::EndsWith(CGit::ms_LastMsysGitDir, L"\\mingw32\\bin") || CStringUtils::EndsWith(CGit::ms_LastMsysGitDir, L"\\mingw64\\bin"))
119 // prefer cmd directory as early Git for Windows 2.x releases only had this
120 CString installRoot = CGit::ms_LastMsysGitDir.Left(CGit::ms_LastMsysGitDir.GetLength() - (int)wcslen(L"\\mingw64\\bin")) + L"\\cmd\\git.exe";
121 if (PathFileExists(installRoot))
122 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Left(CGit::ms_LastMsysGitDir.GetLength() - (int)wcslen(L"\\mingw64\\bin")) + L"\\cmd";
124 if (CStringUtils::EndsWith(CGit::ms_LastMsysGitDir, L"\\cmd"))
126 // often the msysgit\cmd folder is on the %PATH%, but
127 // that git.exe does not work, so try to guess the bin folder
128 if (PathFileExists(CGit::ms_LastMsysGitDir.Left(CGit::ms_LastMsysGitDir.GetLength() - (int)wcslen(L"\\cmd")) + L"\\bin\\git.exe"))
129 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Left(CGit::ms_LastMsysGitDir.GetLength() - (int)wcslen(L"\\cmd")) + L"\\bin";
131 return TRUE;
134 return FALSE;
137 static CString FindExecutableOnPath(const CString& executable, LPCTSTR env)
139 CString filename = executable;
141 if (!CStringUtils::EndsWith(executable, L".exe"))
142 filename += L".exe";
144 if (PathFileExists(filename))
145 return filename;
147 filename = FindFileOnPath(filename, env);
148 if (!filename.IsEmpty())
149 return filename;
151 return executable;
154 static bool g_bSortLogical;
155 static bool g_bSortLocalBranchesFirst;
156 static bool g_bSortTagsReversed;
157 static git_cred_acquire_cb g_Git2CredCallback;
158 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback;
160 static void GetSortOptions()
162 #ifdef GTEST_INCLUDE_GTEST_GTEST_H_
163 g_bSortLogical = true;
164 g_bSortLocalBranchesFirst = true;
165 g_bSortTagsReversed = false;
166 #else
167 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
168 if (g_bSortLogical)
169 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
170 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
171 if (g_bSortLocalBranchesFirst)
172 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
173 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
174 if (!g_bSortTagsReversed)
175 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
176 #endif
179 static int LogicalComparePredicate(const CString &left, const CString &right)
181 if (g_bSortLogical)
182 return StrCmpLogicalW(left, right) < 0;
183 return StrCmpI(left, right) < 0;
186 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
188 return LogicalComparePredicate(right, left);
191 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
193 if (g_bSortLocalBranchesFirst)
195 bool leftIsRemote = CStringUtils::StartsWith(left, L"remotes/");
196 bool rightIsRemote = CStringUtils::StartsWith(right, L"remotes/");
198 if (leftIsRemote && !rightIsRemote)
199 return false;
200 else if (!leftIsRemote && rightIsRemote)
201 return true;
203 return LogicalComparePredicate(left, right);
206 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
208 CString CGit::ms_LastMsysGitDir;
209 CString CGit::ms_MsysGitRootDir;
210 int CGit::ms_LastMsysGitVersion = 0;
211 CGit g_Git;
214 CGit::CGit(void)
216 git_libgit2_init();
217 GetCurrentDirectory(MAX_PATH, CStrBuf(m_CurrentDir, MAX_PATH));
218 m_IsGitDllInited = false;
219 m_GitDiff=0;
220 m_GitSimpleListDiff=0;
221 m_IsUseGitDLL = !!CRegDWORD(L"Software\\TortoiseGit\\UsingGitDLL",1);
222 m_IsUseLibGit2 = !!CRegDWORD(L"Software\\TortoiseGit\\UseLibgit2", TRUE);
223 m_IsUseLibGit2_mask = CRegDWORD(L"Software\\TortoiseGit\\UseLibgit2_mask", DEFAULT_USE_LIBGIT2_MASK);
225 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
227 GetSortOptions();
228 this->m_bInitialized =false;
229 CheckMsysGitDir();
230 m_critGitDllSec.Init();
231 m_critSecThreadMap.Init();
234 CGit::~CGit(void)
236 if(this->m_GitDiff)
238 git_close_diff(m_GitDiff);
239 m_GitDiff=0;
241 if(this->m_GitSimpleListDiff)
243 git_close_diff(m_GitSimpleListDiff);
244 m_GitSimpleListDiff=0;
246 git_libgit2_shutdown();
247 m_critSecThreadMap.Term();
248 m_critGitDllSec.Term();
251 bool CGit::IsBranchNameValid(const CString& branchname)
253 if (CStringUtils::StartsWith(branchname, L"-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
254 return false;
255 if (branchname.FindOneOf(L"\"|<>") >= 0) // not valid on Windows
256 return false;
257 if (branchname == L"HEAD") // Branch name HEAD is discouraged since Git v2.16.0, see https://github.com/git/git/commit/a625b092cc59940521789fe8a3ff69c8d6b14eb2
258 return false;
259 CStringA branchA = CUnicodeUtils::GetUTF8(L"refs/heads/" + branchname);
260 return !!git_reference_is_valid_name(branchA);
263 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION* piOut, HANDLE* hReadOut, HANDLE* hErrReadOut, const CString* StdioFile)
265 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr, hWriteIn, hReadIn;
266 CAutoFile hStdioFile;
268 SECURITY_ATTRIBUTES sa = { 0 };
269 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
270 sa.bInheritHandle=TRUE;
271 if (!CreatePipe(hReadIn.GetPointer(), hWriteIn.GetPointer(), &sa, 0))
273 CString err = CFormatMessageWrapper();
274 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": could not open stdin pipe: %s\n", (LPCTSTR)err.Trim());
275 return TGIT_GIT_ERROR_OPEN_PIP;
277 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
279 CString err = CFormatMessageWrapper();
280 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": could not open stdout pipe: %s\n", (LPCTSTR)err.Trim());
281 return TGIT_GIT_ERROR_OPEN_PIP;
283 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
285 CString err = CFormatMessageWrapper();
286 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": could not open stderr pipe: %s\n", (LPCTSTR)err.Trim());
287 return TGIT_GIT_ERROR_OPEN_PIP;
290 if(StdioFile)
291 hStdioFile = CreateFile(*StdioFile, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
293 STARTUPINFO si = { 0 };
294 PROCESS_INFORMATION pi = { 0 };
295 si.cb=sizeof(STARTUPINFO);
296 si.hStdInput = hReadIn;
297 if (hErrReadOut)
298 si.hStdError = hWriteErr;
299 else
300 si.hStdError = hWrite;
301 if(StdioFile)
302 si.hStdOutput=hStdioFile;
303 else
304 si.hStdOutput=hWrite;
306 si.wShowWindow=SW_HIDE;
307 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
309 LPTSTR pEnv = m_Environment;
310 DWORD dwFlags = CREATE_UNICODE_ENVIRONMENT;
311 dwFlags |= CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS;
313 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
315 bool startsWithGit = CStringUtils::StartsWith(cmd, L"git");
316 if (ms_bMsys2Git && startsWithGit && !CStringUtils::StartsWith(cmd, L"git.exe config "))
318 cmd.Replace(L"\\", L"\\\\\\\\");
319 cmd.Replace(L"\"", L"\\\"");
320 cmd = L'"' + CGit::ms_LastMsysGitDir + L"\\bash.exe\" -c \"/usr/bin/" + cmd + L'"';
322 else if (ms_bCygwinGit && startsWithGit && !CStringUtils::StartsWith(cmd, L"git.exe config "))
324 cmd.Replace(L'\\', L'/');
325 cmd.Replace(L"\"", L"\\\"");
326 cmd = L'"' + CGit::ms_LastMsysGitDir + L"\\bash.exe\" -c \"/bin/" + cmd + L'"';
328 else if (startsWithGit || CStringUtils::StartsWith(cmd, L"bash"))
330 int firstSpace = cmd.Find(L' ');
331 if (firstSpace > 0)
332 cmd = L'"' + CGit::ms_LastMsysGitDir + L'\\' + cmd.Left(firstSpace) + L'"' + cmd.Mid(firstSpace);
333 else
334 cmd = L'"' + CGit::ms_LastMsysGitDir + L'\\' + cmd + L'"';
337 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": executing %s\n", (LPCTSTR)cmd);
338 if(!CreateProcess(nullptr, cmd.GetBuffer(), nullptr, nullptr, TRUE, dwFlags, pEnv, m_CurrentDir.GetBuffer(), &si, &pi))
340 CString err = CFormatMessageWrapper();
341 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": error while executing command: %s\n", (LPCTSTR)err.Trim());
342 return TGIT_GIT_ERROR_CREATE_PROCESS;
345 // Close the pipe handle so the child process stops reading.
346 hWriteIn.CloseHandle();
348 m_CurrentGitPi = pi;
350 if(piOut)
351 *piOut=pi;
352 if(hReadOut)
353 *hReadOut = hRead.Detach();
354 if(hErrReadOut)
355 *hErrReadOut = hReadErr.Detach();
356 return 0;
358 //Must use sperate function to convert ANSI str to union code string
359 //Because A2W use stack as internal convert buffer.
360 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
362 if (!str)
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 = L"HEAD";
384 CString cmdout;
385 if (Run(L"git.exe rev-parse --revs-only " + ref, &cmdout, CP_UTF8))
386 return FALSE;
387 if(cmdout.IsEmpty())
388 return FALSE;
390 return TRUE;
393 // Checks if we have an orphaned HEAD
394 BOOL CGit::IsInitRepos()
396 CGitHash hash;
397 if (GetHash(hash, L"HEAD") != 0)
398 return FALSE;
399 return hash.IsEmpty() ? TRUE : FALSE;
402 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
404 PASYNCREADSTDERRTHREADARGS pDataArray;
405 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
407 DWORD readnumber;
408 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
409 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, nullptr))
411 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
412 break;
415 return 0;
418 #ifdef _MFC_VER
419 void CGit::KillRelatedThreads(CWinThread* thread)
421 CAutoLocker lock(m_critSecThreadMap);
422 auto it = m_AsyncReadStdErrThreadMap.find(thread->m_nThreadID);
423 if (it != m_AsyncReadStdErrThreadMap.cend())
425 TerminateThread(it->second, (DWORD)-1);
426 m_AsyncReadStdErrThreadMap.erase(it);
428 TerminateThread(thread->m_hThread, (DWORD)-1);
430 #endif
432 int CGit::Run(CGitCall* pcall)
434 PROCESS_INFORMATION pi;
435 CAutoGeneralHandle hRead, hReadErr;
436 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
437 return TGIT_GIT_ERROR_CREATE_PROCESS;
439 CAutoGeneralHandle piThread(std::move(pi.hThread));
440 CAutoGeneralHandle piProcess(std::move(pi.hProcess));
442 ASYNCREADSTDERRTHREADARGS threadArguments;
443 threadArguments.fileHandle = hReadErr;
444 threadArguments.pcall = pcall;
445 CAutoGeneralHandle thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
447 if (thread)
449 CAutoLocker lock(m_critSecThreadMap);
450 m_AsyncReadStdErrThreadMap[GetCurrentThreadId()] = thread;
453 DWORD readnumber;
454 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
455 bool bAborted=false;
456 while (ReadFile(hRead, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, nullptr))
458 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
459 if(!bAborted)//For now, flush output when command aborted.
460 if(pcall->OnOutputData(data,readnumber))
461 bAborted=true;
463 if(!bAborted)
464 pcall->OnEnd();
466 if (thread)
468 WaitForSingleObject(thread, INFINITE);
470 CAutoLocker lock(m_critSecThreadMap);
471 m_AsyncReadStdErrThreadMap.erase(GetCurrentThreadId());
474 WaitForSingleObject(pi.hProcess, INFINITE);
475 DWORD exitcode =0;
477 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
479 CString err = CFormatMessageWrapper();
480 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": could not get exit code: %s\n", (LPCTSTR)err.Trim());
481 return TGIT_GIT_ERROR_GET_EXIT_CODE;
483 else
484 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": process exited: %d\n", exitcode);
486 return exitcode;
488 class CGitCall_ByteVector : public CGitCall
490 public:
491 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = nullptr) : CGitCall(cmd),m_pvector(pvector), m_pvectorErr(pvectorErr) {}
492 virtual bool OnOutputData(const BYTE* data, size_t size)
494 if (!m_pvector || size == 0)
495 return false;
496 size_t oldsize=m_pvector->size();
497 m_pvector->resize(m_pvector->size()+size);
498 memcpy(&*(m_pvector->begin()+oldsize),data,size);
499 return false;
501 virtual bool OnOutputErrData(const BYTE* data, size_t size)
503 if (!m_pvectorErr || size == 0)
504 return false;
505 size_t oldsize = m_pvectorErr->size();
506 m_pvectorErr->resize(m_pvectorErr->size() + size);
507 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
508 return false;
510 BYTE_VECTOR* m_pvector;
511 BYTE_VECTOR* m_pvectorErr;
513 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
515 CGitCall_ByteVector call(cmd, vector, vectorErr);
516 return Run(&call);
518 int CGit::Run(CString cmd, CString* output, int code)
520 CString err;
521 int ret;
522 ret = Run(cmd, output, &err, code);
524 if (output && !err.IsEmpty())
526 if (!output->IsEmpty())
527 *output += L'\n';
528 *output += err;
531 return ret;
533 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
535 BYTE_VECTOR vector, vectorErr;
536 int ret;
537 if (outputErr)
538 ret = Run(cmd, &vector, &vectorErr);
539 else
540 ret = Run(cmd, &vector);
542 vector.push_back(0);
543 StringAppend(output, vector.data(), code);
545 if (outputErr)
547 vectorErr.push_back(0);
548 StringAppend(outputErr, vectorErr.data(), code);
551 return ret;
554 class CGitCallCb : public CGitCall
556 public:
557 CGitCallCb(CString cmd, const GitReceiverFunc& recv, BYTE_VECTOR* pvectorErr = nullptr)
558 : CGitCall(cmd)
559 , m_recv(recv)
560 , m_pvectorErr(pvectorErr)
563 virtual bool OnOutputData(const BYTE* data, size_t size) override
565 // Add data
566 if (size == 0)
567 return false;
568 int oldEndPos = m_buffer.GetLength();
569 memcpy(m_buffer.GetBuffer(oldEndPos + (int)size) + oldEndPos, data, size);
570 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
572 // Break into lines and feed to m_recv
573 int eolPos;
574 while ((eolPos = m_buffer.Find('\n')) >= 0)
576 m_recv(m_buffer.Left(eolPos));
577 m_buffer = m_buffer.Mid(eolPos + 1);
579 return false;
582 virtual bool OnOutputErrData(const BYTE* data, size_t size) override
584 if (!m_pvectorErr || size == 0)
585 return false;
586 size_t oldsize = m_pvectorErr->size();
587 m_pvectorErr->resize(m_pvectorErr->size() + size);
588 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
589 return false;
592 virtual void OnEnd() override
594 if (!m_buffer.IsEmpty())
595 m_recv(m_buffer);
596 m_buffer.Empty(); // Just for sure
599 private:
600 GitReceiverFunc m_recv;
601 CStringA m_buffer;
602 BYTE_VECTOR* m_pvectorErr;
605 int CGit::Run(CString cmd, const GitReceiverFunc& recv, CString* outputErr)
607 if (outputErr)
609 BYTE_VECTOR vectorErr;
610 CGitCallCb call(cmd, recv, &vectorErr);
611 int ret = Run(&call);
612 vectorErr.push_back(0);
613 StringAppend(outputErr, vectorErr.data());
614 return ret;
617 CGitCallCb call(cmd, recv);
618 return Run(&call);
621 CString CGit::GetUserName(void)
623 CEnvironment env;
624 env.CopyProcessEnvironment();
625 CString envname = env.GetEnv(L"GIT_AUTHOR_NAME");
626 if (!envname.IsEmpty())
627 return envname;
628 return GetConfigValue(L"user.name");
630 CString CGit::GetUserEmail(void)
632 CEnvironment env;
633 env.CopyProcessEnvironment();
634 CString envmail = env.GetEnv(L"GIT_AUTHOR_EMAIL");
635 if (!envmail.IsEmpty())
636 return envmail;
638 return GetConfigValue(L"user.email");
641 CString CGit::GetConfigValue(const CString& name, const CString& def, bool wantBool)
643 CString configValue;
644 if(this->m_IsUseGitDLL)
646 CAutoLocker lock(g_Git.m_critGitDllSec);
650 CheckAndInitDll();
651 }catch(...)
654 CStringA key, value;
655 key = CUnicodeUtils::GetUTF8(name);
659 if (git_get_config(key, CStrBufA(value, 4096), 4096))
660 return def;
662 catch (const char *msg)
664 ::MessageBox(nullptr, L"Could not get config.\nlibgit reports:\n" + CString(msg), L"TortoiseGit", MB_OK | MB_ICONERROR);
665 return def;
668 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
669 return configValue;
671 else
673 CString cmd;
674 cmd.Format(L"git.exe config%s %s", wantBool ? L" --bool" : L"", (LPCTSTR)name);
675 if (Run(cmd, &configValue, nullptr, CP_UTF8))
676 return def;
677 if (configValue.IsEmpty())
678 return configValue;
679 return configValue.Left(configValue.GetLength() - 1); // strip last newline character
683 bool CGit::GetConfigValueBool(const CString& name, const bool def)
685 CString configValue = GetConfigValue(name, def ? L"true" : L"false", true);
686 configValue.MakeLower();
687 configValue.Trim();
688 if (configValue == L"true" || configValue == L"on" || configValue == L"yes" || StrToInt(configValue) != 0)
689 return true;
690 else
691 return false;
694 int CGit::GetConfigValueInt32(const CString& name, const int def)
696 CString configValue = GetConfigValue(name);
697 int value = def;
698 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
699 return value;
700 return def;
703 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
705 if(this->m_IsUseGitDLL)
707 CAutoLocker lock(g_Git.m_critGitDllSec);
711 CheckAndInitDll();
712 }catch(...)
715 CStringA keya, valuea;
716 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
717 valuea = CUnicodeUtils::GetUTF8(value);
721 return [=]() { return get_set_config(keya, valuea, type); }();
723 catch (const char *msg)
725 ::MessageBox(nullptr, L"Could not set config.\nlibgit reports:\n" + CString(msg), L"TortoiseGit", MB_OK | MB_ICONERROR);
726 return -1;
729 else
731 CString cmd;
732 CString option;
733 switch(type)
735 case CONFIG_GLOBAL:
736 option = L"--global";
737 break;
738 case CONFIG_SYSTEM:
739 option = L"--system";
740 break;
741 default:
742 break;
744 CString mangledValue = value;
745 mangledValue.Replace(L"\\\"", L"\\\\\"");
746 mangledValue.Replace(L"\"", L"\\\"");
747 cmd.Format(L"git.exe config %s %s \"%s\"", (LPCTSTR)option, (LPCTSTR)key, (LPCTSTR)mangledValue);
748 CString out;
749 if (Run(cmd, &out, nullptr, CP_UTF8))
750 return -1;
752 return 0;
755 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
757 if(this->m_IsUseGitDLL)
759 CAutoLocker lock(g_Git.m_critGitDllSec);
763 CheckAndInitDll();
764 }catch(...)
767 CStringA keya;
768 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
772 return [=]() { return get_set_config(keya, nullptr, type); }();
774 catch (const char *msg)
776 ::MessageBox(nullptr, L"Could not unset config.\nlibgit reports:\n" + CString(msg), L"TortoiseGit", MB_OK | MB_ICONERROR);
777 return -1;
780 else
782 CString cmd;
783 CString option;
784 switch(type)
786 case CONFIG_GLOBAL:
787 option = L"--global";
788 break;
789 case CONFIG_SYSTEM:
790 option = L"--system";
791 break;
792 default:
793 break;
795 cmd.Format(L"git.exe config %s --unset %s", (LPCTSTR)option, (LPCTSTR)key);
796 CString out;
797 if (Run(cmd, &out, nullptr, CP_UTF8))
798 return -1;
800 return 0;
803 CString CGit::GetCurrentBranch(bool fallback)
805 CString output;
806 //Run(L"git.exe branch", &branch);
808 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
809 if (result != 0 && ((result == 1 && !fallback) || result != 1))
810 return L"(no branch)";
811 else
812 return output;
815 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
817 if (localBranch.IsEmpty())
818 return;
820 CString configName;
821 configName.Format(L"branch.%s.remote", (LPCTSTR)localBranch);
822 pullRemote = GetConfigValue(configName);
824 //Select pull-branch from current branch
825 configName.Format(L"branch.%s.merge", (LPCTSTR)localBranch);
826 pullBranch = StripRefName(GetConfigValue(configName));
829 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
831 CString refName;
832 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
833 return;
834 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
837 void CGit::GetRemotePushBranch(const CString& localBranch, CString& pushRemote, CString& pushBranch)
839 if (localBranch.IsEmpty())
840 return;
842 CString configName;
844 configName.Format(L"branch.%s.pushremote", (LPCTSTR)localBranch);
845 pushRemote = g_Git.GetConfigValue(configName);
846 if (pushRemote.IsEmpty())
848 pushRemote = g_Git.GetConfigValue(L"remote.pushdefault");
849 if (pushRemote.IsEmpty())
851 configName.Format(L"branch.%s.remote", (LPCTSTR)localBranch);
852 pushRemote = g_Git.GetConfigValue(configName);
856 configName.Format(L"branch.%s.pushbranch", (LPCTSTR)localBranch);
857 pushBranch = g_Git.GetConfigValue(configName); // do not strip branch name (for gerrit), see issue #1609)
858 if (pushBranch.IsEmpty())
860 configName.Format(L"branch.%s.merge", (LPCTSTR)localBranch);
861 pushBranch = CGit::StripRefName(g_Git.GetConfigValue(configName));
865 CString CGit::GetFullRefName(const CString& shortRefName)
867 CString refName;
868 CString cmd;
869 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", (LPCTSTR)shortRefName);
870 if (Run(cmd, &refName, nullptr, CP_UTF8) != 0)
871 return CString();//Error
872 return refName.TrimRight();
875 CString CGit::StripRefName(CString refName)
877 if (CStringUtils::StartsWith(refName, L"refs/heads/"))
878 refName = refName.Mid((int)wcslen(L"refs/heads/"));
879 else if (CStringUtils::StartsWith(refName, L"refs/"))
880 refName = refName.Mid((int)wcslen(L"refs/"));
881 return refName.TrimRight();
884 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
886 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
888 if ( sProjectRoot.IsEmpty() )
889 return -1;
891 CString sDotGitPath;
892 if (!GitAdminDir::GetWorktreeAdminDirPath(sProjectRoot, sDotGitPath))
893 return -1;
895 CString sHeadFile = sDotGitPath + L"HEAD";
897 CAutoFILE pFile = _wfsopen(sHeadFile.GetString(), L"r", SH_DENYWR);
898 if (!pFile)
899 return -1;
901 char s[MAX_PATH] = {0};
902 fgets(s, sizeof(s), pFile);
904 const char *pfx = "ref: refs/heads/";
905 const size_t len = strlen(pfx);
907 if ( !strncmp(s, pfx, len) )
909 //# We're on a branch. It might not exist. But
910 //# HEAD looks good enough to be a branch.
911 CStringA utf8Branch(s + len);
912 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
913 sBranchOut.TrimRight(L" \r\n\t");
915 if ( sBranchOut.IsEmpty() )
916 return -1;
918 else if (fallback)
920 CStringA utf8Hash(s);
921 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
922 unicodeHash.TrimRight(L" \r\n\t");
923 if (CGitHash::IsValidSHA1(unicodeHash))
924 sBranchOut = unicodeHash;
925 else
926 //# Assume this is a detached head.
927 sBranchOut = L"HEAD";
928 return 1;
930 else
932 //# Assume this is a detached head.
933 sBranchOut = "HEAD";
935 return 1;
938 return 0;
941 int CGit::BuildOutputFormat(CString &format,bool IsFull)
943 CString log;
944 log.Format(L"#<%c>%%x00", LOG_REV_ITEM_BEGIN);
945 format += log;
946 if(IsFull)
948 log.Format(L"#<%c>%%an%%x00", LOG_REV_AUTHOR_NAME);
949 format += log;
950 log.Format(L"#<%c>%%ae%%x00", LOG_REV_AUTHOR_EMAIL);
951 format += log;
952 log.Format(L"#<%c>%%ai%%x00", LOG_REV_AUTHOR_DATE);
953 format += log;
954 log.Format(L"#<%c>%%cn%%x00", LOG_REV_COMMIT_NAME);
955 format += log;
956 log.Format(L"#<%c>%%ce%%x00", LOG_REV_COMMIT_EMAIL);
957 format += log;
958 log.Format(L"#<%c>%%ci%%x00", LOG_REV_COMMIT_DATE);
959 format += log;
960 log.Format(L"#<%c>%%b%%x00", LOG_REV_COMMIT_BODY);
961 format += log;
964 log.Format(L"#<%c>%%m%%H%%x00", LOG_REV_COMMIT_HASH);
965 format += log;
966 log.Format(L"#<%c>%%P%%x00", LOG_REV_COMMIT_PARENT);
967 format += log;
968 log.Format(L"#<%c>%%s%%x00", LOG_REV_COMMIT_SUBJECT);
969 format += log;
971 if(IsFull)
973 log.Format(L"#<%c>%%x00", LOG_REV_COMMIT_FILE);
974 format += log;
976 return 0;
979 CString CGit::GetLogCmd(CString range, const CTGitPath* path, int mask, CFilterData* Filter, int logOrderBy)
981 CString param;
983 if(mask& LOG_INFO_STAT )
984 param += L" --numstat";
985 if(mask& LOG_INFO_FILESTATE)
986 param += L" --raw";
988 if(mask& LOG_INFO_BOUNDARY)
989 param += L" --left-right --boundary";
991 if(mask& CGit::LOG_INFO_ALL_BRANCH)
993 param += L" --all";
994 range.Empty();
997 if (mask& CGit::LOG_INFO_BASIC_REFS)
999 param += L" --branches";
1000 param += L" --tags";
1001 param += L" --remotes";
1002 param += L" --glob=stas[h]"; // require at least one glob operator
1003 param += L" --glob=bisect";
1004 range.Empty();
1007 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
1009 param += L" --branches";
1010 range.Empty();
1013 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
1014 param.AppendFormat(L" -C%d%%", ms_iSimilarityIndexThreshold);
1016 if(mask& CGit::LOG_INFO_DETECT_RENAME )
1017 param.AppendFormat(L" -M%d%%", ms_iSimilarityIndexThreshold);
1019 if(mask& CGit::LOG_INFO_FIRST_PARENT )
1020 param += L" --first-parent";
1022 if(mask& CGit::LOG_INFO_NO_MERGE )
1023 param += L" --no-merges";
1025 if(mask& CGit::LOG_INFO_FOLLOW)
1026 param += L" --follow";
1028 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
1029 param += L" -c";
1031 if(mask& CGit::LOG_INFO_FULL_DIFF)
1032 param += L" --full-diff";
1034 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
1035 param += L" --simplify-by-decoration";
1037 if (Filter)
1039 if (Filter->m_NumberOfLogsScale >= CFilterData::SHOW_LAST_N_YEARS)
1041 CTime now = CTime::GetCurrentTime();
1042 CTime time = CTime(now.GetYear(), now.GetMonth(), now.GetDay(), 0, 0, 0);
1043 __time64_t substract = 86400;
1044 CString scale;
1045 switch (Filter->m_NumberOfLogsScale)
1047 case CFilterData::SHOW_LAST_N_YEARS:
1048 substract *= 365;
1049 break;
1050 case CFilterData::SHOW_LAST_N_MONTHS:
1051 substract *= 30;
1052 break;
1053 case CFilterData::SHOW_LAST_N_WEEKS:
1054 substract *= 7;
1055 break;
1057 Filter->m_From = (DWORD)time.GetTime() - (Filter->m_NumberOfLogs * substract);
1059 if (Filter->m_NumberOfLogsScale == CFilterData::SHOW_LAST_N_COMMITS)
1060 param.AppendFormat(L" -n%ld", Filter->m_NumberOfLogs);
1061 else if (Filter->m_NumberOfLogsScale >= CFilterData::SHOW_LAST_SEL_DATE && Filter->m_From > 0)
1062 param.AppendFormat(L" --max-age=%I64u", Filter->m_From);
1065 if( Filter && (Filter->m_To != -1))
1066 param.AppendFormat(L" --min-age=%I64u", Filter->m_To);
1068 if (logOrderBy == LOG_ORDER_TOPOORDER || (mask & CGit::LOG_ORDER_TOPOORDER))
1069 param += L" --topo-order";
1070 else if (logOrderBy == LOG_ORDER_DATEORDER)
1071 param += L" --date-order";
1073 CString cmd;
1074 CString file;
1075 if (path)
1076 file.Format(L" \"%s\"", (LPCTSTR)path->GetGitPathString());
1077 // gitdll.dll:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
1078 cmd.Format(L"-z%s %s --parents --%s", (LPCTSTR)param, (LPCTSTR)range, (LPCTSTR)file);
1080 return cmd;
1082 #define BUFSIZE 512
1083 void GetTempPath(CString &path)
1085 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1086 DWORD dwRetVal;
1087 DWORD dwBufSize=BUFSIZE;
1088 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1089 lpPathBuffer); // buffer for path
1090 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1091 path.Empty();
1092 path.Format(L"%s", lpPathBuffer);
1094 CString GetTempFile()
1096 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1097 DWORD dwRetVal;
1098 DWORD dwBufSize=BUFSIZE;
1099 TCHAR szTempName[BUFSIZE] = { 0 };
1100 UINT uRetVal;
1102 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1103 lpPathBuffer); // buffer for path
1104 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1105 return L"";
1107 // Create a temporary file.
1108 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1109 TEXT("Patch"), // temp file name prefix
1110 0, // create unique name
1111 szTempName); // buffer for name
1113 if (uRetVal == 0)
1114 return L"";
1116 return CString(szTempName);
1119 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1121 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1122 if (result == 0) return 0;
1123 if (!lpBuffer || (result + 13 > nBufferLength))
1125 if (lpBuffer)
1126 lpBuffer[0] = '\0';
1127 return result + 13;
1130 wcscat_s(lpBuffer, nBufferLength, L"TortoiseGit\\");
1131 CreateDirectory(lpBuffer, nullptr);
1133 return result + 13;
1136 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1138 PROCESS_INFORMATION pi;
1139 CAutoGeneralHandle hReadErr;
1140 if (RunAsync(cmd, &pi, nullptr, hReadErr.GetPointer(), &filename))
1141 return TGIT_GIT_ERROR_CREATE_PROCESS;
1143 CAutoGeneralHandle piThread(std::move(pi.hThread));
1144 CAutoGeneralHandle piProcess(std::move(pi.hProcess));
1146 BYTE_VECTOR stderrVector;
1147 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1148 ASYNCREADSTDERRTHREADARGS threadArguments;
1149 threadArguments.fileHandle = hReadErr;
1150 threadArguments.pcall = &pcall;
1151 CAutoGeneralHandle thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1153 if (thread)
1155 CAutoLocker lock(m_critSecThreadMap);
1156 m_AsyncReadStdErrThreadMap[GetCurrentThreadId()] = thread;
1159 WaitForSingleObject(pi.hProcess,INFINITE);
1161 if (thread)
1163 WaitForSingleObject(thread, INFINITE);
1165 CAutoLocker lock(m_critSecThreadMap);
1166 m_AsyncReadStdErrThreadMap.erase(GetCurrentThreadId());
1169 stderrVector.push_back(0);
1170 StringAppend(stdErr, stderrVector.data(), CP_UTF8);
1172 DWORD exitcode = 0;
1173 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1175 CString err = CFormatMessageWrapper();
1176 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": could not get exit code: %s\n", (LPCTSTR)err.Trim());
1177 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1179 else
1180 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": process exited: %d\n", exitcode);
1182 return exitcode;
1185 CAutoRepository CGit::GetGitRepository() const
1187 return CAutoRepository(GetGitPathStringA(m_CurrentDir));
1190 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1192 ATLASSERT(repo);
1194 // no need to parse a ref if it's already a 40-byte hash
1195 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1197 hash = CGitHash(friendname);
1198 return 0;
1201 int isHeadOrphan = git_repository_head_unborn(repo);
1202 if (isHeadOrphan != 0)
1204 hash.Empty();
1205 if (isHeadOrphan == 1)
1206 return 0;
1207 else
1208 return -1;
1211 CAutoObject gitObject;
1212 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1213 return -1;
1215 hash = git_object_id(gitObject);
1217 return 0;
1220 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1222 // no need to parse a ref if it's already a 40-byte hash
1223 if (CGitHash::IsValidSHA1(friendname))
1225 hash = CGitHash(friendname);
1226 return 0;
1229 if (m_IsUseLibGit2)
1231 CAutoRepository repo(GetGitRepository());
1232 if (!repo)
1233 return -1;
1235 return GetHash(repo, hash, friendname, true);
1237 else
1239 CString branch = FixBranchName(friendname);
1240 if (friendname == L"FETCH_HEAD" && branch.IsEmpty())
1241 branch = friendname;
1242 CString cmd;
1243 cmd.Format(L"git.exe rev-parse %s", (LPCTSTR)branch);
1244 gitLastErr.Empty();
1245 int ret = Run(cmd, &gitLastErr, nullptr, CP_UTF8);
1246 hash = CGitHash(gitLastErr.Trim());
1247 if (ret == 0)
1248 gitLastErr.Empty();
1249 else if (friendname == L"HEAD") // special check for unborn branch
1251 CString currentbranch;
1252 if (GetCurrentBranchFromFile(m_CurrentDir, currentbranch))
1253 return -1;
1254 gitLastErr.Empty();
1255 return 0;
1257 return ret;
1261 int CGit::GetInitAddList(CTGitPathList &outputlist)
1263 BYTE_VECTOR cmdout;
1265 outputlist.Clear();
1266 if (Run(L"git.exe ls-files -s -t -z", &cmdout))
1267 return -1;
1269 if (outputlist.ParserFromLsFile(cmdout))
1270 return -1;
1271 for(int i = 0; i < outputlist.GetCount(); ++i)
1272 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1274 return 0;
1276 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1278 CString cmd;
1279 CString ignore;
1280 if (ignoreSpaceAtEol)
1281 ignore += L" --ignore-space-at-eol";
1282 if (ignoreSpaceChange)
1283 ignore += L" --ignore-space-change";
1284 if (ignoreAllSpace)
1285 ignore += L" --ignore-all-space";
1286 if (ignoreBlankLines)
1287 ignore += L" --ignore-blank-lines";
1289 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1291 if(rev1 == GIT_REV_ZERO)
1292 cmd.Format(L"git.exe diff -r --raw -C%d%% -M%d%% --numstat -z %s %s --", ms_iSimilarityIndexThreshold, ms_iSimilarityIndexThreshold, (LPCTSTR)ignore, (LPCTSTR)rev2);
1293 else
1294 cmd.Format(L"git.exe diff -r -R --raw -C%d%% -M%d%% --numstat -z %s %s --", ms_iSimilarityIndexThreshold, ms_iSimilarityIndexThreshold, (LPCTSTR)ignore, (LPCTSTR)rev1);
1296 else
1297 cmd.Format(L"git.exe diff-tree -r --raw -C%d%% -M%d%% --numstat -z %s %s %s --", ms_iSimilarityIndexThreshold, ms_iSimilarityIndexThreshold, (LPCTSTR)ignore, (LPCTSTR)rev2, (LPCTSTR)rev1);
1299 BYTE_VECTOR out;
1300 if (Run(cmd, &out))
1301 return -1;
1303 return outputlist.ParserFromLog(out);
1306 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1308 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1309 list->push_back(CUnicodeUtils::GetUnicode(refname));
1310 return 0;
1313 int CGit::GetTagList(STRING_VECTOR &list)
1315 size_t prevCount = list.size();
1316 if (this->m_IsUseLibGit2)
1318 CAutoRepository repo(GetGitRepository());
1319 if (!repo)
1320 return -1;
1322 CAutoStrArray tag_names;
1324 if (git_tag_list(tag_names, repo))
1325 return -1;
1327 for (size_t i = 0; i < tag_names->count; ++i)
1329 CStringA tagName(tag_names->strings[i]);
1330 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1333 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1335 return 0;
1337 else
1339 int ret = Run(L"git.exe tag -l", [&](const CStringA& lineA)
1341 if (lineA.IsEmpty())
1342 return;
1343 list.push_back(CUnicodeUtils::GetUnicode(lineA));
1345 if (!ret)
1346 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1347 else if (ret == 1 && IsInitRepos())
1348 return 0;
1349 return ret;
1353 CString CGit::GetGitLastErr(const CString& msg)
1355 if (this->m_IsUseLibGit2)
1356 return GetLibGit2LastErr(msg);
1357 else if (gitLastErr.IsEmpty())
1358 return msg + L"\nUnknown git.exe error.";
1359 else
1361 CString lastError = gitLastErr;
1362 gitLastErr.Empty();
1363 return msg + L'\n' + lastError;
1367 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1369 if (UsingLibGit2(cmd))
1370 return GetLibGit2LastErr(msg);
1371 else if (gitLastErr.IsEmpty())
1372 return msg + L"\nUnknown git.exe error.";
1373 else
1375 CString lastError = gitLastErr;
1376 gitLastErr.Empty();
1377 return msg + L'\n' + lastError;
1381 CString CGit::GetLibGit2LastErr()
1383 const git_error *libgit2err = giterr_last();
1384 if (libgit2err)
1386 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1387 giterr_clear();
1388 return L"libgit2 returned: " + lastError;
1390 else
1391 return L"An error occoured in libgit2, but no message is available.";
1394 CString CGit::GetLibGit2LastErr(const CString& msg)
1396 if (!msg.IsEmpty())
1397 return msg + L'\n' + GetLibGit2LastErr();
1398 return GetLibGit2LastErr();
1401 CString CGit::FixBranchName_Mod(CString& branchName)
1403 if (branchName == L"FETCH_HEAD")
1404 branchName = DerefFetchHead();
1405 return branchName;
1408 CString CGit::FixBranchName(const CString& branchName)
1410 CString tempBranchName = branchName;
1411 FixBranchName_Mod(tempBranchName);
1412 return tempBranchName;
1415 bool CGit::IsBranchTagNameUnique(const CString& name)
1417 if (m_IsUseLibGit2)
1419 CAutoRepository repo(GetGitRepository());
1420 if (!repo)
1421 return true; // TODO: optimize error reporting
1423 CAutoReference tagRef;
1424 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1425 return true;
1427 CAutoReference branchRef;
1428 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1429 return true;
1431 return false;
1433 // else
1434 CString cmd;
1435 cmd.Format(L"git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s", (LPCTSTR)name, (LPCTSTR)name);
1437 int refCnt = 0;
1438 Run(cmd, [&](const CStringA& lineA)
1440 if (lineA.IsEmpty())
1441 return;
1442 ++refCnt;
1445 return (refCnt <= 1);
1448 bool CGit::IsLocalBranch(const CString& shortName)
1450 STRING_VECTOR list;
1451 GetBranchList(list, nullptr, CGit::BRANCH_LOCAL);
1452 return std::find(list.cbegin(), list.cend(), shortName) != list.cend();
1455 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1457 if (m_IsUseLibGit2)
1459 CAutoRepository repo(GetGitRepository());
1460 if (!repo)
1461 return false; // TODO: optimize error reporting
1463 CString prefix;
1464 if (isBranch)
1465 prefix = L"refs/heads/";
1466 else
1467 prefix = L"refs/tags/";
1469 CAutoReference ref;
1470 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1471 return false;
1473 return true;
1475 // else
1476 CString cmd, output;
1478 cmd = L"git.exe show-ref ";
1479 if (isBranch)
1480 cmd += L"--heads ";
1481 else
1482 cmd += L"--tags ";
1484 cmd += L"refs/heads/" + name;
1485 cmd += L" refs/tags/" + name;
1487 int ret = Run(cmd, &output, nullptr, CP_UTF8);
1488 if (!ret)
1490 if (!output.IsEmpty())
1491 return true;
1494 return false;
1497 CString CGit::DerefFetchHead()
1499 CString dotGitPath;
1500 GitAdminDir::GetWorktreeAdminDirPath(m_CurrentDir, dotGitPath);
1501 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1502 int forMergeLineCount = 0;
1503 std::string line;
1504 std::string hashToReturn;
1505 while(getline(fetchHeadFile, line))
1507 //Tokenize this line
1508 std::string::size_type prevPos = 0;
1509 std::string::size_type pos = line.find('\t');
1510 if(pos == std::string::npos) continue; //invalid line
1512 std::string hash = line.substr(0, pos);
1513 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1515 bool forMerge = pos == prevPos;
1516 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1518 //std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1520 //Process this line
1521 if(forMerge)
1523 hashToReturn = hash;
1524 ++forMergeLineCount;
1525 if(forMergeLineCount > 1)
1526 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1530 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1533 int CGit::GetBranchList(STRING_VECTOR &list, int *current, BRANCH_TYPE type, bool skipCurrent /*false*/)
1535 size_t prevCount = list.size();
1536 int ret = 0;
1537 CString cur;
1538 bool headIsDetached = false;
1539 if (m_IsUseLibGit2)
1541 CAutoRepository repo(GetGitRepository());
1542 if (!repo)
1543 return -1;
1545 if (git_repository_head_detached(repo) == 1)
1546 headIsDetached = true;
1548 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1550 git_branch_t flags = GIT_BRANCH_LOCAL;
1551 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1552 flags = GIT_BRANCH_ALL;
1553 else if (type & BRANCH_REMOTE)
1554 flags = GIT_BRANCH_REMOTE;
1556 CAutoBranchIterator it;
1557 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1558 return -1;
1560 CAutoReference ref;
1561 git_branch_t branchType;
1562 while (git_branch_next(ref.GetPointer(), &branchType, it) == 0)
1564 const char * name = nullptr;
1565 if (git_branch_name(&name, ref))
1566 continue;
1568 CString branchname = CUnicodeUtils::GetUnicode(name);
1569 if (branchType & GIT_BRANCH_REMOTE)
1570 list.push_back(L"remotes/" + branchname);
1571 else
1573 if (git_branch_is_head(ref))
1575 if (skipCurrent)
1576 continue;
1577 cur = branchname;
1579 list.push_back(branchname);
1584 else
1586 CString cmd = L"git.exe branch --no-color";
1588 if ((type & BRANCH_ALL) == BRANCH_ALL)
1589 cmd += L" -a";
1590 else if (type & BRANCH_REMOTE)
1591 cmd += L" -r";
1593 ret = Run(cmd, [&](CStringA lineA)
1595 lineA.Trim(" \r\n\t");
1596 if (lineA.IsEmpty())
1597 return;
1598 if (lineA.Find(" -> ") >= 0)
1599 return; // skip something like: refs/origin/HEAD -> refs/origin/master
1601 CString branch = CUnicodeUtils::GetUnicode(lineA);
1602 if (lineA[0] == '*')
1604 if (skipCurrent)
1605 return;
1606 branch = branch.Mid((int)wcslen(L"* "));
1607 cur = branch;
1609 // check whether HEAD is detached
1610 CString currentHead;
1611 if (branch[0] == L'(' && GetCurrentBranchFromFile(m_CurrentDir, currentHead) == 1)
1613 headIsDetached = true;
1614 return;
1617 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1618 branch = L"remotes/" + branch;
1619 list.push_back(branch);
1621 if (ret == 1 && IsInitRepos())
1622 return 0;
1625 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1626 list.push_back(L"FETCH_HEAD");
1628 std::sort(list.begin() + prevCount, list.end(), LogicalCompareBranchesPredicate);
1630 if (current && !headIsDetached && !skipCurrent)
1632 for (unsigned int i = 0; i < list.size(); ++i)
1634 if (list[i] == cur)
1636 *current = i;
1637 break;
1642 return ret;
1645 int CGit::GetRefsCommitIsOn(STRING_VECTOR& list, const CGitHash& hash, bool includeTags, bool includeBranches, BRANCH_TYPE type)
1647 if (!includeTags && !includeBranches || hash.IsEmpty())
1648 return 0;
1650 size_t prevCount = list.size();
1651 if (m_IsUseLibGit2)
1653 CAutoRepository repo(GetGitRepository());
1654 if (!repo)
1655 return -1;
1657 CAutoReferenceIterator it;
1658 if (git_reference_iterator_new(it.GetPointer(), repo))
1659 return -1;
1661 auto checkDescendent = [&list, &hash, &repo](const git_oid* oid, const git_reference* ref) {
1662 if (!oid)
1663 return;
1664 if (git_oid_equal(oid, hash) || git_graph_descendant_of(repo, oid, hash) == 1)
1666 const char* name = git_reference_name(ref);
1667 if (!name)
1668 return;
1670 list.push_back(CUnicodeUtils::GetUnicode(name));
1674 CAutoReference ref;
1675 while (git_reference_next(ref.GetPointer(), it) == 0)
1677 if (git_reference_is_tag(ref))
1679 if (!includeTags)
1680 continue;
1682 CAutoTag tag;
1683 if (git_tag_lookup(tag.GetPointer(), repo, git_reference_target(ref)) == 0)
1685 CAutoObject obj;
1686 if (git_tag_peel(obj.GetPointer(), tag) < 0)
1687 continue;
1688 checkDescendent(git_object_id(obj), ref);
1689 continue;
1692 else if (git_reference_is_remote(ref))
1694 if (!includeBranches || !(type & BRANCH_REMOTE))
1695 continue;
1697 else if (git_reference_is_branch(ref))
1699 if (!includeBranches || !(type & GIT_BRANCH_LOCAL))
1700 continue;
1702 else
1703 continue;
1705 if (git_reference_type(ref) == GIT_REF_SYMBOLIC)
1707 CAutoReference peeledRef;
1708 if (git_reference_resolve(peeledRef.GetPointer(), ref) < 0)
1709 continue;
1711 checkDescendent(git_reference_target(peeledRef), ref);
1712 continue;
1715 checkDescendent(git_reference_target(ref), ref);
1718 else
1720 if (includeBranches)
1722 CString cmd = L"git.exe branch --no-color";
1723 if ((type & BRANCH_ALL) == BRANCH_ALL)
1724 cmd += L" -a";
1725 else if (type & BRANCH_REMOTE)
1726 cmd += L" -r";
1727 cmd += L" --contains " + hash.ToString();
1729 if (Run(cmd, [&](CStringA lineA)
1731 lineA.Trim(" \r\n\t");
1732 if (lineA.IsEmpty())
1733 return;
1734 if (lineA.Find(" -> ") >= 0) // normalize symbolic refs: "refs/origin/HEAD -> refs/origin/master" to "refs/origin/HEAD"
1735 lineA.Truncate(lineA.Find(" -> "));
1737 CString branch = CUnicodeUtils::GetUnicode(lineA);
1738 if (lineA[0] == '*')
1740 branch = branch.Mid((int)wcslen(L"* "));
1741 CString currentHead;
1742 if (branch[0] == L'(' && GetCurrentBranchFromFile(m_CurrentDir, currentHead) == 1)
1743 return;
1746 if ((type & BRANCH_REMOTE) != 0 && (type & BRANCH_LOCAL) == 0)
1747 branch = L"refs/remotes/" + branch;
1748 else if (CStringUtils::StartsWith(branch, L"remotes/"))
1749 branch = L"refs/" + branch;
1750 else
1751 branch = L"refs/heads/" + branch;
1752 list.push_back(branch);
1754 return -1;
1757 if (includeTags)
1759 CString cmd = L"git.exe tag --contains " + hash.ToString();
1760 if (Run(cmd, [&list](CStringA lineA)
1762 if (lineA.IsEmpty())
1763 return;
1764 list.push_back(L"refs/tags/" + CUnicodeUtils::GetUnicode(lineA));
1766 return -1;
1770 std::sort(list.begin() + prevCount, list.end(), LogicalCompareBranchesPredicate);
1771 list.erase(std::unique(list.begin() + prevCount, list.end()), list.end());
1773 return 0;
1776 int CGit::GetRemoteList(STRING_VECTOR &list)
1778 size_t prevCount = list.size();
1779 if (this->m_IsUseLibGit2)
1781 CAutoRepository repo(GetGitRepository());
1782 if (!repo)
1783 return -1;
1785 CAutoStrArray remotes;
1786 if (git_remote_list(remotes, repo))
1787 return -1;
1789 for (size_t i = 0; i < remotes->count; ++i)
1791 CStringA remote(remotes->strings[i]);
1792 list.push_back(CUnicodeUtils::GetUnicode(remote));
1795 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1797 return 0;
1800 return Run(L"git.exe remote", [&](const CStringA& lineA)
1802 if (lineA.IsEmpty())
1803 return;
1804 list.push_back(CUnicodeUtils::GetUnicode(lineA));
1808 int CGit::GetRemoteTags(const CString& remote, REF_VECTOR& list)
1810 size_t prevCount = list.size();
1811 if (UsingLibGit2(GIT_CMD_FETCH))
1813 CAutoRepository repo(GetGitRepository());
1814 if (!repo)
1815 return -1;
1817 CStringA remoteA = CUnicodeUtils::GetUTF8(remote);
1818 CAutoRemote gitremote;
1819 // first try with a named remote (e.g. "origin")
1820 if (git_remote_lookup(gitremote.GetPointer(), repo, remoteA) < 0)
1822 // retry with repository located at a specific url
1823 if (git_remote_create_anonymous(gitremote.GetPointer(), repo, remoteA) < 0)
1824 return -1;
1827 git_remote_callbacks callbacks = GIT_REMOTE_CALLBACKS_INIT;
1828 callbacks.credentials = g_Git2CredCallback;
1829 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1830 git_proxy_options proxy = GIT_PROXY_OPTIONS_INIT;
1831 proxy.type = GIT_PROXY_AUTO;
1832 if (git_remote_connect(gitremote, GIT_DIRECTION_FETCH, &callbacks, &proxy, nullptr) < 0)
1833 return -1;
1835 const git_remote_head** heads = nullptr;
1836 size_t size = 0;
1837 if (git_remote_ls(&heads, &size, gitremote) < 0)
1838 return -1;
1840 for (size_t i = 0; i < size; i++)
1842 CString ref = CUnicodeUtils::GetUnicode(heads[i]->name);
1843 CString shortname;
1844 if (!GetShortName(ref, shortname, L"refs/tags/"))
1845 continue;
1846 list.emplace_back(TGitRef{ shortname, &heads[i]->oid });
1848 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1849 return 0;
1852 CString cmd;
1853 cmd.Format(L"git.exe ls-remote -t \"%s\"", (LPCTSTR)remote);
1854 gitLastErr = cmd + L'\n';
1855 if (Run(cmd, [&](CStringA lineA)
1857 CGitHash hash;
1858 hash.ConvertFromStrA(lineA.Left(GIT_HASH_SIZE * 2));
1859 lineA = lineA.Mid(GIT_HASH_SIZE * 2 + (int)wcslen(L"\trefs/tags/")); // sha1, tab + refs/tags/
1860 if (!lineA.IsEmpty())
1861 list.emplace_back(TGitRef{ CUnicodeUtils::GetUnicode(lineA), hash });
1862 }, &gitLastErr))
1863 return -1;
1864 std::sort(list.begin() + prevCount, list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1865 return 0;
1868 int CGit::DeleteRemoteRefs(const CString& sRemote, const STRING_VECTOR& list)
1870 if (UsingLibGit2(GIT_CMD_PUSH))
1872 CAutoRepository repo(GetGitRepository());
1873 if (!repo)
1874 return -1;
1876 CStringA remoteA = CUnicodeUtils::GetUTF8(sRemote);
1877 CAutoRemote remote;
1878 if (git_remote_lookup(remote.GetPointer(), repo, remoteA) < 0)
1879 return -1;
1881 git_push_options pushOpts = GIT_PUSH_OPTIONS_INIT;
1882 git_remote_callbacks& callbacks = pushOpts.callbacks;
1883 callbacks.credentials = g_Git2CredCallback;
1884 callbacks.certificate_check = g_Git2CheckCertificateCallback;
1885 std::vector<CStringA> refspecs;
1886 for (const auto& ref : list)
1887 refspecs.push_back(CUnicodeUtils::GetUTF8(L":" + ref));
1889 std::vector<char*> vc;
1890 vc.reserve(refspecs.size());
1891 std::transform(refspecs.begin(), refspecs.end(), std::back_inserter(vc), [](CStringA& s) -> char* { return s.GetBuffer(); });
1892 git_strarray specs = { vc.data(), vc.size() };
1894 if (git_remote_push(remote, &specs, &pushOpts) < 0)
1895 return -1;
1897 else
1899 CMassiveGitTaskBase mgtPush(L"push " + sRemote, FALSE);
1900 for (const auto& ref : list)
1901 mgtPush.AddFile(L':' + ref);
1903 BOOL cancel = FALSE;
1904 mgtPush.Execute(cancel);
1907 return 0;
1910 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1912 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1913 list->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref)));
1914 return 0;
1917 int CGit::GetRefList(STRING_VECTOR &list)
1919 size_t prevCount = list.size();
1920 if (this->m_IsUseLibGit2)
1922 CAutoRepository repo(GetGitRepository());
1923 if (!repo)
1924 return -1;
1926 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1927 return -1;
1929 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1931 return 0;
1934 int ret = Run(L"git.exe show-ref -d", [&](const CStringA& lineA)
1936 int start = lineA.Find(L' ');
1937 ASSERT(start == 2 * GIT_HASH_SIZE);
1938 if (start <= 0)
1939 return;
1941 CString name = CUnicodeUtils::GetUnicode(lineA.Mid(start + 1));
1942 if (list.empty() || name != *list.crbegin() + L"^{}")
1943 list.push_back(name);
1945 if (!ret)
1946 std::sort(list.begin() + prevCount, list.end(), LogicalComparePredicate);
1947 else if (ret == 1 && IsInitRepos())
1948 return 0;
1949 return ret;
1952 typedef struct map_each_ref_payload {
1953 git_repository * repo;
1954 MAP_HASH_NAME * map;
1955 } map_each_ref_payload;
1957 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1959 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1961 CString str = CUnicodeUtils::GetUnicode(git_reference_name(ref));
1963 CAutoObject gitObject;
1964 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1965 return (git_reference_is_remote(ref) && git_reference_type(ref) == GIT_REF_SYMBOLIC) ? 0 : 1; // don't bail out for symbolic remote references ("git.exe show-ref -d" also doesn't complain), cf. issue #2926
1967 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1969 str += L"^{}"; // deref tag
1970 CAutoObject derefedTag;
1971 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1972 return 1;
1973 gitObject.Swap(derefedTag);
1976 (*payloadContent->map)[git_object_id(gitObject)].push_back(str);
1978 return 0;
1980 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1982 ATLASSERT(repo);
1984 map_each_ref_payload payloadContent = { repo, &map };
1986 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1987 return -1;
1989 for (auto it = map.begin(); it != map.end(); ++it)
1991 std::sort(it->second.begin(), it->second.end());
1994 return 0;
1997 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1999 if (this->m_IsUseLibGit2)
2001 CAutoRepository repo(GetGitRepository());
2002 if (!repo)
2003 return -1;
2005 return GetMapHashToFriendName(repo, map);
2008 int ret = Run(L"git.exe show-ref -d", [&](const CStringA& lineA)
2010 int start = lineA.Find(L' ');
2011 ASSERT(start == 2 * GIT_HASH_SIZE);
2012 if (start <= 0)
2013 return;
2015 CGitHash hash;
2016 hash.ConvertFromStrA(lineA);
2017 map[hash].push_back(CUnicodeUtils::GetUnicode(lineA.Mid(start + 1)));
2020 if (ret == 1 && IsInitRepos())
2021 return 0;
2022 return ret;
2025 int CGit::GuessRefForHash(CString& ref, const CGitHash& hash)
2027 MAP_HASH_NAME map;
2028 if (GetMapHashToFriendName(map))
2029 return -1;
2031 auto it = map.find(hash);
2032 if (it == map.cend())
2034 ref = hash.ToString().Left(GetShortHASHLength());
2035 return 0;
2038 const auto& reflist = it->second;
2039 for (const auto& reftype : { L"refs/heads/", L"refs/remotes/", L"refs/tags/" })
2041 auto found = std::find_if(reflist.cbegin(), reflist.cend(), [&reftype](const auto& ref) { return CStringUtils::StartsWith(ref, reftype); });
2042 if (found == reflist.cend())
2043 continue;
2045 GetShortName(*found, ref, reftype);
2046 return 0;
2049 ref = hash.ToString().Left(GetShortHASHLength());
2050 return 0;
2053 int CGit::GetBranchDescriptions(MAP_STRING_STRING& map)
2055 CAutoConfig config(true);
2056 if (git_config_add_file_ondisk(config, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL, nullptr, FALSE) < 0)
2057 return -1;
2058 return git_config_foreach_match(config, "^branch\\..*\\.description$", [](const git_config_entry* entry, void* data)
2060 MAP_STRING_STRING* descriptions = (MAP_STRING_STRING*)data;
2061 CString key = CUnicodeUtils::GetUnicode(entry->name);
2062 // extract branch name from config key
2063 key = key.Mid((int)wcslen(L"branch."), key.GetLength() - (int)wcslen(L"branch.") - (int)wcslen(L".description"));
2064 descriptions->insert(std::make_pair(key, CUnicodeUtils::GetUnicode(entry->value)));
2065 return 0;
2066 }, &map);
2069 static void SetLibGit2SearchPath(int level, const CString &value)
2071 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
2072 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, (LPCSTR)valueA);
2075 static void SetLibGit2TemplatePath(const CString &value)
2077 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
2078 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, (LPCSTR)valueA);
2081 int CGit::FindAndSetGitExePath(BOOL bFallback)
2083 CRegString msysdir = CRegString(REG_MSYSGIT_PATH, L"", FALSE);
2084 CString str = msysdir;
2085 if (!str.IsEmpty() && PathFileExists(str + L"\\git.exe"))
2087 CGit::ms_LastMsysGitDir = str;
2088 return TRUE;
2091 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": git.exe not exists: %s\n", (LPCTSTR)CGit::ms_LastMsysGitDir);
2092 if (!bFallback)
2093 return FALSE;
2095 // first, search PATH if git/bin directory is already present
2096 if (FindGitPath())
2098 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": FindGitPath() => %s\n", (LPCTSTR)CGit::ms_LastMsysGitDir);
2099 msysdir = CGit::ms_LastMsysGitDir;
2100 msysdir.write();
2101 return TRUE;
2104 if (FindGitForWindows(str))
2106 msysdir = str;
2107 CGit::ms_LastMsysGitDir = str;
2108 msysdir.write();
2109 return TRUE;
2112 return FALSE;
2115 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
2117 if (m_bInitialized)
2118 return TRUE;
2120 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": CheckMsysGitDir(%d)\n", bFallback);
2121 this->m_Environment.clear();
2122 m_Environment.CopyProcessEnvironment();
2124 // Git for Windows 2.10.1 and 2.10.2 require LC_ALL to be set, see https://tortoisegit.org/issue/2859 and https://github.com/git-for-windows/git/issues/945,
2125 // because MSys2 changed the default to "ASCII". SO, make sure we have a proper default set
2126 if (m_Environment.GetEnv(L"LC_ALL").IsEmpty())
2127 m_Environment.SetEnv(L"LC_ALL", L"C");
2129 // set HOME if not set already
2130 size_t homesize;
2131 _wgetenv_s(&homesize, nullptr, 0, L"HOME");
2132 if (!homesize)
2133 m_Environment.SetEnv(L"HOME", GetHomeDirectory());
2135 //setup ssh client
2136 CString sshclient = CRegString(L"Software\\TortoiseGit\\SSH");
2137 if (sshclient.IsEmpty())
2138 sshclient = CRegString(L"Software\\TortoiseGit\\SSH", L"", FALSE, HKEY_LOCAL_MACHINE);
2140 if(!sshclient.IsEmpty())
2142 m_Environment.SetEnv(L"GIT_SSH", sshclient);
2143 if (CStringUtils::EndsWithI(sshclient, L"tortoisegitplink") || CStringUtils::EndsWithI(sshclient, L"tortoisegitplink.exe"))
2144 m_Environment.SetEnv(L"GIT_SSH_VARIANT", L"ssh");
2145 m_Environment.SetEnv(L"SVN_SSH", sshclient);
2147 else
2149 TCHAR sPlink[MAX_PATH] = {0};
2150 GetModuleFileName(nullptr, sPlink, _countof(sPlink));
2151 LPTSTR ptr = wcsrchr(sPlink, L'\\');
2152 if (ptr) {
2153 wcscpy_s(ptr + 1, _countof(sPlink) - (ptr - sPlink + 1), L"TortoiseGitPlink.exe");
2154 m_Environment.SetEnv(L"GIT_SSH", sPlink);
2155 m_Environment.SetEnv(L"GIT_SSH_VARIANT", L"ssh");
2156 m_Environment.SetEnv(L"SVN_SSH", sPlink);
2161 TCHAR sAskPass[MAX_PATH] = {0};
2162 GetModuleFileName(nullptr, sAskPass, _countof(sAskPass));
2163 LPTSTR ptr = wcsrchr(sAskPass, L'\\');
2164 if (ptr)
2166 wcscpy_s(ptr + 1, _countof(sAskPass) - (ptr - sAskPass + 1), L"SshAskPass.exe");
2167 m_Environment.SetEnv(L"DISPLAY",L":9999");
2168 m_Environment.SetEnv(L"SSH_ASKPASS",sAskPass);
2169 m_Environment.SetEnv(L"GIT_ASKPASS",sAskPass);
2170 m_Environment.SetEnv(L"GIT_ASK_YESNO", sAskPass);
2174 if (!FindAndSetGitExePath(bFallback))
2175 return FALSE;
2177 CString msysGitDir;
2178 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + L"\\..\\");
2179 static const CString prefixes[] = { L"mingw64\\etc", L"mingw32\\etc", L"etc" };
2180 static const int prefixes_len[] = { 8, 8, 0 };
2181 for (int i = 0; i < _countof(prefixes); ++i)
2183 #ifndef _WIN64
2184 if (i == 0)
2185 continue;
2186 #endif
2187 if (PathIsDirectory(msysGitDir + prefixes[i])) {
2188 msysGitDir += prefixes[i].Left(prefixes_len[i]);
2189 break;
2192 if (ms_bMsys2Git) // in Msys2 git.exe is in usr\bin; this also need to be after the check for etc folder, as Msys2 also has mingw64\etc, but uses etc
2193 PathCanonicalize(CStrBuf(msysGitDir, MAX_PATH), CGit::ms_LastMsysGitDir + L"\\..\\..");
2194 CGit::ms_MsysGitRootDir = msysGitDir;
2196 if ((CString)CRegString(REG_SYSTEM_GITCONFIGPATH, L"", FALSE) != g_Git.GetGitSystemConfig())
2197 CRegString(REG_SYSTEM_GITCONFIGPATH, L"", FALSE) = g_Git.GetGitSystemConfig();
2199 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": ms_LastMsysGitDir = %s\n", (LPCTSTR)CGit::ms_LastMsysGitDir);
2200 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": ms_MsysGitRootDir = %s\n", (LPCTSTR)CGit::ms_MsysGitRootDir);
2201 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": System config = %s\n", (LPCTSTR)g_Git.GetGitSystemConfig());
2202 if (!ms_bCygwinGit && !ms_bMsys2Git)
2204 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) L": ProgramData config = %s\n", (LPCTSTR)g_Git.GetGitProgramDataConfig());
2205 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA, CTGitPath(g_Git.GetGitProgramDataConfig()).GetContainingDirectory().GetWinPathString());
2207 else
2208 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_PROGRAMDATA, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2210 // Configure libgit2 search paths
2211 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, CTGitPath(g_Git.GetGitSystemConfig()).GetContainingDirectory().GetWinPathString());
2212 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
2213 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
2214 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition = { [](git_smart_subtransport **out, git_transport* owner, void*) -> int { return git_smart_subtransport_ssh_wintunnel(out, owner, FindExecutableOnPath(g_Git.m_Environment.GetEnv(L"GIT_SSH"), g_Git.m_Environment.GetEnv(L"PATH")), g_Git.m_Environment); }, 0 };
2215 git_transport_register("ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2216 git_transport_register("ssh+git", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2217 git_transport_register("git+ssh", git_transport_smart, &ssh_wintunnel_subtransport_definition);
2218 git_libgit2_opts(GIT_OPT_SET_USER_AGENT, "TortoiseGit libgit2");
2219 if (!(ms_bCygwinGit || ms_bMsys2Git))
2220 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + L"share\\git-core\\templates");
2221 else
2222 SetLibGit2TemplatePath(CGit::ms_MsysGitRootDir + L"usr\\share\\git-core\\templates");
2224 m_Environment.AddToPath(CGit::ms_LastMsysGitDir);
2225 m_Environment.AddToPath((CString)CRegString(REG_MSYSGIT_EXTRA_PATH, L"", FALSE));
2227 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2228 // register filter only once
2229 if (!git_filter_lookup("filter"))
2231 CString sh;
2232 for (const CString& binDirPrefix : { L"\\..\\usr\\bin", L"\\..\\bin", L"" })
2234 CString possibleShExe = CGit::ms_LastMsysGitDir + binDirPrefix + L"\\sh.exe";
2235 if (PathFileExists(possibleShExe))
2237 CString temp;
2238 PathCanonicalize(CStrBuf(temp, MAX_PATH), possibleShExe);
2239 sh.Format(L"\"%s\"", (LPCTSTR)temp);
2240 // we need to put the usr\bin folder on the path for Git for Windows based on msys2
2241 m_Environment.AddToPath(temp.Left(temp.GetLength() - (int)wcslen(L"\\sh.exe")));
2242 break;
2246 // Add %GIT_EXEC_PATH% to %PATH% when launching libgit2 filter executable
2247 // It is possible that the filter points to a git subcommand, that is located at libexec\git-core
2248 CString gitExecPath = CGit::ms_MsysGitRootDir;
2249 gitExecPath.Append(L"libexec\\git-core");
2250 m_Environment.AddToPath(gitExecPath);
2252 if (git_filter_register("filter", git_filter_filter_new(sh, m_Environment), GIT_FILTER_DRIVER_PRIORITY))
2253 return FALSE;
2255 #endif
2257 m_bInitialized = TRUE;
2258 return true;
2261 CString CGit::GetHomeDirectory() const
2263 const wchar_t * homeDir = wget_windows_home_directory();
2264 return CString(homeDir, (int)wcslen(homeDir));
2267 CString CGit::GetGitLocalConfig() const
2269 CString path;
2270 GitAdminDir::GetAdminDirPath(m_CurrentDir, path);
2271 path += L"config";
2272 return path;
2275 CStringA CGit::GetGitPathStringA(const CString &path)
2277 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
2280 CString CGit::GetGitGlobalConfig() const
2282 return g_Git.GetHomeDirectory() + L"\\.gitconfig";
2285 CString CGit::GetGitGlobalXDGConfigPath() const
2287 return g_Git.GetHomeDirectory() + L"\\.config\\git";
2290 CString CGit::GetGitGlobalXDGConfig() const
2292 return g_Git.GetGitGlobalXDGConfigPath() + L"\\config";
2295 CString CGit::GetGitProgramDataConfig() const
2297 const wchar_t* programdataConfig = wget_program_data_config();
2298 return CString(programdataConfig);
2301 CString CGit::GetGitSystemConfig() const
2303 const wchar_t * systemConfig = wget_msysgit_etc();
2304 return CString(systemConfig, (int)wcslen(systemConfig));
2307 BOOL CGit::CheckCleanWorkTree(bool stagedOk /* false */)
2309 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT))
2311 CAutoRepository repo(GetGitRepository());
2312 if (!repo)
2313 return FALSE;
2315 if (git_repository_head_unborn(repo))
2316 return FALSE;
2318 git_status_options statusopt = GIT_STATUS_OPTIONS_INIT;
2319 statusopt.show = stagedOk ? GIT_STATUS_SHOW_WORKDIR_ONLY : GIT_STATUS_SHOW_INDEX_AND_WORKDIR;
2320 statusopt.flags = GIT_STATUS_OPT_UPDATE_INDEX | GIT_STATUS_OPT_EXCLUDE_SUBMODULES;
2322 CAutoStatusList status;
2323 if (git_status_list_new(status.GetPointer(), repo, &statusopt))
2324 return FALSE;
2326 return (0 == git_status_list_entrycount(status));
2329 if (Run(L"git.exe rev-parse --verify HEAD", nullptr, nullptr, CP_UTF8))
2330 return FALSE;
2332 if (Run(L"git.exe update-index --ignore-submodules --refresh", nullptr, nullptr, CP_UTF8))
2333 return FALSE;
2335 if (Run(L"git.exe diff-files --quiet --ignore-submodules", nullptr, nullptr, CP_UTF8))
2336 return FALSE;
2338 if (!stagedOk && Run(L"git.exe diff-index --cached --quiet HEAD --ignore-submodules --", nullptr, nullptr, CP_UTF8))
2339 return FALSE;
2341 return TRUE;
2343 int CGit::Revert(const CString& commit, const CTGitPathList &list, CString& err)
2345 for (int i = 0; i < list.GetCount(); ++i)
2347 if (Revert(commit, (CTGitPath&)list[i], err))
2348 return -1;
2350 return 0;
2352 int CGit::Revert(const CString& commit, const CTGitPath &path, CString& err)
2354 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2356 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2358 err.Format(L"Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists.", (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2359 return -1;
2361 if (path.Exists())
2363 CString force;
2364 // if the filenames only differ in case, we have to pass "-f"
2365 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2366 force = L"-f ";
2367 CString cmd;
2368 cmd.Format(L"git.exe mv %s-- \"%s\" \"%s\"", (LPCTSTR)force, (LPCTSTR)path.GetGitPathString(), (LPCTSTR)path.GetGitOldPathString());
2369 if (Run(cmd, &err, CP_UTF8))
2370 return -1;
2372 else
2374 CString cmd;
2375 cmd.Format(L"git.exe rm -f --cached -- \"%s\"", (LPCTSTR)path.GetGitPathString());
2376 if (Run(cmd, &err, CP_UTF8))
2377 return -1;
2380 CString cmd;
2381 cmd.Format(L"git.exe checkout %s -f -- \"%s\"", (LPCTSTR)commit, (LPCWSTR)path.GetGitOldPathString());
2382 if (Run(cmd, &err, CP_UTF8))
2383 return -1;
2385 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2386 { //To init git repository, there are not HEAD, so we can use git reset command
2387 CString cmd;
2388 cmd.Format(L"git.exe rm -f --cached -- \"%s\"", (LPCTSTR)path.GetGitPathString());
2390 if (Run(cmd, &err, CP_UTF8))
2391 return -1;
2393 else
2395 CString cmd;
2396 cmd.Format(L"git.exe checkout %s -f -- \"%s\"", (LPCTSTR)commit, (LPCTSTR)path.GetGitPathString());
2397 if (Run(cmd, &err, CP_UTF8))
2398 return -1;
2401 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2403 CString cmd;
2404 cmd.Format(L"git.exe add -f -- \"%s\"", (LPCTSTR)path.GetGitPathString());
2405 if (Run(cmd, &err, CP_UTF8))
2406 return -1;
2409 return 0;
2412 int CGit::HasWorkingTreeConflicts(git_repository* repo)
2414 ATLASSERT(repo);
2416 CAutoIndex index;
2417 if (git_repository_index(index.GetPointer(), repo))
2418 return -1;
2420 return git_index_has_conflicts(index);
2423 int CGit::HasWorkingTreeConflicts()
2425 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS))
2427 CAutoRepository repo(GetGitRepository());
2428 if (!repo)
2429 return -1;
2431 return HasWorkingTreeConflicts(repo);
2434 CString output;
2435 gitLastErr.Empty();
2436 if (Run(L"git.exe ls-files -u -t -z", &output, &gitLastErr, CP_UTF8))
2437 return -1;
2439 return output.IsEmpty() ? 0 : 1;
2442 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2444 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2446 CAutoRepository repo(GetGitRepository());
2447 if (!repo)
2448 return false;
2450 CGitHash fromHash, toHash, baseHash;
2451 if (GetHash(repo, toHash, FixBranchName(to)))
2452 return false;
2454 if (GetHash(repo, fromHash, FixBranchName(from)))
2455 return false;
2457 git_oid baseOid;
2458 if (git_merge_base(&baseOid, repo, toHash, fromHash))
2459 return false;
2461 baseHash = baseOid;
2463 if (commonAncestor)
2464 *commonAncestor = baseHash;
2466 return fromHash == baseHash;
2468 // else
2469 CString base;
2470 CGitHash basehash,hash;
2471 CString cmd;
2472 cmd.Format(L"git.exe merge-base %s %s", (LPCTSTR)FixBranchName(to), (LPCTSTR)FixBranchName(from));
2474 gitLastErr.Empty();
2475 if (Run(cmd, &base, &gitLastErr, CP_UTF8))
2476 return false;
2477 basehash = base.Trim();
2479 GetHash(hash, from);
2481 if (commonAncestor)
2482 *commonAncestor = basehash;
2484 return hash == basehash;
2487 unsigned int CGit::Hash2int(const CGitHash &hash)
2489 int ret=0;
2490 for (int i = 0; i < 4; ++i)
2492 ret = ret << 8;
2493 ret |= static_cast<const unsigned char*>(hash)[i];
2495 return ret;
2498 int CGit::RefreshGitIndex()
2500 CString adminDir;
2501 GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir);
2502 // HACK: don't use internal update-index if we have a git-lfs enabled repository as the libgit version fails when executing the filter, issue #3220
2503 if (g_Git.m_IsUseGitDLL && !PathFileExists(adminDir + L"lfs"))
2505 CAutoLocker lock(g_Git.m_critGitDllSec);
2508 g_Git.CheckAndInitDll();
2510 int result = git_update_index();
2511 git_exit_cleanup();
2512 return result;
2514 }catch(...)
2516 git_exit_cleanup();
2517 return -1;
2521 else
2522 return Run(L"git.exe update-index --refresh", nullptr, nullptr, CP_UTF8);
2525 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2527 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2529 CAutoRepository repo(GetGitRepository());
2530 if (!repo)
2531 return -1;
2533 CGitHash hash;
2534 if (GetHash(repo, hash, Refname))
2535 return -1;
2537 CAutoCommit commit;
2538 if (git_commit_lookup(commit.GetPointer(), repo, hash))
2539 return -1;
2541 CAutoTree tree;
2542 if (git_commit_tree(tree.GetPointer(), commit))
2543 return -1;
2545 CAutoTreeEntry entry;
2546 int ret = git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString()));
2547 if (ret)
2548 return ret;
2550 if (git_tree_entry_filemode(entry) == GIT_FILEMODE_COMMIT)
2552 giterr_set_str(GITERR_NONE, "The requested object is a submodule and not a file.");
2553 return -1;
2556 CAutoBlob blob;
2557 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2558 return -1;
2560 CAutoFILE file = _wfsopen(outputfile, L"wb", SH_DENYWR);
2561 if (file == nullptr)
2563 giterr_set_str(GITERR_NONE, "Could not create file.");
2564 return -1;
2566 CAutoBuf buf;
2567 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2568 return -1;
2569 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2571 giterr_set_str(GITERR_OS, "Could not write to file.");
2572 return -1;
2575 return 0;
2577 else if (g_Git.m_IsUseGitDLL)
2579 CAutoLocker lock(g_Git.m_critGitDllSec);
2582 g_Git.CheckAndInitDll();
2583 CStringA ref, patha, outa;
2584 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2585 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2586 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2587 ::DeleteFile(outputfile);
2588 int ret = git_checkout_file(ref, patha, outa.GetBuffer());
2589 outa.ReleaseBuffer();
2590 return ret;
2593 catch (const char * msg)
2595 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2596 return -1;
2598 catch (...)
2600 gitLastErr = L"An unknown gitdll.dll error occurred.";
2601 return -1;
2604 else
2606 CString cmd;
2607 cmd.Format(L"git.exe cat-file -p %s:\"%s\"", (LPCTSTR)Refname, (LPCTSTR)path.GetGitPathString());
2608 gitLastErr.Empty();
2609 return RunLogFile(cmd, outputfile, &gitLastErr);
2613 void CEnvironment::clear()
2615 __super::clear();
2616 baseptr = nullptr;
2619 bool CEnvironment::empty()
2621 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2624 CEnvironment::operator LPTSTR()
2626 if (empty())
2627 return nullptr;
2628 return data();
2631 CEnvironment::operator LPWSTR*()
2633 return &baseptr;
2636 void CEnvironment::CopyProcessEnvironment()
2638 if (!empty())
2639 pop_back();
2640 TCHAR *porig = GetEnvironmentStrings();
2641 TCHAR *p = porig;
2642 while(*p !=0 || *(p+1) !=0)
2643 this->push_back(*p++);
2645 push_back(L'\0');
2646 push_back(L'\0');
2647 baseptr = data();
2649 FreeEnvironmentStrings(porig);
2652 CString CEnvironment::GetEnv(const TCHAR *name)
2654 CString str;
2655 for (size_t i = 0; i < size(); ++i)
2657 str = &(*this)[i];
2658 int start =0;
2659 CString sname = str.Tokenize(L"=", start);
2660 if(sname.CompareNoCase(name) == 0)
2661 return &(*this)[i+start];
2662 i+=str.GetLength();
2664 return L"";
2667 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2669 unsigned int i;
2670 for (i = 0; i < size(); ++i)
2672 CString str = &(*this)[i];
2673 int start =0;
2674 CString sname = str.Tokenize(L"=", start);
2675 if(sname.CompareNoCase(name) == 0)
2676 break;
2677 i+=str.GetLength();
2680 if(i == size())
2682 if (!value) // as we haven't found the variable we want to remove, just return
2683 return;
2684 if (i == 0) // make inserting into an empty environment work
2686 this->push_back(L'\0');
2687 ++i;
2689 i -= 1; // roll back terminate \0\0
2690 this->push_back(L'\0');
2693 CEnvironment::iterator it;
2694 it=this->begin();
2695 it += i;
2697 while(*it && i<size())
2699 this->erase(it);
2700 it=this->begin();
2701 it += i;
2704 if (value == nullptr) // remove the variable
2706 this->erase(it);
2707 if (empty())
2708 baseptr = nullptr;
2709 else
2710 baseptr = data();
2711 return;
2714 while(*name)
2716 this->insert(it,*name++);
2717 ++i;
2718 it= begin()+i;
2721 this->insert(it, L'=');
2722 ++i;
2723 it= begin()+i;
2725 while(*value)
2727 this->insert(it,*value++);
2728 ++i;
2729 it= begin()+i;
2731 baseptr = data();
2734 void CEnvironment::AddToPath(CString value)
2736 value.TrimRight(L'\\');
2737 if (value.IsEmpty())
2738 return;
2740 CString path = GetEnv(L"PATH").TrimRight(L';') + L';';
2742 // do not double add paths to %PATH%
2743 if (path.Find(value + L';') >= 0 || path.Find(value + L"\\;") >= 0)
2744 return;
2746 path += value;
2748 SetEnv(L"PATH", path);
2751 int CGit::GetGitEncode(TCHAR* configkey)
2753 CString str=GetConfigValue(configkey);
2755 if(str.IsEmpty())
2756 return CP_UTF8;
2758 return CUnicodeUtils::GetCPCode(str);
2761 int CGit::GetShortHASHLength() const
2763 return 8;
2766 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2768 CString str=ref;
2769 CString shortname;
2770 REF_TYPE type = CGit::UNKNOWN;
2772 if (CGit::GetShortName(str, shortname, L"refs/heads/"))
2773 type = CGit::LOCAL_BRANCH;
2774 else if (CGit::GetShortName(str, shortname, L"refs/remotes/"))
2775 type = CGit::REMOTE_BRANCH;
2776 else if (CStringUtils::EndsWith(str, L"^{}") && CGit::GetShortName(str, shortname, L"refs/tags/"))
2777 type = CGit::ANNOTATED_TAG;
2778 else if (CGit::GetShortName(str, shortname, L"refs/tags/"))
2779 type = CGit::TAG;
2780 else if (CGit::GetShortName(str, shortname, L"refs/stash"))
2782 type = CGit::STASH;
2783 shortname = L"stash";
2785 else if (CGit::GetShortName(str, shortname, L"refs/bisect/"))
2787 CString bisectGood;
2788 CString bisectBad;
2789 g_Git.GetBisectTerms(&bisectGood, &bisectBad);
2790 TCHAR c;
2791 if (CStringUtils::StartsWith(shortname, bisectGood) && ((c = shortname.GetAt(bisectGood.GetLength())) == '-' || c == '\0'))
2793 type = CGit::BISECT_GOOD;
2794 shortname = bisectGood;
2797 if (CStringUtils::StartsWith(shortname, bisectBad) && ((c = shortname.GetAt(bisectBad.GetLength())) == '-' || c == '\0'))
2799 type = CGit::BISECT_BAD;
2800 shortname = bisectBad;
2803 if (CStringUtils::StartsWith(shortname, L"skip") && ((c = shortname.GetAt(4)) == '-' || c == '\0'))
2805 type = CGit::BISECT_SKIP;
2806 shortname = L"skip";
2809 else if (CGit::GetShortName(str, shortname, L"refs/notes/"))
2810 type = CGit::NOTES;
2811 else if (CGit::GetShortName(str, shortname, L"refs/"))
2812 type = CGit::UNKNOWN;
2813 else
2815 type = CGit::UNKNOWN;
2816 shortname = ref;
2819 if(out_type)
2820 *out_type = type;
2822 return shortname;
2825 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2827 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2830 void CGit::SetGit2CredentialCallback(void* callback)
2832 g_Git2CredCallback = (git_cred_acquire_cb)callback;
2835 void CGit::SetGit2CertificateCheckCertificate(void* callback)
2837 g_Git2CheckCertificateCallback = (git_transport_certificate_check_cb)callback;
2840 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const CString& rev1, const CString& rev2, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix)
2842 CString cmd;
2843 if (rev2 == GitRev::GetWorkingCopy())
2844 cmd.Format(L"git.exe diff --stat%s -p %s --", bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev1);
2845 else if (rev1 == GitRev::GetWorkingCopy())
2846 cmd.Format(L"git.exe diff -R --stat%s -p %s --", bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev2);
2847 else
2849 CString merge;
2850 if (bMerge)
2851 merge += L" -m";
2853 if (bCombine)
2854 merge += L" -c";
2856 CString unified;
2857 if (diffContext >= 0)
2858 unified.Format(L" --unified=%d", diffContext);
2859 cmd.Format(L"git.exe diff-tree -r -p%s%s --stat%s %s %s --", (LPCTSTR)merge, (LPCTSTR)unified, bNoPrefix ? L" --no-prefix" : L"", (LPCTSTR)rev1, (LPCTSTR)rev2);
2862 if (!path.IsEmpty())
2864 cmd += L" \"";
2865 cmd += path.GetGitPathString();
2866 cmd += L'"';
2869 return cmd;
2872 static void UnifiedDiffStatToFile(const git_buf* text, void* payload)
2874 ATLASSERT(payload && text);
2875 fwrite(text->ptr, 1, text->size, (FILE *)payload);
2876 fwrite("\n", 1, 1, (FILE *)payload);
2879 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2881 ATLASSERT(payload && line);
2882 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2883 fwrite(&line->origin, 1, 1, (FILE *)payload);
2884 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2885 return 0;
2888 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2890 ATLASSERT(repo && identifier && tree);
2892 /* try to resolve identifier */
2893 CAutoObject obj;
2894 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2895 return -1;
2897 if (obj == nullptr)
2898 return GIT_ENOTFOUND;
2900 int err = 0;
2901 switch (git_object_type(obj))
2903 case GIT_OBJ_TREE:
2904 *tree = (git_tree *)obj.Detach();
2905 break;
2906 case GIT_OBJ_COMMIT:
2907 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2908 break;
2909 default:
2910 err = GIT_ENOTFOUND;
2913 return err;
2916 /* use libgit2 get unified diff */
2917 static int GetUnifiedDiffLibGit2(const CTGitPath& path, const CString& revOld, const CString& revNew, std::function<void(const git_buf*, void*)> statCallback, git_diff_line_cb callback, void* data, bool /* bMerge */, bool bNoPrefix)
2919 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2920 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2922 CAutoRepository repo(g_Git.GetGitRepository());
2923 if (!repo)
2924 return -1;
2926 int isHeadOrphan = git_repository_head_unborn(repo);
2927 if (isHeadOrphan == 1)
2928 return 0;
2929 else if (isHeadOrphan != 0)
2930 return -1;
2932 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2933 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2934 char *buf = pathA.GetBuffer();
2935 if (!pathA.IsEmpty())
2937 opts.pathspec.strings = &buf;
2938 opts.pathspec.count = 1;
2940 if (bNoPrefix)
2942 opts.new_prefix = "";
2943 opts.old_prefix = "";
2945 CAutoDiff diff;
2947 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2949 CAutoTree t1;
2950 CAutoDiff diff2;
2952 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2953 return -1;
2955 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2956 return -1;
2958 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2959 return -1;
2961 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2962 return -1;
2964 if (git_diff_merge(diff, diff2))
2965 return -1;
2967 else
2969 if (tree1.IsEmpty() && tree2.IsEmpty())
2970 return -1;
2972 if (tree1.IsEmpty())
2974 tree1 = tree2;
2975 tree2.Empty();
2978 CAutoTree t1;
2979 CAutoTree t2;
2980 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2981 return -1;
2983 if (tree2.IsEmpty())
2985 /* don't check return value, there are not parent commit at first commit*/
2986 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2988 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2989 return -1;
2990 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2991 return -1;
2994 CAutoDiffStats stats;
2995 if (git_diff_get_stats(stats.GetPointer(), diff))
2996 return -1;
2997 CAutoBuf statBuf;
2998 if (git_diff_stats_to_buf(statBuf, stats, GIT_DIFF_STATS_FULL, 0))
2999 return -1;
3000 statCallback(statBuf, data);
3002 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
3004 CAutoPatch patch;
3005 if (git_patch_from_diff(patch.GetPointer(), diff, i))
3006 return -1;
3008 if (git_patch_print(patch, callback, data))
3009 return -1;
3012 pathA.ReleaseBuffer();
3014 return 0;
3017 int CGit::GetUnifiedDiff(const CTGitPath& path, const CString& rev1, const CString& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix)
3019 if (UsingLibGit2(GIT_CMD_DIFF))
3021 CAutoFILE file = _wfsopen(patchfile, L"wb", SH_DENYRW);
3022 if (!file)
3023 return -1;
3024 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToFile, UnifiedDiffToFile, file, bMerge, bNoPrefix);
3026 else
3028 CString cmd;
3029 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext, bNoPrefix);
3030 gitLastErr.Empty();
3031 return RunLogFile(cmd, patchfile, &gitLastErr);
3035 static void UnifiedDiffStatToStringA(const git_buf* text, void* payload)
3037 ATLASSERT(payload && text);
3038 CStringA *str = (CStringA*) payload;
3039 str->Append(text->ptr, (int)text->size);
3040 str->AppendChar('\n');
3043 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
3045 ATLASSERT(payload && line);
3046 CStringA *str = (CStringA*) payload;
3047 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
3048 str->Append(&line->origin, 1);
3049 str->Append(line->content, (int)line->content_len);
3050 return 0;
3053 int CGit::GetUnifiedDiff(const CTGitPath& path, const CString& rev1, const CString& rev2, CStringA* buffer, bool bMerge, bool bCombine, int diffContext)
3055 if (UsingLibGit2(GIT_CMD_DIFF))
3056 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffStatToStringA, UnifiedDiffToStringA, buffer, bMerge, false);
3057 else
3059 CString cmd;
3060 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
3061 BYTE_VECTOR vector;
3062 int ret = Run(cmd, &vector);
3063 if (!vector.empty())
3065 vector.push_back(0); // vector is not NUL terminated
3066 buffer->Append((char*)vector.data());
3068 return ret;
3072 int CGit::GitRevert(int parent, const CGitHash &hash)
3074 if (UsingLibGit2(GIT_CMD_REVERT))
3076 CAutoRepository repo(GetGitRepository());
3077 if (!repo)
3078 return -1;
3080 CAutoCommit commit;
3081 if (git_commit_lookup(commit.GetPointer(), repo, hash))
3082 return -1;
3084 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
3085 revert_opts.mainline = parent;
3086 int result = git_revert(repo, commit, &revert_opts);
3088 return !result ? 0 : -1;
3090 else
3092 CString cmd, merge;
3093 if (parent)
3094 merge.Format(L"-m %d ", parent);
3095 cmd.Format(L"git.exe revert --no-edit --no-commit %s%s", (LPCTSTR)merge, (LPCTSTR)hash.ToString());
3096 gitLastErr = cmd + L'\n';
3097 if (Run(cmd, &gitLastErr, CP_UTF8))
3098 return -1;
3099 else
3101 gitLastErr.Empty();
3102 return 0;
3107 int CGit::DeleteRef(const CString& reference)
3109 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
3111 CAutoRepository repo(GetGitRepository());
3112 if (!repo)
3113 return -1;
3115 CStringA refA;
3116 if (CStringUtils::EndsWith(reference, L"^{}"))
3117 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
3118 else
3119 refA = CUnicodeUtils::GetUTF8(reference);
3121 CAutoReference ref;
3122 if (git_reference_lookup(ref.GetPointer(), repo, refA))
3123 return -1;
3125 int result = -1;
3126 if (git_reference_is_tag(ref))
3127 result = git_tag_delete(repo, git_reference_shorthand(ref));
3128 else if (git_reference_is_branch(ref))
3129 result = git_branch_delete(ref);
3130 else if (git_reference_is_remote(ref))
3131 result = git_branch_delete(ref);
3132 else
3133 result = git_reference_delete(ref);
3135 return result;
3137 else
3139 CString cmd, shortname;
3140 if (GetShortName(reference, shortname, L"refs/heads/"))
3141 cmd.Format(L"git.exe branch -D -- %s", (LPCTSTR)shortname);
3142 else if (GetShortName(reference, shortname, L"refs/tags/"))
3143 cmd.Format(L"git.exe tag -d -- %s", (LPCTSTR)shortname);
3144 else if (GetShortName(reference, shortname, L"refs/remotes/"))
3145 cmd.Format(L"git.exe branch -r -D -- %s", (LPCTSTR)shortname);
3146 else
3148 gitLastErr = L"unsupported reference type: " + reference;
3149 return -1;
3152 gitLastErr.Empty();
3153 if (Run(cmd, &gitLastErr, CP_UTF8))
3154 return -1;
3156 gitLastErr.Empty();
3157 return 0;
3161 bool CGit::LoadTextFile(const CString &filename, CString &msg)
3163 if (!PathFileExists(filename))
3164 return false;
3166 CAutoFILE pFile = _wfsopen(filename, L"rb", SH_DENYWR);
3167 if (!pFile)
3169 ::MessageBox(nullptr, L"Could not open " + filename, L"TortoiseGit", MB_ICONERROR);
3170 return true; // load no further files
3173 CStringA str;
3176 char s[8196] = { 0 };
3177 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
3178 if (read == 0)
3179 break;
3180 str += CStringA(s, read);
3181 } while (true);
3182 msg += CUnicodeUtils::GetUnicode(str);
3183 msg.Replace(L"\r\n", L"\n");
3184 msg.TrimRight(L'\n');
3185 msg += L'\n';
3187 return true; // load no further files
3190 int CGit::GetWorkingTreeChanges(CTGitPathList& result, bool amend, const CTGitPathList* filterlist, bool includedStaged /* = false */)
3192 if (IsInitRepos())
3193 return GetInitAddList(result);
3195 BYTE_VECTOR out;
3197 int count = 1;
3198 if (filterlist)
3199 count = filterlist->GetCount();
3200 ATLASSERT(count > 0);
3202 CString head = L"HEAD";
3203 if (amend)
3204 head = L"HEAD~1";
3206 CString gitStatusParams;
3207 if (ms_LastMsysGitVersion >= ConvertVersionToInt(2, 17, 0))
3208 gitStatusParams = L" --no-ahead-behind";
3210 for (int i = 0; i < count; ++i)
3212 ATLASSERT(!filterlist || !(*filterlist)[i].GetGitPathString().IsEmpty()); // pathspec must not be empty, be compatible with Git >= 2.16.0
3213 BYTE_VECTOR cmdout;
3214 CString cmd;
3215 if (ms_bCygwinGit || ms_bMsys2Git)
3217 // Prevent showing all files as modified when using cygwin's git
3218 if (!filterlist)
3219 cmd.Format(L"git.exe status%s --", (LPCTSTR)gitStatusParams);
3220 else
3221 cmd.Format(L"git.exe status%s -- \"%s\"", (LPCTSTR)gitStatusParams, (LPCTSTR)(*filterlist)[i].GetGitPathString());
3222 Run(cmd, &cmdout);
3223 cmdout.clear();
3226 // also list staged files which will be in the commit
3227 if (includedStaged || !filterlist)
3228 Run(L"git.exe diff-index --cached --raw " + head + L" --numstat -C -M -z --", &cmdout);
3229 else
3231 cmd.Format(L"git.exe diff-index --cached --raw %s --numstat -C -M -z -- \"%s\"", (LPCTSTR)head, (LPCTSTR)(*filterlist)[i].GetGitPathString());
3232 Run(cmd, &cmdout);
3235 if (!filterlist)
3236 cmd.Format(L"git.exe diff-index --raw %s --numstat -C%d%% -M%d%% -z --", (LPCTSTR)head, ms_iSimilarityIndexThreshold, ms_iSimilarityIndexThreshold);
3237 else
3238 cmd.Format(L"git.exe diff-index --raw %s --numstat -C%d%% -M%d%% -z -- \"%s\"", (LPCTSTR)head, ms_iSimilarityIndexThreshold, ms_iSimilarityIndexThreshold, (LPCTSTR)(*filterlist)[i].GetGitPathString());
3240 BYTE_VECTOR cmdErr;
3241 if (Run(cmd, &cmdout, &cmdErr))
3243 size_t last = cmdErr.RevertFind(0);
3244 CString str;
3245 if (last != BYTE_VECTOR::npos)
3246 CGit::StringAppend(&str, &cmdErr[last + 1], CP_UTF8, (int)(cmdErr.size() - last) - 1);
3247 else if (!cmdErr.empty())
3248 CGit::StringAppend(&str, cmdErr.data(), CP_UTF8, (int)cmdErr.size() - 1);
3249 else
3250 str.Format(L"\"%s\" exited with an error code, but did not output any error message", (LPCTSTR)cmd);
3251 MessageBox(nullptr, str, L"TortoiseGit", MB_OK | MB_ICONERROR);
3254 out.append(cmdout, 0);
3256 result.ParserFromLog(out);
3258 std::map<CString, int> duplicateMap;
3259 for (int i = 0; i < result.GetCount(); ++i)
3260 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), i));
3262 // handle delete conflict case, when remote : modified, local : deleted.
3263 for (int i = 0; i < count; ++i)
3265 BYTE_VECTOR cmdout;
3266 CString cmd;
3268 if (!filterlist)
3269 cmd = L"git.exe ls-files -u -t -z";
3270 else
3271 cmd.Format(L"git.exe ls-files -u -t -z -- \"%s\"", (LPCTSTR)(*filterlist)[i].GetGitPathString());
3273 Run(cmd, &cmdout);
3275 CTGitPathList conflictlist;
3276 conflictlist.ParserFromLog(cmdout);
3277 for (int j = 0; j < conflictlist.GetCount(); ++j)
3279 auto existing = duplicateMap.find(conflictlist[j].GetGitPathString());
3280 if (existing != duplicateMap.end())
3282 CTGitPath& p = const_cast<CTGitPath&>(result[existing->second]);
3283 p.m_Action |= CTGitPath::LOGACTIONS_UNMERGED;
3285 else
3287 result.AddPath(conflictlist[j]);
3288 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), result.GetCount() - 1));
3293 // handle source files of file renames/moves (issue #860)
3294 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3295 for (int i = 0; i < count; ++i)
3297 BYTE_VECTOR cmdout;
3298 CString cmd;
3300 if (!filterlist)
3301 cmd = L"git.exe ls-files -d -z";
3302 else
3303 cmd.Format(L"git.exe ls-files -d -z -- \"%s\"", (LPCTSTR)(*filterlist)[i].GetGitPathString());
3305 Run(cmd, &cmdout);
3307 CTGitPathList deletelist;
3308 deletelist.ParserFromLog(cmdout, true);
3309 for (int j = 0; j < deletelist.GetCount(); ++j)
3311 auto existing = duplicateMap.find(deletelist[j].GetGitPathString());
3312 if (existing == duplicateMap.end())
3314 result.AddPath(deletelist[j]);
3315 duplicateMap.insert(std::pair<CString, int>(result[i].GetGitPathString(), result.GetCount() - 1));
3317 else
3319 CTGitPath& p = const_cast<CTGitPath&>(result[existing->second]);
3320 p.m_Action |= CTGitPath::LOGACTIONS_MISSING;
3325 return 0;
3328 int CGit::IsRebaseRunning()
3330 CString adminDir;
3331 if (!GitAdminDir::GetAdminDirPath(g_Git.m_CurrentDir, adminDir))
3332 return -1;
3334 if (PathIsDirectory(adminDir + L"rebase-apply") || PathIsDirectory(adminDir + L"tgitrebase.active"))
3335 return 1;
3336 return 0;
3339 void CGit::GetBisectTerms(CString* good, CString* bad)
3341 static CString lastGood;
3342 static CString lastBad;
3343 static ULONGLONG lastRead = 0;
3345 SCOPE_EXIT
3347 if (bad)
3348 *bad = lastBad;
3349 if (good)
3350 *good = lastGood;
3353 #ifndef GTEST_INCLUDE_GTEST_GTEST_H_
3354 // add some caching here, because this method might be called multiple times in a short time from LogDlg and RevisionGraph
3355 // as we only read a small file the performance effects should be negligible
3356 if (lastRead + 5000 > GetTickCount64())
3357 return;
3358 #endif
3360 lastGood = L"good";
3361 lastBad = L"bad";
3363 CString adminDir;
3364 if (!GitAdminDir::GetAdminDirPath(m_CurrentDir, adminDir))
3365 return;
3367 CString termsFile = adminDir + L"BISECT_TERMS";
3368 CAutoFILE fp;
3369 _wfopen_s(fp.GetPointer(), termsFile, L"rb");
3370 if (!fp)
3371 return;
3372 char badA[MAX_PATH] = { 0 };
3373 fgets(badA, sizeof(badA), fp);
3374 size_t len = strlen(badA);
3375 if (len > 0 && badA[len - 1] == '\n')
3376 badA[len - 1] = '\0';
3377 char goodA[MAX_PATH] = { 0 };
3378 fgets(goodA, sizeof(goodA), fp);
3379 len = strlen(goodA);
3380 if (len > 0 && goodA[len - 1] == '\n')
3381 goodA[len - 1] = '\0';
3382 lastGood = CUnicodeUtils::GetUnicode(goodA);
3383 lastBad = CUnicodeUtils::GetUnicode(badA);
3384 lastRead = GetTickCount64();
3387 int CGit::GetGitVersion(CString* versiondebug, CString* errStr)
3389 CString version, err;
3390 if (Run(L"git.exe --version", &version, &err, CP_UTF8))
3392 if (errStr)
3393 *errStr = err;
3394 return -1;
3397 int ver = 0;
3398 if (versiondebug)
3399 *versiondebug = version;
3403 int start = 0;
3404 CString str = version.Tokenize(L".", start);
3405 int space = str.ReverseFind(L' ');
3406 str = str.Mid(space + 1, start);
3407 ver = _wtol(str);
3408 ver <<= 24;
3410 version = version.Mid(start);
3411 start = 0;
3413 str = version.Tokenize(L".", start);
3414 ver |= (_wtol(str) & 0xFF) << 16;
3416 str = version.Tokenize(L".", start);
3417 ver |= (_wtol(str) & 0xFF) << 8;
3419 str = version.Tokenize(L".", start);
3420 ver |= (_wtol(str) & 0xFF);
3422 catch (...)
3424 if (!ver)
3425 return -1;
3428 return ver;
3431 int CGit::GetGitNotes(const CGitHash& hash, CString& notes)
3433 CAutoRepository repo(GetGitRepository());
3434 if (!repo)
3435 return -1;
3437 CAutoNote note;
3438 int ret = git_note_read(note.GetPointer(), repo, nullptr, hash);
3439 if (ret == GIT_ENOTFOUND)
3441 notes.Empty();
3442 return 0;
3444 else if (ret)
3445 return -1;
3446 notes = CUnicodeUtils::GetUnicode(git_note_message(note));
3447 return 0;
3450 int CGit::SetGitNotes(const CGitHash& hash, const CString& notes)
3452 CAutoRepository repo(GetGitRepository());
3453 if (!repo)
3454 return -1;
3456 CAutoSignature signature;
3457 if (git_signature_default(signature.GetPointer(), repo) < 0)
3458 return -1;
3460 git_oid oid;
3461 if (git_note_create(&oid, repo, nullptr, signature, signature, hash, CUnicodeUtils::GetUTF8(notes), 1) < 0)
3462 return -1;
3464 return 0;