Can dynamically set show/hide checkboxes in GitStatusListCtrl
[TortoiseGit.git] / src / Git / Git.cpp
blob65771a77a530bd92aab03917bcbaf318d09fbd16
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2013 - 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 "atlconv.h"
23 #include "GitRev.h"
24 #include "registry.h"
25 #include "GitConfig.h"
26 #include <map>
27 #include "UnicodeUtils.h"
28 #include "gitdll.h"
29 #include <fstream>
30 #include "git2.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];
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\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER);
122 if (g_bSortLocalBranchesFirst)
123 g_bSortLocalBranchesFirst = !CRegDWORD(L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE);
126 static int LogicalComparePredicate(CString &left, CString &right)
128 if (g_bSortLogical)
129 return StrCmpLogicalW(left, right) < 0;
130 return StrCmpI(left, right) < 0;
133 static int LogicalCompareBranchesPredicate(CString &left, 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 MAX_DIRBUFFER 1000
151 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
153 CString CGit::ms_LastMsysGitDir;
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 GetSortOptions();
169 this->m_bInitialized =false;
170 CheckMsysGitDir();
171 m_critGitDllSec.Init();
174 CGit::~CGit(void)
176 if(this->m_GitDiff)
178 git_close_diff(m_GitDiff);
179 m_GitDiff=0;
181 if(this->m_GitSimpleListDiff)
183 git_close_diff(m_GitSimpleListDiff);
184 m_GitSimpleListDiff=0;
188 bool CGit::IsBranchNameValid(CString branchname)
190 if (branchname.IsEmpty())
191 return false;
193 for (int i = 0; i < branchname.GetLength(); ++i)
195 TCHAR c = branchname.GetAt(i);
196 if (c <= ' ' || c == '~' || c == '^' || c == ':' || c == '\\' || c == '?' || c == '[')
197 return false;
200 if (branchname.Find(L".") == 0 || branchname.Find(L"/.") >= 0 || branchname.Find(L"..") >= 0 || branchname.Find(L"@{") >= 0 || branchname.ReverseFind('*') >= 0)
201 return false;
203 CString reverseBranchname = branchname.MakeReverse();
204 if (branchname.Find(L'.') == 0 || branchname.Find(L'/') == 0 || reverseBranchname.Find(L"kcol.") >= 0)
205 return false;
207 return true;
210 static char g_Buffer[4096];
212 int CGit::RunAsync(CString cmd, PROCESS_INFORMATION *piOut, HANDLE *hReadOut, HANDLE *hErrReadOut, CString *StdioFile)
214 SECURITY_ATTRIBUTES sa;
215 HANDLE hRead, hWrite, hReadErr = NULL, hWriteErr = NULL;
216 HANDLE hStdioFile = NULL;
218 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
219 sa.lpSecurityDescriptor=NULL;
220 sa.bInheritHandle=TRUE;
221 if(!CreatePipe(&hRead,&hWrite,&sa,0))
223 return TGIT_GIT_ERROR_OPEN_PIP;
225 if (hErrReadOut && !CreatePipe(&hReadErr, &hWriteErr, &sa, 0))
226 return TGIT_GIT_ERROR_OPEN_PIP;
228 if(StdioFile)
230 hStdioFile=CreateFile(*StdioFile,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
231 &sa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
234 STARTUPINFO si;
235 PROCESS_INFORMATION pi;
236 si.cb=sizeof(STARTUPINFO);
237 GetStartupInfo(&si);
239 if (hErrReadOut)
240 si.hStdError = hWriteErr;
241 else
242 si.hStdError = hWrite;
243 if(StdioFile)
244 si.hStdOutput=hStdioFile;
245 else
246 si.hStdOutput=hWrite;
248 si.wShowWindow=SW_HIDE;
249 si.dwFlags=STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
251 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
252 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
254 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
255 dwFlags |= DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP;
257 memset(&this->m_CurrentGitPi,0,sizeof(PROCESS_INFORMATION));
258 memset(&pi, 0, sizeof(PROCESS_INFORMATION));
260 if(cmd.Find(_T("git")) == 0)
262 int firstSpace = cmd.Find(_T(" "));
263 if (firstSpace > 0)
264 cmd = _T('"')+CGit::ms_LastMsysGitDir+_T("\\")+ cmd.Left(firstSpace) + _T('"')+ cmd.Mid(firstSpace);
265 else
266 cmd=_T('"')+CGit::ms_LastMsysGitDir+_T("\\")+cmd+_T('"');
269 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
271 LPVOID lpMsgBuf;
272 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
273 NULL,GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
274 (LPTSTR)&lpMsgBuf,
275 0,NULL);
276 return TGIT_GIT_ERROR_CREATE_PROCESS;
279 m_CurrentGitPi = pi;
281 CloseHandle(hWrite);
282 if (hErrReadOut)
283 CloseHandle(hWriteErr);
284 if(piOut)
285 *piOut=pi;
286 if(hReadOut)
287 *hReadOut=hRead;
288 if(hErrReadOut)
289 *hErrReadOut = hReadErr;
290 return 0;
293 //Must use sperate function to convert ANSI str to union code string
294 //Becuase A2W use stack as internal convert buffer.
295 void CGit::StringAppend(CString *str,BYTE *p,int code,int length)
297 //USES_CONVERSION;
298 //str->Append(A2W_CP((LPCSTR)p,code));
299 if(str == NULL)
300 return ;
302 WCHAR * buf;
304 int len ;
305 if(length<0)
306 len = (int)strlen((const char*)p);
307 else
308 len=length;
309 //if (len==0)
310 // return ;
311 //buf = new WCHAR[len*4 + 1];
312 buf = str->GetBuffer(len*4+1+str->GetLength())+str->GetLength();
313 SecureZeroMemory(buf, (len*4 + 1)*sizeof(WCHAR));
314 MultiByteToWideChar(code, 0, (LPCSTR)p, len, buf, len*4);
315 str->ReleaseBuffer();
316 //str->Append(buf);
317 //delete buf;
320 BOOL CGit::IsOrphanBranch(CString ref)
322 if (ref.IsEmpty())
323 ref = _T("HEAD");
325 CString cmdout;
326 if (Run(_T("git.exe rev-parse --revs-only ") + ref, &cmdout, CP_UTF8))
328 return TRUE;
330 if(cmdout.IsEmpty())
331 return TRUE;
333 return FALSE;
336 BOOL CGit::IsInitRepos()
338 return IsOrphanBranch(_T("HEAD"));
341 DWORD WINAPI CGit::AsyncReadStdErrThread(LPVOID lpParam)
343 PASYNCREADSTDERRTHREADARGS pDataArray;
344 pDataArray = (PASYNCREADSTDERRTHREADARGS)lpParam;
346 DWORD readnumber;
347 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
348 while (ReadFile(pDataArray->fileHandle, data, CALL_OUTPUT_READ_CHUNK_SIZE, &readnumber, NULL))
350 if (pDataArray->pcall->OnOutputErrData(data,readnumber))
351 break;
354 return 0;
357 int CGit::Run(CGitCall* pcall)
359 PROCESS_INFORMATION pi;
360 HANDLE hRead, hReadErr;
361 if(RunAsync(pcall->GetCmd(),&pi,&hRead, &hReadErr))
362 return TGIT_GIT_ERROR_CREATE_PROCESS;
364 HANDLE thread;
365 ASYNCREADSTDERRTHREADARGS threadArguments;
366 threadArguments.fileHandle = hReadErr;
367 threadArguments.pcall = pcall;
368 thread = CreateThread(NULL, 0, AsyncReadStdErrThread, &threadArguments, 0, NULL);
370 DWORD readnumber;
371 BYTE data[CALL_OUTPUT_READ_CHUNK_SIZE];
372 bool bAborted=false;
373 while(ReadFile(hRead,data,CALL_OUTPUT_READ_CHUNK_SIZE,&readnumber,NULL))
375 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
376 if(!bAborted)//For now, flush output when command aborted.
377 if(pcall->OnOutputData(data,readnumber))
378 bAborted=true;
380 if(!bAborted)
381 pcall->OnEnd();
383 if (thread)
384 WaitForSingleObject(thread, INFINITE);
386 CloseHandle(pi.hThread);
388 WaitForSingleObject(pi.hProcess, INFINITE);
389 DWORD exitcode =0;
391 if(!GetExitCodeProcess(pi.hProcess,&exitcode))
393 return TGIT_GIT_ERROR_GET_EXIT_CODE;
396 CloseHandle(pi.hProcess);
398 CloseHandle(hRead);
399 CloseHandle(hReadErr);
400 return exitcode;
402 class CGitCall_ByteVector : public CGitCall
404 public:
405 CGitCall_ByteVector(CString cmd,BYTE_VECTOR* pvector, BYTE_VECTOR* pvectorErr = NULL):CGitCall(cmd),m_pvector(pvector),m_pvectorErr(pvectorErr){}
406 virtual bool OnOutputData(const BYTE* data, size_t size)
408 if (size == 0)
409 return false;
410 size_t oldsize=m_pvector->size();
411 m_pvector->resize(m_pvector->size()+size);
412 memcpy(&*(m_pvector->begin()+oldsize),data,size);
413 return false;
415 virtual bool OnOutputErrData(const BYTE* data, size_t size)
417 if (!m_pvectorErr || size == 0)
418 return false;
419 size_t oldsize = m_pvectorErr->size();
420 m_pvectorErr->resize(m_pvectorErr->size() + size);
421 memcpy(&*(m_pvectorErr->begin() + oldsize), data, size);
422 return false;
424 BYTE_VECTOR* m_pvector;
425 BYTE_VECTOR* m_pvectorErr;
428 int CGit::Run(CString cmd,BYTE_VECTOR *vector, BYTE_VECTOR *vectorErr)
430 CGitCall_ByteVector call(cmd, vector, vectorErr);
431 return Run(&call);
433 int CGit::Run(CString cmd, CString* output, int code)
435 CString err;
436 int ret;
437 ret = Run(cmd, output, &err, code);
439 if (output && !err.IsEmpty())
441 if (!output->IsEmpty())
442 *output += _T("\n");
443 *output += err;
446 return ret;
448 int CGit::Run(CString cmd, CString* output, CString* outputErr, int code)
450 BYTE_VECTOR vector, vectorErr;
451 int ret;
452 if (outputErr)
453 ret = Run(cmd, &vector, &vectorErr);
454 else
455 ret = Run(cmd, &vector);
457 vector.push_back(0);
458 StringAppend(output, &(vector[0]), code);
460 if (outputErr)
462 vectorErr.push_back(0);
463 StringAppend(outputErr, &(vectorErr[0]), code);
466 return ret;
469 CString CGit::GetUserName(void)
471 CEnvironment env;
472 env.CopyProcessEnvironment();
473 CString envname = env.GetEnv(_T("GIT_AUTHOR_NAME"));
474 if (!envname.IsEmpty())
475 return envname;
476 return GetConfigValue(L"user.name", this->GetGitEncode(L"i18n.commitencoding"));
478 CString CGit::GetUserEmail(void)
480 CEnvironment env;
481 env.CopyProcessEnvironment();
482 CString envmail = env.GetEnv(_T("GIT_AUTHOR_EMAIL"));
483 if (!envmail.IsEmpty())
484 return envmail;
486 return GetConfigValue(L"user.email");
489 CString CGit::GetConfigValue(CString name,int encoding, CString *GitPath, BOOL RemoveCR)
491 CString configValue;
492 int start = 0;
493 if(this->m_IsUseGitDLL)
495 CString *git_path=NULL;
497 CAutoLocker lock(g_Git.m_critGitDllSec);
501 CTGitPath path;
503 CheckAndInitDll();
504 git_path = GitPath;
506 }catch(...)
509 CStringA key, value;
510 key = CUnicodeUtils::GetMulti(name, encoding);
511 CStringA p;
512 if(git_path)
513 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
515 if(git_get_config(key.GetBuffer(), value.GetBufferSetLength(4096), 4096, p.GetBuffer()))
516 return CString();
517 else
519 StringAppend(&configValue,(BYTE*)value.GetBuffer(),encoding);
520 if(RemoveCR)
521 return configValue.Tokenize(_T("\n"),start);
522 return configValue;
526 else
528 CString cmd;
529 cmd.Format(L"git.exe config %s", name);
530 Run(cmd, &configValue, NULL, encoding);
531 if(RemoveCR)
532 return configValue.Tokenize(_T("\n"),start);
533 return configValue;
537 int CGit::SetConfigValue(CString key, CString value, CONFIG_TYPE type, int encoding, CString *GitPath)
539 if(this->m_IsUseGitDLL)
541 CAutoLocker lock(g_Git.m_critGitDllSec);
545 CheckAndInitDll();
547 }catch(...)
550 CStringA keya, valuea;
551 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
552 valuea = CUnicodeUtils::GetMulti(value, encoding);
553 CStringA p;
554 if(GitPath)
555 p = CUnicodeUtils::GetMulti(*GitPath, CP_UTF8);
557 return get_set_config(keya.GetBuffer(), valuea.GetBuffer(), type, p.GetBuffer());
560 else
562 CString cmd;
563 CString option;
564 switch(type)
566 case CONFIG_GLOBAL:
567 option = _T("--global");
568 break;
569 case CONFIG_SYSTEM:
570 option = _T("--system");
571 break;
572 default:
573 break;
575 cmd.Format(_T("git.exe config %s %s \"%s\""), option, key, value);
576 CString out;
577 if (Run(cmd, &out, NULL, encoding))
579 return -1;
582 return 0;
585 int CGit::UnsetConfigValue(CString key, CONFIG_TYPE type, int encoding, CString *GitPath)
587 if(this->m_IsUseGitDLL)
589 CAutoLocker lock(g_Git.m_critGitDllSec);
593 CheckAndInitDll();
594 }catch(...)
597 CStringA keya;
598 keya = CUnicodeUtils::GetMulti(key, CP_UTF8);
599 CStringA p;
600 if(GitPath)
601 p=CUnicodeUtils::GetMulti(*GitPath,CP_ACP);
603 return get_set_config(keya.GetBuffer(), NULL, type, p.GetBuffer());
605 else
607 CString cmd;
608 CString option;
609 switch(type)
611 case CONFIG_GLOBAL:
612 option = _T("--global");
613 break;
614 case CONFIG_SYSTEM:
615 option = _T("--system");
616 break;
617 default:
618 break;
620 cmd.Format(_T("git.exe config %s --unset %s"), option, key);
621 CString out;
622 if (Run(cmd, &out, NULL, encoding))
624 return -1;
627 return 0;
630 CString CGit::GetCurrentBranch(void)
632 CString output;
633 //Run(_T("git.exe branch"),&branch);
635 if(this->GetCurrentBranchFromFile(this->m_CurrentDir,output))
637 return _T("(no branch)");
639 else
640 return output;
644 CString CGit::GetSymbolicRef(const wchar_t* symbolicRefName, bool bStripRefsHeads)
646 CString refName;
647 if(this->m_IsUseGitDLL)
649 unsigned char sha1[20];
650 int flag;
652 CAutoLocker lock(g_Git.m_critGitDllSec);
653 const char *refs_heads_master = git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName)), sha1, 0, &flag);
654 if(refs_heads_master && (flag&REF_ISSYMREF))
656 StringAppend(&refName,(BYTE*)refs_heads_master);
657 if(bStripRefsHeads)
658 refName = StripRefName(refName);
662 else
664 CString cmd;
665 cmd.Format(L"git symbolic-ref %s", symbolicRefName);
666 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
667 return CString();//Error
668 int iStart = 0;
669 refName = refName.Tokenize(L"\n", iStart);
670 if(bStripRefsHeads)
671 refName = StripRefName(refName);
673 return refName;
676 CString CGit::GetFullRefName(CString shortRefName)
678 CString refName;
679 CString cmd;
680 cmd.Format(L"git rev-parse --symbolic-full-name %s", shortRefName);
681 if (Run(cmd, &refName, NULL, CP_UTF8) != 0)
682 return CString();//Error
683 int iStart = 0;
684 return refName.Tokenize(L"\n", iStart);
687 CString CGit::StripRefName(CString refName)
689 if(wcsncmp(refName, L"refs/heads/", 11) == 0)
690 refName = refName.Mid(11);
691 else if(wcsncmp(refName, L"refs/", 5) == 0)
692 refName = refName.Mid(5);
693 int start =0;
694 return refName.Tokenize(_T("\n"),start);
697 int CGit::GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut)
699 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
701 if ( sProjectRoot.IsEmpty() )
702 return -1;
704 CString sDotGitPath;
705 if (!g_GitAdminDir.GetAdminDirPath(sProjectRoot, sDotGitPath))
706 return -1;
708 CString sHeadFile = sDotGitPath + _T("HEAD");
710 FILE *pFile;
711 _tfopen_s(&pFile, sHeadFile.GetString(), _T("r"));
713 if (!pFile)
715 return -1;
718 char s[256] = {0};
719 fgets(s, sizeof(s), pFile);
721 fclose(pFile);
723 const char *pfx = "ref: refs/heads/";
724 const int len = 16;//strlen(pfx)
726 if ( !strncmp(s, pfx, len) )
728 //# We're on a branch. It might not exist. But
729 //# HEAD looks good enough to be a branch.
730 CStringA utf8Branch(s + len);
731 sBranchOut = CUnicodeUtils::GetUnicode(utf8Branch);
732 sBranchOut.TrimRight(_T(" \r\n\t"));
734 if ( sBranchOut.IsEmpty() )
735 return -1;
737 else
739 //# Assume this is a detached head.
740 sBranchOut = "HEAD";
742 return 1;
745 return 0;
748 int CGit::BuildOutputFormat(CString &format,bool IsFull)
750 CString log;
751 log.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN);
752 format += log;
753 if(IsFull)
755 log.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME);
756 format += log;
757 log.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL);
758 format += log;
759 log.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE);
760 format += log;
761 log.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME);
762 format += log;
763 log.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL);
764 format += log;
765 log.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE);
766 format += log;
767 log.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY);
768 format += log;
771 log.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH);
772 format += log;
773 log.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT);
774 format += log;
775 log.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT);
776 format += log;
778 if(IsFull)
780 log.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE);
781 format += log;
783 return 0;
786 int CGit::GetLog(BYTE_VECTOR& logOut, const CString &hash, CTGitPath *path ,int count,int mask,CString *from,CString *to)
788 CGitCall_ByteVector gitCall(CString(), &logOut, NULL);
789 return GetLog(&gitCall,hash,path,count,mask,from,to);
792 CString CGit::GetLogCmd( const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to,bool paramonly,
793 CFilterData *Filter)
795 CString cmd;
796 CString num;
797 CString since;
799 CString file;
801 if(path)
802 file.Format(_T(" -- \"%s\""),path->GetGitPathString());
804 if(count>0)
805 num.Format(_T("-n%d"),count);
807 CString param;
809 if(mask& LOG_INFO_STAT )
810 param += _T(" --numstat ");
811 if(mask& LOG_INFO_FILESTATE)
812 param += _T(" --raw ");
814 if(mask& LOG_INFO_FULLHISTORY)
815 param += _T(" --full-history ");
817 if(mask& LOG_INFO_BOUNDARY)
818 param += _T(" --left-right --boundary ");
820 if(mask& CGit::LOG_INFO_ALL_BRANCH)
821 param += _T(" --all ");
823 if(mask& CGit::LOG_INFO_DETECT_COPYRENAME)
824 param += _T(" -C ");
826 if(mask& CGit::LOG_INFO_DETECT_RENAME )
827 param += _T(" -M ");
829 if(mask& CGit::LOG_INFO_FIRST_PARENT )
830 param += _T(" --first-parent ");
832 if(mask& CGit::LOG_INFO_NO_MERGE )
833 param += _T(" --no-merges ");
835 if(mask& CGit::LOG_INFO_FOLLOW)
836 param += _T(" --follow ");
838 if(mask& CGit::LOG_INFO_SHOW_MERGEDFILE)
839 param += _T(" -c ");
841 if(mask& CGit::LOG_INFO_FULL_DIFF)
842 param += _T(" --full-diff ");
844 if(mask& CGit::LOG_INFO_SIMPILFY_BY_DECORATION)
845 param += _T(" --simplify-by-decoration ");
847 if(from != NULL && to != NULL)
849 CString range;
850 range.Format(_T(" %s..%s "),FixBranchName(*from),FixBranchName(*to));
851 param += range;
853 else if(to != NULL && hash.IsEmpty())
855 CString range;
856 range.Format(_T(" %s "), FixBranchName(*to));
857 param += range;
859 param+=hash;
861 CString st1,st2;
863 if( Filter && (Filter->m_From != -1))
865 st1.Format(_T(" --max-age=%I64u "), Filter->m_From);
866 param += st1;
869 if( Filter && (Filter->m_To != -1))
871 st2.Format(_T(" --min-age=%I64u "), Filter->m_To);
872 param += st2;
875 bool isgrep = false;
876 if( Filter && (!Filter->m_Author.IsEmpty()))
878 st1.Format(_T(" --author=\"%s\"" ),Filter->m_Author);
879 param += st1;
880 isgrep = true;
883 if( Filter && (!Filter->m_Committer.IsEmpty()))
885 st1.Format(_T(" --committer=\"%s\"" ),Filter->m_Author);
886 param += st1;
887 isgrep = true;
890 if( Filter && (!Filter->m_MessageFilter.IsEmpty()))
892 st1.Format(_T(" --grep=\"%s\"" ),Filter->m_MessageFilter);
893 param += st1;
894 isgrep = true;
897 if(Filter && isgrep)
899 if(!Filter->m_IsRegex)
900 param += _T(" --fixed-strings ");
902 param += _T(" --regexp-ignore-case --extended-regexp ");
905 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE))
906 param += _T(" --topo-order");
908 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
909 cmd.Format(_T("--ignore-this-parameter %s -z %s --parents "), num, param);
910 else
912 CString log;
913 BuildOutputFormat(log,!(mask&CGit::LOG_INFO_ONLY_HASH));
914 cmd.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
915 num,param,log);
918 cmd += file;
920 return cmd;
922 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
923 int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path, int count, int mask,CString *from,CString *to)
925 pgitCall->SetCmd( GetLogCmd(hash,path,count,mask,from,to) );
927 return Run(pgitCall);
928 // return Run(cmd,&logOut);
931 #define BUFSIZE 512
932 void GetTempPath(CString &path)
934 TCHAR lpPathBuffer[BUFSIZE];
935 DWORD dwRetVal;
936 DWORD dwBufSize=BUFSIZE;
937 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
938 lpPathBuffer); // buffer for path
939 if (dwRetVal > dwBufSize || (dwRetVal == 0))
941 path=_T("");
943 path.Format(_T("%s"),lpPathBuffer);
945 CString GetTempFile()
947 TCHAR lpPathBuffer[BUFSIZE];
948 DWORD dwRetVal;
949 DWORD dwBufSize=BUFSIZE;
950 TCHAR szTempName[BUFSIZE];
951 UINT uRetVal;
953 dwRetVal = GetTortoiseGitTempPath(dwBufSize, // length of the buffer
954 lpPathBuffer); // buffer for path
955 if (dwRetVal > dwBufSize || (dwRetVal == 0))
957 return _T("");
959 // Create a temporary file.
960 uRetVal = GetTempFileName(lpPathBuffer, // directory for tmp files
961 TEXT("Patch"), // temp file name prefix
962 0, // create unique name
963 szTempName); // buffer for name
966 if (uRetVal == 0)
968 return _T("");
971 return CString(szTempName);
975 DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer)
977 DWORD result = ::GetTempPath(nBufferLength, lpBuffer);
978 if (result == 0) return 0;
979 if (lpBuffer == NULL || (result + 13 > nBufferLength))
981 if (lpBuffer)
982 lpBuffer[0] = '\0';
983 return result + 13;
986 _tcscat(lpBuffer, _T("TortoiseGit\\"));
987 CreateDirectory(lpBuffer, NULL);
989 return result + 13;
992 int CGit::RunLogFile(CString cmd,const CString &filename)
994 STARTUPINFO si;
995 PROCESS_INFORMATION pi;
996 si.cb=sizeof(STARTUPINFO);
997 GetStartupInfo(&si);
999 SECURITY_ATTRIBUTES psa={sizeof(psa),NULL,TRUE};;
1000 psa.bInheritHandle=TRUE;
1002 HANDLE houtfile=CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ | FILE_SHARE_WRITE,
1003 &psa,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
1005 si.wShowWindow = SW_HIDE;
1006 si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
1007 si.hStdOutput = houtfile;
1009 LPTSTR pEnv = (!m_Environment.empty()) ? &m_Environment[0]: NULL;
1010 DWORD dwFlags = pEnv ? CREATE_UNICODE_ENVIRONMENT : 0;
1012 if(cmd.Find(_T("git")) == 0)
1013 cmd=CGit::ms_LastMsysGitDir+_T("\\")+cmd;
1015 if(!CreateProcess(NULL,(LPWSTR)cmd.GetString(), NULL,NULL,TRUE,dwFlags,pEnv,(LPWSTR)m_CurrentDir.GetString(),&si,&pi))
1017 LPVOID lpMsgBuf;
1018 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,
1019 NULL,GetLastError(),MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
1020 (LPTSTR)&lpMsgBuf,
1021 0,NULL);
1022 return TGIT_GIT_ERROR_CREATE_PROCESS;
1025 WaitForSingleObject(pi.hProcess,INFINITE);
1027 CloseHandle(pi.hThread);
1028 CloseHandle(pi.hProcess);
1029 CloseHandle(houtfile);
1030 return TGIT_GIT_SUCCESS;
1031 // return 0;
1034 int CGit::GetHash(CGitHash &hash, TCHAR* friendname)
1036 // no need to parse a ref if it's already a 40-byte hash
1037 if (CGitHash::IsValidSHA1(friendname))
1039 CString sHash(friendname);
1040 hash = CGitHash(sHash);
1041 return 0;
1044 if (m_IsUseLibGit2)
1046 git_repository *repo = NULL;
1047 CStringA gitdirA = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1048 if (git_repository_open(&repo, gitdirA.GetBuffer()))
1050 gitdirA.ReleaseBuffer();
1051 return -1;
1053 gitdirA.ReleaseBuffer();
1055 int isHeadOrphan = git_repository_head_orphan(repo);
1056 if (isHeadOrphan != 0)
1058 git_repository_free(repo);
1059 hash.Empty();
1060 if (isHeadOrphan == 1)
1061 return 0;
1062 else
1063 return -1;
1066 CStringA refnameA = CUnicodeUtils::GetMulti(friendname, CP_UTF8);
1068 git_object * gitObject = NULL;
1069 if (git_revparse_single(&gitObject, repo, refnameA.GetBuffer()))
1071 refnameA.ReleaseBuffer();
1072 git_repository_free(repo);
1073 return -1;
1075 refnameA.ReleaseBuffer();
1077 const git_oid * oid = git_object_id(gitObject);
1078 if (oid == NULL)
1080 git_object_free(gitObject);
1081 git_repository_free(repo);
1082 return -1;
1085 hash = CGitHash((char *)oid->id);
1087 git_object_free(gitObject); // also frees oid
1088 git_repository_free(repo);
1090 return 0;
1092 else
1094 CString cmd;
1095 cmd.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname));
1096 int ret = Run(cmd, &gitLastErr, NULL, CP_UTF8);
1097 hash = CGitHash(gitLastErr.Trim());
1098 return ret;
1102 int CGit::GetInitAddList(CTGitPathList &outputlist)
1104 CString cmd;
1105 BYTE_VECTOR cmdout;
1107 cmd=_T("git.exe ls-files -s -t -z");
1108 outputlist.Clear();
1109 if (Run(cmd, &cmdout))
1110 return -1;
1112 outputlist.ParserFromLsFile(cmdout);
1113 for(int i = 0; i < outputlist.GetCount(); ++i)
1114 const_cast<CTGitPath&>(outputlist[i]).m_Action = CTGitPath::LOGACTIONS_ADDED;
1116 return 0;
1118 int CGit::GetCommitDiffList(const CString &rev1,const CString &rev2,CTGitPathList &outputlist)
1120 CString cmd;
1122 if(rev1 == GIT_REV_ZERO || rev2 == GIT_REV_ZERO)
1124 //rev1=+_T("");
1125 if(rev1 == GIT_REV_ZERO)
1126 cmd.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2);
1127 else
1128 cmd.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1);
1130 else
1132 cmd.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2,rev1);
1135 BYTE_VECTOR out;
1136 if (Run(cmd, &out))
1137 return -1;
1139 outputlist.ParserFromLog(out);
1141 return 0;
1144 int addto_list_each_ref_fn(const char *refname, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data)
1146 STRING_VECTOR *list = (STRING_VECTOR*)cb_data;
1147 CString str;
1148 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1149 list->push_back(str);
1150 return 0;
1153 int CGit::GetTagList(STRING_VECTOR &list)
1155 if (this->m_IsUseLibGit2)
1157 git_repository *repo = NULL;
1159 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1160 if (git_repository_open(&repo, gitdir.GetBuffer()))
1162 gitdir.ReleaseBuffer();
1163 return -1;
1165 gitdir.ReleaseBuffer();
1167 git_strarray tag_names;
1169 if (git_tag_list(&tag_names, repo))
1171 git_repository_free(repo);
1172 return -1;
1175 for (size_t i = 0; i < tag_names.count; ++i)
1177 CStringA tagName(tag_names.strings[i]);
1178 list.push_back(CUnicodeUtils::GetUnicode(tagName));
1181 git_strarray_free(&tag_names);
1183 git_repository_free(repo);
1185 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1187 return 0;
1189 else
1191 CString cmd, output;
1192 cmd=_T("git.exe tag -l");
1193 int ret = Run(cmd, &output, NULL, CP_UTF8);
1194 if(!ret)
1196 int pos=0;
1197 CString one;
1198 while( pos>=0 )
1200 one=output.Tokenize(_T("\n"),pos);
1201 if (!one.IsEmpty())
1202 list.push_back(one);
1204 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1206 return ret;
1210 CString CGit::GetGitLastErr(CString msg)
1212 if (this->m_IsUseLibGit2)
1214 const git_error *libgit2err = giterr_last();
1215 if (libgit2err)
1217 CString lastError = CUnicodeUtils::GetUnicode(CStringA(libgit2err->message));
1218 giterr_clear();
1219 return msg + _T("\nlibgit2 returned: ") + lastError;
1221 else
1223 return msg + _T("\nUnknown libgit2 error.");
1226 else if (gitLastErr.IsEmpty())
1227 return msg + _T("\nUnknown git.exe error.");
1228 else
1230 CString lastError = gitLastErr;
1231 gitLastErr.Empty();
1232 return msg + _T("\n") + lastError;
1236 CString CGit::FixBranchName_Mod(CString& branchName)
1238 if(branchName == "FETCH_HEAD")
1239 branchName = DerefFetchHead();
1240 return branchName;
1243 CString CGit::FixBranchName(const CString& branchName)
1245 CString tempBranchName = branchName;
1246 FixBranchName_Mod(tempBranchName);
1247 return tempBranchName;
1250 bool CGit::IsBranchTagNameUnique(const CString& name)
1252 CString output;
1254 CString cmd;
1255 cmd.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name, name);
1256 int ret = Run(cmd, &output, NULL, CP_UTF8);
1257 if (!ret)
1259 int i = 0, pos = 0;
1260 while (pos >= 0)
1262 if (!output.Tokenize(_T("\n"), pos).IsEmpty())
1263 ++i;
1265 if (i >= 2)
1266 return false;
1269 return true;
1273 Checks if a branch or tag with the given name exists
1274 isBranch is true -> branch, tag otherwise
1276 bool CGit::BranchTagExists(const CString& name, bool isBranch /*= true*/)
1278 CString cmd, output;
1280 cmd = _T("git show-ref ");
1281 if (isBranch)
1282 cmd += _T("--heads ");
1283 else
1284 cmd += _T("--tags ");
1286 cmd += _T("refs/heads/") + name;
1287 cmd += _T(" refs/tags/") + name;
1289 int ret = Run(cmd, &output, NULL, CP_UTF8);
1290 if (!ret)
1292 if (!output.IsEmpty())
1293 return true;
1296 return false;
1299 CString CGit::DerefFetchHead()
1301 using namespace std;
1302 CString dotGitPath;
1303 g_GitAdminDir.GetAdminDirPath(m_CurrentDir, dotGitPath);
1304 ifstream fetchHeadFile((dotGitPath + L"FETCH_HEAD").GetString(), ios::in | ios::binary);
1305 int forMergeLineCount = 0;
1306 string line;
1307 string hashToReturn;
1308 while(getline(fetchHeadFile, line))
1310 //Tokenize this line
1311 string::size_type prevPos = 0;
1312 string::size_type pos = line.find('\t');
1313 if(pos == string::npos) continue; //invalid line
1315 string hash = line.substr(0, pos);
1316 ++pos; prevPos = pos; pos = line.find('\t', pos); if(pos == string::npos) continue;
1318 bool forMerge = pos == prevPos;
1319 ++pos; prevPos = pos; pos = line.size(); if(pos == string::npos) continue;
1321 string remoteBranch = line.substr(prevPos, pos - prevPos);
1323 //Process this line
1324 if(forMerge)
1326 hashToReturn = hash;
1327 ++forMergeLineCount;
1328 if(forMergeLineCount > 1)
1329 return L""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1333 return CUnicodeUtils::GetUnicode(hashToReturn.c_str());
1336 int CGit::GetBranchList(STRING_VECTOR &list,int *current,BRANCH_TYPE type)
1338 int ret;
1339 CString cmd, output, cur;
1340 cmd = _T("git.exe branch --no-color");
1342 if((type&BRANCH_ALL) == BRANCH_ALL)
1343 cmd += _T(" -a");
1344 else if(type&BRANCH_REMOTE)
1345 cmd += _T(" -r");
1347 ret = Run(cmd, &output, NULL, CP_UTF8);
1348 if(!ret)
1350 int pos=0;
1351 CString one;
1352 while( pos>=0 )
1354 one=output.Tokenize(_T("\n"),pos);
1355 one.Trim(L" \r\n\t");
1356 if(one.Find(L" -> ") >= 0 || one.IsEmpty())
1357 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1358 if(one[0] == _T('*'))
1360 one = one.Mid(2);
1361 cur = one;
1363 if (one != _T("(no branch)"))
1364 list.push_back(one);
1368 if(type & BRANCH_FETCH_HEAD && !DerefFetchHead().IsEmpty())
1369 list.push_back(L"FETCH_HEAD");
1371 std::sort(list.begin(), list.end(), LogicalCompareBranchesPredicate);
1373 if (current && cur != _T("(no branch)"))
1375 for (unsigned int i = 0; i < list.size(); ++i)
1377 if (list[i] == cur)
1379 *current = i;
1380 break;
1385 return ret;
1388 int CGit::GetRemoteList(STRING_VECTOR &list)
1390 if (this->m_IsUseLibGit2)
1392 git_repository *repo = NULL;
1394 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1395 if (git_repository_open(&repo, gitdir.GetBuffer()))
1397 gitdir.ReleaseBuffer();
1398 return -1;
1400 gitdir.ReleaseBuffer();
1402 git_strarray remotes;
1404 if (git_remote_list(&remotes, repo))
1406 git_repository_free(repo);
1407 return -1;
1410 for (size_t i = 0; i < remotes.count; ++i)
1412 CStringA remote(remotes.strings[i]);
1413 list.push_back(CUnicodeUtils::GetUnicode(remote));
1416 git_strarray_free(&remotes);
1418 git_repository_free(repo);
1420 std::sort(list.begin(), list.end());
1422 return 0;
1424 else
1426 int ret;
1427 CString cmd, output;
1428 cmd=_T("git.exe remote");
1429 ret = Run(cmd, &output, NULL, CP_UTF8);
1430 if(!ret)
1432 int pos=0;
1433 CString one;
1434 while( pos>=0 )
1436 one=output.Tokenize(_T("\n"),pos);
1437 if (!one.IsEmpty())
1438 list.push_back(one);
1441 return ret;
1445 int CGit::GetRemoteTags(CString remote, STRING_VECTOR &list)
1447 CString cmd, out, err;
1448 cmd.Format(_T("git.exe ls-remote -t \"%s\""), remote);
1449 if (Run(cmd, &out, &err, CP_UTF8))
1451 MessageBox(NULL, err, _T("TortoiseGit"), MB_ICONERROR);
1452 return -1;
1455 int pos = 0;
1456 while (pos >= 0)
1458 CString one = out.Tokenize(_T("\n"), pos).Mid(51).Trim(); // sha1, tab + refs/tags/
1459 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1460 if (one.Find(_T("^{}")) >= 1)
1461 continue;
1462 if (!one.IsEmpty())
1463 list.push_back(one);
1465 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1466 return 0;
1469 int libgit2_addto_list_each_ref_fn(const char *refname, void *payload)
1471 STRING_VECTOR *list = (STRING_VECTOR*)payload;
1472 CString str;
1473 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1474 list->push_back(str);
1475 return 0;
1478 int CGit::GetRefList(STRING_VECTOR &list)
1480 if (this->m_IsUseLibGit2)
1482 git_repository *repo = NULL;
1484 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1485 if (git_repository_open(&repo, gitdir.GetBuffer()))
1487 gitdir.ReleaseBuffer();
1488 return -1;
1490 gitdir.ReleaseBuffer();
1492 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_list_each_ref_fn, &list))
1494 git_repository_free(repo);
1495 return -1;
1498 git_repository_free(repo);
1500 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1502 return 0;
1504 else
1506 CString cmd, output;
1507 cmd=_T("git.exe show-ref -d");
1508 int ret = Run(cmd, &output, NULL, CP_UTF8);
1509 if(!ret)
1511 int pos=0;
1512 CString one;
1513 while( pos>=0 )
1515 one=output.Tokenize(_T("\n"),pos);
1516 int start=one.Find(_T(" "),0);
1517 if(start>0)
1519 CString name;
1520 name=one.Right(one.GetLength()-start-1);
1521 list.push_back(name);
1524 std::sort(list.begin(), list.end(), LogicalComparePredicate);
1526 return ret;
1530 typedef struct map_each_ref_payload {
1531 git_repository * repo;
1532 MAP_HASH_NAME * map;
1533 } map_each_ref_payload;
1535 int libgit2_addto_map_each_ref_fn(const char *refname, void *payload)
1537 map_each_ref_payload *payloadContent = (map_each_ref_payload*)payload;
1539 CString str;
1540 g_Git.StringAppend(&str, (BYTE*)refname, CP_UTF8);
1542 git_object * gitObject = NULL;
1546 if (git_revparse_single(&gitObject, payloadContent->repo, refname))
1548 break;
1551 if (git_object_type(gitObject) == GIT_OBJ_TAG)
1553 str += _T("^{}"); // deref tag
1554 git_object * derefedTag = NULL;
1555 if (git_object_peel(&derefedTag, gitObject, GIT_OBJ_ANY))
1557 break;
1559 git_object_free(gitObject);
1560 gitObject = derefedTag;
1563 const git_oid * oid = git_object_id(gitObject);
1564 if (oid == NULL)
1566 break;
1569 CGitHash hash((char *)oid->id);
1570 (*payloadContent->map)[hash].push_back(str);
1571 } while (false);
1573 if (gitObject)
1575 git_object_free(gitObject);
1576 return 0;
1579 return 1;
1582 int CGit::GetMapHashToFriendName(MAP_HASH_NAME &map)
1584 if (this->m_IsUseLibGit2)
1586 git_repository *repo = NULL;
1588 CStringA gitdir = CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir).GetGitPathString(), CP_UTF8);
1589 if (git_repository_open(&repo, gitdir.GetBuffer()))
1591 gitdir.ReleaseBuffer();
1592 return -1;
1594 gitdir.ReleaseBuffer();
1596 map_each_ref_payload payloadContent = { repo, &map };
1598 if (git_reference_foreach(repo, GIT_REF_LISTALL, libgit2_addto_map_each_ref_fn, &payloadContent))
1600 git_repository_free(repo);
1601 return -1;
1604 git_repository_free(repo);
1606 for (auto it = map.begin(); it != map.end(); ++it)
1608 std::sort(it->second.begin(), it->second.end());
1611 return 0;
1613 else
1615 CString cmd, output;
1616 cmd=_T("git.exe show-ref -d");
1617 int ret = Run(cmd, &output, NULL, CP_UTF8);
1618 if(!ret)
1620 int pos=0;
1621 CString one;
1622 while( pos>=0 )
1624 one=output.Tokenize(_T("\n"),pos);
1625 int start=one.Find(_T(" "),0);
1626 if(start>0)
1628 CString name;
1629 name=one.Right(one.GetLength()-start-1);
1631 CString hash;
1632 hash=one.Left(start);
1634 map[CGitHash(hash)].push_back(name);
1638 return ret;
1642 BOOL CGit::CheckMsysGitDir()
1644 if (m_bInitialized)
1646 return TRUE;
1649 this->m_Environment.clear();
1650 m_Environment.CopyProcessEnvironment();
1652 TCHAR *oldpath;
1653 size_t homesize,size;
1655 // set HOME if not set already
1656 _tgetenv_s(&homesize, NULL, 0, _T("HOME"));
1657 if (!homesize)
1659 CString home = GetHomeDirectory();
1660 m_Environment.SetEnv(_T("HOME"), home.GetBuffer());
1661 home.ReleaseBuffer();
1663 CString str;
1665 //setup ssh client
1666 CString sshclient=CRegString(_T("Software\\TortoiseGit\\SSH"));
1668 if(!sshclient.IsEmpty())
1670 m_Environment.SetEnv(_T("GIT_SSH"), sshclient.GetBuffer());
1671 m_Environment.SetEnv(_T("SVN_SSH"), sshclient.GetBuffer());
1673 else
1675 TCHAR sPlink[MAX_PATH];
1676 GetModuleFileName(NULL, sPlink, _countof(sPlink));
1677 LPTSTR ptr = _tcsrchr(sPlink, _T('\\'));
1678 if (ptr) {
1679 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sPlink + 1), _T("TortoiseGitPLink.exe"));
1680 m_Environment.SetEnv(_T("GIT_SSH"), sPlink);
1681 m_Environment.SetEnv(_T("SVN_SSH"), sPlink);
1686 TCHAR sAskPass[MAX_PATH];
1687 GetModuleFileName(NULL, sAskPass, _countof(sAskPass));
1688 LPTSTR ptr = _tcsrchr(sAskPass, _T('\\'));
1689 if (ptr)
1691 _tcscpy_s(ptr + 1, MAX_PATH - (ptr - sAskPass + 1), _T("SshAskPass.exe"));
1692 m_Environment.SetEnv(_T("DISPLAY"),_T(":9999"));
1693 m_Environment.SetEnv(_T("SSH_ASKPASS"),sAskPass);
1694 m_Environment.SetEnv(_T("GIT_ASKPASS"),sAskPass);
1698 // add git/bin path to PATH
1700 CRegString msysdir=CRegString(REG_MSYSGIT_PATH,_T(""),FALSE);
1701 str=msysdir;
1702 if(str.IsEmpty() || !FileExists(str + _T("\\git.exe")))
1704 CRegString msyslocalinstalldir = CRegString(REG_MSYSGIT_INSTALL_LOCAL, _T(""), FALSE, HKEY_CURRENT_USER);
1705 str = msyslocalinstalldir;
1706 str.TrimRight(_T("\\"));
1707 if (str.IsEmpty())
1709 CRegString msysinstalldir = CRegString(REG_MSYSGIT_INSTALL, _T(""), FALSE, HKEY_LOCAL_MACHINE);
1710 str = msysinstalldir;
1711 str.TrimRight(_T("\\"));
1713 if ( !str.IsEmpty() )
1715 str += "\\bin";
1716 msysdir=str;
1717 CGit::ms_LastMsysGitDir = str;
1718 msysdir.write();
1720 else
1722 // search PATH if git/bin directory is already present
1723 if ( FindGitPath() )
1725 m_bInitialized = TRUE;
1726 msysdir = CGit::ms_LastMsysGitDir;
1727 msysdir.write();
1728 return TRUE;
1731 return FALSE;
1734 else
1736 CGit::ms_LastMsysGitDir = str;
1739 // check for git.exe existance (maybe it was deinstalled in the meantime)
1740 if (!FileExists(CGit::ms_LastMsysGitDir + _T("\\git.exe")))
1741 return FALSE;
1743 //set path
1744 _tdupenv_s(&oldpath,&size,_T("PATH"));
1746 CString path;
1747 path.Format(_T("%s;%s"),oldpath,str + _T(";")+ (CString)CRegString(REG_MSYSGIT_EXTRA_PATH,_T(""),FALSE));
1749 m_Environment.SetEnv(_T("PATH"),path.GetBuffer());
1751 CString str1 = m_Environment.GetEnv(_T("PATH"));
1753 CString sOldPath = oldpath;
1754 free(oldpath);
1756 m_bInitialized = TRUE;
1757 return true;
1760 CString CGit::GetHomeDirectory()
1762 const wchar_t * homeDir = wget_windows_home_directory();
1763 return CString(homeDir, (int)wcslen(homeDir));
1766 CString CGit::GetGitLocalConfig()
1768 CString path;
1769 g_GitAdminDir.GetAdminDirPath(g_Git.m_CurrentDir, path);
1770 path += _T("config");
1771 return path;
1774 CString CGit::GetGitGlobalConfig()
1776 return g_Git.GetHomeDirectory() + _T("\\.gitconfig");
1779 CString CGit::GetGitGlobalXDGConfigPath()
1781 return g_Git.GetHomeDirectory() + _T("\\.config\\git");
1784 CString CGit::GetGitGlobalXDGConfig()
1786 return g_Git.GetGitGlobalXDGConfigPath() + _T("\\config");
1789 CString CGit::GetGitSystemConfig()
1791 const wchar_t * systemConfig = wget_msysgit_etc();
1792 return CString(systemConfig, (int)wcslen(systemConfig));
1795 BOOL CGit::CheckCleanWorkTree()
1797 CString out;
1798 CString cmd;
1799 cmd=_T("git.exe rev-parse --verify HEAD");
1801 if(Run(cmd,&out,CP_UTF8))
1802 return FALSE;
1804 cmd=_T("git.exe update-index --ignore-submodules --refresh");
1805 if(Run(cmd,&out,CP_UTF8))
1806 return FALSE;
1808 cmd=_T("git.exe diff-files --quiet --ignore-submodules");
1809 if(Run(cmd,&out,CP_UTF8))
1810 return FALSE;
1812 cmd=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1813 if(Run(cmd,&out,CP_UTF8))
1814 return FALSE;
1816 return TRUE;
1818 int CGit::Revert(CString commit, CTGitPathList &list, bool)
1820 int ret;
1821 for (int i = 0; i < list.GetCount(); ++i)
1823 ret = Revert(commit, (CTGitPath&)list[i]);
1824 if(ret)
1825 return ret;
1827 return 0;
1829 int CGit::Revert(CString commit, CTGitPath &path)
1831 CString cmd, out;
1833 if(path.m_Action & CTGitPath::LOGACTIONS_REPLACED && !path.GetGitOldPathString().IsEmpty())
1835 if (CTGitPath(path.GetGitOldPathString()).IsDirectory())
1837 CString err;
1838 err.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path.GetGitPathString(), path.GetGitOldPathString());
1839 ::MessageBox(NULL, err, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1840 return -1;
1842 CString force;
1843 // if the filenames only differ in case, we have to pass "-f"
1844 if (path.GetGitPathString().CompareNoCase(path.GetGitOldPathString()) == 0)
1845 force = _T("-f ");
1846 cmd.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force, path.GetGitPathString(), path.GetGitOldPathString());
1847 if (Run(cmd, &out, CP_UTF8))
1849 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1850 return -1;
1853 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitOldPathString());
1854 if (Run(cmd, &out, CP_UTF8))
1856 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1857 return -1;
1861 else if(path.m_Action & CTGitPath::LOGACTIONS_ADDED)
1862 { //To init git repository, there are not HEAD, so we can use git reset command
1863 cmd.Format(_T("git.exe rm -f --cached -- \"%s\""),path.GetGitPathString());
1865 if (Run(cmd, &out, CP_UTF8))
1867 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1868 return -1;
1871 else
1873 cmd.Format(_T("git.exe checkout %s -f -- \"%s\""), commit, path.GetGitPathString());
1874 if (Run(cmd, &out, CP_UTF8))
1876 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1877 return -1;
1881 if (path.m_Action & CTGitPath::LOGACTIONS_DELETED)
1883 cmd.Format(_T("git.exe add -f -- \"%s\""), path.GetGitPathString());
1884 if (Run(cmd, &out, CP_UTF8))
1886 ::MessageBox(NULL, out, _T("TortoiseGit"), MB_OK|MB_ICONERROR);
1887 return -1;
1891 return 0;
1894 int CGit::ListConflictFile(CTGitPathList &list,CTGitPath *path)
1896 BYTE_VECTOR vector;
1898 CString cmd;
1899 if(path)
1900 cmd.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path->GetGitPathString());
1901 else
1902 cmd=_T("git.exe ls-files -u -t -z");
1904 if (Run(cmd, &vector))
1906 return -1;
1909 list.ParserFromLsFile(vector);
1911 return 0;
1914 bool CGit::IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor)
1916 CString base;
1917 CGitHash basehash,hash;
1918 CString cmd, err;
1919 cmd.Format(_T("git.exe merge-base %s %s"), FixBranchName(to), FixBranchName(from));
1921 if (Run(cmd, &base, &err, CP_UTF8))
1923 return false;
1925 basehash = base.Trim();
1927 GetHash(hash, from);
1929 if (commonAncestor)
1930 *commonAncestor = basehash;
1932 return hash == basehash;
1935 unsigned int CGit::Hash2int(CGitHash &hash)
1937 int ret=0;
1938 for (int i = 0; i < 4; ++i)
1940 ret = ret << 8;
1941 ret |= hash.m_hash[i];
1943 return ret;
1946 int CGit::RefreshGitIndex()
1948 if(g_Git.m_IsUseGitDLL)
1950 CAutoLocker lock(g_Git.m_critGitDllSec);
1953 return git_run_cmd("update-index","update-index -q --refresh");
1955 }catch(...)
1957 return -1;
1961 else
1963 CString cmd,output;
1964 cmd=_T("git.exe update-index --refresh");
1965 return Run(cmd, &output, CP_UTF8);
1969 int CGit::GetOneFile(CString Refname, CTGitPath &path, const CString &outputfile)
1971 if(g_Git.m_IsUseGitDLL)
1973 CAutoLocker lock(g_Git.m_critGitDllSec);
1976 g_Git.CheckAndInitDll();
1977 CStringA ref, patha, outa;
1978 ref = CUnicodeUtils::GetMulti(Refname, CP_UTF8);
1979 patha = CUnicodeUtils::GetMulti(path.GetGitPathString(), CP_UTF8);
1980 outa = CUnicodeUtils::GetMulti(outputfile, CP_UTF8);
1981 ::DeleteFile(outputfile);
1982 return git_checkout_file((const char*)ref.GetBuffer(),(const char*)patha.GetBuffer(),(const char*)outa.GetBuffer());
1984 }catch(...)
1986 return -1;
1989 else
1991 CString cmd;
1992 cmd.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname, path.GetGitPathString());
1993 return RunLogFile(cmd,outputfile);
1996 void CEnvironment::CopyProcessEnvironment()
1998 TCHAR *p = GetEnvironmentStrings();
1999 while(*p !=0 || *(p+1) !=0)
2000 this->push_back(*p++);
2002 push_back(_T('\0'));
2003 push_back(_T('\0'));
2006 CString CEnvironment::GetEnv(TCHAR *name)
2008 CString str;
2009 for (size_t i = 0; i < size(); ++i)
2011 str = &(*this)[i];
2012 int start =0;
2013 CString sname = str.Tokenize(_T("="),start);
2014 if(sname.CompareNoCase(name) == 0)
2016 return &(*this)[i+start];
2018 i+=str.GetLength();
2020 return _T("");
2023 void CEnvironment::SetEnv(TCHAR *name, TCHAR* value)
2025 unsigned int i;
2026 for (i = 0; i < size(); ++i)
2028 CString str = &(*this)[i];
2029 int start =0;
2030 CString sname = str.Tokenize(_T("="),start);
2031 if(sname.CompareNoCase(name) == 0)
2033 break;
2035 i+=str.GetLength();
2038 if(i == size())
2040 i -= 1; // roll back terminate \0\0
2041 this->push_back(_T('\0'));
2044 CEnvironment::iterator it;
2045 it=this->begin();
2046 it += i;
2048 while(*it && i<size())
2050 this->erase(it);
2051 it=this->begin();
2052 it += i;
2055 while(*name)
2057 this->insert(it,*name++);
2058 ++i;
2059 it= begin()+i;
2062 this->insert(it, _T('='));
2063 ++i;
2064 it= begin()+i;
2066 while(*value)
2068 this->insert(it,*value++);
2069 ++i;
2070 it= begin()+i;
2075 int CGit::GetGitEncode(TCHAR* configkey)
2077 CString str=GetConfigValue(configkey);
2079 if(str.IsEmpty())
2080 return CP_UTF8;
2082 return CUnicodeUtils::GetCPCode(str);
2086 int CGit::GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg)
2088 GIT_FILE file=0;
2089 int ret=0;
2090 GIT_DIFF diff=0;
2092 CAutoLocker lock(g_Git.m_critGitDllSec);
2094 if(arg == NULL)
2095 diff = GetGitDiff();
2096 else
2097 git_open_diff(&diff, arg);
2099 if(diff ==NULL)
2100 return -1;
2102 bool isStat = 0;
2103 if(arg == NULL)
2104 isStat = true;
2105 else
2106 isStat = !!strstr(arg, "stat");
2108 int count=0;
2110 if(hash2 == NULL)
2111 ret = git_root_diff(diff, hash1->m_hash, &file, &count,isStat);
2112 else
2113 ret = git_diff(diff,hash2->m_hash,hash1->m_hash,&file,&count,isStat);
2115 if(ret)
2116 return -1;
2118 CTGitPath path;
2119 CString strnewname;
2120 CString stroldname;
2122 for (int j = 0; j < count; ++j)
2124 path.Reset();
2125 char *newname;
2126 char *oldname;
2128 strnewname.Empty();
2129 stroldname.Empty();
2131 int mode=0,IsBin=0,inc=0,dec=0;
2132 git_get_diff_file(diff,file,j,&newname,&oldname,
2133 &mode,&IsBin,&inc,&dec);
2135 StringAppend(&strnewname, (BYTE*)newname, CP_UTF8);
2136 StringAppend(&stroldname, (BYTE*)oldname, CP_UTF8);
2138 path.SetFromGit(strnewname,&stroldname);
2139 path.ParserAction((BYTE)mode);
2141 if(IsBin)
2143 path.m_StatAdd=_T("-");
2144 path.m_StatDel=_T("-");
2146 else
2148 path.m_StatAdd.Format(_T("%d"),inc);
2149 path.m_StatDel.Format(_T("%d"),dec);
2151 PathList->AddPath(path);
2153 git_diff_flush(diff);
2155 if(arg)
2156 git_close_diff(diff);
2158 return 0;
2161 int CGit::GetShortHASHLength()
2163 return 7;
2166 CString CGit::GetShortName(CString ref, REF_TYPE *out_type)
2168 CString str=ref;
2169 CString shortname;
2170 REF_TYPE type = CGit::UNKNOWN;
2172 if (CGit::GetShortName(str, shortname, _T("refs/heads/")))
2174 type = CGit::LOCAL_BRANCH;
2177 else if (CGit::GetShortName(str, shortname, _T("refs/remotes/")))
2179 type = CGit::REMOTE_BRANCH;
2181 else if (CGit::GetShortName(str, shortname, _T("refs/tags/")))
2183 type = CGit::TAG;
2185 else if (CGit::GetShortName(str, shortname, _T("refs/stash")))
2187 type = CGit::STASH;
2188 shortname=_T("stash");
2190 else if (CGit::GetShortName(str, shortname, _T("refs/bisect/")))
2192 if (shortname.Find(_T("good")) == 0)
2194 type = CGit::BISECT_GOOD;
2195 shortname = _T("good");
2198 if (shortname.Find(_T("bad")) == 0)
2200 type = CGit::BISECT_BAD;
2201 shortname = _T("bad");
2204 else if (CGit::GetShortName(str, shortname, _T("refs/notes/")))
2206 type = CGit::NOTES;
2208 else
2210 type = CGit::UNKNOWN;
2211 shortname = _T("Unknown");
2214 if(out_type)
2215 *out_type = type;
2217 return shortname;
2220 BOOL CGit::UsingLibGit2(int cmd)
2222 if (cmd >= 0 && cmd < 32)
2223 return ((1 << cmd) & m_IsUseLibGit2_mask) ? FALSE : TRUE;
2224 return FALSE;