Unbreak /logmsg and /logmsgfile params of commit command
[TortoiseGit.git] / src / Git / Git.cpp
blob39773280e836ce4b99ecd42d699bc8030f7e9d48
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 // CREATE_NEW_CONSOLE makes ssh recognize that it has no console in order to launch askpass to ask for the password.
249 // DETACHED_PROCESS which was originally used here has the same effect, however, it prevents PowerShell from working (cf. issue #2143)
250 dwFlags |= CREATE_NEW_PROCESS_GROUP | CREATE_NEW_CONSOLE;
252 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
253 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
255 if(cmd.Find(_T("git")) == 0)
257 int firstSpace = cmd.Find(_T(" "));
258 if (firstSpace > 0)
259 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
260 else
261 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
264 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
265 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
267 CString err = CFormatMessageWrapper();
268 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": error while executing command: %s\n"), err.Trim());
269 return TGIT_GIT_ERROR_CREATE_PROCESS;
272 m_CurrentGitPi = pi;
274 if(piOut)
275 *piOut=pi;
276 if(hReadOut)
277 *hReadOut = hRead.Detach();
278 if(hErrReadOut)
279 *hErrReadOut = hReadErr.Detach();
280 return 0;
283 //Must use sperate function to convert ANSI str to union code string
284 //Becuase A2W use stack as internal convert buffer.
285 void CGit::StringAppend(CString *str, const BYTE *p, int code,int length)
287 if(str == NULL)
288 return ;
290 int len ;
291 if(length<0)
292 len = (int)strlen((const char*)p);
293 else
294 len=length;
295 if (len == 0)
296 return;
297 int currentContentLen = str->GetLength();
298 WCHAR * buf = str->GetBuffer(len * 4 + 1 + currentContentLen) + currentContentLen;
299 int appendedLen = MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len * 4);
300 str->ReleaseBuffer(currentContentLen + appendedLen); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
303 // This method was originally used to check for orphaned branches
304 BOOL CGit::CanParseRev(CString ref)
306 if (ref.IsEmpty())
307 ref = _T("HEAD");
309 CString cmdout;
310 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
312 return FALSE;
314 if(cmdout.IsEmpty())
315 return FALSE;
317 return TRUE;
320 // Checks if we have an orphaned HEAD
321 BOOL CGit::IsInitRepos()
323 CGitHash hash;
324 // handle error on reading HEAD hash as init repo
325 if (GetHash(hash, _T("HEAD")) != 0)
326 return TRUE;
327 return hash.IsEmpty() ? TRUE : FALSE;
330 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
332 PASYNCREADSTDERRTHREADARGS pDataArray;
333 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
335 DWORD readnumber;
336 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
337 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
339 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
340 break;
343 return 0;
346 int CGit::Run(CGitCall* pcall)
348 PROCESS_INFORMATION pi;
349 CAutoGeneralHandle hRead, hReadErr;
350 if (RunAsync(pcall->GetCmd(), &pi, hRead.GetPointer(), hReadErr.GetPointer()))
351 return TGIT_GIT_ERROR_CREATE_PROCESS;
353 CAutoGeneralHandle piThread(pi.hThread);
354 CAutoGeneralHandle piProcess(pi.hProcess);
356 ASYNCREADSTDERRTHREADARGS threadArguments;
357 threadArguments.fileHandle = hReadErr;
358 threadArguments.pcall = pcall;
359 CAutoGeneralHandle thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
361 DWORD readnumber;
362 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
363 bool bAborted=false;
364 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
366 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
367 if(!bAborted)//For now, flush output when command aborted.
368 if(pcall->OnOutputData(data,readnumber))
369 bAborted=true;
371 if(!bAborted)
372 pcall->OnEnd();
374 if (thread)
375 WaitForSingleObject(thread, INFINITE);
377 WaitForSingleObject(pi.hProcess, INFINITE);
378 DWORD exitcode =0;
380 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
382 CString err = CFormatMessageWrapper();
383 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
384 return TGIT_GIT_ERROR_GET_EXIT_CODE;
386 else
387 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
389 return exitcode;
391 class CGitCall_ByteVector : public CGitCall
393 public:
394 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
395 virtual bool OnOutputData(const BYTE* data, size_t size)
397 if (!m_pvector || size == 0)
398 return false;
399 size_t oldsize=m_pvector->size();
400 m_pvector->resize(m_pvector->size()+size);
401 memcpy(&*(m_pvector->begin()+oldsize),data,size);
402 return false;
404 virtual bool OnOutputErrData(const BYTE* data, size_t size)
406 if (!m_pvectorErr || size == 0)
407 return false;
408 size_t oldsize = m_pvectorErr->size();
409 m_pvectorErr->resize(m_pvectorErr->size() + size);
410 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
411 return false;
413 BYTE_VECTOR* m_pvector;
414 BYTE_VECTOR* m_pvectorErr;
417 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
419 CGitCall_ByteVector call(cmd, vector, vectorErr);
420 return Run(&call);
422 int CGit::Run(CString cmd, CString* output, int code)
424 CString err;
425 int ret;
426 ret = Run(cmd, output, &err, code);
428 if (output && !err.IsEmpty())
430 if (!output->IsEmpty())
431 *output += _T("\n");
432 *output += err;
435 return ret;
437 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
439 BYTE_VECTOR vector, vectorErr;
440 int ret;
441 if (outputErr)
442 ret = Run(cmd, &vector, &vectorErr);
443 else
444 ret = Run(cmd, &vector);
446 vector.push_back(0);
447 StringAppend(output, &(vector[0]), code);
449 if (outputErr)
451 vectorErr.push_back(0);
452 StringAppend(outputErr, &(vectorErr[0]), code);
455 return ret;
458 class CGitCallCb : public CGitCall
460 public:
461 CGitCallCb(CString cmd, const GitReceiverFunc& recv): CGitCall(cmd), m_recv(recv) {}
463 virtual bool OnOutputData(const BYTE* data, size_t size) override
465 // Add data
466 if (size == 0)
467 return false;
468 int oldEndPos = m_buffer.GetLength();
469 memcpy(m_buffer.GetBufferSetLength(oldEndPos + (int)size) + oldEndPos, data, size);
470 m_buffer.ReleaseBuffer(oldEndPos + (int)size);
472 // Break into lines and feed to m_recv
473 int eolPos;
474 while ((eolPos = m_buffer.Find('\n')) >= 0)
476 m_recv(m_buffer.Left(eolPos));
477 m_buffer = m_buffer.Mid(eolPos + 1);
479 return false;
482 virtual bool OnOutputErrData(const BYTE*, size_t) override
484 return false; // Ignore error output for now
487 virtual void OnEnd() override
489 if (!m_buffer.IsEmpty())
490 m_recv(m_buffer);
491 m_buffer.Empty(); // Just for sure
494 private:
495 GitReceiverFunc m_recv;
496 CStringA m_buffer;
499 int CGit::Run(CString cmd, const GitReceiverFunc& recv)
501 CGitCallCb call(cmd, recv);
502 return Run(&call);
505 CString CGit::GetUserName(void)
507 CEnvironment env;
508 env.CopyProcessEnvironment();
509 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
510 if (!envname.IsEmpty())
511 return envname;
512 return GetConfigValue(L"user.name");
514 CString CGit::GetUserEmail(void)
516 CEnvironment env;
517 env.CopyProcessEnvironment();
518 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
519 if (!envmail.IsEmpty())
520 return envmail;
522 return GetConfigValue(L"user.email");
525 CString CGit::GetConfigValue(const CString& name)
527 CString configValue;
528 int start = 0;
529 if(this->m_IsUseGitDLL)
531 CAutoLocker lock(g_Git.m_critGitDllSec);
535 CheckAndInitDll();
536 }catch(...)
539 CStringA key, value;
540 key = CUnicodeUtils::GetUTF8(name);
544 if (git_get_config(key, value.GetBufferSetLength(4096), 4096))
545 return CString();
547 catch (const char *msg)
549 ::MessageBox(NULL, _T("Could not get config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
550 return CString();
553 StringAppend(&configValue, (BYTE*)(LPCSTR)value);
554 return configValue.Tokenize(_T("\n"),start);
556 else
558 CString cmd;
559 cmd.Format(L"git.exe config %s", name);
560 Run(cmd, &configValue, nullptr, CP_UTF8);
561 return configValue.Tokenize(_T("\n"),start);
565 bool CGit::GetConfigValueBool(const CString& name)
567 CString configValue = GetConfigValue(name);
568 configValue.MakeLower();
569 configValue.Trim();
570 if(configValue == _T("true") || configValue == _T("on") || configValue == _T("yes") || StrToInt(configValue) != 0)
571 return true;
572 else
573 return false;
576 int CGit::SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type)
578 if(this->m_IsUseGitDLL)
580 CAutoLocker lock(g_Git.m_critGitDllSec);
584 CheckAndInitDll();
586 }catch(...)
589 CStringA keya, valuea;
590 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
591 valuea = CUnicodeUtils::GetUTF8(value);
595 return [=]() { return get_set_config(keya, valuea, type); }();
597 catch (const char *msg)
599 ::MessageBox(NULL, _T("Could not set config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
600 return -1;
603 else
605 CString cmd;
606 CString option;
607 switch(type)
609 case CONFIG_GLOBAL:
610 option = _T("--global");
611 break;
612 case CONFIG_SYSTEM:
613 option = _T("--system");
614 break;
615 default:
616 break;
618 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
619 CString out;
620 if (Run(cmd, &out, nullptr, CP_UTF8))
622 return -1;
625 return 0;
628 int CGit::UnsetConfigValue(const CString& key, CONFIG_TYPE type)
630 if(this->m_IsUseGitDLL)
632 CAutoLocker lock(g_Git.m_critGitDllSec);
636 CheckAndInitDll();
637 }catch(...)
640 CStringA keya;
641 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
645 return [=]() { return get_set_config(keya, nullptr, type); }();
647 catch (const char *msg)
649 ::MessageBox(NULL, _T("Could not unset config.\nlibgit reports:\n") + CString(msg), _T("TortoiseGit"), MB_OK | MB_ICONERROR);
650 return -1;
653 else
655 CString cmd;
656 CString option;
657 switch(type)
659 case CONFIG_GLOBAL:
660 option = _T("--global");
661 break;
662 case CONFIG_SYSTEM:
663 option = _T("--system");
664 break;
665 default:
666 break;
668 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
669 CString out;
670 if (Run(cmd, &out, nullptr, CP_UTF8))
672 return -1;
675 return 0;
678 CString CGit::GetCurrentBranch(bool fallback)
680 CString output;
681 //Run(_T("git.exe branch"),&branch);
683 int result = GetCurrentBranchFromFile(m_CurrentDir, output, fallback);
684 if (result != 0 && ((result == 1 && !fallback) || result != 1))
686 return _T("(no branch)");
688 else
689 return output;
693 void CGit::GetRemoteTrackedBranch(const CString& localBranch, CString& pullRemote, CString& pullBranch)
695 if (localBranch.IsEmpty())
696 return;
698 CString configName;
699 configName.Format(L"branch.%s.remote", localBranch);
700 pullRemote = GetConfigValue(configName);
702 //Select pull-branch from current branch
703 configName.Format(L"branch.%s.merge", localBranch);
704 pullBranch = StripRefName(GetConfigValue(configName));
707 void CGit::GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch)
709 CString refName;
710 if (GetCurrentBranchFromFile(m_CurrentDir, refName))
711 return;
712 GetRemoteTrackedBranch(StripRefName(refName), remote, branch);
715 CString CGit::GetFullRefName(const CString& shortRefName)
717 CString refName;
718 CString cmd;
719 cmd.Format(L"git.exe rev-parse --symbolic-full-name %s", shortRefName);
720 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
721 return CString();//Error
722 int iStart = 0;
723 return refName.Tokenize(L"\n", iStart);
726 CString CGit::StripRefName(CString refName)
728 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
729 refName = refName.Mid(11);
730 else if(wcsncmp(refName, L"refs/", 5) == 0)
731 refName = refName.Mid(5);
732 int start =0;
733 return refName.Tokenize(_T("\n"),start);
736 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback)
738 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
740 if ( sProjectRoot.IsEmpty() )
741 return -1;
743 CString sDotGitPath;
744 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
745 return -1;
747 CString sHeadFile = sDotGitPath + _T("HEAD");
749 FILE *pFile;
750 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
752 if (!pFile)
754 return -1;
757 char s[256] = {0};
758 fgets(s, sizeof(s), pFile);
760 fclose(pFile);
762 const char *pfx = "ref: refs/heads/";
763 const int len = 16;//strlen(pfx)
765 if ( !strncmp(s, pfx, len) )
767 //# We're on a branch. It might not exist. But
768 //# HEAD looks good enough to be a branch.
769 CStringA utf8Branch(s + len);
770 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
771 sBranchOut.TrimRight(_T(" \r\n\t"));
773 if ( sBranchOut.IsEmpty() )
774 return -1;
776 else if (fallback)
778 CStringA utf8Hash(s);
779 CString unicodeHash = CUnicodeUtils::GetUnicode(utf8Hash);
780 unicodeHash.TrimRight(_T(" \r\n\t"));
781 if (CGitHash::IsValidSHA1(unicodeHash))
782 sBranchOut = unicodeHash;
783 else
784 //# Assume this is a detached head.
785 sBranchOut = _T("HEAD");
786 return 1;
788 else
790 //# Assume this is a detached head.
791 sBranchOut = "HEAD";
793 return 1;
796 return 0;
799 int CGit::BuildOutputFormat(CString &format,bool IsFull)
801 CString log;
802 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
803 format += log;
804 if(IsFull)
806 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
807 format += log;
808 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
809 format += log;
810 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
811 format += log;
812 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
813 format += log;
814 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
815 format += log;
816 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
817 format += log;
818 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
819 format += log;
822 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
823 format += log;
824 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
825 format += log;
826 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
827 format += log;
829 if(IsFull)
831 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
832 format += log;
834 return 0;
837 CString CGit::GetLogCmd(const CString &range, const CTGitPath *path, int count, int mask, bool paramonly,
838 CFilterData *Filter)
840 CString cmd;
841 CString num;
842 CString since;
844 CString file = _T(" --");
846 if(path)
847 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
849 if(count>0)
850 num.Format(_T("-n%d"),count);
852 CString param;
854 if(mask& LOG_INFO_STAT )
855 param += _T(" --numstat ");
856 if(mask& LOG_INFO_FILESTATE)
857 param += _T(" --raw ");
859 if(mask& LOG_INFO_FULLHISTORY)
860 param += _T(" --full-history ");
862 if(mask& LOG_INFO_BOUNDARY)
863 param += _T(" --left-right --boundary ");
865 if(mask& CGit::LOG_INFO_ALL_BRANCH)
866 param += _T(" --all ");
868 if(mask & CGit::LOG_INFO_LOCAL_BRANCHES)
869 param += _T(" --branches ");
871 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
872 param += _T(" -C ");
874 if(mask& CGit::LOG_INFO_DETECT_RENAME )
875 param += _T(" -M ");
877 if(mask& CGit::LOG_INFO_FIRST_PARENT )
878 param += _T(" --first-parent ");
880 if(mask& CGit::LOG_INFO_NO_MERGE )
881 param += _T(" --no-merges ");
883 if(mask& CGit::LOG_INFO_FOLLOW)
884 param += _T(" --follow ");
886 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
887 param += _T(" -c ");
889 if(mask& CGit::LOG_INFO_FULL_DIFF)
890 param += _T(" --full-diff ");
892 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
893 param += _T(" --simplify-by-decoration ");
895 param += range;
897 CString st1,st2;
899 if( Filter && (Filter->m_From != -1))
901 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
902 param += st1;
905 if( Filter && (Filter->m_To != -1))
907 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
908 param += st2;
911 bool isgrep = false;
912 if( Filter && (!Filter->m_Author.IsEmpty()))
914 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
915 param += st1;
916 isgrep = true;
919 if( Filter && (!Filter->m_Committer.IsEmpty()))
921 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
922 param += st1;
923 isgrep = true;
926 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
928 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
929 param += st1;
930 isgrep = true;
933 if(Filter && isgrep)
935 if(!Filter->m_IsRegex)
936 param += _T(" --fixed-strings ");
938 param += _T(" --regexp-ignore-case --extended-regexp ");
941 DWORD logOrderBy = CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER);
942 if (logOrderBy == LOG_ORDER_TOPOORDER)
943 param += _T(" --topo-order");
944 else if (logOrderBy == LOG_ORDER_DATEORDER)
945 param += _T(" --date-order");
947 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
948 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
949 else
951 CString log;
952 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
953 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
954 num,param,log);
957 cmd += file;
959 return cmd;
961 #define BUFSIZE 512
962 void GetTempPath(CString &path)
964 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
965 DWORD dwRetVal;
966 DWORD dwBufSize=BUFSIZE;
967 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
968 lpPathBuffer); // buffer for path
969 if (dwRetVal > dwBufSize || (dwRetVal == 0))
971 path=_T("");
973 path.Format(_T("%s"),lpPathBuffer);
975 CString GetTempFile()
977 TCHAR lpPathBuffer[BUFSIZE] = { 0 };
978 DWORD dwRetVal;
979 DWORD dwBufSize=BUFSIZE;
980 TCHAR szTempName[BUFSIZE] = { 0 };
981 UINT uRetVal;
983 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
984 lpPathBuffer); // buffer for path
985 if (dwRetVal > dwBufSize || (dwRetVal == 0))
987 return _T("");
989 // Create a temporary file.
990 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
991 TEXT("Patch"), // temp file name prefix
992 0, // create unique name
993 szTempName); // buffer for name
996 if (uRetVal == 0)
998 return _T("");
1001 return CString(szTempName);
1005 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
1007 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
1008 if (result == 0) return 0;
1009 if (lpBuffer == NULL || (result + 13 > nBufferLength))
1011 if (lpBuffer)
1012 lpBuffer[0] = '\0';
1013 return result + 13;
1016 _tcscat_s(lpBuffer, nBufferLength, _T("TortoiseGit\\"));
1017 CreateDirectory(lpBuffer, NULL);
1019 return result + 13;
1022 int CGit::RunLogFile(CString cmd, const CString &filename, CString *stdErr)
1024 STARTUPINFO si;
1025 PROCESS_INFORMATION pi;
1026 si.cb=sizeof(STARTUPINFO);
1027 GetStartupInfo(&si);
1029 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1030 psa.bInheritHandle=TRUE;
1032 HANDLE hReadErr, hWriteErr;
1033 if (!CreatePipe(&hReadErr, &hWriteErr, &psa, 0))
1035 CString err = CFormatMessageWrapper();
1036 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stderr pipe: %s\n"), err.Trim());
1037 return TGIT_GIT_ERROR_OPEN_PIP;
1040 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1041 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1043 if (houtfile == INVALID_HANDLE_VALUE)
1045 CString err = CFormatMessageWrapper();
1046 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not open stdout pipe: %s\n"), err.Trim());
1047 CloseHandle(hReadErr);
1048 CloseHandle(hWriteErr);
1049 return TGIT_GIT_ERROR_OPEN_PIP;
1052 si.wShowWindow = SW_HIDE;
1053 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1054 si.hStdOutput = houtfile;
1055 si.hStdError = hWriteErr;
1057 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1058 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1060 if(cmd.Find(_T("git")) == 0)
1061 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1063 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": executing %s\n"), cmd);
1064 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1066 CString err = CFormatMessageWrapper();
1067 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": failed to create Process: %s\n"), err.Trim());
1068 stdErr = &err;
1069 CloseHandle(hReadErr);
1070 CloseHandle(hWriteErr);
1071 CloseHandle(houtfile);
1072 return TGIT_GIT_ERROR_CREATE_PROCESS;
1075 BYTE_VECTOR stderrVector;
1076 CGitCall_ByteVector pcall(L"", nullptr, &stderrVector);
1077 HANDLE thread;
1078 ASYNCREADSTDERRTHREADARGS threadArguments;
1079 threadArguments.fileHandle = hReadErr;
1080 threadArguments.pcall = &pcall;
1081 thread = CreateThread(nullptr, 0, AsyncReadStdErrThread, &threadArguments, 0, nullptr);
1083 WaitForSingleObject(pi.hProcess,INFINITE);
1085 CloseHandle(hWriteErr);
1086 CloseHandle(hReadErr);
1088 if (thread)
1089 WaitForSingleObject(thread, INFINITE);
1091 stderrVector.push_back(0);
1092 StringAppend(stdErr, &(stderrVector[0]), CP_UTF8);
1094 DWORD exitcode = 0;
1095 if (!GetExitCodeProcess(pi.hProcess, &exitcode))
1097 CString err = CFormatMessageWrapper();
1098 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": could not get exit code: %s\n"), err.Trim());
1099 return TGIT_GIT_ERROR_GET_EXIT_CODE;
1101 else
1102 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__) _T(": process exited: %d\n"), exitcode);
1104 CloseHandle(pi.hThread);
1105 CloseHandle(pi.hProcess);
1106 CloseHandle(houtfile);
1107 return exitcode;
1110 git_repository * CGit::GetGitRepository() const
1112 git_repository * repo = nullptr;
1113 git_repository_open(&repo, GetGitPathStringA(m_CurrentDir));
1114 return repo;
1117 int CGit::GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck /* = false */)
1119 ATLASSERT(repo);
1121 // no need to parse a ref if it's already a 40-byte hash
1122 if (!skipFastCheck && CGitHash::IsValidSHA1(friendname))
1124 hash = CGitHash(friendname);
1125 return 0;
1128 int isHeadOrphan = git_repository_head_unborn(repo);
1129 if (isHeadOrphan != 0)
1131 hash.Empty();
1132 if (isHeadOrphan == 1)
1133 return 0;
1134 else
1135 return -1;
1138 CAutoObject gitObject;
1139 if (git_revparse_single(gitObject.GetPointer(), repo, CUnicodeUtils::GetUTF8(friendname)))
1140 return -1;
1142 const git_oid * oid = git_object_id(gitObject);
1143 if (!oid)
1144 return -1;
1146 hash = CGitHash((char *)oid->id);
1148 return 0;
1151 int CGit::GetHash(CGitHash &hash, const CString& friendname)
1153 // no need to parse a ref if it's already a 40-byte hash
1154 if (CGitHash::IsValidSHA1(friendname))
1156 hash = CGitHash(friendname);
1157 return 0;
1160 if (m_IsUseLibGit2)
1162 CAutoRepository repo(GetGitRepository());
1163 if (!repo)
1164 return -1;
1166 return GetHash(repo, hash, friendname, true);
1168 else
1170 CString cmd;
1171 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1172 gitLastErr.Empty();
1173 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1174 hash = CGitHash(gitLastErr.Trim());
1175 if (ret == 0)
1176 gitLastErr.Empty();
1177 return ret;
1181 int CGit::GetInitAddList(CTGitPathList &outputlist)
1183 CString cmd;
1184 BYTE_VECTOR cmdout;
1186 cmd=_T("git.exe ls-files -s -t -z");
1187 outputlist.Clear();
1188 if (Run(cmd, &cmdout))
1189 return -1;
1191 if (outputlist.ParserFromLsFile(cmdout))
1192 return -1;
1193 for(int i = 0; i < outputlist.GetCount(); ++i)
1194 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1196 return 0;
1198 int CGit::GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outputlist, bool ignoreSpaceAtEol, bool ignoreSpaceChange, bool ignoreAllSpace , bool ignoreBlankLines)
1200 CString cmd;
1201 CString ignore;
1202 if (ignoreSpaceAtEol)
1203 ignore += _T(" --ignore-space-at-eol");
1204 if (ignoreSpaceChange)
1205 ignore += _T(" --ignore-space-change");
1206 if (ignoreAllSpace)
1207 ignore += _T(" --ignore-all-space");
1208 if (ignoreBlankLines)
1209 ignore += _T(" --ignore-blank-lines");
1211 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1213 //rev1=+_T("");
1214 if(rev1 == GIT_REV_ZERO)
1215 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore, rev2);
1216 else
1217 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore, rev1);
1219 else
1221 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore, rev2, rev1);
1224 BYTE_VECTOR out;
1225 if (Run(cmd, &out))
1226 return -1;
1228 outputlist.ParserFromLog(out);
1230 return 0;
1233 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1235 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1236 CString str;
1237 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1238 list->push_back(str);
1239 return 0;
1242 int CGit::GetTagList(STRING_VECTOR &list)
1244 if (this->m_IsUseLibGit2)
1246 CAutoRepository repo(GetGitRepository());
1247 if (!repo)
1248 return -1;
1250 CAutoStrArray tag_names;
1252 if (git_tag_list(tag_names, repo))
1253 return -1;
1255 for (size_t i = 0; i < tag_names->count; ++i)
1257 CStringA tagName(tag_names->strings[i]);
1258 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1261 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1263 return 0;
1265 else
1267 CString cmd, output;
1268 cmd=_T("git.exe tag -l");
1269 int ret = Run(cmd, &output, NULL, CP_UTF8);
1270 if(!ret)
1272 int pos=0;
1273 CString one;
1274 while( pos>=0 )
1276 one=output.Tokenize(_T("\n"),pos);
1277 if (!one.IsEmpty())
1278 list.push_back(one);
1280 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1282 return ret;
1286 CString CGit::GetGitLastErr(const CString& msg)
1288 if (this->m_IsUseLibGit2)
1289 return GetLibGit2LastErr(msg);
1290 else if (gitLastErr.IsEmpty())
1291 return msg + _T("\nUnknown git.exe error.");
1292 else
1294 CString lastError = gitLastErr;
1295 gitLastErr.Empty();
1296 return msg + _T("\n") + lastError;
1300 CString CGit::GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd)
1302 if (UsingLibGit2(cmd))
1303 return GetLibGit2LastErr(msg);
1304 else if (gitLastErr.IsEmpty())
1305 return msg + _T("\nUnknown git.exe error.");
1306 else
1308 CString lastError = gitLastErr;
1309 gitLastErr.Empty();
1310 return msg + _T("\n") + lastError;
1314 CString CGit::GetLibGit2LastErr()
1316 const git_error *libgit2err = giterr_last();
1317 if (libgit2err)
1319 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1320 giterr_clear();
1321 return _T("libgit2 returned: ") + lastError;
1323 else
1324 return _T("An error occoured in libgit2, but no message is available.");
1327 CString CGit::GetLibGit2LastErr(const CString& msg)
1329 if (!msg.IsEmpty())
1330 return msg + _T("\n") + GetLibGit2LastErr();
1331 return GetLibGit2LastErr();
1334 CString CGit::FixBranchName_Mod(CString& branchName)
1336 if(branchName == "FETCH_HEAD")
1337 branchName = DerefFetchHead();
1338 return branchName;
1341 CString CGit::FixBranchName(const CString& branchName)
1343 CString tempBranchName = branchName;
1344 FixBranchName_Mod(tempBranchName);
1345 return tempBranchName;
1348 bool CGit::IsBranchTagNameUnique(const CString& name)
1350 if (m_IsUseLibGit2)
1352 CAutoRepository repo(GetGitRepository());
1353 if (!repo)
1354 return true; // TODO: optimize error reporting
1356 CAutoReference tagRef;
1357 if (git_reference_lookup(tagRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/tags/" + name)))
1358 return true;
1360 CAutoReference branchRef;
1361 if (git_reference_lookup(branchRef.GetPointer(), repo, CUnicodeUtils::GetUTF8(L"refs/heads/" + name)))
1362 return true;
1364 return false;
1366 // else
1367 CString output;
1369 CString cmd;
1370 cmd.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1371 int ret = Run(cmd, &output, NULL, CP_UTF8);
1372 if (!ret)
1374 int i = 0, pos = 0;
1375 while (pos >= 0)
1377 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1378 ++i;
1380 if (i >= 2)
1381 return false;
1384 return true;
1387 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1389 if (m_IsUseLibGit2)
1391 CAutoRepository repo(GetGitRepository());
1392 if (!repo)
1393 return false; // TODO: optimize error reporting
1395 CString prefix;
1396 if (isBranch)
1397 prefix = _T("refs/heads/");
1398 else
1399 prefix = _T("refs/tags/");
1401 CAutoReference ref;
1402 if (git_reference_lookup(ref.GetPointer(), repo, CUnicodeUtils::GetUTF8(prefix + name)))
1403 return false;
1405 return true;
1407 // else
1408 CString cmd, output;
1410 cmd = _T("git.exe show-ref ");
1411 if (isBranch)
1412 cmd += _T("--heads ");
1413 else
1414 cmd += _T("--tags ");
1416 cmd += _T("refs/heads/") + name;
1417 cmd += _T(" refs/tags/") + name;
1419 int ret = Run(cmd, &output, NULL, CP_UTF8);
1420 if (!ret)
1422 if (!output.IsEmpty())
1423 return true;
1426 return false;
1429 CString CGit::DerefFetchHead()
1431 CString dotGitPath;
1432 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1433 std::ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), std::ios::in | std::ios::binary);
1434 int forMergeLineCount = 0;
1435 std::string line;
1436 std::string hashToReturn;
1437 while(getline(fetchHeadFile, line))
1439 //Tokenize this line
1440 std::string::size_type prevPos = 0;
1441 std::string::size_type pos = line.find('\t');
1442 if(pos == std::string::npos) continue; //invalid line
1444 std::string hash = line.substr(0, pos);
1445 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == std::string::npos) continue;
1447 bool forMerge = pos == prevPos;
1448 ++pos; prevPos = pos; pos = line.size(); if(pos == std::string::npos) continue;
1450 std::string remoteBranch = line.substr(prevPos, pos - prevPos);
1452 //Process this line
1453 if(forMerge)
1455 hashToReturn = hash;
1456 ++forMergeLineCount;
1457 if(forMergeLineCount > 1)
1458 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1462 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1465 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1467 int ret = 0;
1468 CString cur;
1469 if (m_IsUseLibGit2)
1471 CAutoRepository repo(GetGitRepository());
1472 if (!repo)
1473 return -1;
1475 if (git_repository_head_detached(repo) == 1)
1476 cur = _T("(detached from ");
1478 if ((type & (BRANCH_LOCAL | BRANCH_REMOTE)) != 0)
1480 git_branch_t flags = GIT_BRANCH_LOCAL;
1481 if ((type & BRANCH_LOCAL) && (type & BRANCH_REMOTE))
1482 flags = GIT_BRANCH_ALL;
1483 else if (type & BRANCH_REMOTE)
1484 flags = GIT_BRANCH_REMOTE;
1486 CAutoBranchIterator it;
1487 if (git_branch_iterator_new(it.GetPointer(), repo, flags))
1488 return -1;
1490 git_reference * ref = nullptr;
1491 git_branch_t branchType;
1492 while (git_branch_next(&ref, &branchType, it) == 0)
1494 CAutoReference autoRef(ref);
1495 const char * name = nullptr;
1496 if (git_branch_name(&name, ref))
1497 continue;
1499 CString branchname = CUnicodeUtils::GetUnicode(name);
1500 if (branchType & GIT_BRANCH_REMOTE)
1501 list.push_back(_T("remotes/") + branchname);
1502 else
1504 if (git_branch_is_head(ref))
1505 cur = branchname;
1506 list.push_back(branchname);
1511 else
1513 CString cmd, output;
1514 cmd = _T("git.exe branch --no-color");
1516 if ((type & BRANCH_ALL) == BRANCH_ALL)
1517 cmd += _T(" -a");
1518 else if (type & BRANCH_REMOTE)
1519 cmd += _T(" -r");
1521 ret = Run(cmd, &output, nullptr, CP_UTF8);
1522 if (!ret)
1524 int pos = 0;
1525 CString one;
1526 while (pos >= 0)
1528 one = output.Tokenize(_T("\n"), pos);
1529 one.Trim(L" \r\n\t");
1530 if (one.Find(L" -> ") >= 0 || one.IsEmpty())
1531 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1532 if (one[0] == _T('*'))
1534 one = one.Mid(2);
1535 cur = one;
1537 if (one.Left(10) != _T("(no branch") && one.Left(15) != _T("(detached from "))
1538 list.push_back(one);
1543 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1544 list.push_back(L"FETCH_HEAD");
1546 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1548 if (current && cur.Left(10) != _T("(no branch") && cur.Left(15) != _T("(detached from "))
1550 for (unsigned int i = 0; i < list.size(); ++i)
1552 if (list[i] == cur)
1554 *current = i;
1555 break;
1560 return ret;
1563 int CGit::GetRemoteList(STRING_VECTOR &list)
1565 if (this->m_IsUseLibGit2)
1567 CAutoRepository repo(GetGitRepository());
1568 if (!repo)
1569 return -1;
1571 CAutoStrArray remotes;
1572 if (git_remote_list(remotes, repo))
1573 return -1;
1575 for (size_t i = 0; i < remotes->count; ++i)
1577 CStringA remote(remotes->strings[i]);
1578 list.push_back(CUnicodeUtils::GetUnicode(remote));
1581 std::sort(list.begin(), list.end());
1583 return 0;
1585 else
1587 int ret;
1588 CString cmd, output;
1589 cmd=_T("git.exe remote");
1590 ret = Run(cmd, &output, NULL, CP_UTF8);
1591 if(!ret)
1593 int pos=0;
1594 CString one;
1595 while( pos>=0 )
1597 one=output.Tokenize(_T("\n"),pos);
1598 if (!one.IsEmpty())
1599 list.push_back(one);
1602 return ret;
1606 int CGit::GetRemoteTags(const CString& remote, STRING_VECTOR &list)
1608 CString cmd, out, err;
1609 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1610 if (Run(cmd, &out, &err, CP_UTF8))
1612 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1613 return -1;
1616 int pos = 0;
1617 while (pos >= 0)
1619 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1620 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1621 if (one.Find(_T("^{}")) >= 1)
1622 continue;
1623 if (!one.IsEmpty())
1624 list.push_back(one);
1626 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1627 return 0;
1630 int libgit2_addto_list_each_ref_fn(git_reference *ref, void *payload)
1632 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1633 CString str;
1634 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1635 list->push_back(str);
1636 return 0;
1639 int CGit::GetRefList(STRING_VECTOR &list)
1641 if (this->m_IsUseLibGit2)
1643 CAutoRepository repo(GetGitRepository());
1644 if (!repo)
1645 return -1;
1647 if (git_reference_foreach(repo, libgit2_addto_list_each_ref_fn, &list))
1648 return -1;
1650 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1652 return 0;
1654 else
1656 CString cmd, output;
1657 cmd=_T("git.exe show-ref -d");
1658 int ret = Run(cmd, &output, NULL, CP_UTF8);
1659 if(!ret)
1661 int pos=0;
1662 CString one;
1663 while( pos>=0 )
1665 one=output.Tokenize(_T("\n"),pos);
1666 int start=one.Find(_T(" "),0);
1667 if(start>0)
1669 CString name;
1670 name=one.Right(one.GetLength()-start-1);
1671 list.push_back(name);
1674 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1676 return ret;
1680 typedef struct map_each_ref_payload {
1681 git_repository * repo;
1682 MAP_HASH_NAME * map;
1683 } map_each_ref_payload;
1685 int libgit2_addto_map_each_ref_fn(git_reference *ref, void *payload)
1687 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1689 CString str;
1690 g_Git.StringAppend(&str, (BYTE*)git_reference_name(ref), CP_UTF8);
1692 CAutoObject gitObject;
1693 if (git_revparse_single(gitObject.GetPointer(), payloadContent->repo, git_reference_name(ref)))
1694 return 1;
1696 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1698 str += _T("^{}"); // deref tag
1699 CAutoObject derefedTag;
1700 if (git_object_peel(derefedTag.GetPointer(), gitObject, GIT_OBJ_ANY))
1701 return 1;
1702 gitObject.Swap(derefedTag);
1705 const git_oid * oid = git_object_id(gitObject);
1706 if (oid == NULL)
1707 return 1;
1709 CGitHash hash((char *)oid->id);
1710 (*payloadContent->map)[hash].push_back(str);
1712 return 0;
1714 int CGit::GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map)
1716 ATLASSERT(repo);
1718 map_each_ref_payload payloadContent = { repo, &map };
1720 if (git_reference_foreach(repo, libgit2_addto_map_each_ref_fn, &payloadContent))
1721 return -1;
1723 for (auto it = map.begin(); it != map.end(); ++it)
1725 std::sort(it->second.begin(), it->second.end());
1728 return 0;
1731 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1733 if (this->m_IsUseLibGit2)
1735 CAutoRepository repo(GetGitRepository());
1736 if (!repo)
1737 return -1;
1739 return GetMapHashToFriendName(repo, map);
1741 else
1743 CString cmd, output;
1744 cmd=_T("git.exe show-ref -d");
1745 int ret = Run(cmd, &output, NULL, CP_UTF8);
1746 if(!ret)
1748 int pos=0;
1749 CString one;
1750 while( pos>=0 )
1752 one=output.Tokenize(_T("\n"),pos);
1753 int start=one.Find(_T(" "),0);
1754 if(start>0)
1756 CString name;
1757 name=one.Right(one.GetLength()-start-1);
1759 CString hash;
1760 hash=one.Left(start);
1762 map[CGitHash(hash)].push_back(name);
1766 return ret;
1770 static void SetLibGit2SearchPath(int level, const CString &value)
1772 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1773 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH, level, valueA);
1776 static void SetLibGit2TemplatePath(const CString &value)
1778 CStringA valueA = CUnicodeUtils::GetMulti(value, CP_UTF8);
1779 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH, valueA);
1782 BOOL CGit::CheckMsysGitDir(BOOL bFallback)
1784 if (m_bInitialized)
1786 return TRUE;
1789 this->m_Environment.clear();
1790 m_Environment.CopyProcessEnvironment();
1792 TCHAR *oldpath;
1793 size_t homesize,size;
1795 // set HOME if not set already
1796 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1797 if (!homesize)
1798 m_Environment.SetEnv(_T("HOME"), GetHomeDirectory());
1800 //setup ssh client
1801 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1802 if (sshclient.IsEmpty())
1803 sshclient = CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE, HKEY_LOCAL_MACHINE);
1805 if(!sshclient.IsEmpty())
1807 m_Environment.SetEnv(_T("GIT_SSH"), sshclient);
1808 m_Environment.SetEnv(_T("SVN_SSH"), sshclient);
1810 else
1812 TCHAR sPlink[MAX_PATH] = {0};
1813 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1814 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1815 if (ptr) {
1816 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1817 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1818 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1823 TCHAR sAskPass[MAX_PATH] = {0};
1824 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1825 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1826 if (ptr)
1828 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1829 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1830 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1831 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1835 // add git/bin path to PATH
1837 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1838 CString str = msysdir;
1839 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1841 if (!bFallback)
1842 return FALSE;
1844 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1845 str = msyslocalinstalldir;
1846 str.TrimRight(_T("\\"));
1847 if (str.IsEmpty())
1849 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1850 str = msysinstalldir;
1851 str.TrimRight(_T("\\"));
1853 if ( !str.IsEmpty() )
1855 str += "\\bin";
1856 msysdir=str;
1857 CGit::ms_LastMsysGitDir = str;
1858 msysdir.write();
1860 else
1862 // search PATH if git/bin directory is already present
1863 if ( FindGitPath() )
1865 m_bInitialized = TRUE;
1866 msysdir = CGit::ms_LastMsysGitDir;
1867 msysdir.write();
1868 return TRUE;
1871 return FALSE;
1874 else
1876 CGit::ms_LastMsysGitDir = str;
1879 // check for git.exe existance (maybe it was deinstalled in the meantime)
1880 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1881 return FALSE;
1883 // Configure libgit2 search paths
1884 CString msysGitDir;
1885 PathCanonicalize(msysGitDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\etc"));
1886 msysGitDir.ReleaseBuffer();
1887 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM, msysGitDir);
1888 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL, g_Git.GetHomeDirectory());
1889 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG, g_Git.GetGitGlobalXDGConfigPath());
1890 CString msysGitTemplateDir;
1891 PathCanonicalize(msysGitTemplateDir.GetBufferSetLength(MAX_PATH), CGit::ms_LastMsysGitDir + _T("\\..\\share\\git-core\\templates"));
1892 msysGitTemplateDir.ReleaseBuffer();
1893 SetLibGit2TemplatePath(msysGitTemplateDir);
1895 //set path
1896 _tdupenv_s(&oldpath,&size,_T("PATH"));
1898 CString path;
1899 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1901 m_Environment.SetEnv(_T("PATH"), path);
1903 CString str1 = m_Environment.GetEnv(_T("PATH"));
1905 CString sOldPath = oldpath;
1906 free(oldpath);
1908 m_bInitialized = TRUE;
1909 return true;
1912 CString CGit::GetHomeDirectory() const
1914 const wchar_t * homeDir = wget_windows_home_directory();
1915 return CString(homeDir, (int)wcslen(homeDir));
1918 CString CGit::GetGitLocalConfig() const
1920 CString path;
1921 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, path);
1922 path += _T("config");
1923 return path;
1926 CStringA CGit::GetGitPathStringA(const CString &path)
1928 return CUnicodeUtils::GetUTF8(CTGitPath(path).GetGitPathString());
1931 CString CGit::GetGitGlobalConfig() const
1933 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1936 CString CGit::GetGitGlobalXDGConfigPath() const
1938 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1941 CString CGit::GetGitGlobalXDGConfig() const
1943 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1946 CString CGit::GetGitSystemConfig() const
1948 const wchar_t * systemConfig = wget_msysgit_etc();
1949 return CString(systemConfig, (int)wcslen(systemConfig));
1952 BOOL CGit::CheckCleanWorkTree()
1954 CString out;
1955 CString cmd;
1956 cmd=_T("git.exe rev-parse --verify HEAD");
1958 if(Run(cmd,&out,CP_UTF8))
1959 return FALSE;
1961 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1962 if(Run(cmd,&out,CP_UTF8))
1963 return FALSE;
1965 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1966 if(Run(cmd,&out,CP_UTF8))
1967 return FALSE;
1969 cmd = _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1970 if(Run(cmd,&out,CP_UTF8))
1971 return FALSE;
1973 return TRUE;
1975 int CGit::Revert(const CString& commit, const CTGitPathList &list, bool)
1977 int ret;
1978 for (int i = 0; i < list.GetCount(); ++i)
1980 ret = Revert(commit, (CTGitPath&)list[i]);
1981 if(ret)
1982 return ret;
1984 return 0;
1986 int CGit::Revert(const CString& commit, const CTGitPath &path)
1988 CString cmd, out;
1990 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1992 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1994 CString err;
1995 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1996 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1997 return -1;
1999 CString force;
2000 // if the filenames only differ in case, we have to pass "-f"
2001 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
2002 force = _T("-f ");
2003 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
2004 if (Run(cmd, &out, CP_UTF8))
2006 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2007 return -1;
2010 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
2011 if (Run(cmd, &out, CP_UTF8))
2013 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2014 return -1;
2018 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
2019 { //To init git repository, there are not HEAD, so we can use git reset command
2020 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
2022 if (Run(cmd, &out, CP_UTF8))
2024 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2025 return -1;
2028 else
2030 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
2031 if (Run(cmd, &out, CP_UTF8))
2033 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2034 return -1;
2038 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
2040 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
2041 if (Run(cmd, &out, CP_UTF8))
2043 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
2044 return -1;
2048 return 0;
2051 int CGit::ListConflictFile(CTGitPathList &list, const CTGitPath *path)
2053 BYTE_VECTOR vector;
2055 CString cmd;
2056 if(path)
2057 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
2058 else
2059 cmd=_T("git.exe ls-files -u -t -z");
2061 if (Run(cmd, &vector))
2063 return -1;
2066 if (list.ParserFromLsFile(vector))
2067 return -1;
2069 return 0;
2072 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
2074 if (UsingLibGit2(GIT_CMD_MERGE_BASE))
2076 CAutoRepository repo(GetGitRepository());
2077 if (!repo)
2078 return false;
2080 CGitHash fromHash, toHash, baseHash;
2081 if (GetHash(repo, toHash, FixBranchName(to)))
2082 return false;
2084 if (GetHash(repo, fromHash, FixBranchName(from)))
2085 return false;
2087 git_oid baseOid;
2088 if (git_merge_base(&baseOid, repo, (const git_oid*)toHash.m_hash, (const git_oid*)fromHash.m_hash))
2089 return false;
2091 baseHash = baseOid.id;
2093 if (commonAncestor)
2094 *commonAncestor = baseHash;
2096 return fromHash == baseHash;
2098 // else
2099 CString base;
2100 CGitHash basehash,hash;
2101 CString cmd, err;
2102 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
2104 if (Run(cmd, &base, &err, CP_UTF8))
2106 return false;
2108 basehash = base.Trim();
2110 GetHash(hash, from);
2112 if (commonAncestor)
2113 *commonAncestor = basehash;
2115 return hash == basehash;
2118 unsigned int CGit::Hash2int(const CGitHash &hash)
2120 int ret=0;
2121 for (int i = 0; i < 4; ++i)
2123 ret = ret << 8;
2124 ret |= hash.m_hash[i];
2126 return ret;
2129 int CGit::RefreshGitIndex()
2131 if(g_Git.m_IsUseGitDLL)
2133 CAutoLocker lock(g_Git.m_critGitDllSec);
2136 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2138 }catch(...)
2140 return -1;
2144 else
2146 CString cmd,output;
2147 cmd=_T("git.exe update-index --refresh");
2148 return Run(cmd, &output, CP_UTF8);
2152 int CGit::GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile)
2154 if (UsingLibGit2(GIT_CMD_GETONEFILE))
2156 CAutoRepository repo(GetGitRepository());
2157 if (!repo)
2158 return -1;
2160 CGitHash hash;
2161 if (GetHash(repo, hash, Refname))
2162 return -1;
2164 CAutoCommit commit;
2165 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2166 return -1;
2168 CAutoTree tree;
2169 if (git_commit_tree(tree.GetPointer(), commit))
2170 return -1;
2172 CAutoTreeEntry entry;
2173 if (git_tree_entry_bypath(entry.GetPointer(), tree, CUnicodeUtils::GetUTF8(path.GetGitPathString())))
2174 return -1;
2176 CAutoBlob blob;
2177 if (git_tree_entry_to_object((git_object**)blob.GetPointer(), repo, entry))
2178 return -1;
2180 FILE *file = nullptr;
2181 _tfopen_s(&file, outputfile, _T("w"));
2182 if (file == nullptr)
2184 giterr_set_str(GITERR_NONE, "Could not create file.");
2185 return -1;
2187 CAutoBuf buf;
2188 if (git_blob_filtered_content(buf, blob, CUnicodeUtils::GetUTF8(path.GetGitPathString()), 0))
2190 fclose(file);
2191 return -1;
2193 if (fwrite(buf->ptr, sizeof(char), buf->size, file) != buf->size)
2195 giterr_set_str(GITERR_OS, "Could not write to file.");
2196 fclose(file);
2198 return -1;
2200 fclose(file);
2202 return 0;
2204 else if (g_Git.m_IsUseGitDLL)
2206 CAutoLocker lock(g_Git.m_critGitDllSec);
2209 g_Git.CheckAndInitDll();
2210 CStringA ref, patha, outa;
2211 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
2212 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2213 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
2214 ::DeleteFile(outputfile);
2215 return git_checkout_file(ref, patha, outa);
2218 catch (const char * msg)
2220 gitLastErr = L"gitdll.dll reports: " + CString(msg);
2221 return -1;
2223 catch (...)
2225 gitLastErr = L"An unknown gitdll.dll error occurred.";
2226 return -1;
2229 else
2231 CString cmd;
2232 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
2233 return RunLogFile(cmd, outputfile, &gitLastErr);
2236 void CEnvironment::CopyProcessEnvironment()
2238 TCHAR *porig = GetEnvironmentStrings();
2239 TCHAR *p = porig;
2240 while(*p !=0 || *(p+1) !=0)
2241 this->push_back(*p++);
2243 push_back(_T('\0'));
2244 push_back(_T('\0'));
2246 FreeEnvironmentStrings(porig);
2249 CString CEnvironment::GetEnv(const TCHAR *name)
2251 CString str;
2252 for (size_t i = 0; i < size(); ++i)
2254 str = &(*this)[i];
2255 int start =0;
2256 CString sname = str.Tokenize(_T("="),start);
2257 if(sname.CompareNoCase(name) == 0)
2259 return &(*this)[i+start];
2261 i+=str.GetLength();
2263 return _T("");
2266 void CEnvironment::SetEnv(const TCHAR *name, const TCHAR* value)
2268 unsigned int i;
2269 for (i = 0; i < size(); ++i)
2271 CString str = &(*this)[i];
2272 int start =0;
2273 CString sname = str.Tokenize(_T("="),start);
2274 if(sname.CompareNoCase(name) == 0)
2276 break;
2278 i+=str.GetLength();
2281 if(i == size())
2283 i -= 1; // roll back terminate \0\0
2284 this->push_back(_T('\0'));
2287 CEnvironment::iterator it;
2288 it=this->begin();
2289 it += i;
2291 while(*it && i<size())
2293 this->erase(it);
2294 it=this->begin();
2295 it += i;
2298 while(*name)
2300 this->insert(it,*name++);
2301 ++i;
2302 it= begin()+i;
2305 this->insert(it, _T('='));
2306 ++i;
2307 it= begin()+i;
2309 while(*value)
2311 this->insert(it,*value++);
2312 ++i;
2313 it= begin()+i;
2318 int CGit::GetGitEncode(TCHAR* configkey)
2320 CString str=GetConfigValue(configkey);
2322 if(str.IsEmpty())
2323 return CP_UTF8;
2325 return CUnicodeUtils::GetCPCode(str);
2329 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2331 GIT_FILE file=0;
2332 int ret=0;
2333 GIT_DIFF diff=0;
2335 CAutoLocker lock(g_Git.m_critGitDllSec);
2337 if(arg == NULL)
2338 diff = GetGitDiff();
2339 else
2340 git_open_diff(&diff, arg);
2342 if(diff ==NULL)
2343 return -1;
2345 bool isStat = 0;
2346 if(arg == NULL)
2347 isStat = true;
2348 else
2349 isStat = !!strstr(arg, "stat");
2351 int count=0;
2353 if(hash2 == NULL)
2354 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2355 else
2356 ret = git_do_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2358 if(ret)
2359 return -1;
2361 CTGitPath path;
2362 CString strnewname;
2363 CString stroldname;
2365 for (int j = 0; j < count; ++j)
2367 path.Reset();
2368 char *newname;
2369 char *oldname;
2371 strnewname.Empty();
2372 stroldname.Empty();
2374 int mode=0,IsBin=0,inc=0,dec=0;
2375 git_get_diff_file(diff,file,j,&newname,&oldname,
2376 &mode,&IsBin,&inc,&dec);
2378 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2379 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2381 path.SetFromGit(strnewname,&stroldname);
2382 path.ParserAction((BYTE)mode);
2384 if(IsBin)
2386 path.m_StatAdd=_T("-");
2387 path.m_StatDel=_T("-");
2389 else
2391 path.m_StatAdd.Format(_T("%d"),inc);
2392 path.m_StatDel.Format(_T("%d"),dec);
2394 PathList->AddPath(path);
2396 git_diff_flush(diff);
2398 if(arg)
2399 git_close_diff(diff);
2401 return 0;
2404 int CGit::GetShortHASHLength() const
2406 return 7;
2409 CString CGit::GetShortName(const CString& ref, REF_TYPE *out_type)
2411 CString str=ref;
2412 CString shortname;
2413 REF_TYPE type = CGit::UNKNOWN;
2415 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2417 type = CGit::LOCAL_BRANCH;
2420 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2422 type = CGit::REMOTE_BRANCH;
2424 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2426 type = CGit::TAG;
2428 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2430 type = CGit::STASH;
2431 shortname=_T("stash");
2433 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2435 if (shortname.Find(_T("good")) == 0)
2437 type = CGit::BISECT_GOOD;
2438 shortname = _T("good");
2441 if (shortname.Find(_T("bad")) == 0)
2443 type = CGit::BISECT_BAD;
2444 shortname = _T("bad");
2447 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2449 type = CGit::NOTES;
2451 else if (CGit::GetShortName(str, shortname, _T("refs/")))
2453 type = CGit::UNKNOWN;
2455 else
2457 type = CGit::UNKNOWN;
2458 shortname = ref;
2461 if(out_type)
2462 *out_type = type;
2464 return shortname;
2467 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd) const
2469 return m_IsUseLibGit2 && ((1 << cmd) & m_IsUseLibGit2_mask) ? true : false;
2472 CString CGit::GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext)
2474 CString cmd;
2475 if (rev2 == GitRev::GetWorkingCopy())
2476 cmd.Format(_T("git.exe diff --stat -p %s --"), rev1);
2477 else if (rev1 == GitRev::GetWorkingCopy())
2478 cmd.Format(_T("git.exe diff -R --stat -p %s --"), rev2);
2479 else
2481 CString merge;
2482 if (bMerge)
2483 merge += _T(" -m");
2485 if (bCombine)
2486 merge += _T(" -c");
2488 CString unified;
2489 if (diffContext > 0)
2490 unified.Format(_T(" --unified=%d"), diffContext);
2491 cmd.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge, unified, rev1, rev2);
2494 if (!path.IsEmpty())
2496 cmd += _T(" \"");
2497 cmd += path.GetGitPathString();
2498 cmd += _T("\"");
2501 return cmd;
2504 static int UnifiedDiffToFile(const git_diff_delta * /* delta */, const git_diff_hunk * /* hunk */, const git_diff_line * line, void *payload)
2506 ATLASSERT(payload && line);
2507 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2508 fwrite(&line->origin, 1, 1, (FILE *)payload);
2509 fwrite(line->content, 1, line->content_len, (FILE *)payload);
2510 return 0;
2513 static int resolve_to_tree(git_repository *repo, const char *identifier, git_tree **tree)
2515 ATLASSERT(repo && identifier && tree);
2517 /* try to resolve identifier */
2518 CAutoObject obj;
2519 if (git_revparse_single(obj.GetPointer(), repo, identifier))
2520 return -1;
2522 if (obj == nullptr)
2523 return GIT_ENOTFOUND;
2525 int err = 0;
2526 switch (git_object_type(obj))
2528 case GIT_OBJ_TREE:
2529 *tree = (git_tree *)obj.Detach();
2530 break;
2531 case GIT_OBJ_COMMIT:
2532 err = git_commit_tree(tree, (git_commit *)(git_object*)obj);
2533 break;
2534 default:
2535 err = GIT_ENOTFOUND;
2538 return err;
2541 /* use libgit2 get unified diff */
2542 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 */)
2544 CStringA tree1 = CUnicodeUtils::GetMulti(revNew, CP_UTF8);
2545 CStringA tree2 = CUnicodeUtils::GetMulti(revOld, CP_UTF8);
2547 CAutoRepository repo(g_Git.GetGitRepository());
2548 if (!repo)
2549 return -1;
2551 int isHeadOrphan = git_repository_head_unborn(repo);
2552 if (isHeadOrphan == 1)
2553 return 0;
2554 else if (isHeadOrphan != 0)
2555 return -1;
2557 git_diff_options opts = GIT_DIFF_OPTIONS_INIT;
2558 CStringA pathA = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
2559 char *buf = pathA.GetBuffer();
2560 if (!pathA.IsEmpty())
2562 opts.pathspec.strings = &buf;
2563 opts.pathspec.count = 1;
2565 CAutoDiff diff;
2567 if (revNew == GitRev::GetWorkingCopy() || revOld == GitRev::GetWorkingCopy())
2569 CAutoTree t1;
2570 CAutoDiff diff2;
2572 if (revNew != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2573 return -1;
2575 if (revOld != GitRev::GetWorkingCopy() && resolve_to_tree(repo, tree2, t1.GetPointer()))
2576 return -1;
2578 if (git_diff_tree_to_index(diff.GetPointer(), repo, t1, nullptr, &opts))
2579 return -1;
2581 if (git_diff_index_to_workdir(diff2.GetPointer(), repo, nullptr, &opts))
2582 return -1;
2584 if (git_diff_merge(diff, diff2))
2585 return -1;
2587 else
2589 if (tree1.IsEmpty() && tree2.IsEmpty())
2590 return -1;
2592 if (tree1.IsEmpty())
2594 tree1 = tree2;
2595 tree2.Empty();
2598 CAutoTree t1;
2599 CAutoTree t2;
2600 if (!tree1.IsEmpty() && resolve_to_tree(repo, tree1, t1.GetPointer()))
2601 return -1;
2603 if (tree2.IsEmpty())
2605 /* don't check return value, there are not parent commit at first commit*/
2606 resolve_to_tree(repo, tree1 + "~1", t2.GetPointer());
2608 else if (resolve_to_tree(repo, tree2, t2.GetPointer()))
2609 return -1;
2610 if (git_diff_tree_to_tree(diff.GetPointer(), repo, t2, t1, &opts))
2611 return -1;
2614 for (size_t i = 0; i < git_diff_num_deltas(diff); ++i)
2616 CAutoPatch patch;
2617 if (git_patch_from_diff(patch.GetPointer(), diff, i))
2618 return -1;
2620 if (git_patch_print(patch, callback, data))
2621 return -1;
2624 pathA.ReleaseBuffer();
2626 return 0;
2629 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext)
2631 if (UsingLibGit2(GIT_CMD_DIFF))
2633 FILE *file = nullptr;
2634 _tfopen_s(&file, patchfile, _T("w"));
2635 if (file == nullptr)
2636 return -1;
2637 int ret = GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToFile, file, bMerge);
2638 fclose(file);
2639 return ret;
2641 else
2643 CString cmd;
2644 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2645 return RunLogFile(cmd, patchfile, &gitLastErr);
2649 static int UnifiedDiffToStringA(const git_diff_delta * /*delta*/, const git_diff_hunk * /*hunk*/, const git_diff_line *line, void *payload)
2651 ATLASSERT(payload && line);
2652 CStringA *str = (CStringA*) payload;
2653 if (line->origin == GIT_DIFF_LINE_CONTEXT || line->origin == GIT_DIFF_LINE_ADDITION || line->origin == GIT_DIFF_LINE_DELETION)
2654 str->Append(&line->origin, 1);
2655 str->Append(line->content, (int)line->content_len);
2656 return 0;
2659 int CGit::GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext)
2661 if (UsingLibGit2(GIT_CMD_DIFF))
2662 return GetUnifiedDiffLibGit2(path, rev1, rev2, UnifiedDiffToStringA, buffer, bMerge);
2663 else
2665 CString cmd;
2666 cmd = GetUnifiedDiffCmd(path, rev1, rev2, bMerge, bCombine, diffContext);
2667 BYTE_VECTOR vector;
2668 int ret = Run(cmd, &vector);
2669 if (!vector.empty())
2671 vector.push_back(0); // vector is not NUL terminated
2672 buffer->Append((char *)&vector[0]);
2674 return ret;
2678 int CGit::GitRevert(int parent, const CGitHash &hash)
2680 if (UsingLibGit2(GIT_CMD_REVERT))
2682 CAutoRepository repo(GetGitRepository());
2683 if (!repo)
2684 return -1;
2686 CAutoCommit commit;
2687 if (git_commit_lookup(commit.GetPointer(), repo, (const git_oid *)hash.m_hash))
2688 return -1;
2690 git_revert_options revert_opts = GIT_REVERT_OPTIONS_INIT;
2691 revert_opts.mainline = parent;
2692 int result = git_revert(repo, commit, &revert_opts);
2694 return !result ? 0 : -1;
2696 else
2698 CString cmd, merge;
2699 if (parent)
2700 merge.Format(_T("-m %d "), parent);
2701 cmd.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge, hash.ToString());
2702 gitLastErr = cmd + _T("\n");
2703 if (Run(cmd, &gitLastErr, CP_UTF8))
2705 return -1;
2707 else
2709 gitLastErr.Empty();
2710 return 0;
2715 int CGit::DeleteRef(const CString& reference)
2717 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH))
2719 CAutoRepository repo(GetGitRepository());
2720 if (!repo)
2721 return -1;
2723 CStringA refA;
2724 if (reference.Right(3) == _T("^{}"))
2725 refA = CUnicodeUtils::GetUTF8(reference.Left(reference.GetLength() - 3));
2726 else
2727 refA = CUnicodeUtils::GetUTF8(reference);
2729 CAutoReference ref;
2730 if (git_reference_lookup(ref.GetPointer(), repo, refA))
2731 return -1;
2733 int result = -1;
2734 if (git_reference_is_tag(ref))
2735 result = git_tag_delete(repo, git_reference_shorthand(ref));
2736 else if (git_reference_is_branch(ref))
2737 result = git_branch_delete(ref);
2738 else if (git_reference_is_remote(ref))
2739 result = git_branch_delete(ref);
2740 else
2741 giterr_set_str(GITERR_REFERENCE, CUnicodeUtils::GetUTF8(L"unsupported reference type: " + reference));
2743 return result;
2745 else
2747 CString cmd, shortname;
2748 if (GetShortName(reference, shortname, _T("refs/heads/")))
2749 cmd.Format(_T("git.exe branch -D -- %s"), shortname);
2750 else if (GetShortName(reference, shortname, _T("refs/tags/")))
2751 cmd.Format(_T("git.exe tag -d -- %s"), shortname);
2752 else if (GetShortName(reference, shortname, _T("refs/remotes/")))
2753 cmd.Format(_T("git.exe branch -r -D -- %s"), shortname);
2754 else
2756 gitLastErr = L"unsupported reference type: " + reference;
2757 return -1;
2760 if (Run(cmd, &gitLastErr, CP_UTF8))
2761 return -1;
2763 gitLastErr.Empty();
2764 return 0;
2768 bool CGit::LoadTextFile(const CString &filename, CString &msg)
2770 if (PathFileExists(filename))
2772 FILE *pFile = nullptr;
2773 _tfopen_s(&pFile, filename, _T("r"));
2774 if (pFile)
2776 CStringA str;
2779 char s[8196] = { 0 };
2780 int read = (int)fread(s, sizeof(char), sizeof(s), pFile);
2781 if (read == 0)
2782 break;
2783 str += CStringA(s, read);
2784 } while (true);
2785 fclose(pFile);
2786 msg = CUnicodeUtils::GetUnicode(str);
2787 msg.Replace(_T("\r\n"), _T("\n"));
2788 msg.TrimRight(_T("\n"));
2789 msg += _T("\n");
2791 else
2792 ::MessageBox(nullptr, _T("Could not open ") + filename, _T("TortoiseGit"), MB_ICONERROR);
2793 return true; // load no further files
2795 return false;