Optimize comment about discouraged branch names starting with a dash
[TortoiseGit.git] / src / Git / Git.cpp
blob4e2fff62d36b8421bd8dec71cee8cdb52df929b7
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 "GitConfig.h"
25 #include <map>
26 #include "UnicodeUtils.h"
27 #include "gitdll.h"
28 #include <fstream>
29 #include "FormatMessageWrapper.h"
31 int CGit::m_LogEncode=CP_UTF8;
32 typedef CComCritSecLock<CComCriticalSection> CAutoLocker;
34 static LPTSTR nextpath(wchar_t *path, wchar_t *buf, size_t buflen)
36 wchar_t term, *base = path;
38 if (path == NULL || buf == NULL || buflen == 0)
39 return NULL;
41 term = (*path == L'"') ? *path++ : L';';
43 for (buflen--; *path && *path != term && buflen; buflen--)
44 *buf++ = *path++;
46 *buf = L'\0'; /* reserved a byte via initial subtract */
48 while (*path == term || *path == L';')
49 ++path;
51 return (path != base) ? path : NULL;
54 static inline BOOL FileExists(LPCTSTR lpszFileName)
56 struct _stat st;
57 return _tstat(lpszFileName, &st) == 0;
60 static BOOL FindGitPath()
62 size_t size;
63 _tgetenv_s(&size, NULL, 0, _T("PATH"));
65 if (!size)
67 return FALSE;
70 TCHAR *env = (TCHAR*)alloca(size * sizeof(TCHAR));
71 _tgetenv_s(&size, env, size, _T("PATH"));
73 TCHAR buf[MAX_PATH] = {0};
75 // search in all paths defined in PATH
76 while ((env = nextpath(env, buf, MAX_PATH - 1)) != NULL && *buf)
78 TCHAR *pfin = buf + _tcslen(buf)-1;
80 // ensure trailing slash
81 if (*pfin != _T('/') && *pfin != _T('\\'))
82 _tcscpy_s(++pfin, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len = _tcslen(buf);
86 if ((len + 7) < MAX_PATH)
87 _tcscpy_s(pfin + 1, MAX_PATH - len, _T("git.exe"));
88 else
89 break;
91 if ( FileExists(buf) )
93 // dir found
94 pfin[1] = 0;
95 CGit::ms_LastMsysGitDir = buf;
96 CGit::ms_LastMsysGitDir.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir))
103 CGit::ms_LastMsysGitDir = CGit::ms_LastMsysGitDir.Mid(0, CGit::ms_LastMsysGitDir.GetLength() - 4) + _T("\\bin");
105 return TRUE;
109 return FALSE;
112 static bool g_bSortLogical;
113 static bool g_bSortLocalBranchesFirst;
115 static void GetSortOptions()
117 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER);
118 if (g_bSortLogical)
119 g_bSortLogical = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE);
120 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
121 if (g_bSortLocalBranchesFirst)
122 g_bSortLocalBranchesFirst = !CRegDWORD(L"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
125 static int LogicalComparePredicate(const CString &left, const CString &right)
127 if (g_bSortLogical)
128 return StrCmpLogicalW(left, right) < 0;
129 return StrCmpI(left, right) < 0;
132 static int LogicalCompareBranchesPredicate(const CString &left, const CString &right)
134 if (g_bSortLocalBranchesFirst)
136 int leftIsRemote = left.Find(_T("remotes/"));
137 int rightIsRemote = right.Find(_T("remotes/"));
139 if (leftIsRemote == 0 && rightIsRemote < 0)
140 return false;
141 else if (leftIsRemote < 0 && rightIsRemote == 0)
142 return true;
144 if (g_bSortLogical)
145 return StrCmpLogicalW(left, right) < 0;
146 return StrCmpI(left, right) < 0;
149 #define MAX_DIRBUFFER 1000
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_DIRBUFFER,m_CurrentDir.GetBuffer(MAX_DIRBUFFER));
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"), 0);
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 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
204 HANDLE hStdioFile = NULL;
206 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
207 sa.lpSecurityDescriptor=NULL;
208 sa.bInheritHandle=TRUE;
209 if(!CreatePipe(&hRead,&hWrite,&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, &hWriteErr, &sa, 0))
217 CString err = CFormatMessageWrapper();
218 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
219 CloseHandle(hRead);
220 CloseHandle(hWrite);
221 return TGIT_GIT_ERROR_OPEN_PIP;
224 if(StdioFile)
226 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
227 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
230 STARTUPINFO si;
231 PROCESS_INFORMATION pi;
232 si.cb=sizeof(STARTUPINFO);
233 GetStartupInfo(&si);
235 if (hErrReadOut)
236 si.hStdError = hWriteErr;
237 else
238 si.hStdError = hWrite;
239 if(StdioFile)
240 si.hStdOutput=hStdioFile;
241 else
242 si.hStdOutput=hWrite;
244 si.wShowWindow=SW_HIDE;
245 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
247 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
248 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
250 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
251 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
253 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
254 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
256 if(cmd.Find(_T("git")) == 0)
258 int firstSpace = cmd.Find(_T(" "));
259 if (firstSpace > 0)
260 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
261 else
262 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
265 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
266 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
268 CString err = CFormatMessageWrapper();
269 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
270 CloseHandle(hRead);
271 CloseHandle(hWrite);
272 if (hErrReadOut)
274 CloseHandle(hReadErr);
275 CloseHandle(hWriteErr);
277 return TGIT_GIT_ERROR_CREATE_PROCESS;
280 m_CurrentGitPi = pi;
282 CloseHandle(hWrite);
283 if (hErrReadOut)
284 CloseHandle(hWriteErr);
285 if(piOut)
286 *piOut=pi;
287 if(hReadOut)
288 *hReadOut=hRead;
289 else
290 CloseHandle(hRead);
291 if(hErrReadOut)
292 *hErrReadOut = hReadErr;
293 return 0;
296 //Must use sperate function to convert ANSI str to union code string
297 //Becuase A2W use stack as internal convert buffer.
298 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
300 if(str == NULL)
301 return ;
303 int len ;
304 if(length<0)
305 len = (int)strlen((const char*)p);
306 else
307 len=length;
308 if (len == 0)
309 return;
310 int currentContentLen = str->GetLength();
311 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
312 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
313 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
316 // This method was originally used to check for orphaned branches
317 BOOL CGit::CanParseRev(CString ref)
319 if (ref.IsEmpty())
320 ref = _T("HEAD");
322 CString cmdout;
323 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
325 return FALSE;
327 if(cmdout.IsEmpty())
328 return FALSE;
330 return TRUE;
333 // Checks if we have an orphaned HEAD
334 BOOL CGit::IsInitRepos()
336 CGitHash hash;
337 // handle error on reading HEAD hash as init repo
338 if (GetHash(hash, _T("HEAD")) != 0)
339 return TRUE;
340 return hash.IsEmpty() ? TRUE : FALSE;
343 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
345 PASYNCREADSTDERRTHREADARGS pDataArray;
346 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
348 DWORD readnumber;
349 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
350 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
352 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
353 break;
356 return 0;
359 int CGit::Run(CGitCall* pcall)
361 PROCESS_INFORMATION pi;
362 HANDLE hRead, hReadErr;
363 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
364 return TGIT_GIT_ERROR_CREATE_PROCESS;
366 HANDLE thread;
367 ASYNCREADSTDERRTHREADARGS threadArguments;
368 threadArguments.fileHandle = hReadErr;
369 threadArguments.pcall = pcall;
370 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 CloseHandle(pi.hThread);
390 WaitForSingleObject(pi.hProcess, INFINITE);
391 DWORD exitcode =0;
393 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
395 CString err = CFormatMessageWrapper();
396 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
397 return TGIT_GIT_ERROR_GET_EXIT_CODE;
399 else
400 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
402 CloseHandle(pi.hProcess);
404 CloseHandle(hRead);
405 CloseHandle(hReadErr);
406 return exitcode;
408 class CGitCall_ByteVector : public CGitCall
410 public:
411 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
412 virtual bool OnOutputData(const BYTE* data, size_t size)
414 if (!m_pvector || size == 0)
415 return false;
416 size_t oldsize=m_pvector->size();
417 m_pvector->resize(m_pvector->size()+size);
418 memcpy(&*(m_pvector->begin()+oldsize),data,size);
419 return false;
421 virtual bool OnOutputErrData(const BYTE* data, size_t size)
423 if (!m_pvectorErr || size == 0)
424 return false;
425 size_t oldsize = m_pvectorErr->size();
426 m_pvectorErr->resize(m_pvectorErr->size() + size);
427 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
428 return false;
430 BYTE_VECTOR* m_pvector;
431 BYTE_VECTOR* m_pvectorErr;
434 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
436 CGitCall_ByteVector call(cmd, vector, vectorErr);
437 return Run(&call);
439 int CGit::Run(CString cmd, CString* output, int code)
441 CString err;
442 int ret;
443 ret = Run(cmd, output, &err, code);
445 if (output && !err.IsEmpty())
447 if (!output->IsEmpty())
448 *output += _T("\n");
449 *output += err;
452 return ret;
454 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
456 BYTE_VECTOR vector, vectorErr;
457 int ret;
458 if (outputErr)
459 ret = Run(cmd, &vector, &vectorErr);
460 else
461 ret = Run(cmd, &vector);
463 vector.push_back(0);
464 StringAppend(output, &(vector[0]), code);
466 if (outputErr)
468 vectorErr.push_back(0);
469 StringAppend(outputErr, &(vectorErr[0]), code);
472 return ret;
475 class CGitCallCb : public CGitCall
477 public:
478 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
480 virtual bool OnOutputData(const BYTE* data, size_t size) override
482 // Add data
483 if (size == 0)
484 return false;
485 int oldEndPos = m_buffer.GetLength();
486 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
487 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
489 // Break into lines and feed to m_recv
490 int eolPos;
491 while ((eolPos = m_buffer.Find('\n')) >= 0)
493 m_recv(m_buffer.Left(eolPos));
494 m_buffer = m_buffer.Mid(eolPos + 1);
496 return false;
499 virtual bool OnOutputErrData(const BYTE*, size_t) override
501 return false; // Ignore error output for now
504 virtual void OnEnd() override
506 if (!m_buffer.IsEmpty())
507 m_recv(m_buffer);
508 m_buffer.Empty(); // Just for sure
511 private:
512 GitReceiverFunc m_recv;
513 CStringA m_buffer;
516 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
518 CGitCallCb call(cmd, recv);
519 return Run(&call);
522 CString CGit::GetUserName(void)
524 CEnvironment env;
525 env.CopyProcessEnvironment();
526 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
527 if (!envname.IsEmpty())
528 return envname;
529 return GetConfigValue(L"user.name");
531 CString CGit::GetUserEmail(void)
533 CEnvironment env;
534 env.CopyProcessEnvironment();
535 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
536 if (!envmail.IsEmpty())
537 return envmail;
539 return GetConfigValue(L"user.email");
542 CString CGit::GetConfigValue(const CString& name, int encoding, BOOL RemoveCR)
544 CString configValue;
545 int start = 0;
546 if(this->m_IsUseGitDLL)
548 CAutoLocker lock(g_Git.m_critGitDllSec);
552 CheckAndInitDll();
553 }catch(...)
556 CStringA key, value;
557 key = CUnicodeUtils::GetMulti(name, encoding);
561 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
562 return CString();
564 catch (const char *msg)
566 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
567 return CString();
570 StringAppend(&configValue, (BYTE*)(LPCSTR)value, encoding);
571 if(RemoveCR)
572 return configValue.Tokenize(_T("\n"),start);
573 return configValue;
575 else
577 CString cmd;
578 cmd.Format(L"git.exe config %s", name);
579 Run(cmd, &configValue, NULL, encoding);
580 if(RemoveCR)
581 return configValue.Tokenize(_T("\n"),start);
582 return configValue;
586 bool CGit::GetConfigValueBool(const CString& name)
588 CString configValue = GetConfigValue(name);
589 configValue.MakeLower();
590 configValue.Trim();
591 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
592 return true;
593 else
594 return false;
597 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type, int encoding)
599 if(this->m_IsUseGitDLL)
601 CAutoLocker lock(g_Git.m_critGitDllSec);
605 CheckAndInitDll();
607 }catch(...)
610 CStringA keya, valuea;
611 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
612 valuea = CUnicodeUtils::GetMulti(value, encoding);
616 return get_set_config(keya, valuea, type);
618 catch (const char *msg)
620 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
621 return -1;
624 else
626 CString cmd;
627 CString option;
628 switch(type)
630 case CONFIG_GLOBAL:
631 option = _T("--global");
632 break;
633 case CONFIG_SYSTEM:
634 option = _T("--system");
635 break;
636 default:
637 break;
639 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
640 CString out;
641 if (Run(cmd, &out, NULL, encoding))
643 return -1;
646 return 0;
649 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type, int encoding)
651 if(this->m_IsUseGitDLL)
653 CAutoLocker lock(g_Git.m_critGitDllSec);
657 CheckAndInitDll();
658 }catch(...)
661 CStringA keya;
662 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
666 return get_set_config(keya, nullptr, type);
668 catch (const char *msg)
670 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
671 return -1;
674 else
676 CString cmd;
677 CString option;
678 switch(type)
680 case CONFIG_GLOBAL:
681 option = _T("--global");
682 break;
683 case CONFIG_SYSTEM:
684 option = _T("--system");
685 break;
686 default:
687 break;
689 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
690 CString out;
691 if (Run(cmd, &out, NULL, encoding))
693 return -1;
696 return 0;
699 CString CGit::GetCurrentBranch(bool fallback)
701 CString output;
702 //Run(_T("git.exe branch"),&branch);
704 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
705 if (result != 0 && ((result == 1 && !fallback) || result != 1))
707 return _T("(no branch)");
709 else
710 return output;
714 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
716 CString refName;
717 if(this->m_IsUseGitDLL)
719 unsigned char sha1[20] = { 0 };
720 int flag = 0;
722 CAutoLocker lock(g_Git.m_critGitDllSec);
723 const char *refs_heads_master = nullptr;
726 refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
728 catch (const char *err)
730 ::MessageBox(NULL, _T("Could not resolve ref ") + CString(symbolicRefName) + _T(".\nlibgit reports:\n") + CString(err), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
732 if(refs_heads_master && (flag&REF_ISSYMREF))
734 StringAppend(&refName,(BYTE*)refs_heads_master);
735 if(bStripRefsHeads)
736 refName = StripRefName(refName);
740 else
742 CString cmd;
743 cmd.Format(L"git.exe symbolic-ref %s", symbolicRefName);
744 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
745 return CString();//Error
746 int iStart = 0;
747 refName = refName.Tokenize(L"\n", iStart);
748 if(bStripRefsHeads)
749 refName = StripRefName(refName);
751 return refName;
754 CString CGit::GetFullRefName(const CString& shortRefName)
756 CString refName;
757 CString cmd;
758 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
759 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
760 return CString();//Error
761 int iStart = 0;
762 return refName.Tokenize(L"\n", iStart);
765 CString CGit::StripRefName(CString refName)
767 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
768 refName = refName.Mid(11);
769 else if(wcsncmp(refName, L"refs/", 5) == 0)
770 refName = refName.Mid(5);
771 int start =0;
772 return refName.Tokenize(_T("\n"),start);
775 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
777 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
779 if ( sProjectRoot.IsEmpty() )
780 return -1;
782 CString sDotGitPath;
783 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
784 return -1;
786 CString sHeadFile = sDotGitPath + _T("HEAD");
788 FILE *pFile;
789 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
791 if (!pFile)
793 return -1;
796 char s[256] = {0};
797 fgets(s, sizeof(s), pFile);
799 fclose(pFile);
801 const char *pfx = "ref: refs/heads/";
802 const int len = 16;//strlen(pfx)
804 if ( !strncmp(s, pfx, len) )
806 //# We're on a branch. It might not exist. But
807 //# HEAD looks good enough to be a branch.
808 CStringA utf8Branch(s + len);
809 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
810 sBranchOut.TrimRight(_T(" \r\n\t"));
812 if ( sBranchOut.IsEmpty() )
813 return -1;
815 else if (fallback)
817 CStringA utf8Hash(s);
818 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
819 unicodeHash.TrimRight(_T(" \r\n\t"));
820 if (CGitHash::IsValidSHA1(unicodeHash))
821 sBranchOut = unicodeHash;
822 else
823 //# Assume this is a detached head.
824 sBranchOut = _T("HEAD");
825 return 1;
827 else
829 //# Assume this is a detached head.
830 sBranchOut = "HEAD";
832 return 1;
835 return 0;
838 int CGit::BuildOutputFormat(CString &format,bool IsFull)
840 CString log;
841 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
842 format += log;
843 if(IsFull)
845 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
846 format += log;
847 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
848 format += log;
849 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
850 format += log;
851 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
852 format += log;
853 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
854 format += log;
855 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
856 format += log;
857 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
858 format += log;
861 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
862 format += log;
863 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
864 format += log;
865 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
866 format += log;
868 if(IsFull)
870 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
871 format += log;
873 return 0;
876 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
877 CFilterData *Filter)
879 CString cmd;
880 CString num;
881 CString since;
883 CString file = _T(" --");
885 if(path)
886 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
888 if(count>0)
889 num.Format(_T("-n%d"),count);
891 CString param;
893 if(mask& LOG_INFO_STAT )
894 param += _T(" --numstat ");
895 if(mask& LOG_INFO_FILESTATE)
896 param += _T(" --raw ");
898 if(mask& LOG_INFO_FULLHISTORY)
899 param += _T(" --full-history ");
901 if(mask& LOG_INFO_BOUNDARY)
902 param += _T(" --left-right --boundary ");
904 if(mask& CGit::LOG_INFO_ALL_BRANCH)
905 param += _T(" --all ");
907 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
908 param += _T(" --branches ");
910 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
911 param += _T(" -C ");
913 if(mask& CGit::LOG_INFO_DETECT_RENAME )
914 param += _T(" -M ");
916 if(mask& CGit::LOG_INFO_FIRST_PARENT )
917 param += _T(" --first-parent ");
919 if(mask& CGit::LOG_INFO_NO_MERGE )
920 param += _T(" --no-merges ");
922 if(mask& CGit::LOG_INFO_FOLLOW)
923 param += _T(" --follow ");
925 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
926 param += _T(" -c ");
928 if(mask& CGit::LOG_INFO_FULL_DIFF)
929 param += _T(" --full-diff ");
931 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
932 param += _T(" --simplify-by-decoration ");
934 param += range;
936 CString st1,st2;
938 if( Filter && (Filter->m_From != -1))
940 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
941 param += st1;
944 if( Filter && (Filter->m_To != -1))
946 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
947 param += st2;
950 bool isgrep = false;
951 if( Filter && (!Filter->m_Author.IsEmpty()))
953 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
954 param += st1;
955 isgrep = true;
958 if( Filter && (!Filter->m_Committer.IsEmpty()))
960 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
961 param += st1;
962 isgrep = true;
965 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
967 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
968 param += st1;
969 isgrep = true;
972 if(Filter && isgrep)
974 if(!Filter->m_IsRegex)
975 param += _T(" --fixed-strings ");
977 param += _T(" --regexp-ignore-case --extended-regexp ");
980 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
981 if (logOrderBy == LOG_ORDER_TOPOORDER)
982 param += _T(" --topo-order");
983 else if (logOrderBy == LOG_ORDER_DATEORDER)
984 param += _T(" --date-order");
986 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
987 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
988 else
990 CString log;
991 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
992 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
993 num,param,log);
996 cmd += file;
998 return cmd;
1000 #define BUFSIZE 512
1001 void GetTempPath(CString &path)
1003 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1004 DWORD dwRetVal;
1005 DWORD dwBufSize=BUFSIZE;
1006 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1007 lpPathBuffer); // buffer for path
1008 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1010 path=_T("");
1012 path.Format(_T("%s"),lpPathBuffer);
1014 CString GetTempFile()
1016 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
1017 DWORD dwRetVal;
1018 DWORD dwBufSize=BUFSIZE;
1019 TCHAR szTempName[BUFSIZE] = { 0 };
1020 UINT uRetVal;
1022 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
1023 lpPathBuffer); // buffer for path
1024 if (dwRetVal > dwBufSize || (dwRetVal == 0))
1026 return _T("");
1028 // Create a temporary file.
1029 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
1030 TEXT("Patch"), // temp file name prefix
1031 0, // create unique name
1032 szTempName); // buffer for name
1035 if (uRetVal == 0)
1037 return _T("");
1040 return CString(szTempName);
1044 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1046 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1047 if (result == 0) return 0;
1048 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1050 if (lpBuffer)
1051 lpBuffer[0] = '\0';
1052 return result + 13;
1055 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1056 CreateDirectory(lpBuffer, NULL);
1058 return result + 13;
1061 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1063 STARTUPINFO si;
1064 PROCESS_INFORMATION pi;
1065 si.cb=sizeof(STARTUPINFO);
1066 GetStartupInfo(&si);
1068 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1069 psa.bInheritHandle=TRUE;
1071 HANDLE hReadErr, hWriteErr;
1072 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1074 CString err = CFormatMessageWrapper();
1075 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1076 return TGIT_GIT_ERROR_OPEN_PIP;
1079 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1080 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1082 if (houtfile == INVALID_HANDLE_VALUE)
1084 CString err = CFormatMessageWrapper();
1085 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1086 CloseHandle(hReadErr);
1087 CloseHandle(hWriteErr);
1088 return TGIT_GIT_ERROR_OPEN_PIP;
1091 si.wShowWindow = SW_HIDE;
1092 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1093 si.hStdOutput = houtfile;
1094 si.hStdError = hWriteErr;
1096 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1097 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1099 if(cmd.Find(_T("git")) == 0)
1100 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1102 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1103 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1105 CString err = CFormatMessageWrapper();
1106 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1107 stdErr = &err;
1108 CloseHandle(hReadErr);
1109 CloseHandle(hWriteErr);
1110 CloseHandle(houtfile);
1111 return TGIT_GIT_ERROR_CREATE_PROCESS;
1114 BYTE_VECTOR stderrVector;
1115 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1116 HANDLE thread;
1117 ASYNCREADSTDERRTHREADARGS threadArguments;
1118 threadArguments.fileHandle = hReadErr;
1119 threadArguments.pcall = &pcall;
1120 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1122 WaitForSingleObject(pi.hProcess,INFINITE);
1124 CloseHandle(hWriteErr);
1125 CloseHandle(hReadErr);
1127 if (thread)
1128 WaitForSingleObject(thread, INFINITE);
1130 stderrVector.push_back(0);
1131 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1133 DWORD exitcode = 0;
1134 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1136 CString err = CFormatMessageWrapper();
1137 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1138 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1140 else
1141 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1143 CloseHandle(pi.hThread);
1144 CloseHandle(pi.hProcess);
1145 CloseHandle(houtfile);
1146 return exitcode;
1149 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1151 // no need to parse a ref if it's already a 40-byte hash
1152 if (CGitHash::IsValidSHA1(friendname))
1154 hash = CGitHash(friendname);
1155 return 0;
1158 if (m_IsUseLibGit2)
1160 git_repository *repo = NULL;
1161 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1162 if (git_repository_open(&repo, gitdirA))
1163 return -1;
1165 int isHeadOrphan = git_repository_head_unborn(repo);
1166 if (isHeadOrphan != 0)
1168 git_repository_free(repo);
1169 hash.Empty();
1170 if (isHeadOrphan == 1)
1171 return 0;
1172 else
1173 return -1;
1176 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1178 git_object * gitObject = NULL;
1179 if (git_revparse_single(&gitObject, repo, refnameA))
1181 git_repository_free(repo);
1182 return -1;
1185 const git_oid * oid = git_object_id(gitObject);
1186 if (oid == NULL)
1188 git_object_free(gitObject);
1189 git_repository_free(repo);
1190 return -1;
1193 hash = CGitHash((char *)oid->id);
1195 git_object_free(gitObject); // also frees oid
1196 git_repository_free(repo);
1198 return 0;
1200 else
1202 CString cmd;
1203 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1204 gitLastErr.Empty();
1205 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1206 hash = CGitHash(gitLastErr.Trim());
1207 if (ret == 0)
1208 gitLastErr.Empty();
1209 return ret;
1213 int CGit::GetInitAddList(CTGitPathList &outputlist)
1215 CString cmd;
1216 BYTE_VECTOR cmdout;
1218 cmd=_T("git.exe ls-files -s -t -z");
1219 outputlist.Clear();
1220 if (Run(cmd, &cmdout))
1221 return -1;
1223 if (outputlist.ParserFromLsFile(cmdout))
1224 return -1;
1225 for(int i = 0; i < outputlist.GetCount(); ++i)
1226 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1228 return 0;
1230 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1232 CString cmd;
1233 CString ignore;
1234 if (ignoreSpaceAtEol)
1235 ignore += _T(" --ignore-space-at-eol");
1236 if (ignoreSpaceChange)
1237 ignore += _T(" --ignore-space-change");
1238 if (ignoreAllSpace)
1239 ignore += _T(" --ignore-all-space");
1240 if (ignoreBlankLines)
1241 ignore += _T(" --ignore-blank-lines");
1243 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1245 //rev1=+_T("");
1246 if(rev1 == GIT_REV_ZERO)
1247 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1248 else
1249 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), ignore, rev1);
1251 else
1253 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1256 BYTE_VECTOR out;
1257 if (Run(cmd, &out))
1258 return -1;
1260 outputlist.ParserFromLog(out);
1262 return 0;
1265 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1267 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1268 CString str;
1269 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1270 list->push_back(str);
1271 return 0;
1274 int CGit::GetTagList(STRING_VECTOR &list)
1276 if (this->m_IsUseLibGit2)
1278 git_repository *repo = NULL;
1280 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1281 if (git_repository_open(&repo, gitdir))
1282 return -1;
1284 git_strarray tag_names;
1286 if (git_tag_list(&tag_names, repo))
1288 git_repository_free(repo);
1289 return -1;
1292 for (size_t i = 0; i < tag_names.count; ++i)
1294 CStringA tagName(tag_names.strings[i]);
1295 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1298 git_strarray_free(&tag_names);
1300 git_repository_free(repo);
1302 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1304 return 0;
1306 else
1308 CString cmd, output;
1309 cmd=_T("git.exe tag -l");
1310 int ret = Run(cmd, &output, NULL, CP_UTF8);
1311 if(!ret)
1313 int pos=0;
1314 CString one;
1315 while( pos>=0 )
1317 one=output.Tokenize(_T("\n"),pos);
1318 if (!one.IsEmpty())
1319 list.push_back(one);
1321 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1323 return ret;
1328 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1329 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1331 CString CGit::GetGitLastErr(const CString& msg)
1333 if (this->m_IsUseLibGit2)
1334 return GetLibGit2LastErr(msg);
1335 else if (gitLastErr.IsEmpty())
1336 return msg + _T("\nUnknown git.exe error.");
1337 else
1339 CString lastError = gitLastErr;
1340 gitLastErr.Empty();
1341 return msg + _T("\n") + lastError;
1345 CString CGit::GetGitLastErr(const CString& msg, int cmd)
1347 if (UsingLibGit2(cmd))
1348 return GetLibGit2LastErr(msg);
1349 else if (gitLastErr.IsEmpty())
1350 return msg + _T("\nUnknown git.exe error.");
1351 else
1353 CString lastError = gitLastErr;
1354 gitLastErr.Empty();
1355 return msg + _T("\n") + lastError;
1359 CString CGit::GetLibGit2LastErr()
1361 const git_error *libgit2err = giterr_last();
1362 if (libgit2err)
1364 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1365 giterr_clear();
1366 return _T("libgit2 returned: ") + lastError;
1368 else
1369 return _T("An error occoured in libgit2, but no message is available.");
1372 CString CGit::GetLibGit2LastErr(const CString& msg)
1374 if (!msg.IsEmpty())
1375 return msg + _T("\n") + GetLibGit2LastErr();
1376 return GetLibGit2LastErr();
1379 CString CGit::FixBranchName_Mod(CString& branchName)
1381 if(branchName == "FETCH_HEAD")
1382 branchName = DerefFetchHead();
1383 return branchName;
1386 CString CGit::FixBranchName(const CString& branchName)
1388 CString tempBranchName = branchName;
1389 FixBranchName_Mod(tempBranchName);
1390 return tempBranchName;
1393 bool CGit::IsBranchTagNameUnique(const CString& name)
1395 CString output;
1397 CString cmd;
1398 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1399 int ret = Run(cmd, &output, NULL, CP_UTF8);
1400 if (!ret)
1402 int i = 0, pos = 0;
1403 while (pos >= 0)
1405 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1406 ++i;
1408 if (i >= 2)
1409 return false;
1412 return true;
1416 Checks if a branch or tag with the given name exists
1417 isBranch is true -> branch, tag otherwise
1419 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1421 CString cmd, output;
1423 cmd = _T("git.exe show-ref ");
1424 if (isBranch)
1425 cmd += _T("--heads ");
1426 else
1427 cmd += _T("--tags ");
1429 cmd += _T("refs/heads/") + name;
1430 cmd += _T(" refs/tags/") + name;
1432 int ret = Run(cmd, &output, NULL, CP_UTF8);
1433 if (!ret)
1435 if (!output.IsEmpty())
1436 return true;
1439 return false;
1442 CString CGit::DerefFetchHead()
1444 CString dotGitPath;
1445 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1446 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1447 int forMergeLineCount = 0;
1448 std::string line;
1449 std::string hashToReturn;
1450 while(getline(fetchHeadFile, line))
1452 //Tokenize this line
1453 std::string::size_type prevPos = 0;
1454 std::string::size_type pos = line.find('\t');
1455 if(pos == std::string::npos) continue; //invalid line
1457 std::string hash = line.substr(0, pos);
1458 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1460 bool forMerge = pos == prevPos;
1461 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1463 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1465 //Process this line
1466 if(forMerge)
1468 hashToReturn = hash;
1469 ++forMergeLineCount;
1470 if(forMergeLineCount > 1)
1471 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1475 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1478 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1480 int ret;
1481 CString cmd, output, cur;
1482 cmd = _T("git.exe branch --no-color");
1484 if((type&BRANCH_ALL) == BRANCH_ALL)
1485 cmd += _T(" -a");
1486 else if(type&BRANCH_REMOTE)
1487 cmd += _T(" -r");
1489 ret = Run(cmd, &output, NULL, CP_UTF8);
1490 if(!ret)
1492 int pos=0;
1493 CString one;
1494 while( pos>=0 )
1496 one=output.Tokenize(_T("\n"),pos);
1497 one.Trim(L" \r\n\t");
1498 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1499 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1500 if(one[0] == _T('*'))
1502 one = one.Mid(2);
1503 cur = one;
1505 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1506 list.push_back(one);
1510 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1511 list.push_back(L"FETCH_HEAD");
1513 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1515 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1517 for (unsigned int i = 0; i < list.size(); ++i)
1519 if (list[i] == cur)
1521 *current = i;
1522 break;
1527 return ret;
1530 int CGit::GetRemoteList(STRING_VECTOR &list)
1532 if (this->m_IsUseLibGit2)
1534 git_repository *repo = NULL;
1536 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1537 if (git_repository_open(&repo, gitdir))
1538 return -1;
1540 git_strarray remotes;
1542 if (git_remote_list(&remotes, repo))
1544 git_repository_free(repo);
1545 return -1;
1548 for (size_t i = 0; i < remotes.count; ++i)
1550 CStringA remote(remotes.strings[i]);
1551 list.push_back(CUnicodeUtils::GetUnicode(remote));
1554 git_strarray_free(&remotes);
1556 git_repository_free(repo);
1558 std::sort(list.begin(), list.end());
1560 return 0;
1562 else
1564 int ret;
1565 CString cmd, output;
1566 cmd=_T("git.exe remote");
1567 ret = Run(cmd, &output, NULL, CP_UTF8);
1568 if(!ret)
1570 int pos=0;
1571 CString one;
1572 while( pos>=0 )
1574 one=output.Tokenize(_T("\n"),pos);
1575 if (!one.IsEmpty())
1576 list.push_back(one);
1579 return ret;
1583 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR &list)
1585 CString cmd, out, err;
1586 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1587 if (Run(cmd, &out, &err, CP_UTF8))
1589 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1590 return -1;
1593 int pos = 0;
1594 while (pos >= 0)
1596 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1597 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1598 if (one.Find(_T("^{}")) >= 1)
1599 continue;
1600 if (!one.IsEmpty())
1601 list.push_back(one);
1603 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1604 return 0;
1607 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1609 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1610 CString str;
1611 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1612 list->push_back(str);
1613 return 0;
1616 int CGit::GetRefList(STRING_VECTOR &list)
1618 if (this->m_IsUseLibGit2)
1620 git_repository *repo = NULL;
1622 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1623 if (git_repository_open(&repo, gitdir))
1624 return -1;
1626 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1628 git_repository_free(repo);
1629 return -1;
1632 git_repository_free(repo);
1634 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1636 return 0;
1638 else
1640 CString cmd, output;
1641 cmd=_T("git.exe show-ref -d");
1642 int ret = Run(cmd, &output, NULL, CP_UTF8);
1643 if(!ret)
1645 int pos=0;
1646 CString one;
1647 while( pos>=0 )
1649 one=output.Tokenize(_T("\n"),pos);
1650 int start=one.Find(_T(" "),0);
1651 if(start>0)
1653 CString name;
1654 name=one.Right(one.GetLength()-start-1);
1655 list.push_back(name);
1658 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1660 return ret;
1664 typedef struct map_each_ref_payload {
1665 git_repository * repo;
1666 MAP_HASH_NAME * map;
1667 } map_each_ref_payload;
1669 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1671 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1673 CString str;
1674 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1676 git_object * gitObject = NULL;
1680 if (git_revparse_single(&gitObject, payloadContent->repo, git_reference_name(ref)))
1682 break;
1685 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1687 str += _T("^{}"); // deref tag
1688 git_object * derefedTag = NULL;
1689 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1691 break;
1693 git_object_free(gitObject);
1694 gitObject = derefedTag;
1697 const git_oid * oid = git_object_id(gitObject);
1698 if (oid == NULL)
1700 break;
1703 CGitHash hash((char *)oid->id);
1704 (*payloadContent->map)[hash].push_back(str);
1705 } while (false);
1707 if (gitObject)
1709 git_object_free(gitObject);
1710 return 0;
1713 return 1;
1716 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1718 if (this->m_IsUseLibGit2)
1720 git_repository *repo = NULL;
1722 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1723 if (git_repository_open(&repo, gitdir))
1724 return -1;
1726 map_each_ref_payload payloadContent = { repo, &map };
1728 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1730 git_repository_free(repo);
1731 return -1;
1734 git_repository_free(repo);
1736 for (auto it = map.begin(); it != map.end(); ++it)
1738 std::sort(it->second.begin(), it->second.end());
1741 return 0;
1743 else
1745 CString cmd, output;
1746 cmd=_T("git.exe show-ref -d");
1747 int ret = Run(cmd, &output, NULL, CP_UTF8);
1748 if(!ret)
1750 int pos=0;
1751 CString one;
1752 while( pos>=0 )
1754 one=output.Tokenize(_T("\n"),pos);
1755 int start=one.Find(_T(" "),0);
1756 if(start>0)
1758 CString name;
1759 name=one.Right(one.GetLength()-start-1);
1761 CString hash;
1762 hash=one.Left(start);
1764 map[CGitHash(hash)].push_back(name);
1768 return ret;
1772 static void SetLibGit2SearchPath(int level, const CString &value)
1774 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1775 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1778 static void SetLibGit2TemplatePath(const CString &value)
1780 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1781 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1784 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1786 if (m_bInitialized)
1788 return TRUE;
1791 this->m_Environment.clear();
1792 m_Environment.CopyProcessEnvironment();
1794 TCHAR *oldpath;
1795 size_t homesize,size;
1797 // set HOME if not set already
1798 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1799 if (!homesize)
1800 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1802 //setup ssh client
1803 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1804 if (sshclient.IsEmpty())
1805 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1807 if(!sshclient.IsEmpty())
1809 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1810 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1812 else
1814 TCHAR sPlink[MAX_PATH] = {0};
1815 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1816 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1817 if (ptr) {
1818 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1819 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1820 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1825 TCHAR sAskPass[MAX_PATH] = {0};
1826 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1827 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1828 if (ptr)
1830 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1831 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1832 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1833 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1837 // add git/bin path to PATH
1839 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1840 CString str = msysdir;
1841 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1843 if (!bFallback)
1844 return FALSE;
1846 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1847 str = msyslocalinstalldir;
1848 str.TrimRight(_T("\\"));
1849 if (str.IsEmpty())
1851 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1852 str = msysinstalldir;
1853 str.TrimRight(_T("\\"));
1855 if ( !str.IsEmpty() )
1857 str += "\\bin";
1858 msysdir=str;
1859 CGit::ms_LastMsysGitDir = str;
1860 msysdir.write();
1862 else
1864 // search PATH if git/bin directory is already present
1865 if ( FindGitPath() )
1867 m_bInitialized = TRUE;
1868 msysdir = CGit::ms_LastMsysGitDir;
1869 msysdir.write();
1870 return TRUE;
1873 return FALSE;
1876 else
1878 CGit::ms_LastMsysGitDir = str;
1881 // check for git.exe existance (maybe it was deinstalled in the meantime)
1882 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1883 return FALSE;
1885 // Configure libgit2 search paths
1886 CString msysGitDir;
1887 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
1888 msysGitDir.ReleaseBuffer();
1889 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
1890 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
1891 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
1892 CString msysGitTemplateDir;
1893 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
1894 msysGitTemplateDir.ReleaseBuffer();
1895 SetLibGit2TemplatePath(msysGitTemplateDir);
1897 //set path
1898 _tdupenv_s(&oldpath,&size,_T("PATH"));
1900 CString path;
1901 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1903 m_Environment.SetEnv(_T("PATH"), path);
1905 CString str1 = m_Environment.GetEnv(_T("PATH"));
1907 CString sOldPath = oldpath;
1908 free(oldpath);
1910 m_bInitialized = TRUE;
1911 return true;
1914 CString CGit::GetHomeDirectory()
1916 const wchar_t * homeDir = wget_windows_home_directory();
1917 return CString(homeDir, (int)wcslen(homeDir));
1920 CString CGit::GetGitLocalConfig()
1922 CString path;
1923 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
1924 path += _T("config");
1925 return path;
1928 CStringA CGit::GetGitPathStringA(const CString &path)
1930 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
1933 CString CGit::GetGitGlobalConfig()
1935 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1938 CString CGit::GetGitGlobalXDGConfigPath()
1940 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1943 CString CGit::GetGitGlobalXDGConfig()
1945 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1948 CString CGit::GetGitSystemConfig()
1950 const wchar_t * systemConfig = wget_msysgit_etc();
1951 return CString(systemConfig, (int)wcslen(systemConfig));
1954 BOOL CGit::CheckCleanWorkTree()
1956 CString out;
1957 CString cmd;
1958 cmd=_T("git.exe rev-parse --verify HEAD");
1960 if(Run(cmd,&out,CP_UTF8))
1961 return FALSE;
1963 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1964 if(Run(cmd,&out,CP_UTF8))
1965 return FALSE;
1967 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1968 if(Run(cmd,&out,CP_UTF8))
1969 return FALSE;
1971 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1972 if(Run(cmd,&out,CP_UTF8))
1973 return FALSE;
1975 return TRUE;
1977 int CGit::Revert(const CString& commit, const CTGitPathList &list, bool)
1979 int ret;
1980 for (int i = 0; i < list.GetCount(); ++i)
1982 ret = Revert(commit, (CTGitPath&)list[i]);
1983 if(ret)
1984 return ret;
1986 return 0;
1988 int CGit::Revert(const CString& commit, const CTGitPath &path)
1990 CString cmd, out;
1992 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1994 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1996 CString err;
1997 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1998 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1999 return -1;
2001 CString force;
2002 // if the filenames only differ in case, we have to pass "-f"
2003 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2004 force = _T("-f ");
2005 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2006 if (Run(cmd, &out, CP_UTF8))
2008 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2009 return -1;
2012 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2013 if (Run(cmd, &out, CP_UTF8))
2015 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2016 return -1;
2020 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2021 { //To init git repository, there are not HEAD, so we can use git reset command
2022 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2024 if (Run(cmd, &out, CP_UTF8))
2026 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2027 return -1;
2030 else
2032 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2033 if (Run(cmd, &out, CP_UTF8))
2035 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2036 return -1;
2040 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2042 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2043 if (Run(cmd, &out, CP_UTF8))
2045 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2046 return -1;
2050 return 0;
2053 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2055 BYTE_VECTOR vector;
2057 CString cmd;
2058 if(path)
2059 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2060 else
2061 cmd=_T("git.exe ls-files -u -t -z");
2063 if (Run(cmd, &vector))
2065 return -1;
2068 if (list.ParserFromLsFile(vector))
2069 return -1;
2071 return 0;
2074 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2076 CString base;
2077 CGitHash basehash,hash;
2078 CString cmd, err;
2079 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2081 if (Run(cmd, &base, &err, CP_UTF8))
2083 return false;
2085 basehash = base.Trim();
2087 GetHash(hash, from);
2089 if (commonAncestor)
2090 *commonAncestor = basehash;
2092 return hash == basehash;
2095 unsigned int CGit::Hash2int(const CGitHash &hash)
2097 int ret=0;
2098 for (int i = 0; i < 4; ++i)
2100 ret = ret << 8;
2101 ret |= hash.m_hash[i];
2103 return ret;
2106 int CGit::RefreshGitIndex()
2108 if(g_Git.m_IsUseGitDLL)
2110 CAutoLocker lock(g_Git.m_critGitDllSec);
2113 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2115 }catch(...)
2117 return -1;
2121 else
2123 CString cmd,output;
2124 cmd=_T("git.exe update-index --refresh");
2125 return Run(cmd, &output, CP_UTF8);
2129 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2131 if(g_Git.m_IsUseGitDLL)
2133 CAutoLocker lock(g_Git.m_critGitDllSec);
2136 g_Git.CheckAndInitDll();
2137 CStringA ref, patha, outa;
2138 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2139 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2140 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2141 ::DeleteFile(outputfile);
2142 return git_checkout_file(ref, patha, outa);
2144 }catch(...)
2146 return -1;
2149 else
2151 CString cmd;
2152 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2153 return RunLogFile(cmd, outputfile, &gitLastErr);
2156 void CEnvironment::CopyProcessEnvironment()
2158 TCHAR *porig = GetEnvironmentStrings();
2159 TCHAR *p = porig;
2160 while(*p !=0 || *(p+1) !=0)
2161 this->push_back(*p++);
2163 push_back(_T('\0'));
2164 push_back(_T('\0'));
2166 FreeEnvironmentStrings(porig);
2169 CString CEnvironment::GetEnv(const TCHAR *name)
2171 CString str;
2172 for (size_t i = 0; i < size(); ++i)
2174 str = &(*this)[i];
2175 int start =0;
2176 CString sname = str.Tokenize(_T("="),start);
2177 if(sname.CompareNoCase(name) == 0)
2179 return &(*this)[i+start];
2181 i+=str.GetLength();
2183 return _T("");
2186 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2188 unsigned int i;
2189 for (i = 0; i < size(); ++i)
2191 CString str = &(*this)[i];
2192 int start =0;
2193 CString sname = str.Tokenize(_T("="),start);
2194 if(sname.CompareNoCase(name) == 0)
2196 break;
2198 i+=str.GetLength();
2201 if(i == size())
2203 i -= 1; // roll back terminate \0\0
2204 this->push_back(_T('\0'));
2207 CEnvironment::iterator it;
2208 it=this->begin();
2209 it += i;
2211 while(*it && i<size())
2213 this->erase(it);
2214 it=this->begin();
2215 it += i;
2218 while(*name)
2220 this->insert(it,*name++);
2221 ++i;
2222 it= begin()+i;
2225 this->insert(it, _T('='));
2226 ++i;
2227 it= begin()+i;
2229 while(*value)
2231 this->insert(it,*value++);
2232 ++i;
2233 it= begin()+i;
2238 int CGit::GetGitEncode(TCHAR* configkey)
2240 CString str=GetConfigValue(configkey);
2242 if(str.IsEmpty())
2243 return CP_UTF8;
2245 return CUnicodeUtils::GetCPCode(str);
2249 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2251 GIT_FILE file=0;
2252 int ret=0;
2253 GIT_DIFF diff=0;
2255 CAutoLocker lock(g_Git.m_critGitDllSec);
2257 if(arg == NULL)
2258 diff = GetGitDiff();
2259 else
2260 git_open_diff(&diff, arg);
2262 if(diff ==NULL)
2263 return -1;
2265 bool isStat = 0;
2266 if(arg == NULL)
2267 isStat = true;
2268 else
2269 isStat = !!strstr(arg, "stat");
2271 int count=0;
2273 if(hash2 == NULL)
2274 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2275 else
2276 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2278 if(ret)
2279 return -1;
2281 CTGitPath path;
2282 CString strnewname;
2283 CString stroldname;
2285 for (int j = 0; j < count; ++j)
2287 path.Reset();
2288 char *newname;
2289 char *oldname;
2291 strnewname.Empty();
2292 stroldname.Empty();
2294 int mode=0,IsBin=0,inc=0,dec=0;
2295 git_get_diff_file(diff,file,j,&newname,&oldname,
2296 &mode,&IsBin,&inc,&dec);
2298 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2299 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2301 path.SetFromGit(strnewname,&stroldname);
2302 path.ParserAction((BYTE)mode);
2304 if(IsBin)
2306 path.m_StatAdd=_T("-");
2307 path.m_StatDel=_T("-");
2309 else
2311 path.m_StatAdd.Format(_T("%d"),inc);
2312 path.m_StatDel.Format(_T("%d"),dec);
2314 PathList->AddPath(path);
2316 git_diff_flush(diff);
2318 if(arg)
2319 git_close_diff(diff);
2321 return 0;
2324 int CGit::GetShortHASHLength()
2326 return 7;
2329 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2331 CString str=ref;
2332 CString shortname;
2333 REF_TYPE type = CGit::UNKNOWN;
2335 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2337 type = CGit::LOCAL_BRANCH;
2340 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2342 type = CGit::REMOTE_BRANCH;
2344 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2346 type = CGit::TAG;
2348 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2350 type = CGit::STASH;
2351 shortname=_T("stash");
2353 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2355 if (shortname.Find(_T("good")) == 0)
2357 type = CGit::BISECT_GOOD;
2358 shortname = _T("good");
2361 if (shortname.Find(_T("bad")) == 0)
2363 type = CGit::BISECT_BAD;
2364 shortname = _T("bad");
2367 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2369 type = CGit::NOTES;
2371 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2373 type = CGit::UNKNOWN;
2375 else
2377 type = CGit::UNKNOWN;
2378 shortname = ref;
2381 if(out_type)
2382 *out_type = type;
2384 return shortname;
2387 bool CGit::UsingLibGit2(int cmd)
2389 if (cmd >= 0 && cmd < 32)
2390 return ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2391 return false;
2394 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2396 CString cmd;
2397 if (rev2 == GitRev::GetWorkingCopy())
2398 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2399 else if (rev1 == GitRev::GetWorkingCopy())
2400 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2401 else
2403 CString merge;
2404 if (bMerge)
2405 merge += _T(" -m");
2407 if (bCombine)
2408 merge += _T(" -c");
2410 CString unified;
2411 if (diffContext > 0)
2412 unified.Format(_T(" --unified=%d"), diffContext);
2413 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2416 if (!path.IsEmpty())
2418 cmd += _T(" \"");
2419 cmd += path.GetGitPathString();
2420 cmd += _T("\"");
2423 return cmd;
2426 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2428 ATLASSERT(payload && line);
2429 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2430 fwrite(&line->origin, 1, 1, (FILE *)payload);
2431 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2432 return 0;
2435 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2437 ATLASSERT(repo && identifier && tree);
2439 /* try to resolve identifier */
2440 git_object *obj = nullptr;
2441 if (git_revparse_single(&obj, repo, identifier))
2442 return -1;
2444 if (obj == nullptr)
2445 return GIT_ENOTFOUND;
2447 int err = 0;
2448 switch (git_object_type(obj))
2450 case GIT_OBJ_TREE:
2451 *tree = (git_tree *)obj;
2452 break;
2453 case GIT_OBJ_COMMIT:
2454 err = git_commit_tree(tree, (git_commit *)obj);
2455 git_object_free(obj);
2456 break;
2457 default:
2458 err = GIT_ENOTFOUND;
2461 return err;
2464 /* use libgit2 get unified diff */
2465 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 */)
2467 git_repository *repo = nullptr;
2468 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(g_Git.m_CurrentDir).GetGitPathString(), CP_UTF8);
2469 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2470 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2471 int ret = 0;
2473 if (git_repository_open(&repo, gitdirA))
2474 return -1;
2476 int isHeadOrphan = git_repository_head_unborn(repo);
2477 if (isHeadOrphan != 0)
2479 git_repository_free(repo);
2480 if (isHeadOrphan == 1)
2481 return 0;
2482 else
2483 return -1;
2486 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2487 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2488 char *buf = pathA.GetBuffer();
2489 if (!pathA.IsEmpty())
2491 opts.pathspec.strings = &buf;
2492 opts.pathspec.count = 1;
2494 git_diff *diff = nullptr;
2496 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2498 git_tree *t1 = nullptr;
2499 git_diff *diff2 = nullptr;
2503 if (revNew != GitRev::GetWorkingCopy())
2505 if (resolve_to_tree(repo, tree1, &t1))
2507 ret = -1;
2508 break;
2511 if (revOld != GitRev::GetWorkingCopy())
2513 if (resolve_to_tree(repo, tree2, &t1))
2515 ret = -1;
2516 break;
2520 ret = git_diff_tree_to_index(&diff, repo, t1, nullptr, &opts);
2521 if (ret)
2522 break;
2524 ret = git_diff_index_to_workdir(&diff2, repo, nullptr, &opts);
2525 if (ret)
2526 break;
2528 ret = git_diff_merge(diff, diff2);
2529 if (ret)
2530 break;
2532 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2534 git_patch *patch;
2535 if (git_patch_from_diff(&patch, diff, i))
2537 ret = -1;
2538 break;
2541 if (git_patch_print(patch, callback, data))
2543 git_patch_free(patch);
2544 ret = -1;
2545 break;
2548 git_patch_free(patch);
2550 } while(0);
2551 if (diff)
2552 git_diff_free(diff);
2553 if (diff2)
2554 git_diff_free(diff2);
2555 if (t1)
2556 git_tree_free(t1);
2558 else
2560 git_tree *t1 = nullptr, *t2 = nullptr;
2563 if (tree1.IsEmpty() && tree2.IsEmpty())
2565 ret = -1;
2566 break;
2569 if (tree1.IsEmpty())
2571 tree1 = tree2;
2572 tree2.Empty();
2575 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, &t1))
2577 ret = -1;
2578 break;
2581 if (tree2.IsEmpty())
2583 /* don't check return value, there are not parent commit at first commit*/
2584 resolve_to_tree(repo, tree1 + "~1", &t2);
2586 else if (resolve_to_tree(repo, tree2, &t2))
2588 ret = -1;
2589 break;
2591 if (git_diff_tree_to_tree(&diff, repo, t2, t1, &opts))
2593 ret = -1;
2594 break;
2597 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2599 git_patch *patch;
2600 if (git_patch_from_diff(&patch, diff, i))
2602 ret = -1;
2603 break;
2606 if (git_patch_print(patch, callback, data))
2608 git_patch_free(patch);
2609 ret = -1;
2610 break;
2613 git_patch_free(patch);
2615 } while(0);
2617 if (diff)
2618 git_diff_free(diff);
2619 if (t1)
2620 git_tree_free(t1);
2621 if (t2)
2622 git_tree_free(t2);
2624 git_repository_free(repo);
2625 pathA.ReleaseBuffer();
2627 return ret;
2630 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2632 if (UsingLibGit2(GIT_CMD_DIFF))
2634 FILE *file = nullptr;
2635 _tfopen_s(&file, patchfile, _T("w"));
2636 if (file == nullptr)
2637 return -1;
2638 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToFile, file, bMerge);
2639 fclose(file);
2640 return ret;
2642 else
2644 CString cmd;
2645 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2646 return g_Git.RunLogFile(cmd, patchfile, &gitLastErr);
2650 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2652 ATLASSERT(payload && line);
2653 CStringA *str = (CStringA*) payload;
2654 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2655 str->Append(&line->origin, 1);
2656 str->Append(line->content, (int)line->content_len);
2657 return 0;
2660 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2662 if (UsingLibGit2(GIT_CMD_DIFF))
2663 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToStringA, buffer, bMerge);
2664 else
2666 CString cmd;
2667 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2668 BYTE_VECTOR vector;
2669 int ret = Run(cmd, &vector);
2670 if (!vector.empty())
2672 vector.push_back(0); // vector is not NUL terminated
2673 buffer->Append((char *)&vector[0]);
2675 return ret;
2679 int CGit::GitRevert(int parent, const CGitHash &hash)
2681 if (UsingLibGit2(GIT_CMD_REVERT))
2683 git_repository *repo = nullptr;
2684 CStringA gitdirA = CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir).GetGitPathString());
2685 if (git_repository_open(&repo, gitdirA))
2686 return -1;
2688 git_commit *commit = nullptr;
2689 if (git_commit_lookup(&commit, repo, (const git_oid *)hash.m_hash))
2691 git_repository_free(repo);
2692 return -1;
2695 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2696 revert_opts.mainline = parent;
2697 int result = git_revert(repo, commit, &revert_opts);
2699 git_commit_free(commit);
2700 git_repository_free(repo);
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 (g_Git.Run(cmd, &gitLastErr, CP_UTF8))
2712 return -1;
2714 else
2716 gitLastErr.Empty();
2717 return 0;