Correctly show reverse diff to working tree
[TortoiseGit.git] / src / Git / Git.cpp
blob1a53baf36e8ae8dc3caae0b30f573c710642ccd2
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;
116 static void GetSortOptions()
118 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
119 if (g_bSortLogical)
120 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
121 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
122 if (g_bSortLocalBranchesFirst)
123 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
126 static int LogicalComparePredicate(const CString &left, const CString &right)
128 if (g_bSortLogical)
129 return StrCmpLogicalW(left, right) < 0;
130 return StrCmpI(left, right) < 0;
133 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
135 if (g_bSortLocalBranchesFirst)
137 int leftIsRemote = left.Find(_T("remotes/"));
138 int rightIsRemote = right.Find(_T("remotes/"));
140 if (leftIsRemote == 0 && rightIsRemote < 0)
141 return false;
142 else if (leftIsRemote < 0 && rightIsRemote == 0)
143 return true;
145 if (g_bSortLogical)
146 return StrCmpLogicalW(left, right) < 0;
147 return StrCmpI(left, right) < 0;
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString CGit::ms_LastMsysGitDir;
153 int CGit::ms_LastMsysGitVersion = 0;
154 CGit g_Git;
157 CGit::CGit(void)
159 GetCurrentDirectory(MAX_PATH, m_CurrentDir.GetBuffer(MAX_PATH));
160 m_CurrentDir.ReleaseBuffer();
161 m_IsGitDllInited = false;
162 m_GitDiff=0;
163 m_GitSimpleListDiff=0;
164 m_IsUseGitDLL = !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
165 m_IsUseLibGit2 = !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE);
166 m_IsUseLibGit2_mask = CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), (1 << GIT_CMD_MERGE_BASE) | (1 << GIT_CMD_DELETETAGBRANCH) | (1 << GIT_CMD_GETONEFILE));
168 SecureZeroMemory(&m_CurrentGitPi, sizeof(PROCESS_INFORMATION));
170 GetSortOptions();
171 this->m_bInitialized =false;
172 CheckMsysGitDir();
173 m_critGitDllSec.Init();
176 CGit::~CGit(void)
178 if(this->m_GitDiff)
180 git_close_diff(m_GitDiff);
181 m_GitDiff=0;
183 if(this->m_GitSimpleListDiff)
185 git_close_diff(m_GitSimpleListDiff);
186 m_GitSimpleListDiff=0;
190 bool CGit::IsBranchNameValid(const CString& branchname)
192 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
193 return false;
194 if (branchname.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
195 return false;
196 CStringA branchA = CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname);
197 return !!git_reference_is_valid_name(branchA);
200 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
202 SECURITY_ATTRIBUTES sa;
203 CAutoGeneralHandle hRead, hWrite, hReadErr, hWriteErr;
204 CAutoGeneralHandle hStdioFile;
206 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
207 sa.lpSecurityDescriptor=NULL;
208 sa.bInheritHandle=TRUE;
209 if (!CreatePipe(hRead.GetPointer(), hWrite.GetPointer(), &sa, 0))
211 CString err = CFormatMessageWrapper();
212 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
213 return TGIT_GIT_ERROR_OPEN_PIP;
215 if (hErrReadOut && !CreatePipe(hReadErr.GetPointer(), hWriteErr.GetPointer(), &sa, 0))
217 CString err = CFormatMessageWrapper();
218 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
219 return TGIT_GIT_ERROR_OPEN_PIP;
222 if(StdioFile)
224 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
225 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
228 STARTUPINFO si;
229 PROCESS_INFORMATION pi;
230 si.cb=sizeof(STARTUPINFO);
231 GetStartupInfo(&si);
233 if (hErrReadOut)
234 si.hStdError = hWriteErr;
235 else
236 si.hStdError = hWrite;
237 if(StdioFile)
238 si.hStdOutput=hStdioFile;
239 else
240 si.hStdOutput=hWrite;
242 si.wShowWindow=SW_HIDE;
243 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
245 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
246 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
248 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
249 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
251 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
252 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
254 if(cmd.Find(_T("git")) == 0)
256 int firstSpace = cmd.Find(_T(" "));
257 if (firstSpace > 0)
258 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
259 else
260 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
263 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
264 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
266 CString err = CFormatMessageWrapper();
267 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
268 return TGIT_GIT_ERROR_CREATE_PROCESS;
271 m_CurrentGitPi = pi;
273 if(piOut)
274 *piOut=pi;
275 if(hReadOut)
276 *hReadOut = hRead.Detach();
277 if(hErrReadOut)
278 *hErrReadOut = hReadErr.Detach();
279 return 0;
282 //Must use sperate function to convert ANSI str to union code string
283 //Becuase A2W use stack as internal convert buffer.
284 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
286 if(str == NULL)
287 return ;
289 int len ;
290 if(length<0)
291 len = (int)strlen((const char*)p);
292 else
293 len=length;
294 if (len == 0)
295 return;
296 int currentContentLen = str->GetLength();
297 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
298 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
299 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
302 // This method was originally used to check for orphaned branches
303 BOOL CGit::CanParseRev(CString ref)
305 if (ref.IsEmpty())
306 ref = _T("HEAD");
308 CString cmdout;
309 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
311 return FALSE;
313 if(cmdout.IsEmpty())
314 return FALSE;
316 return TRUE;
319 // Checks if we have an orphaned HEAD
320 BOOL CGit::IsInitRepos()
322 CGitHash hash;
323 // handle error on reading HEAD hash as init repo
324 if (GetHash(hash, _T("HEAD")) != 0)
325 return TRUE;
326 return hash.IsEmpty() ? TRUE : FALSE;
329 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
331 PASYNCREADSTDERRTHREADARGS pDataArray;
332 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
334 DWORD readnumber;
335 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
336 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
338 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
339 break;
342 return 0;
345 int CGit::Run(CGitCall* pcall)
347 PROCESS_INFORMATION pi;
348 CAutoGeneralHandle hRead, hReadErr;
349 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
350 return TGIT_GIT_ERROR_CREATE_PROCESS;
352 CAutoGeneralHandle piThread(pi.hThread);
353 CAutoGeneralHandle piProcess(pi.hProcess);
355 ASYNCREADSTDERRTHREADARGS threadArguments;
356 threadArguments.fileHandle = hReadErr;
357 threadArguments.pcall = pcall;
358 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
360 DWORD readnumber;
361 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
362 bool bAborted=false;
363 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
365 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
366 if(!bAborted)//For now, flush output when command aborted.
367 if(pcall->OnOutputData(data,readnumber))
368 bAborted=true;
370 if(!bAborted)
371 pcall->OnEnd();
373 if (thread)
374 WaitForSingleObject(thread, INFINITE);
376 WaitForSingleObject(pi.hProcess, INFINITE);
377 DWORD exitcode =0;
379 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
381 CString err = CFormatMessageWrapper();
382 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
383 return TGIT_GIT_ERROR_GET_EXIT_CODE;
385 else
386 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
388 return exitcode;
390 class CGitCall_ByteVector : public CGitCall
392 public:
393 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
394 virtual bool OnOutputData(const BYTE* data, size_t size)
396 if (!m_pvector || size == 0)
397 return false;
398 size_t oldsize=m_pvector->size();
399 m_pvector->resize(m_pvector->size()+size);
400 memcpy(&*(m_pvector->begin()+oldsize),data,size);
401 return false;
403 virtual bool OnOutputErrData(const BYTE* data, size_t size)
405 if (!m_pvectorErr || size == 0)
406 return false;
407 size_t oldsize = m_pvectorErr->size();
408 m_pvectorErr->resize(m_pvectorErr->size() + size);
409 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
410 return false;
412 BYTE_VECTOR* m_pvector;
413 BYTE_VECTOR* m_pvectorErr;
416 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
418 CGitCall_ByteVector call(cmd, vector, vectorErr);
419 return Run(&call);
421 int CGit::Run(CString cmd, CString* output, int code)
423 CString err;
424 int ret;
425 ret = Run(cmd, output, &err, code);
427 if (output && !err.IsEmpty())
429 if (!output->IsEmpty())
430 *output += _T("\n");
431 *output += err;
434 return ret;
436 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
438 BYTE_VECTOR vector, vectorErr;
439 int ret;
440 if (outputErr)
441 ret = Run(cmd, &vector, &vectorErr);
442 else
443 ret = Run(cmd, &vector);
445 vector.push_back(0);
446 StringAppend(output, &(vector[0]), code);
448 if (outputErr)
450 vectorErr.push_back(0);
451 StringAppend(outputErr, &(vectorErr[0]), code);
454 return ret;
457 class CGitCallCb : public CGitCall
459 public:
460 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
462 virtual bool OnOutputData(const BYTE* data, size_t size) override
464 // Add data
465 if (size == 0)
466 return false;
467 int oldEndPos = m_buffer.GetLength();
468 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
469 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
471 // Break into lines and feed to m_recv
472 int eolPos;
473 while ((eolPos = m_buffer.Find('\n')) >= 0)
475 m_recv(m_buffer.Left(eolPos));
476 m_buffer = m_buffer.Mid(eolPos + 1);
478 return false;
481 virtual bool OnOutputErrData(const BYTE*, size_t) override
483 return false; // Ignore error output for now
486 virtual void OnEnd() override
488 if (!m_buffer.IsEmpty())
489 m_recv(m_buffer);
490 m_buffer.Empty(); // Just for sure
493 private:
494 GitReceiverFunc m_recv;
495 CStringA m_buffer;
498 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
500 CGitCallCb call(cmd, recv);
501 return Run(&call);
504 CString CGit::GetUserName(void)
506 CEnvironment env;
507 env.CopyProcessEnvironment();
508 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
509 if (!envname.IsEmpty())
510 return envname;
511 return GetConfigValue(L"user.name");
513 CString CGit::GetUserEmail(void)
515 CEnvironment env;
516 env.CopyProcessEnvironment();
517 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
518 if (!envmail.IsEmpty())
519 return envmail;
521 return GetConfigValue(L"user.email");
524 CString CGit::GetConfigValue(const CString& name)
526 CString configValue;
527 int start = 0;
528 if(this->m_IsUseGitDLL)
530 CAutoLocker lock(g_Git.m_critGitDllSec);
534 CheckAndInitDll();
535 }catch(...)
538 CStringA key, value;
539 key = CUnicodeUtils::GetUTF8(name);
543 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
544 return CString();
546 catch (const char *msg)
548 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
549 return CString();
552 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
553 return configValue.Tokenize(_T("\n"),start);
555 else
557 CString cmd;
558 cmd.Format(L"git.exe config %s", name);
559 Run(cmd, &configValue, nullptr, CP_UTF8);
560 return configValue.Tokenize(_T("\n"),start);
564 bool CGit::GetConfigValueBool(const CString& name)
566 CString configValue = GetConfigValue(name);
567 configValue.MakeLower();
568 configValue.Trim();
569 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
570 return true;
571 else
572 return false;
575 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
577 if(this->m_IsUseGitDLL)
579 CAutoLocker lock(g_Git.m_critGitDllSec);
583 CheckAndInitDll();
585 }catch(...)
588 CStringA keya, valuea;
589 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
590 valuea = CUnicodeUtils::GetUTF8(value);
594 return [=]() { return get_set_config(keya, valuea, type); }();
596 catch (const char *msg)
598 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
599 return -1;
602 else
604 CString cmd;
605 CString option;
606 switch(type)
608 case CONFIG_GLOBAL:
609 option = _T("--global");
610 break;
611 case CONFIG_SYSTEM:
612 option = _T("--system");
613 break;
614 default:
615 break;
617 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
618 CString out;
619 if (Run(cmd, &out, nullptr, CP_UTF8))
621 return -1;
624 return 0;
627 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
629 if(this->m_IsUseGitDLL)
631 CAutoLocker lock(g_Git.m_critGitDllSec);
635 CheckAndInitDll();
636 }catch(...)
639 CStringA keya;
640 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
644 return [=]() { return get_set_config(keya, nullptr, type); }();
646 catch (const char *msg)
648 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
649 return -1;
652 else
654 CString cmd;
655 CString option;
656 switch(type)
658 case CONFIG_GLOBAL:
659 option = _T("--global");
660 break;
661 case CONFIG_SYSTEM:
662 option = _T("--system");
663 break;
664 default:
665 break;
667 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
668 CString out;
669 if (Run(cmd, &out, nullptr, CP_UTF8))
671 return -1;
674 return 0;
677 CString CGit::GetCurrentBranch(bool fallback)
679 CString output;
680 //Run(_T("git.exe branch"),&branch);
682 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
683 if (result != 0 && ((result == 1 && !fallback) || result != 1))
685 return _T("(no branch)");
687 else
688 return output;
692 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
694 if (localBranch.IsEmpty())
695 return;
697 CString configName;
698 configName.Format(L"branch.%s.remote", localBranch);
699 pullRemote = GetConfigValue(configName);
701 //Select pull-branch from current branch
702 configName.Format(L"branch.%s.merge", localBranch);
703 pullBranch = StripRefName(GetConfigValue(configName));
706 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
708 CString refName;
709 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
710 return;
711 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
714 CString CGit::GetFullRefName(const CString& shortRefName)
716 CString refName;
717 CString cmd;
718 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
719 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
720 return CString();//Error
721 int iStart = 0;
722 return refName.Tokenize(L"\n", iStart);
725 CString CGit::StripRefName(CString refName)
727 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
728 refName = refName.Mid(11);
729 else if(wcsncmp(refName, L"refs/", 5) == 0)
730 refName = refName.Mid(5);
731 int start =0;
732 return refName.Tokenize(_T("\n"),start);
735 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
737 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
739 if ( sProjectRoot.IsEmpty() )
740 return -1;
742 CString sDotGitPath;
743 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
744 return -1;
746 CString sHeadFile = sDotGitPath + _T("HEAD");
748 FILE *pFile;
749 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
751 if (!pFile)
753 return -1;
756 char s[256] = {0};
757 fgets(s, sizeof(s), pFile);
759 fclose(pFile);
761 const char *pfx = "ref: refs/heads/";
762 const int len = 16;//strlen(pfx)
764 if ( !strncmp(s, pfx, len) )
766 //# We're on a branch. It might not exist. But
767 //# HEAD looks good enough to be a branch.
768 CStringA utf8Branch(s + len);
769 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
770 sBranchOut.TrimRight(_T(" \r\n\t"));
772 if ( sBranchOut.IsEmpty() )
773 return -1;
775 else if (fallback)
777 CStringA utf8Hash(s);
778 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
779 unicodeHash.TrimRight(_T(" \r\n\t"));
780 if (CGitHash::IsValidSHA1(unicodeHash))
781 sBranchOut = unicodeHash;
782 else
783 //# Assume this is a detached head.
784 sBranchOut = _T("HEAD");
785 return 1;
787 else
789 //# Assume this is a detached head.
790 sBranchOut = "HEAD";
792 return 1;
795 return 0;
798 int CGit::BuildOutputFormat(CString &format,bool IsFull)
800 CString log;
801 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
802 format += log;
803 if(IsFull)
805 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
806 format += log;
807 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
808 format += log;
809 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
810 format += log;
811 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
812 format += log;
813 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
814 format += log;
815 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
816 format += log;
817 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
818 format += log;
821 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
822 format += log;
823 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
824 format += log;
825 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
826 format += log;
828 if(IsFull)
830 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
831 format += log;
833 return 0;
836 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
837 CFilterData *Filter)
839 CString cmd;
840 CString num;
841 CString since;
843 CString file = _T(" --");
845 if(path)
846 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
848 if(count>0)
849 num.Format(_T("-n%d"),count);
851 CString param;
853 if(mask& LOG_INFO_STAT )
854 param += _T(" --numstat ");
855 if(mask& LOG_INFO_FILESTATE)
856 param += _T(" --raw ");
858 if(mask& LOG_INFO_FULLHISTORY)
859 param += _T(" --full-history ");
861 if(mask& LOG_INFO_BOUNDARY)
862 param += _T(" --left-right --boundary ");
864 if(mask& CGit::LOG_INFO_ALL_BRANCH)
865 param += _T(" --all ");
867 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
868 param += _T(" --branches ");
870 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
871 param += _T(" -C ");
873 if(mask& CGit::LOG_INFO_DETECT_RENAME )
874 param += _T(" -M ");
876 if(mask& CGit::LOG_INFO_FIRST_PARENT )
877 param += _T(" --first-parent ");
879 if(mask& CGit::LOG_INFO_NO_MERGE )
880 param += _T(" --no-merges ");
882 if(mask& CGit::LOG_INFO_FOLLOW)
883 param += _T(" --follow ");
885 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
886 param += _T(" -c ");
888 if(mask& CGit::LOG_INFO_FULL_DIFF)
889 param += _T(" --full-diff ");
891 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
892 param += _T(" --simplify-by-decoration ");
894 param += range;
896 CString st1,st2;
898 if( Filter && (Filter->m_From != -1))
900 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
901 param += st1;
904 if( Filter && (Filter->m_To != -1))
906 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
907 param += st2;
910 bool isgrep = false;
911 if( Filter && (!Filter->m_Author.IsEmpty()))
913 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
914 param += st1;
915 isgrep = true;
918 if( Filter && (!Filter->m_Committer.IsEmpty()))
920 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
921 param += st1;
922 isgrep = true;
925 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
927 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
928 param += st1;
929 isgrep = true;
932 if(Filter && isgrep)
934 if(!Filter->m_IsRegex)
935 param += _T(" --fixed-strings ");
937 param += _T(" --regexp-ignore-case --extended-regexp ");
940 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
941 if (logOrderBy == LOG_ORDER_TOPOORDER)
942 param += _T(" --topo-order");
943 else if (logOrderBy == LOG_ORDER_DATEORDER)
944 param += _T(" --date-order");
946 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
947 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
948 else
950 CString log;
951 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
952 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
953 num,param,log);
956 cmd += file;
958 return cmd;
960 #define BUFSIZE 512
961 void GetTempPath(CString &path)
963 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
964 DWORD dwRetVal;
965 DWORD dwBufSize=BUFSIZE;
966 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
967 lpPathBuffer); // buffer for path
968 if (dwRetVal > dwBufSize || (dwRetVal == 0))
970 path=_T("");
972 path.Format(_T("%s"),lpPathBuffer);
974 CString GetTempFile()
976 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
977 DWORD dwRetVal;
978 DWORD dwBufSize=BUFSIZE;
979 TCHAR szTempName[BUFSIZE] = { 0 };
980 UINT uRetVal;
982 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
983 lpPathBuffer); // buffer for path
984 if (dwRetVal > dwBufSize || (dwRetVal == 0))
986 return _T("");
988 // Create a temporary file.
989 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
990 TEXT("Patch"), // temp file name prefix
991 0, // create unique name
992 szTempName); // buffer for name
995 if (uRetVal == 0)
997 return _T("");
1000 return CString(szTempName);
1004 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1006 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1007 if (result == 0) return 0;
1008 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1010 if (lpBuffer)
1011 lpBuffer[0] = '\0';
1012 return result + 13;
1015 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1016 CreateDirectory(lpBuffer, NULL);
1018 return result + 13;
1021 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1023 STARTUPINFO si;
1024 PROCESS_INFORMATION pi;
1025 si.cb=sizeof(STARTUPINFO);
1026 GetStartupInfo(&si);
1028 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1029 psa.bInheritHandle=TRUE;
1031 HANDLE hReadErr, hWriteErr;
1032 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1034 CString err = CFormatMessageWrapper();
1035 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1036 return TGIT_GIT_ERROR_OPEN_PIP;
1039 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1040 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1042 if (houtfile == INVALID_HANDLE_VALUE)
1044 CString err = CFormatMessageWrapper();
1045 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1046 CloseHandle(hReadErr);
1047 CloseHandle(hWriteErr);
1048 return TGIT_GIT_ERROR_OPEN_PIP;
1051 si.wShowWindow = SW_HIDE;
1052 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1053 si.hStdOutput = houtfile;
1054 si.hStdError = hWriteErr;
1056 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1057 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1059 if(cmd.Find(_T("git")) == 0)
1060 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1062 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1063 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1065 CString err = CFormatMessageWrapper();
1066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1067 stdErr = &err;
1068 CloseHandle(hReadErr);
1069 CloseHandle(hWriteErr);
1070 CloseHandle(houtfile);
1071 return TGIT_GIT_ERROR_CREATE_PROCESS;
1074 BYTE_VECTOR stderrVector;
1075 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1076 HANDLE thread;
1077 ASYNCREADSTDERRTHREADARGS threadArguments;
1078 threadArguments.fileHandle = hReadErr;
1079 threadArguments.pcall = &pcall;
1080 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1082 WaitForSingleObject(pi.hProcess,INFINITE);
1084 CloseHandle(hWriteErr);
1085 CloseHandle(hReadErr);
1087 if (thread)
1088 WaitForSingleObject(thread, INFINITE);
1090 stderrVector.push_back(0);
1091 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1093 DWORD exitcode = 0;
1094 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1096 CString err = CFormatMessageWrapper();
1097 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1098 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1100 else
1101 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1103 CloseHandle(pi.hThread);
1104 CloseHandle(pi.hProcess);
1105 CloseHandle(houtfile);
1106 return exitcode;
1109 git_repository * CGit::GetGitRepository() const
1111 git_repository * repo = nullptr;
1112 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1113 return repo;
1116 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1118 ATLASSERT(repo);
1120 // no need to parse a ref if it's already a 40-byte hash
1121 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1123 hash = CGitHash(friendname);
1124 return 0;
1127 int isHeadOrphan = git_repository_head_unborn(repo);
1128 if (isHeadOrphan != 0)
1130 hash.Empty();
1131 if (isHeadOrphan == 1)
1132 return 0;
1133 else
1134 return -1;
1137 CAutoObject gitObject;
1138 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1139 return -1;
1141 const git_oid * oid = git_object_id(gitObject);
1142 if (!oid)
1143 return -1;
1145 hash = CGitHash((char *)oid->id);
1147 return 0;
1150 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1152 // no need to parse a ref if it's already a 40-byte hash
1153 if (CGitHash::IsValidSHA1(friendname))
1155 hash = CGitHash(friendname);
1156 return 0;
1159 if (m_IsUseLibGit2)
1161 CAutoRepository repo(GetGitRepository());
1162 if (!repo)
1163 return -1;
1165 return GetHash(repo, hash, friendname, true);
1167 else
1169 CString cmd;
1170 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1171 gitLastErr.Empty();
1172 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1173 hash = CGitHash(gitLastErr.Trim());
1174 if (ret == 0)
1175 gitLastErr.Empty();
1176 return ret;
1180 int CGit::GetInitAddList(CTGitPathList &outputlist)
1182 CString cmd;
1183 BYTE_VECTOR cmdout;
1185 cmd=_T("git.exe ls-files -s -t -z");
1186 outputlist.Clear();
1187 if (Run(cmd, &cmdout))
1188 return -1;
1190 if (outputlist.ParserFromLsFile(cmdout))
1191 return -1;
1192 for(int i = 0; i < outputlist.GetCount(); ++i)
1193 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1195 return 0;
1197 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1199 CString cmd;
1200 CString ignore;
1201 if (ignoreSpaceAtEol)
1202 ignore += _T(" --ignore-space-at-eol");
1203 if (ignoreSpaceChange)
1204 ignore += _T(" --ignore-space-change");
1205 if (ignoreAllSpace)
1206 ignore += _T(" --ignore-all-space");
1207 if (ignoreBlankLines)
1208 ignore += _T(" --ignore-blank-lines");
1210 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1212 //rev1=+_T("");
1213 if(rev1 == GIT_REV_ZERO)
1214 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1215 else
1216 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1218 else
1220 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1223 BYTE_VECTOR out;
1224 if (Run(cmd, &out))
1225 return -1;
1227 outputlist.ParserFromLog(out);
1229 return 0;
1232 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1234 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1235 CString str;
1236 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1237 list->push_back(str);
1238 return 0;
1241 int CGit::GetTagList(STRING_VECTOR &list)
1243 if (this->m_IsUseLibGit2)
1245 CAutoRepository repo(GetGitRepository());
1246 if (!repo)
1247 return -1;
1249 CAutoStrArray tag_names;
1251 if (git_tag_list(tag_names, repo))
1252 return -1;
1254 for (size_t i = 0; i < tag_names->count; ++i)
1256 CStringA tagName(tag_names->strings[i]);
1257 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1260 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1262 return 0;
1264 else
1266 CString cmd, output;
1267 cmd=_T("git.exe tag -l");
1268 int ret = Run(cmd, &output, NULL, CP_UTF8);
1269 if(!ret)
1271 int pos=0;
1272 CString one;
1273 while( pos>=0 )
1275 one=output.Tokenize(_T("\n"),pos);
1276 if (!one.IsEmpty())
1277 list.push_back(one);
1279 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1281 return ret;
1286 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1287 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1289 CString CGit::GetGitLastErr(const CString& msg)
1291 if (this->m_IsUseLibGit2)
1292 return GetLibGit2LastErr(msg);
1293 else if (gitLastErr.IsEmpty())
1294 return msg + _T("\nUnknown git.exe error.");
1295 else
1297 CString lastError = gitLastErr;
1298 gitLastErr.Empty();
1299 return msg + _T("\n") + lastError;
1303 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1305 if (UsingLibGit2(cmd))
1306 return GetLibGit2LastErr(msg);
1307 else if (gitLastErr.IsEmpty())
1308 return msg + _T("\nUnknown git.exe error.");
1309 else
1311 CString lastError = gitLastErr;
1312 gitLastErr.Empty();
1313 return msg + _T("\n") + lastError;
1317 CString CGit::GetLibGit2LastErr()
1319 const git_error *libgit2err = giterr_last();
1320 if (libgit2err)
1322 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1323 giterr_clear();
1324 return _T("libgit2 returned: ") + lastError;
1326 else
1327 return _T("An error occoured in libgit2, but no message is available.");
1330 CString CGit::GetLibGit2LastErr(const CString& msg)
1332 if (!msg.IsEmpty())
1333 return msg + _T("\n") + GetLibGit2LastErr();
1334 return GetLibGit2LastErr();
1337 CString CGit::FixBranchName_Mod(CString& branchName)
1339 if(branchName == "FETCH_HEAD")
1340 branchName = DerefFetchHead();
1341 return branchName;
1344 CString CGit::FixBranchName(const CString& branchName)
1346 CString tempBranchName = branchName;
1347 FixBranchName_Mod(tempBranchName);
1348 return tempBranchName;
1351 bool CGit::IsBranchTagNameUnique(const CString& name)
1353 if (m_IsUseLibGit2)
1355 CAutoRepository repo(GetGitRepository());
1356 if (!repo)
1357 return true; // TODO: optimize error reporting
1359 CAutoReference tagRef;
1360 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1361 return true;
1363 CAutoReference branchRef;
1364 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1365 return true;
1367 return false;
1369 // else
1370 CString output;
1372 CString cmd;
1373 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1374 int ret = Run(cmd, &output, NULL, CP_UTF8);
1375 if (!ret)
1377 int i = 0, pos = 0;
1378 while (pos >= 0)
1380 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1381 ++i;
1383 if (i >= 2)
1384 return false;
1387 return true;
1391 Checks if a branch or tag with the given name exists
1392 isBranch is true -> branch, tag otherwise
1394 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1396 if (m_IsUseLibGit2)
1398 CAutoRepository repo(GetGitRepository());
1399 if (!repo)
1400 return false; // TODO: optimize error reporting
1402 CString prefix;
1403 if (isBranch)
1404 prefix = _T("refs/heads/");
1405 else
1406 prefix = _T("refs/tags/");
1408 CAutoReference ref;
1409 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1410 return false;
1412 return true;
1414 // else
1415 CString cmd, output;
1417 cmd = _T("git.exe show-ref ");
1418 if (isBranch)
1419 cmd += _T("--heads ");
1420 else
1421 cmd += _T("--tags ");
1423 cmd += _T("refs/heads/") + name;
1424 cmd += _T(" refs/tags/") + name;
1426 int ret = Run(cmd, &output, NULL, CP_UTF8);
1427 if (!ret)
1429 if (!output.IsEmpty())
1430 return true;
1433 return false;
1436 CString CGit::DerefFetchHead()
1438 CString dotGitPath;
1439 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1440 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1441 int forMergeLineCount = 0;
1442 std::string line;
1443 std::string hashToReturn;
1444 while(getline(fetchHeadFile, line))
1446 //Tokenize this line
1447 std::string::size_type prevPos = 0;
1448 std::string::size_type pos = line.find('\t');
1449 if(pos == std::string::npos) continue; //invalid line
1451 std::string hash = line.substr(0, pos);
1452 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1454 bool forMerge = pos == prevPos;
1455 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1457 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1459 //Process this line
1460 if(forMerge)
1462 hashToReturn = hash;
1463 ++forMergeLineCount;
1464 if(forMergeLineCount > 1)
1465 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1469 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1472 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1474 int ret = 0;
1475 CString cur;
1476 if (m_IsUseLibGit2)
1478 CAutoRepository repo(GetGitRepository());
1479 if (!repo)
1480 return -1;
1482 if (git_repository_head_detached(repo) == 1)
1483 cur = _T("(detached from ");
1485 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1487 git_branch_t flags = GIT_BRANCH_LOCAL;
1488 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1489 flags = GIT_BRANCH_ALL;
1490 else if (type & BRANCH_REMOTE)
1491 flags = GIT_BRANCH_REMOTE;
1493 CAutoBranchIterator it;
1494 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1495 return -1;
1497 git_reference * ref = nullptr;
1498 git_branch_t branchType;
1499 while (git_branch_next(&ref, &branchType, it) == 0)
1501 CAutoReference autoRef(ref);
1502 const char * name = nullptr;
1503 if (git_branch_name(&name, ref))
1504 continue;
1506 CString branchname = CUnicodeUtils::GetUnicode(name);
1507 if (branchType & GIT_BRANCH_REMOTE)
1508 list.push_back(_T("remotes/") + branchname);
1509 else
1511 if (git_branch_is_head(ref))
1512 cur = branchname;
1513 list.push_back(branchname);
1518 else
1520 CString cmd, output;
1521 cmd = _T("git.exe branch --no-color");
1523 if ((type & BRANCH_ALL) == BRANCH_ALL)
1524 cmd += _T(" -a");
1525 else if (type & BRANCH_REMOTE)
1526 cmd += _T(" -r");
1528 ret = Run(cmd, &output, nullptr, CP_UTF8);
1529 if (!ret)
1531 int pos = 0;
1532 CString one;
1533 while (pos >= 0)
1535 one = output.Tokenize(_T("\n"), pos);
1536 one.Trim(L" \r\n\t");
1537 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1538 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1539 if (one[0] == _T('*'))
1541 one = one.Mid(2);
1542 cur = one;
1544 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1545 list.push_back(one);
1550 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1551 list.push_back(L"FETCH_HEAD");
1553 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1555 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1557 for (unsigned int i = 0; i < list.size(); ++i)
1559 if (list[i] == cur)
1561 *current = i;
1562 break;
1567 return ret;
1570 int CGit::GetRemoteList(STRING_VECTOR &list)
1572 if (this->m_IsUseLibGit2)
1574 CAutoRepository repo(GetGitRepository());
1575 if (!repo)
1576 return -1;
1578 CAutoStrArray remotes;
1579 if (git_remote_list(remotes, repo))
1580 return -1;
1582 for (size_t i = 0; i < remotes->count; ++i)
1584 CStringA remote(remotes->strings[i]);
1585 list.push_back(CUnicodeUtils::GetUnicode(remote));
1588 std::sort(list.begin(), list.end());
1590 return 0;
1592 else
1594 int ret;
1595 CString cmd, output;
1596 cmd=_T("git.exe remote");
1597 ret = Run(cmd, &output, NULL, CP_UTF8);
1598 if(!ret)
1600 int pos=0;
1601 CString one;
1602 while( pos>=0 )
1604 one=output.Tokenize(_T("\n"),pos);
1605 if (!one.IsEmpty())
1606 list.push_back(one);
1609 return ret;
1613 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR &list)
1615 CString cmd, out, err;
1616 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1617 if (Run(cmd, &out, &err, CP_UTF8))
1619 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1620 return -1;
1623 int pos = 0;
1624 while (pos >= 0)
1626 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1627 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1628 if (one.Find(_T("^{}")) >= 1)
1629 continue;
1630 if (!one.IsEmpty())
1631 list.push_back(one);
1633 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1634 return 0;
1637 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1639 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1640 CString str;
1641 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1642 list->push_back(str);
1643 return 0;
1646 int CGit::GetRefList(STRING_VECTOR &list)
1648 if (this->m_IsUseLibGit2)
1650 CAutoRepository repo(GetGitRepository());
1651 if (!repo)
1652 return -1;
1654 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1655 return -1;
1657 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1659 return 0;
1661 else
1663 CString cmd, output;
1664 cmd=_T("git.exe show-ref -d");
1665 int ret = Run(cmd, &output, NULL, CP_UTF8);
1666 if(!ret)
1668 int pos=0;
1669 CString one;
1670 while( pos>=0 )
1672 one=output.Tokenize(_T("\n"),pos);
1673 int start=one.Find(_T(" "),0);
1674 if(start>0)
1676 CString name;
1677 name=one.Right(one.GetLength()-start-1);
1678 list.push_back(name);
1681 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1683 return ret;
1687 typedef struct map_each_ref_payload {
1688 git_repository * repo;
1689 MAP_HASH_NAME * map;
1690 } map_each_ref_payload;
1692 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1694 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1696 CString str;
1697 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1699 CAutoObject gitObject;
1700 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1701 return 1;
1703 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1705 str += _T("^{}"); // deref tag
1706 CAutoObject derefedTag;
1707 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1708 return 1;
1709 gitObject.Swap(derefedTag);
1712 const git_oid * oid = git_object_id(gitObject);
1713 if (oid == NULL)
1714 return 1;
1716 CGitHash hash((char *)oid->id);
1717 (*payloadContent->map)[hash].push_back(str);
1719 return 0;
1721 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1723 ATLASSERT(repo);
1725 map_each_ref_payload payloadContent = { repo, &map };
1727 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1728 return -1;
1730 for (auto it = map.begin(); it != map.end(); ++it)
1732 std::sort(it->second.begin(), it->second.end());
1735 return 0;
1738 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1740 if (this->m_IsUseLibGit2)
1742 CAutoRepository repo(GetGitRepository());
1743 if (!repo)
1744 return -1;
1746 return GetMapHashToFriendName(repo, map);
1748 else
1750 CString cmd, output;
1751 cmd=_T("git.exe show-ref -d");
1752 int ret = Run(cmd, &output, NULL, CP_UTF8);
1753 if(!ret)
1755 int pos=0;
1756 CString one;
1757 while( pos>=0 )
1759 one=output.Tokenize(_T("\n"),pos);
1760 int start=one.Find(_T(" "),0);
1761 if(start>0)
1763 CString name;
1764 name=one.Right(one.GetLength()-start-1);
1766 CString hash;
1767 hash=one.Left(start);
1769 map[CGitHash(hash)].push_back(name);
1773 return ret;
1777 static void SetLibGit2SearchPath(int level, const CString &value)
1779 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1780 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1783 static void SetLibGit2TemplatePath(const CString &value)
1785 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1786 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1789 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1791 if (m_bInitialized)
1793 return TRUE;
1796 this->m_Environment.clear();
1797 m_Environment.CopyProcessEnvironment();
1799 TCHAR *oldpath;
1800 size_t homesize,size;
1802 // set HOME if not set already
1803 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1804 if (!homesize)
1805 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1807 //setup ssh client
1808 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1809 if (sshclient.IsEmpty())
1810 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1812 if(!sshclient.IsEmpty())
1814 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1815 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1817 else
1819 TCHAR sPlink[MAX_PATH] = {0};
1820 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1821 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1822 if (ptr) {
1823 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1824 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1825 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1830 TCHAR sAskPass[MAX_PATH] = {0};
1831 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1832 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1833 if (ptr)
1835 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1836 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1837 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1838 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1842 // add git/bin path to PATH
1844 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1845 CString str = msysdir;
1846 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1848 if (!bFallback)
1849 return FALSE;
1851 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1852 str = msyslocalinstalldir;
1853 str.TrimRight(_T("\\"));
1854 if (str.IsEmpty())
1856 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1857 str = msysinstalldir;
1858 str.TrimRight(_T("\\"));
1860 if ( !str.IsEmpty() )
1862 str += "\\bin";
1863 msysdir=str;
1864 CGit::ms_LastMsysGitDir = str;
1865 msysdir.write();
1867 else
1869 // search PATH if git/bin directory is already present
1870 if ( FindGitPath() )
1872 m_bInitialized = TRUE;
1873 msysdir = CGit::ms_LastMsysGitDir;
1874 msysdir.write();
1875 return TRUE;
1878 return FALSE;
1881 else
1883 CGit::ms_LastMsysGitDir = str;
1886 // check for git.exe existance (maybe it was deinstalled in the meantime)
1887 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1888 return FALSE;
1890 // Configure libgit2 search paths
1891 CString msysGitDir;
1892 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
1893 msysGitDir.ReleaseBuffer();
1894 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
1895 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
1896 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
1897 CString msysGitTemplateDir;
1898 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
1899 msysGitTemplateDir.ReleaseBuffer();
1900 SetLibGit2TemplatePath(msysGitTemplateDir);
1902 //set path
1903 _tdupenv_s(&oldpath,&size,_T("PATH"));
1905 CString path;
1906 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1908 m_Environment.SetEnv(_T("PATH"), path);
1910 CString str1 = m_Environment.GetEnv(_T("PATH"));
1912 CString sOldPath = oldpath;
1913 free(oldpath);
1915 m_bInitialized = TRUE;
1916 return true;
1919 CString CGit::GetHomeDirectory() const
1921 const wchar_t * homeDir = wget_windows_home_directory();
1922 return CString(homeDir, (int)wcslen(homeDir));
1925 CString CGit::GetGitLocalConfig() const
1927 CString path;
1928 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
1929 path += _T("config");
1930 return path;
1933 CStringA CGit::GetGitPathStringA(const CString &path)
1935 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
1938 CString CGit::GetGitGlobalConfig() const
1940 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1943 CString CGit::GetGitGlobalXDGConfigPath() const
1945 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1948 CString CGit::GetGitGlobalXDGConfig() const
1950 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1953 CString CGit::GetGitSystemConfig() const
1955 const wchar_t * systemConfig = wget_msysgit_etc();
1956 return CString(systemConfig, (int)wcslen(systemConfig));
1959 BOOL CGit::CheckCleanWorkTree()
1961 CString out;
1962 CString cmd;
1963 cmd=_T("git.exe rev-parse --verify HEAD");
1965 if(Run(cmd,&out,CP_UTF8))
1966 return FALSE;
1968 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1969 if(Run(cmd,&out,CP_UTF8))
1970 return FALSE;
1972 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1973 if(Run(cmd,&out,CP_UTF8))
1974 return FALSE;
1976 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1977 if(Run(cmd,&out,CP_UTF8))
1978 return FALSE;
1980 return TRUE;
1982 int CGit::Revert(const CString& commit, const CTGitPathList &list, bool)
1984 int ret;
1985 for (int i = 0; i < list.GetCount(); ++i)
1987 ret = Revert(commit, (CTGitPath&)list[i]);
1988 if(ret)
1989 return ret;
1991 return 0;
1993 int CGit::Revert(const CString& commit, const CTGitPath &path)
1995 CString cmd, out;
1997 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1999 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
2001 CString err;
2002 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
2003 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2004 return -1;
2006 CString force;
2007 // if the filenames only differ in case, we have to pass "-f"
2008 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2009 force = _T("-f ");
2010 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2011 if (Run(cmd, &out, CP_UTF8))
2013 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2014 return -1;
2017 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2018 if (Run(cmd, &out, CP_UTF8))
2020 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2021 return -1;
2025 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2026 { //To init git repository, there are not HEAD, so we can use git reset command
2027 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2029 if (Run(cmd, &out, CP_UTF8))
2031 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2032 return -1;
2035 else
2037 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2038 if (Run(cmd, &out, CP_UTF8))
2040 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2041 return -1;
2045 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2047 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2048 if (Run(cmd, &out, CP_UTF8))
2050 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2051 return -1;
2055 return 0;
2058 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2060 BYTE_VECTOR vector;
2062 CString cmd;
2063 if(path)
2064 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2065 else
2066 cmd=_T("git.exe ls-files -u -t -z");
2068 if (Run(cmd, &vector))
2070 return -1;
2073 if (list.ParserFromLsFile(vector))
2074 return -1;
2076 return 0;
2079 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2081 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2083 CAutoRepository repo(GetGitRepository());
2084 if (!repo)
2085 return false;
2087 CGitHash fromHash, toHash, baseHash;
2088 if (GetHash(repo, toHash, FixBranchName(to)))
2089 return false;
2091 if (GetHash(repo, fromHash, FixBranchName(from)))
2092 return false;
2094 git_oid baseOid;
2095 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2096 return false;
2098 baseHash = baseOid.id;
2100 if (commonAncestor)
2101 *commonAncestor = baseHash;
2103 return fromHash == baseHash;
2105 // else
2106 CString base;
2107 CGitHash basehash,hash;
2108 CString cmd, err;
2109 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2111 if (Run(cmd, &base, &err, CP_UTF8))
2113 return false;
2115 basehash = base.Trim();
2117 GetHash(hash, from);
2119 if (commonAncestor)
2120 *commonAncestor = basehash;
2122 return hash == basehash;
2125 unsigned int CGit::Hash2int(const CGitHash &hash)
2127 int ret=0;
2128 for (int i = 0; i < 4; ++i)
2130 ret = ret << 8;
2131 ret |= hash.m_hash[i];
2133 return ret;
2136 int CGit::RefreshGitIndex()
2138 if(g_Git.m_IsUseGitDLL)
2140 CAutoLocker lock(g_Git.m_critGitDllSec);
2143 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2145 }catch(...)
2147 return -1;
2151 else
2153 CString cmd,output;
2154 cmd=_T("git.exe update-index --refresh");
2155 return Run(cmd, &output, CP_UTF8);
2159 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2161 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2163 CAutoRepository repo(GetGitRepository());
2164 if (!repo)
2165 return -1;
2167 CGitHash hash;
2168 if (GetHash(repo, hash, Refname))
2169 return -1;
2171 CAutoCommit commit;
2172 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2173 return -1;
2175 CAutoTree tree;
2176 if (git_commit_tree(tree.GetPointer(), commit))
2177 return -1;
2179 CAutoTreeEntry entry;
2180 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2181 return -1;
2183 CAutoBlob blob;
2184 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2185 return -1;
2187 FILE *file = nullptr;
2188 _tfopen_s(&file, outputfile, _T("w"));
2189 if (file == nullptr)
2191 giterr_set_str(GITERR_NONE, "Could not create file.");
2192 return -1;
2194 CAutoBuf buf;
2195 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2197 fclose(file);
2198 return -1;
2200 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2202 giterr_set_str(GITERR_OS, "Could not write to file.");
2203 fclose(file);
2205 return -1;
2207 fclose(file);
2209 return 0;
2211 else if (g_Git.m_IsUseGitDLL)
2213 CAutoLocker lock(g_Git.m_critGitDllSec);
2216 g_Git.CheckAndInitDll();
2217 CStringA ref, patha, outa;
2218 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2219 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2220 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2221 ::DeleteFile(outputfile);
2222 return git_checkout_file(ref, patha, outa);
2225 catch (const char * msg)
2227 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2228 return -1;
2230 catch (...)
2232 gitLastErr = L"An unknown gitdll.dll error occurred.";
2233 return -1;
2236 else
2238 CString cmd;
2239 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2240 return RunLogFile(cmd, outputfile, &gitLastErr);
2243 void CEnvironment::CopyProcessEnvironment()
2245 TCHAR *porig = GetEnvironmentStrings();
2246 TCHAR *p = porig;
2247 while(*p !=0 || *(p+1) !=0)
2248 this->push_back(*p++);
2250 push_back(_T('\0'));
2251 push_back(_T('\0'));
2253 FreeEnvironmentStrings(porig);
2256 CString CEnvironment::GetEnv(const TCHAR *name)
2258 CString str;
2259 for (size_t i = 0; i < size(); ++i)
2261 str = &(*this)[i];
2262 int start =0;
2263 CString sname = str.Tokenize(_T("="),start);
2264 if(sname.CompareNoCase(name) == 0)
2266 return &(*this)[i+start];
2268 i+=str.GetLength();
2270 return _T("");
2273 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2275 unsigned int i;
2276 for (i = 0; i < size(); ++i)
2278 CString str = &(*this)[i];
2279 int start =0;
2280 CString sname = str.Tokenize(_T("="),start);
2281 if(sname.CompareNoCase(name) == 0)
2283 break;
2285 i+=str.GetLength();
2288 if(i == size())
2290 i -= 1; // roll back terminate \0\0
2291 this->push_back(_T('\0'));
2294 CEnvironment::iterator it;
2295 it=this->begin();
2296 it += i;
2298 while(*it && i<size())
2300 this->erase(it);
2301 it=this->begin();
2302 it += i;
2305 while(*name)
2307 this->insert(it,*name++);
2308 ++i;
2309 it= begin()+i;
2312 this->insert(it, _T('='));
2313 ++i;
2314 it= begin()+i;
2316 while(*value)
2318 this->insert(it,*value++);
2319 ++i;
2320 it= begin()+i;
2325 int CGit::GetGitEncode(TCHAR* configkey)
2327 CString str=GetConfigValue(configkey);
2329 if(str.IsEmpty())
2330 return CP_UTF8;
2332 return CUnicodeUtils::GetCPCode(str);
2336 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2338 GIT_FILE file=0;
2339 int ret=0;
2340 GIT_DIFF diff=0;
2342 CAutoLocker lock(g_Git.m_critGitDllSec);
2344 if(arg == NULL)
2345 diff = GetGitDiff();
2346 else
2347 git_open_diff(&diff, arg);
2349 if(diff ==NULL)
2350 return -1;
2352 bool isStat = 0;
2353 if(arg == NULL)
2354 isStat = true;
2355 else
2356 isStat = !!strstr(arg, "stat");
2358 int count=0;
2360 if(hash2 == NULL)
2361 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2362 else
2363 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2365 if(ret)
2366 return -1;
2368 CTGitPath path;
2369 CString strnewname;
2370 CString stroldname;
2372 for (int j = 0; j < count; ++j)
2374 path.Reset();
2375 char *newname;
2376 char *oldname;
2378 strnewname.Empty();
2379 stroldname.Empty();
2381 int mode=0,IsBin=0,inc=0,dec=0;
2382 git_get_diff_file(diff,file,j,&newname,&oldname,
2383 &mode,&IsBin,&inc,&dec);
2385 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2386 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2388 path.SetFromGit(strnewname,&stroldname);
2389 path.ParserAction((BYTE)mode);
2391 if(IsBin)
2393 path.m_StatAdd=_T("-");
2394 path.m_StatDel=_T("-");
2396 else
2398 path.m_StatAdd.Format(_T("%d"),inc);
2399 path.m_StatDel.Format(_T("%d"),dec);
2401 PathList->AddPath(path);
2403 git_diff_flush(diff);
2405 if(arg)
2406 git_close_diff(diff);
2408 return 0;
2411 int CGit::GetShortHASHLength() const
2413 return 7;
2416 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2418 CString str=ref;
2419 CString shortname;
2420 REF_TYPE type = CGit::UNKNOWN;
2422 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2424 type = CGit::LOCAL_BRANCH;
2427 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2429 type = CGit::REMOTE_BRANCH;
2431 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2433 type = CGit::TAG;
2435 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2437 type = CGit::STASH;
2438 shortname=_T("stash");
2440 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2442 if (shortname.Find(_T("good")) == 0)
2444 type = CGit::BISECT_GOOD;
2445 shortname = _T("good");
2448 if (shortname.Find(_T("bad")) == 0)
2450 type = CGit::BISECT_BAD;
2451 shortname = _T("bad");
2454 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2456 type = CGit::NOTES;
2458 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2460 type = CGit::UNKNOWN;
2462 else
2464 type = CGit::UNKNOWN;
2465 shortname = ref;
2468 if(out_type)
2469 *out_type = type;
2471 return shortname;
2474 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2476 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2479 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2481 CString cmd;
2482 if (rev2 == GitRev::GetWorkingCopy())
2483 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2484 else if (rev1 == GitRev::GetWorkingCopy())
2485 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2486 else
2488 CString merge;
2489 if (bMerge)
2490 merge += _T(" -m");
2492 if (bCombine)
2493 merge += _T(" -c");
2495 CString unified;
2496 if (diffContext > 0)
2497 unified.Format(_T(" --unified=%d"), diffContext);
2498 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2501 if (!path.IsEmpty())
2503 cmd += _T(" \"");
2504 cmd += path.GetGitPathString();
2505 cmd += _T("\"");
2508 return cmd;
2511 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2513 ATLASSERT(payload && line);
2514 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2515 fwrite(&line->origin, 1, 1, (FILE *)payload);
2516 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2517 return 0;
2520 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2522 ATLASSERT(repo && identifier && tree);
2524 /* try to resolve identifier */
2525 CAutoObject obj;
2526 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2527 return -1;
2529 if (obj == nullptr)
2530 return GIT_ENOTFOUND;
2532 int err = 0;
2533 switch (git_object_type(obj))
2535 case GIT_OBJ_TREE:
2536 *tree = (git_tree *)obj.Detach();
2537 break;
2538 case GIT_OBJ_COMMIT:
2539 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2540 break;
2541 default:
2542 err = GIT_ENOTFOUND;
2545 return err;
2548 /* use libgit2 get unified diff */
2549 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 */)
2551 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2552 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2554 CAutoRepository repo(g_Git.GetGitRepository());
2555 if (!repo)
2556 return -1;
2558 int isHeadOrphan = git_repository_head_unborn(repo);
2559 if (isHeadOrphan == 1)
2560 return 0;
2561 else if (isHeadOrphan != 0)
2562 return -1;
2564 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2565 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2566 char *buf = pathA.GetBuffer();
2567 if (!pathA.IsEmpty())
2569 opts.pathspec.strings = &buf;
2570 opts.pathspec.count = 1;
2572 CAutoDiff diff;
2574 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2576 CAutoTree t1;
2577 CAutoDiff diff2;
2579 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2580 return -1;
2582 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2583 return -1;
2585 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2586 return -1;
2588 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2589 return -1;
2591 if (git_diff_merge(diff, diff2))
2592 return -1;
2594 else
2596 if (tree1.IsEmpty() && tree2.IsEmpty())
2597 return -1;
2599 if (tree1.IsEmpty())
2601 tree1 = tree2;
2602 tree2.Empty();
2605 CAutoTree t1;
2606 CAutoTree t2;
2607 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2608 return -1;
2610 if (tree2.IsEmpty())
2612 /* don't check return value, there are not parent commit at first commit*/
2613 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2615 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2616 return -1;
2617 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2618 return -1;
2621 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2623 CAutoPatch patch;
2624 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2625 return -1;
2627 if (git_patch_print(patch, callback, data))
2628 return -1;
2631 pathA.ReleaseBuffer();
2633 return 0;
2636 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2638 if (UsingLibGit2(GIT_CMD_DIFF))
2640 FILE *file = nullptr;
2641 _tfopen_s(&file, patchfile, _T("w"));
2642 if (file == nullptr)
2643 return -1;
2644 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToFile, file, bMerge);
2645 fclose(file);
2646 return ret;
2648 else
2650 CString cmd;
2651 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2652 return RunLogFile(cmd, patchfile, &gitLastErr);
2656 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2658 ATLASSERT(payload && line);
2659 CStringA *str = (CStringA*) payload;
2660 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2661 str->Append(&line->origin, 1);
2662 str->Append(line->content, (int)line->content_len);
2663 return 0;
2666 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2668 if (UsingLibGit2(GIT_CMD_DIFF))
2669 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToStringA, buffer, bMerge);
2670 else
2672 CString cmd;
2673 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2674 BYTE_VECTOR vector;
2675 int ret = Run(cmd, &vector);
2676 if (!vector.empty())
2678 vector.push_back(0); // vector is not NUL terminated
2679 buffer->Append((char *)&vector[0]);
2681 return ret;
2685 int CGit::GitRevert(int parent, const CGitHash &hash)
2687 if (UsingLibGit2(GIT_CMD_REVERT))
2689 CAutoRepository repo(GetGitRepository());
2690 if (!repo)
2691 return -1;
2693 CAutoCommit commit;
2694 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2695 return -1;
2697 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2698 revert_opts.mainline = parent;
2699 int result = git_revert(repo, commit, &revert_opts);
2701 return !result ? 0 : -1;
2703 else
2705 CString cmd, merge;
2706 if (parent)
2707 merge.Format(_T("-m %d "), parent);
2708 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2709 gitLastErr = cmd + _T("\n");
2710 if (Run(cmd, &gitLastErr, CP_UTF8))
2712 return -1;
2714 else
2716 gitLastErr.Empty();
2717 return 0;
2722 int CGit::DeleteRef(const CString& reference)
2724 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2726 CAutoRepository repo(GetGitRepository());
2727 if (!repo)
2728 return -1;
2730 CStringA refA;
2731 if (reference.Right(3) == _T("^{}"))
2732 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2733 else
2734 refA = CUnicodeUtils::GetUTF8(reference);
2736 CAutoReference ref;
2737 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2738 return -1;
2740 int result = -1;
2741 if (git_reference_is_tag(ref))
2742 result = git_tag_delete(repo, git_reference_shorthand(ref));
2743 else if (git_reference_is_branch(ref))
2744 result = git_branch_delete(ref);
2745 else if (git_reference_is_remote(ref))
2746 result = git_branch_delete(ref);
2747 else
2748 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2750 return result;
2752 else
2754 CString cmd, shortname;
2755 if (GetShortName(reference, shortname, _T("refs/heads/")))
2756 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2757 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2758 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2759 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2760 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2761 else
2763 gitLastErr = L"unsupported reference type: " + reference;
2764 return -1;
2767 if (Run(cmd, &gitLastErr, CP_UTF8))
2768 return -1;
2770 gitLastErr.Empty();
2771 return 0;
2775 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2777 if (PathFileExists(filename))
2779 FILE *pFile = nullptr;
2780 _tfopen_s(&pFile, filename, _T("r"));
2781 if (pFile)
2783 CStringA str;
2786 char s[8196] = { 0 };
2787 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
2788 if (read == 0)
2789 break;
2790 str += CStringA(s, read);
2791 } while (true);
2792 fclose(pFile);
2793 msg = CUnicodeUtils::GetUnicode(str);
2794 msg.Replace(_T("\r\n"), _T("\n"));
2795 msg.TrimRight(_T("\n"));
2796 msg += _T("\n");
2798 else
2799 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
2800 return true; // load no further files
2802 return false;