Add an option to the TortoiseGitMerge settings dialog to specify the number of contex...
[TortoiseGit.git] / src / Git / Git.cpp
blobc89c6ad252830a55986d21eb72c63a1b2f067467
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - TortoiseGit
5 // This program is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU General Public License
7 // as published by the Free Software Foundation; either version 2
8 // of the License, or (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software Foundation,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "stdafx.h"
21 #include "Git.h"
22 #include "GitRev.h"
23 #include "registry.h"
24 #include "GitForWindows.h"
25 #include <map>
26 #include "UnicodeUtils.h"
27 #include "gitdll.h"
28 #include <fstream>
29 #include "FormatMessageWrapper.h"
30 #include "SmartHandle.h"
32 int CGit::m_LogEncode=CP_UTF8;
33 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
35 static LPTSTR nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
37 wchar_t term, *base = path;
39 if (path == NULL || buf == NULL || buflen == 0)
40 return NULL;
42 term = (*path == L'"') ? *path++ : L';';
44 for (buflen--; *path && *path != term && buflen; buflen--)
45 *buf++ = *path++;
47 *buf = L'\0'; /* reserved a byte via initial subtract */
49 while (*path == term || *path == L';')
50 ++path;
52 return (path != base) ? path : NULL;
55 static inline BOOL FileExists(LPCTSTR lpszFileName)
57 struct _stat st;
58 return _tstat(lpszFileName, &st) == 0;
61 static BOOL FindGitPath()
63 size_t size;
64 _tgetenv_s(&size, NULL, 0, _T("PATH"));
66 if (!size)
68 return FALSE;
71 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
72 _tgetenv_s(&size, env, size, _T("PATH"));
74 TCHAR buf[MAX_PATH] = {0};
76 // search in all paths defined in PATH
77 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
79 TCHAR *pfin = buf + _tcslen(buf)-1;
81 // ensure trailing slash
82 if (*pfin != _T('/') && *pfin != _T('\\'))
83 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
85 const size_t len = _tcslen(buf);
87 if ((len + 7) < MAX_PATH)
88 _tcscpy_s(pfin + 1, MAX_PATH - len, _T("git.exe"));
89 else
90 break;
92 if ( FileExists(buf) )
94 // dir found
95 pfin[1] = 0;
96 CGit::ms_LastMsysGitDir = buf;
97 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
98 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
100 // often the msysgit\cmd folder is on the %PATH%, but
101 // that git.exe does not work, so try to guess the bin folder
102 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
103 if (FileExists(binDir))
104 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
106 return TRUE;
110 return FALSE;
113 static bool g_bSortLogical;
114 static bool g_bSortLocalBranchesFirst;
115 static bool g_bSortTagsReversed;
117 static void GetSortOptions()
119 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
120 if (g_bSortLogical)
121 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
122 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
123 if (g_bSortLocalBranchesFirst)
124 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
125 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE);
126 if (!g_bSortTagsReversed)
127 g_bSortTagsReversed = !!CRegDWORD(L"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER);
130 static int LogicalComparePredicate(const CString &left, const CString &right)
132 if (g_bSortLogical)
133 return StrCmpLogicalW(left, right) < 0;
134 return StrCmpI(left, right) < 0;
137 static int LogicalCompareReversedPredicate(const CString &left, const CString &right)
139 if (g_bSortLogical)
140 return StrCmpLogicalW(left, right) > 0;
141 return StrCmpI(left, right) > 0;
144 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
146 if (g_bSortLocalBranchesFirst)
148 int leftIsRemote = left.Find(_T("remotes/"));
149 int rightIsRemote = right.Find(_T("remotes/"));
151 if (leftIsRemote == 0 && rightIsRemote < 0)
152 return false;
153 else if (leftIsRemote < 0 && rightIsRemote == 0)
154 return true;
156 if (g_bSortLogical)
157 return StrCmpLogicalW(left, right) < 0;
158 return StrCmpI(left, right) < 0;
161 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
163 CString CGit::ms_LastMsysGitDir;
164 int CGit::ms_LastMsysGitVersion = 0;
165 CGit g_Git;
168 CGit::CGit(void)
170 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
171 m_CurrentDir.ReleaseBuffer();
172 m_IsGitDllInited = false;
173 m_GitDiff=0;
174 m_GitSimpleListDiff=0;
175 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
176 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
177 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), (1 << GIT_CMD_MERGE_BASE) | (1 << GIT_CMD_DELETETAGBRANCH) | (1 << GIT_CMD_GETONEFILE) | (1 << GIT_CMD_ADD));
179 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
181 GetSortOptions();
182 this->m_bInitialized =false;
183 CheckMsysGitDir();
184 m_critGitDllSec.Init();
187 CGit::~CGit(void)
189 if(this->m_GitDiff)
191 git_close_diff(m_GitDiff);
192 m_GitDiff=0;
194 if(this->m_GitSimpleListDiff)
196 git_close_diff(m_GitSimpleListDiff);
197 m_GitSimpleListDiff=0;
201 bool CGit::IsBranchNameValid(const CString& branchname)
203 if (branchname.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
204 return false;
205 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
206 return false;
207 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
208 return !!git_reference_is_valid_name(branchA);
211 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
213 SECURITY_ATTRIBUTES sa;
214 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
215 CAutoGeneralHandle hStdioFile;
217 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
218 sa.lpSecurityDescriptor=NULL;
219 sa.bInheritHandle=TRUE;
220 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
222 CString err = CFormatMessageWrapper();
223 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
224 return TGIT_GIT_ERROR_OPEN_PIP;
226 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
228 CString err = CFormatMessageWrapper();
229 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
230 return TGIT_GIT_ERROR_OPEN_PIP;
233 if(StdioFile)
235 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
236 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
239 STARTUPINFO si;
240 PROCESS_INFORMATION pi;
241 si.cb=sizeof(STARTUPINFO);
242 GetStartupInfo(&si);
244 if (hErrReadOut)
245 si.hStdError = hWriteErr;
246 else
247 si.hStdError = hWrite;
248 if(StdioFile)
249 si.hStdOutput=hStdioFile;
250 else
251 si.hStdOutput=hWrite;
253 si.wShowWindow=SW_HIDE;
254 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
256 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
257 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
259 // CREATE_NEW_CONSOLE makes ssh recognize that it has no console in order to launch askpass to ask for the password.
260 // DETACHED_PROCESS which was originally used here has the same effect, however, it prevents PowerShell from working (cf. issue #2143)
261 dwFlags |= CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE;
263 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
264 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
266 if(cmd.Find(_T("git")) == 0)
268 int firstSpace = cmd.Find(_T(" "));
269 if (firstSpace > 0)
270 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
271 else
272 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
275 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
276 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
278 CString err = CFormatMessageWrapper();
279 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
280 return TGIT_GIT_ERROR_CREATE_PROCESS;
283 m_CurrentGitPi = pi;
285 if(piOut)
286 *piOut=pi;
287 if(hReadOut)
288 *hReadOut = hRead.Detach();
289 if(hErrReadOut)
290 *hErrReadOut = hReadErr.Detach();
291 return 0;
294 //Must use sperate function to convert ANSI str to union code string
295 //Becuase A2W use stack as internal convert buffer.
296 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
298 if(str == NULL)
299 return ;
301 int len ;
302 if(length<0)
303 len = (int)strlen((const char*)p);
304 else
305 len=length;
306 if (len == 0)
307 return;
308 int currentContentLen = str->GetLength();
309 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
310 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
311 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
314 // This method was originally used to check for orphaned branches
315 BOOL CGit::CanParseRev(CString ref)
317 if (ref.IsEmpty())
318 ref = _T("HEAD");
320 CString cmdout;
321 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
323 return FALSE;
325 if(cmdout.IsEmpty())
326 return FALSE;
328 return TRUE;
331 // Checks if we have an orphaned HEAD
332 BOOL CGit::IsInitRepos()
334 CGitHash hash;
335 // handle error on reading HEAD hash as init repo
336 if (GetHash(hash, _T("HEAD")) != 0)
337 return TRUE;
338 return hash.IsEmpty() ? TRUE : FALSE;
341 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
343 PASYNCREADSTDERRTHREADARGS pDataArray;
344 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
346 DWORD readnumber;
347 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
348 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
350 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
351 break;
354 return 0;
357 int CGit::Run(CGitCall* pcall)
359 PROCESS_INFORMATION pi;
360 CAutoGeneralHandle hRead, hReadErr;
361 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
362 return TGIT_GIT_ERROR_CREATE_PROCESS;
364 CAutoGeneralHandle piThread(pi.hThread);
365 CAutoGeneralHandle piProcess(pi.hProcess);
367 ASYNCREADSTDERRTHREADARGS threadArguments;
368 threadArguments.fileHandle = hReadErr;
369 threadArguments.pcall = pcall;
370 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
372 DWORD readnumber;
373 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
374 bool bAborted=false;
375 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
377 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
378 if(!bAborted)//For now, flush output when command aborted.
379 if(pcall->OnOutputData(data,readnumber))
380 bAborted=true;
382 if(!bAborted)
383 pcall->OnEnd();
385 if (thread)
386 WaitForSingleObject(thread, INFINITE);
388 WaitForSingleObject(pi.hProcess, INFINITE);
389 DWORD exitcode =0;
391 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
393 CString err = CFormatMessageWrapper();
394 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
395 return TGIT_GIT_ERROR_GET_EXIT_CODE;
397 else
398 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
400 return exitcode;
402 class CGitCall_ByteVector : public CGitCall
404 public:
405 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
406 virtual bool OnOutputData(const BYTE* data, size_t size)
408 if (!m_pvector || size == 0)
409 return false;
410 size_t oldsize=m_pvector->size();
411 m_pvector->resize(m_pvector->size()+size);
412 memcpy(&*(m_pvector->begin()+oldsize),data,size);
413 return false;
415 virtual bool OnOutputErrData(const BYTE* data, size_t size)
417 if (!m_pvectorErr || size == 0)
418 return false;
419 size_t oldsize = m_pvectorErr->size();
420 m_pvectorErr->resize(m_pvectorErr->size() + size);
421 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
422 return false;
424 BYTE_VECTOR* m_pvector;
425 BYTE_VECTOR* m_pvectorErr;
428 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
430 CGitCall_ByteVector call(cmd, vector, vectorErr);
431 return Run(&call);
433 int CGit::Run(CString cmd, CString* output, int code)
435 CString err;
436 int ret;
437 ret = Run(cmd, output, &err, code);
439 if (output && !err.IsEmpty())
441 if (!output->IsEmpty())
442 *output += _T("\n");
443 *output += err;
446 return ret;
448 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
450 BYTE_VECTOR vector, vectorErr;
451 int ret;
452 if (outputErr)
453 ret = Run(cmd, &vector, &vectorErr);
454 else
455 ret = Run(cmd, &vector);
457 vector.push_back(0);
458 StringAppend(output, &(vector[0]), code);
460 if (outputErr)
462 vectorErr.push_back(0);
463 StringAppend(outputErr, &(vectorErr[0]), code);
466 return ret;
469 class CGitCallCb : public CGitCall
471 public:
472 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
474 virtual bool OnOutputData(const BYTE* data, size_t size) override
476 // Add data
477 if (size == 0)
478 return false;
479 int oldEndPos = m_buffer.GetLength();
480 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
481 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
483 // Break into lines and feed to m_recv
484 int eolPos;
485 while ((eolPos = m_buffer.Find('\n')) >= 0)
487 m_recv(m_buffer.Left(eolPos));
488 m_buffer = m_buffer.Mid(eolPos + 1);
490 return false;
493 virtual bool OnOutputErrData(const BYTE*, size_t) override
495 return false; // Ignore error output for now
498 virtual void OnEnd() override
500 if (!m_buffer.IsEmpty())
501 m_recv(m_buffer);
502 m_buffer.Empty(); // Just for sure
505 private:
506 GitReceiverFunc m_recv;
507 CStringA m_buffer;
510 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
512 CGitCallCb call(cmd, recv);
513 return Run(&call);
516 CString CGit::GetUserName(void)
518 CEnvironment env;
519 env.CopyProcessEnvironment();
520 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
521 if (!envname.IsEmpty())
522 return envname;
523 return GetConfigValue(L"user.name");
525 CString CGit::GetUserEmail(void)
527 CEnvironment env;
528 env.CopyProcessEnvironment();
529 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
530 if (!envmail.IsEmpty())
531 return envmail;
533 return GetConfigValue(L"user.email");
536 CString CGit::GetConfigValue(const CString& name)
538 CString configValue;
539 int start = 0;
540 if(this->m_IsUseGitDLL)
542 CAutoLocker lock(g_Git.m_critGitDllSec);
546 CheckAndInitDll();
547 }catch(...)
550 CStringA key, value;
551 key = CUnicodeUtils::GetUTF8(name);
555 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
556 return CString();
558 catch (const char *msg)
560 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
561 return CString();
564 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
565 return configValue.Tokenize(_T("\n"),start);
567 else
569 CString cmd;
570 cmd.Format(L"git.exe config %s", name);
571 Run(cmd, &configValue, nullptr, CP_UTF8);
572 return configValue.Tokenize(_T("\n"),start);
576 bool CGit::GetConfigValueBool(const CString& name)
578 CString configValue = GetConfigValue(name);
579 configValue.MakeLower();
580 configValue.Trim();
581 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
582 return true;
583 else
584 return false;
587 int CGit::GetConfigValueInt32(const CString& name, int def)
589 CString configValue = GetConfigValue(name);
590 int value = def;
591 if (!git_config_parse_int32(&value, CUnicodeUtils::GetUTF8(configValue)))
592 return value;
593 return def;
596 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
598 if(this->m_IsUseGitDLL)
600 CAutoLocker lock(g_Git.m_critGitDllSec);
604 CheckAndInitDll();
606 }catch(...)
609 CStringA keya, valuea;
610 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
611 valuea = CUnicodeUtils::GetUTF8(value);
615 return [=]() { return get_set_config(keya, valuea, type); }();
617 catch (const char *msg)
619 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
620 return -1;
623 else
625 CString cmd;
626 CString option;
627 switch(type)
629 case CONFIG_GLOBAL:
630 option = _T("--global");
631 break;
632 case CONFIG_SYSTEM:
633 option = _T("--system");
634 break;
635 default:
636 break;
638 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
639 CString out;
640 if (Run(cmd, &out, nullptr, CP_UTF8))
642 return -1;
645 return 0;
648 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
650 if(this->m_IsUseGitDLL)
652 CAutoLocker lock(g_Git.m_critGitDllSec);
656 CheckAndInitDll();
657 }catch(...)
660 CStringA keya;
661 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
665 return [=]() { return get_set_config(keya, nullptr, type); }();
667 catch (const char *msg)
669 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
670 return -1;
673 else
675 CString cmd;
676 CString option;
677 switch(type)
679 case CONFIG_GLOBAL:
680 option = _T("--global");
681 break;
682 case CONFIG_SYSTEM:
683 option = _T("--system");
684 break;
685 default:
686 break;
688 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
689 CString out;
690 if (Run(cmd, &out, nullptr, CP_UTF8))
692 return -1;
695 return 0;
698 CString CGit::GetCurrentBranch(bool fallback)
700 CString output;
701 //Run(_T("git.exe branch"),&branch);
703 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
704 if (result != 0 && ((result == 1 && !fallback) || result != 1))
706 return _T("(no branch)");
708 else
709 return output;
713 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
715 if (localBranch.IsEmpty())
716 return;
718 CString configName;
719 configName.Format(L"branch.%s.remote", localBranch);
720 pullRemote = GetConfigValue(configName);
722 //Select pull-branch from current branch
723 configName.Format(L"branch.%s.merge", localBranch);
724 pullBranch = StripRefName(GetConfigValue(configName));
727 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
729 CString refName;
730 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
731 return;
732 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
735 CString CGit::GetFullRefName(const CString& shortRefName)
737 CString refName;
738 CString cmd;
739 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
740 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
741 return CString();//Error
742 int iStart = 0;
743 return refName.Tokenize(L"\n", iStart);
746 CString CGit::StripRefName(CString refName)
748 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
749 refName = refName.Mid(11);
750 else if(wcsncmp(refName, L"refs/", 5) == 0)
751 refName = refName.Mid(5);
752 int start =0;
753 return refName.Tokenize(_T("\n"),start);
756 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
758 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
760 if ( sProjectRoot.IsEmpty() )
761 return -1;
763 CString sDotGitPath;
764 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
765 return -1;
767 CString sHeadFile = sDotGitPath + _T("HEAD");
769 FILE *pFile;
770 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
772 if (!pFile)
774 return -1;
777 char s[256] = {0};
778 fgets(s, sizeof(s), pFile);
780 fclose(pFile);
782 const char *pfx = "ref: refs/heads/";
783 const int len = 16;//strlen(pfx)
785 if ( !strncmp(s, pfx, len) )
787 //# We're on a branch. It might not exist. But
788 //# HEAD looks good enough to be a branch.
789 CStringA utf8Branch(s + len);
790 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
791 sBranchOut.TrimRight(_T(" \r\n\t"));
793 if ( sBranchOut.IsEmpty() )
794 return -1;
796 else if (fallback)
798 CStringA utf8Hash(s);
799 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
800 unicodeHash.TrimRight(_T(" \r\n\t"));
801 if (CGitHash::IsValidSHA1(unicodeHash))
802 sBranchOut = unicodeHash;
803 else
804 //# Assume this is a detached head.
805 sBranchOut = _T("HEAD");
806 return 1;
808 else
810 //# Assume this is a detached head.
811 sBranchOut = "HEAD";
813 return 1;
816 return 0;
819 int CGit::BuildOutputFormat(CString &format,bool IsFull)
821 CString log;
822 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
823 format += log;
824 if(IsFull)
826 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
827 format += log;
828 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
829 format += log;
830 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
831 format += log;
832 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
833 format += log;
834 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
835 format += log;
836 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
837 format += log;
838 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
839 format += log;
842 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
843 format += log;
844 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
845 format += log;
846 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
847 format += log;
849 if(IsFull)
851 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
852 format += log;
854 return 0;
857 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
858 CFilterData *Filter)
860 CString cmd;
861 CString num;
862 CString since;
864 CString file = _T(" --");
866 if(path)
867 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
869 if(count>0)
870 num.Format(_T("-n%d"),count);
872 CString param;
874 if(mask& LOG_INFO_STAT )
875 param += _T(" --numstat ");
876 if(mask& LOG_INFO_FILESTATE)
877 param += _T(" --raw ");
879 if(mask& LOG_INFO_FULLHISTORY)
880 param += _T(" --full-history ");
882 if(mask& LOG_INFO_BOUNDARY)
883 param += _T(" --left-right --boundary ");
885 if(mask& CGit::LOG_INFO_ALL_BRANCH)
886 param += _T(" --all ");
888 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
889 param += _T(" --branches ");
891 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
892 param += _T(" -C ");
894 if(mask& CGit::LOG_INFO_DETECT_RENAME )
895 param += _T(" -M ");
897 if(mask& CGit::LOG_INFO_FIRST_PARENT )
898 param += _T(" --first-parent ");
900 if(mask& CGit::LOG_INFO_NO_MERGE )
901 param += _T(" --no-merges ");
903 if(mask& CGit::LOG_INFO_FOLLOW)
904 param += _T(" --follow ");
906 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
907 param += _T(" -c ");
909 if(mask& CGit::LOG_INFO_FULL_DIFF)
910 param += _T(" --full-diff ");
912 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
913 param += _T(" --simplify-by-decoration ");
915 param += range;
917 CString st1,st2;
919 if( Filter && (Filter->m_From != -1))
921 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
922 param += st1;
925 if( Filter && (Filter->m_To != -1))
927 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
928 param += st2;
931 bool isgrep = false;
932 if( Filter && (!Filter->m_Author.IsEmpty()))
934 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
935 param += st1;
936 isgrep = true;
939 if( Filter && (!Filter->m_Committer.IsEmpty()))
941 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
942 param += st1;
943 isgrep = true;
946 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
948 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
949 param += st1;
950 isgrep = true;
953 if(Filter && isgrep)
955 if(!Filter->m_IsRegex)
956 param += _T(" --fixed-strings ");
958 param += _T(" --regexp-ignore-case --extended-regexp ");
961 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
962 if (logOrderBy == LOG_ORDER_TOPOORDER)
963 param += _T(" --topo-order");
964 else if (logOrderBy == LOG_ORDER_DATEORDER)
965 param += _T(" --date-order");
967 if(paramonly) //tgit.dll.Git.cpp:setup_revisions() only looks at args[1] and greater. To account for this, pass a dummy parameter in the 0th place
968 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
969 else
971 CString log;
972 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
973 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
974 num,param,log);
977 cmd += file;
979 return cmd;
981 #define BUFSIZE 512
982 void GetTempPath(CString &path)
984 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
985 DWORD dwRetVal;
986 DWORD dwBufSize=BUFSIZE;
987 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
988 lpPathBuffer); // buffer for path
989 if (dwRetVal > dwBufSize || (dwRetVal == 0))
991 path=_T("");
993 path.Format(_T("%s"),lpPathBuffer);
995 CString GetTempFile()
997 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
998 DWORD dwRetVal;
999 DWORD dwBufSize=BUFSIZE;
1000 TCHAR szTempName[BUFSIZE] = { 0 };
1001 UINT uRetVal;
1003 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1004 lpPathBuffer); // buffer for path
1005 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1007 return _T("");
1009 // Create a temporary file.
1010 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1011 TEXT("Patch"), // temp file name prefix
1012 0, // create unique name
1013 szTempName); // buffer for name
1016 if (uRetVal == 0)
1018 return _T("");
1021 return CString(szTempName);
1025 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1027 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1028 if (result == 0) return 0;
1029 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1031 if (lpBuffer)
1032 lpBuffer[0] = '\0';
1033 return result + 13;
1036 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1037 CreateDirectory(lpBuffer, NULL);
1039 return result + 13;
1042 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1044 STARTUPINFO si;
1045 PROCESS_INFORMATION pi;
1046 si.cb=sizeof(STARTUPINFO);
1047 GetStartupInfo(&si);
1049 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1050 psa.bInheritHandle=TRUE;
1052 HANDLE hReadErr, hWriteErr;
1053 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1055 CString err = CFormatMessageWrapper();
1056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1057 return TGIT_GIT_ERROR_OPEN_PIP;
1060 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1061 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1063 if (houtfile == INVALID_HANDLE_VALUE)
1065 CString err = CFormatMessageWrapper();
1066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1067 CloseHandle(hReadErr);
1068 CloseHandle(hWriteErr);
1069 return TGIT_GIT_ERROR_OPEN_PIP;
1072 si.wShowWindow = SW_HIDE;
1073 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1074 si.hStdOutput = houtfile;
1075 si.hStdError = hWriteErr;
1077 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1078 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1080 if(cmd.Find(_T("git")) == 0)
1081 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1083 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1084 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1086 CString err = CFormatMessageWrapper();
1087 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1088 stdErr = &err;
1089 CloseHandle(hReadErr);
1090 CloseHandle(hWriteErr);
1091 CloseHandle(houtfile);
1092 return TGIT_GIT_ERROR_CREATE_PROCESS;
1095 BYTE_VECTOR stderrVector;
1096 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1097 HANDLE thread;
1098 ASYNCREADSTDERRTHREADARGS threadArguments;
1099 threadArguments.fileHandle = hReadErr;
1100 threadArguments.pcall = &pcall;
1101 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1103 WaitForSingleObject(pi.hProcess,INFINITE);
1105 CloseHandle(hWriteErr);
1106 CloseHandle(hReadErr);
1108 if (thread)
1109 WaitForSingleObject(thread, INFINITE);
1111 stderrVector.push_back(0);
1112 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1114 DWORD exitcode = 0;
1115 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1117 CString err = CFormatMessageWrapper();
1118 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1119 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1121 else
1122 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1124 CloseHandle(pi.hThread);
1125 CloseHandle(pi.hProcess);
1126 CloseHandle(houtfile);
1127 return exitcode;
1130 git_repository * CGit::GetGitRepository() const
1132 git_repository * repo = nullptr;
1133 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1134 return repo;
1137 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1139 ATLASSERT(repo);
1141 // no need to parse a ref if it's already a 40-byte hash
1142 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1144 hash = CGitHash(friendname);
1145 return 0;
1148 int isHeadOrphan = git_repository_head_unborn(repo);
1149 if (isHeadOrphan != 0)
1151 hash.Empty();
1152 if (isHeadOrphan == 1)
1153 return 0;
1154 else
1155 return -1;
1158 CAutoObject gitObject;
1159 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1160 return -1;
1162 const git_oid * oid = git_object_id(gitObject);
1163 if (!oid)
1164 return -1;
1166 hash = CGitHash((char *)oid->id);
1168 return 0;
1171 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1173 // no need to parse a ref if it's already a 40-byte hash
1174 if (CGitHash::IsValidSHA1(friendname))
1176 hash = CGitHash(friendname);
1177 return 0;
1180 if (m_IsUseLibGit2)
1182 CAutoRepository repo(GetGitRepository());
1183 if (!repo)
1184 return -1;
1186 return GetHash(repo, hash, friendname, true);
1188 else
1190 CString cmd;
1191 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1192 gitLastErr.Empty();
1193 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1194 hash = CGitHash(gitLastErr.Trim());
1195 if (ret == 0)
1196 gitLastErr.Empty();
1197 return ret;
1201 int CGit::GetInitAddList(CTGitPathList &outputlist)
1203 CString cmd;
1204 BYTE_VECTOR cmdout;
1206 cmd=_T("git.exe ls-files -s -t -z");
1207 outputlist.Clear();
1208 if (Run(cmd, &cmdout))
1209 return -1;
1211 if (outputlist.ParserFromLsFile(cmdout))
1212 return -1;
1213 for(int i = 0; i < outputlist.GetCount(); ++i)
1214 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1216 return 0;
1218 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1220 CString cmd;
1221 CString ignore;
1222 if (ignoreSpaceAtEol)
1223 ignore += _T(" --ignore-space-at-eol");
1224 if (ignoreSpaceChange)
1225 ignore += _T(" --ignore-space-change");
1226 if (ignoreAllSpace)
1227 ignore += _T(" --ignore-all-space");
1228 if (ignoreBlankLines)
1229 ignore += _T(" --ignore-blank-lines");
1231 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1233 //rev1=+_T("");
1234 if(rev1 == GIT_REV_ZERO)
1235 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1236 else
1237 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1239 else
1241 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1244 BYTE_VECTOR out;
1245 if (Run(cmd, &out))
1246 return -1;
1248 outputlist.ParserFromLog(out);
1250 return 0;
1253 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1255 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1256 CString str;
1257 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1258 list->push_back(str);
1259 return 0;
1262 int CGit::GetTagList(STRING_VECTOR &list)
1264 if (this->m_IsUseLibGit2)
1266 CAutoRepository repo(GetGitRepository());
1267 if (!repo)
1268 return -1;
1270 CAutoStrArray tag_names;
1272 if (git_tag_list(tag_names, repo))
1273 return -1;
1275 for (size_t i = 0; i < tag_names->count; ++i)
1277 CStringA tagName(tag_names->strings[i]);
1278 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1281 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1283 return 0;
1285 else
1287 CString cmd, output;
1288 cmd=_T("git.exe tag -l");
1289 int ret = Run(cmd, &output, NULL, CP_UTF8);
1290 if(!ret)
1292 int pos=0;
1293 CString one;
1294 while( pos>=0 )
1296 one=output.Tokenize(_T("\n"),pos);
1297 if (!one.IsEmpty())
1298 list.push_back(one);
1300 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1302 return ret;
1306 CString CGit::GetGitLastErr(const CString& msg)
1308 if (this->m_IsUseLibGit2)
1309 return GetLibGit2LastErr(msg);
1310 else if (gitLastErr.IsEmpty())
1311 return msg + _T("\nUnknown git.exe error.");
1312 else
1314 CString lastError = gitLastErr;
1315 gitLastErr.Empty();
1316 return msg + _T("\n") + lastError;
1320 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1322 if (UsingLibGit2(cmd))
1323 return GetLibGit2LastErr(msg);
1324 else if (gitLastErr.IsEmpty())
1325 return msg + _T("\nUnknown git.exe error.");
1326 else
1328 CString lastError = gitLastErr;
1329 gitLastErr.Empty();
1330 return msg + _T("\n") + lastError;
1334 CString CGit::GetLibGit2LastErr()
1336 const git_error *libgit2err = giterr_last();
1337 if (libgit2err)
1339 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1340 giterr_clear();
1341 return _T("libgit2 returned: ") + lastError;
1343 else
1344 return _T("An error occoured in libgit2, but no message is available.");
1347 CString CGit::GetLibGit2LastErr(const CString& msg)
1349 if (!msg.IsEmpty())
1350 return msg + _T("\n") + GetLibGit2LastErr();
1351 return GetLibGit2LastErr();
1354 CString CGit::FixBranchName_Mod(CString& branchName)
1356 if(branchName == "FETCH_HEAD")
1357 branchName = DerefFetchHead();
1358 return branchName;
1361 CString CGit::FixBranchName(const CString& branchName)
1363 CString tempBranchName = branchName;
1364 FixBranchName_Mod(tempBranchName);
1365 return tempBranchName;
1368 bool CGit::IsBranchTagNameUnique(const CString& name)
1370 if (m_IsUseLibGit2)
1372 CAutoRepository repo(GetGitRepository());
1373 if (!repo)
1374 return true; // TODO: optimize error reporting
1376 CAutoReference tagRef;
1377 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1378 return true;
1380 CAutoReference branchRef;
1381 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1382 return true;
1384 return false;
1386 // else
1387 CString output;
1389 CString cmd;
1390 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1391 int ret = Run(cmd, &output, NULL, CP_UTF8);
1392 if (!ret)
1394 int i = 0, pos = 0;
1395 while (pos >= 0)
1397 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1398 ++i;
1400 if (i >= 2)
1401 return false;
1404 return true;
1407 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1409 if (m_IsUseLibGit2)
1411 CAutoRepository repo(GetGitRepository());
1412 if (!repo)
1413 return false; // TODO: optimize error reporting
1415 CString prefix;
1416 if (isBranch)
1417 prefix = _T("refs/heads/");
1418 else
1419 prefix = _T("refs/tags/");
1421 CAutoReference ref;
1422 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1423 return false;
1425 return true;
1427 // else
1428 CString cmd, output;
1430 cmd = _T("git.exe show-ref ");
1431 if (isBranch)
1432 cmd += _T("--heads ");
1433 else
1434 cmd += _T("--tags ");
1436 cmd += _T("refs/heads/") + name;
1437 cmd += _T(" refs/tags/") + name;
1439 int ret = Run(cmd, &output, NULL, CP_UTF8);
1440 if (!ret)
1442 if (!output.IsEmpty())
1443 return true;
1446 return false;
1449 CString CGit::DerefFetchHead()
1451 CString dotGitPath;
1452 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1453 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1454 int forMergeLineCount = 0;
1455 std::string line;
1456 std::string hashToReturn;
1457 while(getline(fetchHeadFile, line))
1459 //Tokenize this line
1460 std::string::size_type prevPos = 0;
1461 std::string::size_type pos = line.find('\t');
1462 if(pos == std::string::npos) continue; //invalid line
1464 std::string hash = line.substr(0, pos);
1465 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1467 bool forMerge = pos == prevPos;
1468 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1470 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1472 //Process this line
1473 if(forMerge)
1475 hashToReturn = hash;
1476 ++forMergeLineCount;
1477 if(forMergeLineCount > 1)
1478 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1482 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1485 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1487 int ret = 0;
1488 CString cur;
1489 if (m_IsUseLibGit2)
1491 CAutoRepository repo(GetGitRepository());
1492 if (!repo)
1493 return -1;
1495 if (git_repository_head_detached(repo) == 1)
1496 cur = _T("(detached from ");
1498 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1500 git_branch_t flags = GIT_BRANCH_LOCAL;
1501 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1502 flags = GIT_BRANCH_ALL;
1503 else if (type & BRANCH_REMOTE)
1504 flags = GIT_BRANCH_REMOTE;
1506 CAutoBranchIterator it;
1507 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1508 return -1;
1510 git_reference * ref = nullptr;
1511 git_branch_t branchType;
1512 while (git_branch_next(&ref, &branchType, it) == 0)
1514 CAutoReference autoRef(ref);
1515 const char * name = nullptr;
1516 if (git_branch_name(&name, ref))
1517 continue;
1519 CString branchname = CUnicodeUtils::GetUnicode(name);
1520 if (branchType & GIT_BRANCH_REMOTE)
1521 list.push_back(_T("remotes/") + branchname);
1522 else
1524 if (git_branch_is_head(ref))
1525 cur = branchname;
1526 list.push_back(branchname);
1531 else
1533 CString cmd, output;
1534 cmd = _T("git.exe branch --no-color");
1536 if ((type & BRANCH_ALL) == BRANCH_ALL)
1537 cmd += _T(" -a");
1538 else if (type & BRANCH_REMOTE)
1539 cmd += _T(" -r");
1541 ret = Run(cmd, &output, nullptr, CP_UTF8);
1542 if (!ret)
1544 int pos = 0;
1545 CString one;
1546 while (pos >= 0)
1548 one = output.Tokenize(_T("\n"), pos);
1549 one.Trim(L" \r\n\t");
1550 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1551 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1552 if (one[0] == _T('*'))
1554 one = one.Mid(2);
1555 cur = one;
1557 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1558 list.push_back(one);
1563 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1564 list.push_back(L"FETCH_HEAD");
1566 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1568 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1570 for (unsigned int i = 0; i < list.size(); ++i)
1572 if (list[i] == cur)
1574 *current = i;
1575 break;
1580 return ret;
1583 int CGit::GetRemoteList(STRING_VECTOR &list)
1585 if (this->m_IsUseLibGit2)
1587 CAutoRepository repo(GetGitRepository());
1588 if (!repo)
1589 return -1;
1591 CAutoStrArray remotes;
1592 if (git_remote_list(remotes, repo))
1593 return -1;
1595 for (size_t i = 0; i < remotes->count; ++i)
1597 CStringA remote(remotes->strings[i]);
1598 list.push_back(CUnicodeUtils::GetUnicode(remote));
1601 std::sort(list.begin(), list.end());
1603 return 0;
1605 else
1607 int ret;
1608 CString cmd, output;
1609 cmd=_T("git.exe remote");
1610 ret = Run(cmd, &output, NULL, CP_UTF8);
1611 if(!ret)
1613 int pos=0;
1614 CString one;
1615 while( pos>=0 )
1617 one=output.Tokenize(_T("\n"),pos);
1618 if (!one.IsEmpty())
1619 list.push_back(one);
1622 return ret;
1626 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR &list)
1628 CString cmd, out, err;
1629 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1630 if (Run(cmd, &out, &err, CP_UTF8))
1632 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1633 return -1;
1636 int pos = 0;
1637 while (pos >= 0)
1639 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1640 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1641 if (one.Find(_T("^{}")) >= 1)
1642 continue;
1643 if (!one.IsEmpty())
1644 list.push_back(one);
1646 std::sort(list.begin(), list.end(), g_bSortTagsReversed ? LogicalCompareReversedPredicate : LogicalComparePredicate);
1647 return 0;
1650 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1652 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1653 CString str;
1654 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1655 list->push_back(str);
1656 return 0;
1659 int CGit::GetRefList(STRING_VECTOR &list)
1661 if (this->m_IsUseLibGit2)
1663 CAutoRepository repo(GetGitRepository());
1664 if (!repo)
1665 return -1;
1667 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1668 return -1;
1670 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1672 return 0;
1674 else
1676 CString cmd, output;
1677 cmd=_T("git.exe show-ref -d");
1678 int ret = Run(cmd, &output, NULL, CP_UTF8);
1679 if(!ret)
1681 int pos=0;
1682 CString one;
1683 while( pos>=0 )
1685 one=output.Tokenize(_T("\n"),pos);
1686 int start=one.Find(_T(" "),0);
1687 if(start>0)
1689 CString name;
1690 name=one.Right(one.GetLength()-start-1);
1691 list.push_back(name);
1694 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1696 return ret;
1700 typedef struct map_each_ref_payload {
1701 git_repository * repo;
1702 MAP_HASH_NAME * map;
1703 } map_each_ref_payload;
1705 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1707 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1709 CString str;
1710 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1712 CAutoObject gitObject;
1713 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1714 return 1;
1716 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1718 str += _T("^{}"); // deref tag
1719 CAutoObject derefedTag;
1720 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1721 return 1;
1722 gitObject.Swap(derefedTag);
1725 const git_oid * oid = git_object_id(gitObject);
1726 if (oid == NULL)
1727 return 1;
1729 CGitHash hash((char *)oid->id);
1730 (*payloadContent->map)[hash].push_back(str);
1732 return 0;
1734 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1736 ATLASSERT(repo);
1738 map_each_ref_payload payloadContent = { repo, &map };
1740 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1741 return -1;
1743 for (auto it = map.begin(); it != map.end(); ++it)
1745 std::sort(it->second.begin(), it->second.end());
1748 return 0;
1751 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1753 if (this->m_IsUseLibGit2)
1755 CAutoRepository repo(GetGitRepository());
1756 if (!repo)
1757 return -1;
1759 return GetMapHashToFriendName(repo, map);
1761 else
1763 CString cmd, output;
1764 cmd=_T("git.exe show-ref -d");
1765 int ret = Run(cmd, &output, NULL, CP_UTF8);
1766 if(!ret)
1768 int pos=0;
1769 CString one;
1770 while( pos>=0 )
1772 one=output.Tokenize(_T("\n"),pos);
1773 int start=one.Find(_T(" "),0);
1774 if(start>0)
1776 CString name;
1777 name=one.Right(one.GetLength()-start-1);
1779 CString hash;
1780 hash=one.Left(start);
1782 map[CGitHash(hash)].push_back(name);
1786 return ret;
1790 static void SetLibGit2SearchPath(int level, const CString &value)
1792 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1793 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1796 static void SetLibGit2TemplatePath(const CString &value)
1798 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1799 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1802 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1804 if (m_bInitialized)
1806 return TRUE;
1809 this->m_Environment.clear();
1810 m_Environment.CopyProcessEnvironment();
1812 TCHAR *oldpath;
1813 size_t homesize,size;
1815 // set HOME if not set already
1816 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1817 if (!homesize)
1818 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1820 //setup ssh client
1821 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1822 if (sshclient.IsEmpty())
1823 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1825 if(!sshclient.IsEmpty())
1827 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1828 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1830 else
1832 TCHAR sPlink[MAX_PATH] = {0};
1833 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1834 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1835 if (ptr) {
1836 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1837 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1838 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1843 TCHAR sAskPass[MAX_PATH] = {0};
1844 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1845 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1846 if (ptr)
1848 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1849 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1850 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1851 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1855 // add git/bin path to PATH
1857 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1858 CString str = msysdir;
1859 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1861 if (!bFallback)
1862 return FALSE;
1864 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1865 str = msyslocalinstalldir;
1866 str.TrimRight(_T("\\"));
1867 if (str.IsEmpty())
1869 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1870 str = msysinstalldir;
1871 str.TrimRight(_T("\\"));
1873 if ( !str.IsEmpty() )
1875 str += "\\bin";
1876 msysdir=str;
1877 CGit::ms_LastMsysGitDir = str;
1878 msysdir.write();
1880 else
1882 // search PATH if git/bin directory is already present
1883 if ( FindGitPath() )
1885 m_bInitialized = TRUE;
1886 msysdir = CGit::ms_LastMsysGitDir;
1887 msysdir.write();
1888 return TRUE;
1891 return FALSE;
1894 else
1896 CGit::ms_LastMsysGitDir = str;
1899 // check for git.exe existance (maybe it was deinstalled in the meantime)
1900 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1901 return FALSE;
1903 // Configure libgit2 search paths
1904 CString msysGitDir;
1905 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
1906 msysGitDir.ReleaseBuffer();
1907 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
1908 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
1909 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
1910 CString msysGitTemplateDir;
1911 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
1912 msysGitTemplateDir.ReleaseBuffer();
1913 SetLibGit2TemplatePath(msysGitTemplateDir);
1915 //set path
1916 _tdupenv_s(&oldpath,&size,_T("PATH"));
1918 CString path;
1919 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1921 m_Environment.SetEnv(_T("PATH"), path);
1923 CString str1 = m_Environment.GetEnv(_T("PATH"));
1925 CString sOldPath = oldpath;
1926 free(oldpath);
1928 m_bInitialized = TRUE;
1929 return true;
1932 CString CGit::GetHomeDirectory() const
1934 const wchar_t * homeDir = wget_windows_home_directory();
1935 return CString(homeDir, (int)wcslen(homeDir));
1938 CString CGit::GetGitLocalConfig() const
1940 CString path;
1941 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
1942 path += _T("config");
1943 return path;
1946 CStringA CGit::GetGitPathStringA(const CString &path)
1948 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
1951 CString CGit::GetGitGlobalConfig() const
1953 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1956 CString CGit::GetGitGlobalXDGConfigPath() const
1958 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1961 CString CGit::GetGitGlobalXDGConfig() const
1963 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1966 CString CGit::GetGitSystemConfig() const
1968 const wchar_t * systemConfig = wget_msysgit_etc();
1969 return CString(systemConfig, (int)wcslen(systemConfig));
1972 BOOL CGit::CheckCleanWorkTree()
1974 CString out;
1975 CString cmd;
1976 cmd=_T("git.exe rev-parse --verify HEAD");
1978 if(Run(cmd,&out,CP_UTF8))
1979 return FALSE;
1981 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1982 if(Run(cmd,&out,CP_UTF8))
1983 return FALSE;
1985 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1986 if(Run(cmd,&out,CP_UTF8))
1987 return FALSE;
1989 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1990 if(Run(cmd,&out,CP_UTF8))
1991 return FALSE;
1993 return TRUE;
1995 int CGit::Revert(const CString& commit, const CTGitPathList &list, bool)
1997 int ret;
1998 for (int i = 0; i < list.GetCount(); ++i)
2000 ret = Revert(commit, (CTGitPath&)list[i]);
2001 if(ret)
2002 return ret;
2004 return 0;
2006 int CGit::Revert(const CString& commit, const CTGitPath &path)
2008 CString cmd, out;
2010 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
2012 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2014 CString err;
2015 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2016 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2017 return -1;
2019 CString force;
2020 // if the filenames only differ in case, we have to pass "-f"
2021 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2022 force = _T("-f ");
2023 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2024 if (Run(cmd, &out, CP_UTF8))
2026 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2027 return -1;
2030 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2031 if (Run(cmd, &out, CP_UTF8))
2033 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2034 return -1;
2038 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2039 { //To init git repository, there are not HEAD, so we can use git reset command
2040 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2042 if (Run(cmd, &out, CP_UTF8))
2044 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2045 return -1;
2048 else
2050 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2051 if (Run(cmd, &out, CP_UTF8))
2053 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2054 return -1;
2058 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2060 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2061 if (Run(cmd, &out, CP_UTF8))
2063 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2064 return -1;
2068 return 0;
2071 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2073 BYTE_VECTOR vector;
2075 CString cmd;
2076 if(path)
2077 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2078 else
2079 cmd=_T("git.exe ls-files -u -t -z");
2081 if (Run(cmd, &vector))
2083 return -1;
2086 if (list.ParserFromLsFile(vector))
2087 return -1;
2089 return 0;
2092 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2094 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2096 CAutoRepository repo(GetGitRepository());
2097 if (!repo)
2098 return false;
2100 CGitHash fromHash, toHash, baseHash;
2101 if (GetHash(repo, toHash, FixBranchName(to)))
2102 return false;
2104 if (GetHash(repo, fromHash, FixBranchName(from)))
2105 return false;
2107 git_oid baseOid;
2108 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2109 return false;
2111 baseHash = baseOid.id;
2113 if (commonAncestor)
2114 *commonAncestor = baseHash;
2116 return fromHash == baseHash;
2118 // else
2119 CString base;
2120 CGitHash basehash,hash;
2121 CString cmd, err;
2122 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2124 if (Run(cmd, &base, &err, CP_UTF8))
2126 return false;
2128 basehash = base.Trim();
2130 GetHash(hash, from);
2132 if (commonAncestor)
2133 *commonAncestor = basehash;
2135 return hash == basehash;
2138 unsigned int CGit::Hash2int(const CGitHash &hash)
2140 int ret=0;
2141 for (int i = 0; i < 4; ++i)
2143 ret = ret << 8;
2144 ret |= hash.m_hash[i];
2146 return ret;
2149 int CGit::RefreshGitIndex()
2151 if(g_Git.m_IsUseGitDLL)
2153 CAutoLocker lock(g_Git.m_critGitDllSec);
2156 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2158 }catch(...)
2160 return -1;
2164 else
2166 CString cmd,output;
2167 cmd=_T("git.exe update-index --refresh");
2168 return Run(cmd, &output, CP_UTF8);
2172 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2174 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2176 CAutoRepository repo(GetGitRepository());
2177 if (!repo)
2178 return -1;
2180 CGitHash hash;
2181 if (GetHash(repo, hash, Refname))
2182 return -1;
2184 CAutoCommit commit;
2185 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2186 return -1;
2188 CAutoTree tree;
2189 if (git_commit_tree(tree.GetPointer(), commit))
2190 return -1;
2192 CAutoTreeEntry entry;
2193 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2194 return -1;
2196 CAutoBlob blob;
2197 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2198 return -1;
2200 FILE *file = nullptr;
2201 _tfopen_s(&file, outputfile, _T("w"));
2202 if (file == nullptr)
2204 giterr_set_str(GITERR_NONE, "Could not create file.");
2205 return -1;
2207 CAutoBuf buf;
2208 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2210 fclose(file);
2211 return -1;
2213 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2215 giterr_set_str(GITERR_OS, "Could not write to file.");
2216 fclose(file);
2218 return -1;
2220 fclose(file);
2222 return 0;
2224 else if (g_Git.m_IsUseGitDLL)
2226 CAutoLocker lock(g_Git.m_critGitDllSec);
2229 g_Git.CheckAndInitDll();
2230 CStringA ref, patha, outa;
2231 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2232 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2233 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2234 ::DeleteFile(outputfile);
2235 return git_checkout_file(ref, patha, outa);
2238 catch (const char * msg)
2240 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2241 return -1;
2243 catch (...)
2245 gitLastErr = L"An unknown gitdll.dll error occurred.";
2246 return -1;
2249 else
2251 CString cmd;
2252 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2253 return RunLogFile(cmd, outputfile, &gitLastErr);
2256 void CEnvironment::CopyProcessEnvironment()
2258 TCHAR *porig = GetEnvironmentStrings();
2259 TCHAR *p = porig;
2260 while(*p !=0 || *(p+1) !=0)
2261 this->push_back(*p++);
2263 push_back(_T('\0'));
2264 push_back(_T('\0'));
2266 FreeEnvironmentStrings(porig);
2269 CString CEnvironment::GetEnv(const TCHAR *name)
2271 CString str;
2272 for (size_t i = 0; i < size(); ++i)
2274 str = &(*this)[i];
2275 int start =0;
2276 CString sname = str.Tokenize(_T("="),start);
2277 if(sname.CompareNoCase(name) == 0)
2279 return &(*this)[i+start];
2281 i+=str.GetLength();
2283 return _T("");
2286 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2288 unsigned int i;
2289 for (i = 0; i < size(); ++i)
2291 CString str = &(*this)[i];
2292 int start =0;
2293 CString sname = str.Tokenize(_T("="),start);
2294 if(sname.CompareNoCase(name) == 0)
2296 break;
2298 i+=str.GetLength();
2301 if(i == size())
2303 i -= 1; // roll back terminate \0\0
2304 this->push_back(_T('\0'));
2307 CEnvironment::iterator it;
2308 it=this->begin();
2309 it += i;
2311 while(*it && i<size())
2313 this->erase(it);
2314 it=this->begin();
2315 it += i;
2318 while(*name)
2320 this->insert(it,*name++);
2321 ++i;
2322 it= begin()+i;
2325 this->insert(it, _T('='));
2326 ++i;
2327 it= begin()+i;
2329 while(*value)
2331 this->insert(it,*value++);
2332 ++i;
2333 it= begin()+i;
2338 int CGit::GetGitEncode(TCHAR* configkey)
2340 CString str=GetConfigValue(configkey);
2342 if(str.IsEmpty())
2343 return CP_UTF8;
2345 return CUnicodeUtils::GetCPCode(str);
2349 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2351 GIT_FILE file=0;
2352 int ret=0;
2353 GIT_DIFF diff=0;
2355 CAutoLocker lock(g_Git.m_critGitDllSec);
2357 if(arg == NULL)
2358 diff = GetGitDiff();
2359 else
2360 git_open_diff(&diff, arg);
2362 if(diff ==NULL)
2363 return -1;
2365 bool isStat = 0;
2366 if(arg == NULL)
2367 isStat = true;
2368 else
2369 isStat = !!strstr(arg, "stat");
2371 int count=0;
2373 if(hash2 == NULL)
2374 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2375 else
2376 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2378 if(ret)
2379 return -1;
2381 CTGitPath path;
2382 CString strnewname;
2383 CString stroldname;
2385 for (int j = 0; j < count; ++j)
2387 path.Reset();
2388 char *newname;
2389 char *oldname;
2391 strnewname.Empty();
2392 stroldname.Empty();
2394 int mode=0,IsBin=0,inc=0,dec=0;
2395 git_get_diff_file(diff,file,j,&newname,&oldname,
2396 &mode,&IsBin,&inc,&dec);
2398 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2399 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2401 path.SetFromGit(strnewname,&stroldname);
2402 path.ParserAction((BYTE)mode);
2404 if(IsBin)
2406 path.m_StatAdd=_T("-");
2407 path.m_StatDel=_T("-");
2409 else
2411 path.m_StatAdd.Format(_T("%d"),inc);
2412 path.m_StatDel.Format(_T("%d"),dec);
2414 PathList->AddPath(path);
2416 git_diff_flush(diff);
2418 if(arg)
2419 git_close_diff(diff);
2421 return 0;
2424 int CGit::GetShortHASHLength() const
2426 return 7;
2429 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2431 CString str=ref;
2432 CString shortname;
2433 REF_TYPE type = CGit::UNKNOWN;
2435 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2437 type = CGit::LOCAL_BRANCH;
2440 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2442 type = CGit::REMOTE_BRANCH;
2444 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2446 type = CGit::TAG;
2448 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2450 type = CGit::STASH;
2451 shortname=_T("stash");
2453 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2455 if (shortname.Find(_T("good")) == 0)
2457 type = CGit::BISECT_GOOD;
2458 shortname = _T("good");
2461 if (shortname.Find(_T("bad")) == 0)
2463 type = CGit::BISECT_BAD;
2464 shortname = _T("bad");
2467 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2469 type = CGit::NOTES;
2471 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2473 type = CGit::UNKNOWN;
2475 else
2477 type = CGit::UNKNOWN;
2478 shortname = ref;
2481 if(out_type)
2482 *out_type = type;
2484 return shortname;
2487 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2489 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2492 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2494 CString cmd;
2495 if (rev2 == GitRev::GetWorkingCopy())
2496 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2497 else if (rev1 == GitRev::GetWorkingCopy())
2498 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2499 else
2501 CString merge;
2502 if (bMerge)
2503 merge += _T(" -m");
2505 if (bCombine)
2506 merge += _T(" -c");
2508 CString unified;
2509 if (diffContext >= 0)
2510 unified.Format(_T(" --unified=%d"), diffContext);
2511 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2514 if (!path.IsEmpty())
2516 cmd += _T(" \"");
2517 cmd += path.GetGitPathString();
2518 cmd += _T("\"");
2521 return cmd;
2524 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2526 ATLASSERT(payload && line);
2527 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2528 fwrite(&line->origin, 1, 1, (FILE *)payload);
2529 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2530 return 0;
2533 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2535 ATLASSERT(repo && identifier && tree);
2537 /* try to resolve identifier */
2538 CAutoObject obj;
2539 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2540 return -1;
2542 if (obj == nullptr)
2543 return GIT_ENOTFOUND;
2545 int err = 0;
2546 switch (git_object_type(obj))
2548 case GIT_OBJ_TREE:
2549 *tree = (git_tree *)obj.Detach();
2550 break;
2551 case GIT_OBJ_COMMIT:
2552 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2553 break;
2554 default:
2555 err = GIT_ENOTFOUND;
2558 return err;
2561 /* use libgit2 get unified diff */
2562 static int GetUnifiedDiffLibGit2(const CTGitPath& path, const git_revnum_t& revOld, const git_revnum_t& revNew, git_diff_line_cb callback, void *data, bool /* bMerge */)
2564 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2565 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2567 CAutoRepository repo(g_Git.GetGitRepository());
2568 if (!repo)
2569 return -1;
2571 int isHeadOrphan = git_repository_head_unborn(repo);
2572 if (isHeadOrphan == 1)
2573 return 0;
2574 else if (isHeadOrphan != 0)
2575 return -1;
2577 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2578 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2579 char *buf = pathA.GetBuffer();
2580 if (!pathA.IsEmpty())
2582 opts.pathspec.strings = &buf;
2583 opts.pathspec.count = 1;
2585 CAutoDiff diff;
2587 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2589 CAutoTree t1;
2590 CAutoDiff diff2;
2592 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2593 return -1;
2595 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2596 return -1;
2598 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2599 return -1;
2601 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2602 return -1;
2604 if (git_diff_merge(diff, diff2))
2605 return -1;
2607 else
2609 if (tree1.IsEmpty() && tree2.IsEmpty())
2610 return -1;
2612 if (tree1.IsEmpty())
2614 tree1 = tree2;
2615 tree2.Empty();
2618 CAutoTree t1;
2619 CAutoTree t2;
2620 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2621 return -1;
2623 if (tree2.IsEmpty())
2625 /* don't check return value, there are not parent commit at first commit*/
2626 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2628 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2629 return -1;
2630 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2631 return -1;
2634 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2636 CAutoPatch patch;
2637 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2638 return -1;
2640 if (git_patch_print(patch, callback, data))
2641 return -1;
2644 pathA.ReleaseBuffer();
2646 return 0;
2649 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2651 if (UsingLibGit2(GIT_CMD_DIFF))
2653 FILE *file = nullptr;
2654 _tfopen_s(&file, patchfile, _T("w"));
2655 if (file == nullptr)
2656 return -1;
2657 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToFile, file, bMerge);
2658 fclose(file);
2659 return ret;
2661 else
2663 CString cmd;
2664 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2665 return RunLogFile(cmd, patchfile, &gitLastErr);
2669 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2671 ATLASSERT(payload && line);
2672 CStringA *str = (CStringA*) payload;
2673 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2674 str->Append(&line->origin, 1);
2675 str->Append(line->content, (int)line->content_len);
2676 return 0;
2679 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2681 if (UsingLibGit2(GIT_CMD_DIFF))
2682 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToStringA, buffer, bMerge);
2683 else
2685 CString cmd;
2686 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2687 BYTE_VECTOR vector;
2688 int ret = Run(cmd, &vector);
2689 if (!vector.empty())
2691 vector.push_back(0); // vector is not NUL terminated
2692 buffer->Append((char *)&vector[0]);
2694 return ret;
2698 int CGit::GitRevert(int parent, const CGitHash &hash)
2700 if (UsingLibGit2(GIT_CMD_REVERT))
2702 CAutoRepository repo(GetGitRepository());
2703 if (!repo)
2704 return -1;
2706 CAutoCommit commit;
2707 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2708 return -1;
2710 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2711 revert_opts.mainline = parent;
2712 int result = git_revert(repo, commit, &revert_opts);
2714 return !result ? 0 : -1;
2716 else
2718 CString cmd, merge;
2719 if (parent)
2720 merge.Format(_T("-m %d "), parent);
2721 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2722 gitLastErr = cmd + _T("\n");
2723 if (Run(cmd, &gitLastErr, CP_UTF8))
2725 return -1;
2727 else
2729 gitLastErr.Empty();
2730 return 0;
2735 int CGit::DeleteRef(const CString& reference)
2737 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2739 CAutoRepository repo(GetGitRepository());
2740 if (!repo)
2741 return -1;
2743 CStringA refA;
2744 if (reference.Right(3) == _T("^{}"))
2745 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2746 else
2747 refA = CUnicodeUtils::GetUTF8(reference);
2749 CAutoReference ref;
2750 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2751 return -1;
2753 int result = -1;
2754 if (git_reference_is_tag(ref))
2755 result = git_tag_delete(repo, git_reference_shorthand(ref));
2756 else if (git_reference_is_branch(ref))
2757 result = git_branch_delete(ref);
2758 else if (git_reference_is_remote(ref))
2759 result = git_branch_delete(ref);
2760 else
2761 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2763 return result;
2765 else
2767 CString cmd, shortname;
2768 if (GetShortName(reference, shortname, _T("refs/heads/")))
2769 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2770 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2771 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2772 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2773 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2774 else
2776 gitLastErr = L"unsupported reference type: " + reference;
2777 return -1;
2780 if (Run(cmd, &gitLastErr, CP_UTF8))
2781 return -1;
2783 gitLastErr.Empty();
2784 return 0;
2788 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2790 if (PathFileExists(filename))
2792 FILE *pFile = nullptr;
2793 _tfopen_s(&pFile, filename, _T("r"));
2794 if (pFile)
2796 CStringA str;
2799 char s[8196] = { 0 };
2800 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
2801 if (read == 0)
2802 break;
2803 str += CStringA(s, read);
2804 } while (true);
2805 fclose(pFile);
2806 msg = CUnicodeUtils::GetUnicode(str);
2807 msg.Replace(_T("\r\n"), _T("\n"));
2808 msg.TrimRight(_T("\n"));
2809 msg += _T("\n");
2811 else
2812 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
2813 return true; // load no further files
2815 return false;