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.
25 #include "GitConfig.h"
27 #include "UnicodeUtils.h"
31 int CGit::m_LogEncode
=CP_UTF8
;
32 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
34 static LPTSTR
nextpath(wchar_t *path
, wchar_t *buf
, size_t buflen
)
36 wchar_t term
, *base
= path
;
38 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
41 term
= (*path
== L
'"') ? *path
++ : L
';';
43 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
46 *buf
= L
'\0'; /* reserved a byte via initial subtract */
48 while (*path
== term
|| *path
== L
';')
51 return (path
!= base
) ? path
: NULL
;
54 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
57 return _tstat(lpszFileName
, &st
) == 0;
60 static BOOL
FindGitPath()
63 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
70 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
71 _tgetenv_s(&size
, env
, size
, _T("PATH"));
75 // search in all paths defined in PATH
76 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
78 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
80 // ensure trailing slash
81 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
82 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len
= _tcslen(buf
);
86 if ((len
+ 7) < MAX_PATH
)
87 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, _T("git.exe"));
91 if ( FileExists(buf
) )
95 CGit::ms_LastMsysGitDir
= buf
;
96 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir
))
103 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
112 static bool g_bSortLogical
;
113 static bool g_bSortLocalBranchesFirst
;
115 static void GetSortOptions()
117 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
119 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
120 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
121 if (g_bSortLocalBranchesFirst
)
122 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
125 static int LogicalComparePredicate(CString
&left
, CString
&right
)
128 return StrCmpLogicalW(left
, right
) < 0;
129 return StrCmpI(left
, right
) < 0;
132 static int LogicalCompareBranchesPredicate(CString
&left
, CString
&right
)
134 if (g_bSortLocalBranchesFirst
)
136 int leftIsRemote
= left
.Find(_T("remotes/"));
137 int rightIsRemote
= right
.Find(_T("remotes/"));
139 if (leftIsRemote
== 0 && rightIsRemote
< 0)
141 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
145 return StrCmpLogicalW(left
, right
) < 0;
146 return StrCmpI(left
, right
) < 0;
149 #define MAX_DIRBUFFER 1000
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString
CGit::ms_LastMsysGitDir
;
158 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
159 m_CurrentDir
.ReleaseBuffer();
160 m_IsGitDllInited
= false;
162 m_GitSimpleListDiff
=0;
163 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
164 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
165 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), 0);
168 this->m_bInitialized
=false;
170 m_critGitDllSec
.Init();
177 git_close_diff(m_GitDiff
);
180 if(this->m_GitSimpleListDiff
)
182 git_close_diff(m_GitSimpleListDiff
);
183 m_GitSimpleListDiff
=0;
187 bool CGit::IsBranchNameValid(CString branchname
)
189 if (branchname
.IsEmpty())
192 for (int i
= 0; i
< branchname
.GetLength(); ++i
)
194 TCHAR c
= branchname
.GetAt(i
);
195 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
199 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
202 CString reverseBranchname
= branchname
.MakeReverse();
203 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
209 static char g_Buffer
[4096];
211 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
213 SECURITY_ATTRIBUTES sa
;
214 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
215 HANDLE hStdioFile
= NULL
;
217 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
218 sa
.lpSecurityDescriptor
=NULL
;
219 sa
.bInheritHandle
=TRUE
;
220 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
222 return TGIT_GIT_ERROR_OPEN_PIP
;
224 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
225 return TGIT_GIT_ERROR_OPEN_PIP
;
229 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
230 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
234 PROCESS_INFORMATION pi
;
235 si
.cb
=sizeof(STARTUPINFO
);
239 si
.hStdError
= hWriteErr
;
241 si
.hStdError
= hWrite
;
243 si
.hStdOutput
=hStdioFile
;
245 si
.hStdOutput
=hWrite
;
247 si
.wShowWindow
=SW_HIDE
;
248 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
250 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
251 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
253 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
254 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
256 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
257 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
259 if(cmd
.Find(_T("git")) == 0)
261 int firstSpace
= cmd
.Find(_T(" "));
263 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
265 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
268 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
271 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
272 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
275 return TGIT_GIT_ERROR_CREATE_PROCESS
;
282 CloseHandle(hWriteErr
);
288 *hErrReadOut
= hReadErr
;
292 //Must use sperate function to convert ANSI str to union code string
293 //Becuase A2W use stack as internal convert buffer.
294 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
297 //str->Append(A2W_CP((LPCSTR)p,code));
305 len
= (int)strlen((const char*)p
);
310 //buf = new WCHAR[len*4 + 1];
311 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
312 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
313 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
314 str
->ReleaseBuffer();
319 // This method was originally used to check for orphaned branches
320 BOOL
CGit::CanParseRev(CString ref
)
326 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
336 // Checks if we have an orphaned HEAD
337 BOOL
CGit::IsInitRepos()
340 // handle error on reading HEAD hash as init repo
341 if (GetHash(hash
, _T("HEAD")) != 0)
343 return hash
.IsEmpty() ? TRUE
: FALSE
;
346 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
348 PASYNCREADSTDERRTHREADARGS pDataArray
;
349 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
352 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
353 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
355 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
362 int CGit::Run(CGitCall
* pcall
)
364 PROCESS_INFORMATION pi
;
365 HANDLE hRead
, hReadErr
;
366 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
367 return TGIT_GIT_ERROR_CREATE_PROCESS
;
370 ASYNCREADSTDERRTHREADARGS threadArguments
;
371 threadArguments
.fileHandle
= hReadErr
;
372 threadArguments
.pcall
= pcall
;
373 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
376 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
378 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
380 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
381 if(!bAborted
)//For now, flush output when command aborted.
382 if(pcall
->OnOutputData(data
,readnumber
))
389 WaitForSingleObject(thread
, INFINITE
);
391 CloseHandle(pi
.hThread
);
393 WaitForSingleObject(pi
.hProcess
, INFINITE
);
396 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
398 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
401 CloseHandle(pi
.hProcess
);
404 CloseHandle(hReadErr
);
407 class CGitCall_ByteVector
: public CGitCall
410 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
411 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
415 size_t oldsize
=m_pvector
->size();
416 m_pvector
->resize(m_pvector
->size()+size
);
417 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
420 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
422 if (!m_pvectorErr
|| size
== 0)
424 size_t oldsize
= m_pvectorErr
->size();
425 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
426 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
429 BYTE_VECTOR
* m_pvector
;
430 BYTE_VECTOR
* m_pvectorErr
;
433 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
435 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
438 int CGit::Run(CString cmd
, CString
* output
, int code
)
442 ret
= Run(cmd
, output
, &err
, code
);
444 if (output
&& !err
.IsEmpty())
446 if (!output
->IsEmpty())
453 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
455 BYTE_VECTOR vector
, vectorErr
;
458 ret
= Run(cmd
, &vector
, &vectorErr
);
460 ret
= Run(cmd
, &vector
);
463 StringAppend(output
, &(vector
[0]), code
);
467 vectorErr
.push_back(0);
468 StringAppend(outputErr
, &(vectorErr
[0]), code
);
474 CString
CGit::GetUserName(void)
477 env
.CopyProcessEnvironment();
478 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
479 if (!envname
.IsEmpty())
481 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
483 CString
CGit::GetUserEmail(void)
486 env
.CopyProcessEnvironment();
487 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
488 if (!envmail
.IsEmpty())
491 return GetConfigValue(L
"user.email");
494 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
498 if(this->m_IsUseGitDLL
)
500 CString
*git_path
=NULL
;
502 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
515 key
= CUnicodeUtils::GetMulti(name
, encoding
);
518 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
520 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
524 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
526 return configValue
.Tokenize(_T("\n"),start
);
534 cmd
.Format(L
"git.exe config %s", name
);
535 Run(cmd
, &configValue
, NULL
, encoding
);
537 return configValue
.Tokenize(_T("\n"),start
);
542 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
544 if(this->m_IsUseGitDLL
)
546 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
555 CStringA keya
, valuea
;
556 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
557 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
560 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
562 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
572 option
= _T("--global");
575 option
= _T("--system");
580 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
582 if (Run(cmd
, &out
, NULL
, encoding
))
590 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
592 if(this->m_IsUseGitDLL
)
594 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
603 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
606 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
608 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
617 option
= _T("--global");
620 option
= _T("--system");
625 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
627 if (Run(cmd
, &out
, NULL
, encoding
))
635 CString
CGit::GetCurrentBranch(void)
638 //Run(_T("git.exe branch"),&branch);
640 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
642 return _T("(no branch)");
649 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
652 if(this->m_IsUseGitDLL
)
654 unsigned char sha1
[20];
657 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
658 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
659 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
661 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
663 refName
= StripRefName(refName
);
670 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
671 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
672 return CString();//Error
674 refName
= refName
.Tokenize(L
"\n", iStart
);
676 refName
= StripRefName(refName
);
681 CString
CGit::GetFullRefName(CString shortRefName
)
685 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
686 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
687 return CString();//Error
689 return refName
.Tokenize(L
"\n", iStart
);
692 CString
CGit::StripRefName(CString refName
)
694 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
695 refName
= refName
.Mid(11);
696 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
697 refName
= refName
.Mid(5);
699 return refName
.Tokenize(_T("\n"),start
);
702 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
704 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
706 if ( sProjectRoot
.IsEmpty() )
710 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
713 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
716 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
724 fgets(s
, sizeof(s
), pFile
);
728 const char *pfx
= "ref: refs/heads/";
729 const int len
= 16;//strlen(pfx)
731 if ( !strncmp(s
, pfx
, len
) )
733 //# We're on a branch. It might not exist. But
734 //# HEAD looks good enough to be a branch.
735 CStringA
utf8Branch(s
+ len
);
736 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
737 sBranchOut
.TrimRight(_T(" \r\n\t"));
739 if ( sBranchOut
.IsEmpty() )
744 //# Assume this is a detached head.
753 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
756 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
760 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
762 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
764 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
766 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
768 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
770 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
772 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
776 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
778 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
780 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
785 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
791 CString
CGit::GetLogCmd(CString
&range
, CTGitPath
*path
, int count
, int mask
, bool paramonly
,
801 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
804 num
.Format(_T("-n%d"),count
);
808 if(mask
& LOG_INFO_STAT
)
809 param
+= _T(" --numstat ");
810 if(mask
& LOG_INFO_FILESTATE
)
811 param
+= _T(" --raw ");
813 if(mask
& LOG_INFO_FULLHISTORY
)
814 param
+= _T(" --full-history ");
816 if(mask
& LOG_INFO_BOUNDARY
)
817 param
+= _T(" --left-right --boundary ");
819 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
820 param
+= _T(" --all ");
822 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
825 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
828 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
829 param
+= _T(" --first-parent ");
831 if(mask
& CGit::LOG_INFO_NO_MERGE
)
832 param
+= _T(" --no-merges ");
834 if(mask
& CGit::LOG_INFO_FOLLOW
)
835 param
+= _T(" --follow ");
837 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
840 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
841 param
+= _T(" --full-diff ");
843 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
844 param
+= _T(" --simplify-by-decoration ");
850 if( Filter
&& (Filter
->m_From
!= -1))
852 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
856 if( Filter
&& (Filter
->m_To
!= -1))
858 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
863 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
865 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
870 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
872 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
877 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
879 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
886 if(!Filter
->m_IsRegex
)
887 param
+= _T(" --fixed-strings ");
889 param
+= _T(" --regexp-ignore-case --extended-regexp ");
892 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
893 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
894 param
+= _T(" --topo-order");
895 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
896 param
+= _T(" --date-order");
898 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
899 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
903 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
904 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
913 void GetTempPath(CString
&path
)
915 TCHAR lpPathBuffer
[BUFSIZE
];
917 DWORD dwBufSize
=BUFSIZE
;
918 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
919 lpPathBuffer
); // buffer for path
920 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
924 path
.Format(_T("%s"),lpPathBuffer
);
926 CString
GetTempFile()
928 TCHAR lpPathBuffer
[BUFSIZE
];
930 DWORD dwBufSize
=BUFSIZE
;
931 TCHAR szTempName
[BUFSIZE
];
934 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
935 lpPathBuffer
); // buffer for path
936 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
940 // Create a temporary file.
941 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
942 TEXT("Patch"), // temp file name prefix
943 0, // create unique name
944 szTempName
); // buffer for name
952 return CString(szTempName
);
956 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
958 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
959 if (result
== 0) return 0;
960 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
967 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
968 CreateDirectory(lpBuffer
, NULL
);
973 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
976 PROCESS_INFORMATION pi
;
977 si
.cb
=sizeof(STARTUPINFO
);
980 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
981 psa
.bInheritHandle
=TRUE
;
983 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
984 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
986 si
.wShowWindow
= SW_HIDE
;
987 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
988 si
.hStdOutput
= houtfile
;
990 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
991 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
993 if(cmd
.Find(_T("git")) == 0)
994 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
996 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
999 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
1000 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1003 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1006 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1008 CloseHandle(pi
.hThread
);
1009 CloseHandle(pi
.hProcess
);
1010 CloseHandle(houtfile
);
1011 return TGIT_GIT_SUCCESS
;
1015 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1017 // no need to parse a ref if it's already a 40-byte hash
1018 if (CGitHash::IsValidSHA1(friendname
))
1020 CString
sHash(friendname
);
1021 hash
= CGitHash(sHash
);
1027 git_repository
*repo
= NULL
;
1028 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1029 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1031 gitdirA
.ReleaseBuffer();
1034 gitdirA
.ReleaseBuffer();
1036 int isHeadOrphan
= git_repository_head_orphan(repo
);
1037 if (isHeadOrphan
!= 0)
1039 git_repository_free(repo
);
1041 if (isHeadOrphan
== 1)
1047 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1049 git_object
* gitObject
= NULL
;
1050 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1052 refnameA
.ReleaseBuffer();
1053 git_repository_free(repo
);
1056 refnameA
.ReleaseBuffer();
1058 const git_oid
* oid
= git_object_id(gitObject
);
1061 git_object_free(gitObject
);
1062 git_repository_free(repo
);
1066 hash
= CGitHash((char *)oid
->id
);
1068 git_object_free(gitObject
); // also frees oid
1069 git_repository_free(repo
);
1076 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1077 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1078 hash
= CGitHash(gitLastErr
.Trim());
1083 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1088 cmd
=_T("git.exe ls-files -s -t -z");
1090 if (Run(cmd
, &cmdout
))
1093 outputlist
.ParserFromLsFile(cmdout
);
1094 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1095 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1099 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1103 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1106 if(rev1
== GIT_REV_ZERO
)
1107 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1109 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1113 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1120 outputlist
.ParserFromLog(out
);
1125 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1127 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1129 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1130 list
->push_back(str
);
1134 int CGit::GetTagList(STRING_VECTOR
&list
)
1136 if (this->m_IsUseLibGit2
)
1138 git_repository
*repo
= NULL
;
1140 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1141 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1143 gitdir
.ReleaseBuffer();
1146 gitdir
.ReleaseBuffer();
1148 git_strarray tag_names
;
1150 if (git_tag_list(&tag_names
, repo
))
1152 git_repository_free(repo
);
1156 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1158 CStringA
tagName(tag_names
.strings
[i
]);
1159 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1162 git_strarray_free(&tag_names
);
1164 git_repository_free(repo
);
1166 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1172 CString cmd
, output
;
1173 cmd
=_T("git.exe tag -l");
1174 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1181 one
=output
.Tokenize(_T("\n"),pos
);
1183 list
.push_back(one
);
1185 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1192 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1193 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1195 CString
CGit::GetGitLastErr(CString msg
)
1197 if (this->m_IsUseLibGit2
)
1198 return GetLibGit2LastErr(msg
);
1199 else if (gitLastErr
.IsEmpty())
1200 return msg
+ _T("\nUnknown git.exe error.");
1203 CString lastError
= gitLastErr
;
1205 return msg
+ _T("\n") + lastError
;
1209 CString
CGit::GetLibGit2LastErr()
1211 const git_error
*libgit2err
= giterr_last();
1214 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1216 return _T("libgit2 returned: ") + lastError
;
1219 return _T("An error occoured in libgit2, but no message is available.");
1222 CString
CGit::GetLibGit2LastErr(CString msg
)
1225 return msg
+ _T("\n") + GetLibGit2LastErr();
1226 return GetLibGit2LastErr();
1229 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1231 if(branchName
== "FETCH_HEAD")
1232 branchName
= DerefFetchHead();
1236 CString
CGit::FixBranchName(const CString
& branchName
)
1238 CString tempBranchName
= branchName
;
1239 FixBranchName_Mod(tempBranchName
);
1240 return tempBranchName
;
1243 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1248 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1249 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1255 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1266 Checks if a branch or tag with the given name exists
1267 isBranch is true -> branch, tag otherwise
1269 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1271 CString cmd
, output
;
1273 cmd
= _T("git show-ref ");
1275 cmd
+= _T("--heads ");
1277 cmd
+= _T("--tags ");
1279 cmd
+= _T("refs/heads/") + name
;
1280 cmd
+= _T(" refs/tags/") + name
;
1282 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1285 if (!output
.IsEmpty())
1292 CString
CGit::DerefFetchHead()
1294 using namespace std
;
1296 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1297 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1298 int forMergeLineCount
= 0;
1300 string hashToReturn
;
1301 while(getline(fetchHeadFile
, line
))
1303 //Tokenize this line
1304 string::size_type prevPos
= 0;
1305 string::size_type pos
= line
.find('\t');
1306 if(pos
== string::npos
) continue; //invalid line
1308 string hash
= line
.substr(0, pos
);
1309 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1311 bool forMerge
= pos
== prevPos
;
1312 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1314 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1319 hashToReturn
= hash
;
1320 ++forMergeLineCount
;
1321 if(forMergeLineCount
> 1)
1322 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1326 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1329 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1332 CString cmd
, output
, cur
;
1333 cmd
= _T("git.exe branch --no-color");
1335 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1337 else if(type
&BRANCH_REMOTE
)
1340 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1347 one
=output
.Tokenize(_T("\n"),pos
);
1348 one
.Trim(L
" \r\n\t");
1349 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1350 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1351 if(one
[0] == _T('*'))
1356 if (one
!= _T("(no branch)"))
1357 list
.push_back(one
);
1361 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1362 list
.push_back(L
"FETCH_HEAD");
1364 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1366 if (current
&& cur
!= _T("(no branch)"))
1368 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1381 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1383 if (this->m_IsUseLibGit2
)
1385 git_repository
*repo
= NULL
;
1387 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1388 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1390 gitdir
.ReleaseBuffer();
1393 gitdir
.ReleaseBuffer();
1395 git_strarray remotes
;
1397 if (git_remote_list(&remotes
, repo
))
1399 git_repository_free(repo
);
1403 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1405 CStringA
remote(remotes
.strings
[i
]);
1406 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1409 git_strarray_free(&remotes
);
1411 git_repository_free(repo
);
1413 std::sort(list
.begin(), list
.end());
1420 CString cmd
, output
;
1421 cmd
=_T("git.exe remote");
1422 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1429 one
=output
.Tokenize(_T("\n"),pos
);
1431 list
.push_back(one
);
1438 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1440 CString cmd
, out
, err
;
1441 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1442 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1444 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1451 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1452 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1453 if (one
.Find(_T("^{}")) >= 1)
1456 list
.push_back(one
);
1458 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1462 int libgit2_addto_list_each_ref_fn(const char *refname
, void *payload
)
1464 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1466 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1467 list
->push_back(str
);
1471 int CGit::GetRefList(STRING_VECTOR
&list
)
1473 if (this->m_IsUseLibGit2
)
1475 git_repository
*repo
= NULL
;
1477 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1478 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1480 gitdir
.ReleaseBuffer();
1483 gitdir
.ReleaseBuffer();
1485 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_list_each_ref_fn
, &list
))
1487 git_repository_free(repo
);
1491 git_repository_free(repo
);
1493 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1499 CString cmd
, output
;
1500 cmd
=_T("git.exe show-ref -d");
1501 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1508 one
=output
.Tokenize(_T("\n"),pos
);
1509 int start
=one
.Find(_T(" "),0);
1513 name
=one
.Right(one
.GetLength()-start
-1);
1514 list
.push_back(name
);
1517 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1523 typedef struct map_each_ref_payload
{
1524 git_repository
* repo
;
1525 MAP_HASH_NAME
* map
;
1526 } map_each_ref_payload
;
1528 int libgit2_addto_map_each_ref_fn(const char *refname
, void *payload
)
1530 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1533 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1535 git_object
* gitObject
= NULL
;
1539 if (git_revparse_single(&gitObject
, payloadContent
->repo
, refname
))
1544 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1546 str
+= _T("^{}"); // deref tag
1547 git_object
* derefedTag
= NULL
;
1548 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1552 git_object_free(gitObject
);
1553 gitObject
= derefedTag
;
1556 const git_oid
* oid
= git_object_id(gitObject
);
1562 CGitHash
hash((char *)oid
->id
);
1563 (*payloadContent
->map
)[hash
].push_back(str
);
1568 git_object_free(gitObject
);
1575 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1577 if (this->m_IsUseLibGit2
)
1579 git_repository
*repo
= NULL
;
1581 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1582 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1584 gitdir
.ReleaseBuffer();
1587 gitdir
.ReleaseBuffer();
1589 map_each_ref_payload payloadContent
= { repo
, &map
};
1591 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1593 git_repository_free(repo
);
1597 git_repository_free(repo
);
1599 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1601 std::sort(it
->second
.begin(), it
->second
.end());
1608 CString cmd
, output
;
1609 cmd
=_T("git.exe show-ref -d");
1610 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1617 one
=output
.Tokenize(_T("\n"),pos
);
1618 int start
=one
.Find(_T(" "),0);
1622 name
=one
.Right(one
.GetLength()-start
-1);
1625 hash
=one
.Left(start
);
1627 map
[CGitHash(hash
)].push_back(name
);
1635 BOOL
CGit::CheckMsysGitDir()
1642 this->m_Environment
.clear();
1643 m_Environment
.CopyProcessEnvironment();
1646 size_t homesize
,size
;
1648 // set HOME if not set already
1649 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1652 CString home
= GetHomeDirectory();
1653 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1654 home
.ReleaseBuffer();
1659 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1661 if(!sshclient
.IsEmpty())
1663 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1664 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1668 TCHAR sPlink
[MAX_PATH
];
1669 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1670 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1672 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1673 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1674 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1679 TCHAR sAskPass
[MAX_PATH
];
1680 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1681 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1684 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1685 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1686 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1687 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1691 // add git/bin path to PATH
1693 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1695 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1697 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1698 str
= msyslocalinstalldir
;
1699 str
.TrimRight(_T("\\"));
1702 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1703 str
= msysinstalldir
;
1704 str
.TrimRight(_T("\\"));
1706 if ( !str
.IsEmpty() )
1710 CGit::ms_LastMsysGitDir
= str
;
1715 // search PATH if git/bin directory is already present
1716 if ( FindGitPath() )
1718 m_bInitialized
= TRUE
;
1719 msysdir
= CGit::ms_LastMsysGitDir
;
1729 CGit::ms_LastMsysGitDir
= str
;
1732 // check for git.exe existance (maybe it was deinstalled in the meantime)
1733 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1737 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1740 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1742 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1744 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1746 CString sOldPath
= oldpath
;
1749 m_bInitialized
= TRUE
;
1753 CString
CGit::GetHomeDirectory()
1755 const wchar_t * homeDir
= wget_windows_home_directory();
1756 return CString(homeDir
, (int)wcslen(homeDir
));
1759 CString
CGit::GetGitLocalConfig()
1762 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1763 path
+= _T("config");
1767 CString
CGit::GetGitGlobalConfig()
1769 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1772 CString
CGit::GetGitGlobalXDGConfigPath()
1774 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1777 CString
CGit::GetGitGlobalXDGConfig()
1779 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1782 CString
CGit::GetGitSystemConfig()
1784 const wchar_t * systemConfig
= wget_msysgit_etc();
1785 return CString(systemConfig
, (int)wcslen(systemConfig
));
1788 BOOL
CGit::CheckCleanWorkTree()
1792 cmd
=_T("git.exe rev-parse --verify HEAD");
1794 if(Run(cmd
,&out
,CP_UTF8
))
1797 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1798 if(Run(cmd
,&out
,CP_UTF8
))
1801 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1802 if(Run(cmd
,&out
,CP_UTF8
))
1805 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1806 if(Run(cmd
,&out
,CP_UTF8
))
1811 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1814 for (int i
= 0; i
< list
.GetCount(); ++i
)
1816 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1822 int CGit::Revert(CString commit
, CTGitPath
&path
)
1826 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1828 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1831 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1832 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1836 // if the filenames only differ in case, we have to pass "-f"
1837 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1839 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1840 if (Run(cmd
, &out
, CP_UTF8
))
1842 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1846 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1847 if (Run(cmd
, &out
, CP_UTF8
))
1849 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1854 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1855 { //To init git repository, there are not HEAD, so we can use git reset command
1856 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1858 if (Run(cmd
, &out
, CP_UTF8
))
1860 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1866 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1867 if (Run(cmd
, &out
, CP_UTF8
))
1869 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1874 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1876 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1877 if (Run(cmd
, &out
, CP_UTF8
))
1879 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1887 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1893 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1895 cmd
=_T("git.exe ls-files -u -t -z");
1897 if (Run(cmd
, &vector
))
1902 list
.ParserFromLsFile(vector
);
1907 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1910 CGitHash basehash
,hash
;
1912 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1914 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1918 basehash
= base
.Trim();
1920 GetHash(hash
, from
);
1923 *commonAncestor
= basehash
;
1925 return hash
== basehash
;
1928 unsigned int CGit::Hash2int(CGitHash
&hash
)
1931 for (int i
= 0; i
< 4; ++i
)
1934 ret
|= hash
.m_hash
[i
];
1939 int CGit::RefreshGitIndex()
1941 if(g_Git
.m_IsUseGitDLL
)
1943 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1946 return git_run_cmd("update-index","update-index -q --refresh");
1957 cmd
=_T("git.exe update-index --refresh");
1958 return Run(cmd
, &output
, CP_UTF8
);
1962 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1964 if(g_Git
.m_IsUseGitDLL
)
1966 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1969 g_Git
.CheckAndInitDll();
1970 CStringA ref
, patha
, outa
;
1971 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1972 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1973 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1974 ::DeleteFile(outputfile
);
1975 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1985 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1986 return RunLogFile(cmd
,outputfile
);
1989 void CEnvironment::CopyProcessEnvironment()
1991 TCHAR
*p
= GetEnvironmentStrings();
1992 while(*p
!=0 || *(p
+1) !=0)
1993 this->push_back(*p
++);
1995 push_back(_T('\0'));
1996 push_back(_T('\0'));
1999 CString
CEnvironment::GetEnv(TCHAR
*name
)
2002 for (size_t i
= 0; i
< size(); ++i
)
2006 CString sname
= str
.Tokenize(_T("="),start
);
2007 if(sname
.CompareNoCase(name
) == 0)
2009 return &(*this)[i
+start
];
2016 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2019 for (i
= 0; i
< size(); ++i
)
2021 CString str
= &(*this)[i
];
2023 CString sname
= str
.Tokenize(_T("="),start
);
2024 if(sname
.CompareNoCase(name
) == 0)
2033 i
-= 1; // roll back terminate \0\0
2034 this->push_back(_T('\0'));
2037 CEnvironment::iterator it
;
2041 while(*it
&& i
<size())
2050 this->insert(it
,*name
++);
2055 this->insert(it
, _T('='));
2061 this->insert(it
,*value
++);
2068 int CGit::GetGitEncode(TCHAR
* configkey
)
2070 CString str
=GetConfigValue(configkey
);
2075 return CUnicodeUtils::GetCPCode(str
);
2079 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2085 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2088 diff
= GetGitDiff();
2090 git_open_diff(&diff
, arg
);
2099 isStat
= !!strstr(arg
, "stat");
2104 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2106 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2115 for (int j
= 0; j
< count
; ++j
)
2124 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2125 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2126 &mode
,&IsBin
,&inc
,&dec
);
2128 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2129 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2131 path
.SetFromGit(strnewname
,&stroldname
);
2132 path
.ParserAction((BYTE
)mode
);
2136 path
.m_StatAdd
=_T("-");
2137 path
.m_StatDel
=_T("-");
2141 path
.m_StatAdd
.Format(_T("%d"),inc
);
2142 path
.m_StatDel
.Format(_T("%d"),dec
);
2144 PathList
->AddPath(path
);
2146 git_diff_flush(diff
);
2149 git_close_diff(diff
);
2154 int CGit::GetShortHASHLength()
2159 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2163 REF_TYPE type
= CGit::UNKNOWN
;
2165 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2167 type
= CGit::LOCAL_BRANCH
;
2170 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2172 type
= CGit::REMOTE_BRANCH
;
2174 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2178 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2181 shortname
=_T("stash");
2183 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2185 if (shortname
.Find(_T("good")) == 0)
2187 type
= CGit::BISECT_GOOD
;
2188 shortname
= _T("good");
2191 if (shortname
.Find(_T("bad")) == 0)
2193 type
= CGit::BISECT_BAD
;
2194 shortname
= _T("bad");
2197 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2203 type
= CGit::UNKNOWN
;
2204 shortname
= _T("Unknown");
2213 bool CGit::UsingLibGit2(int cmd
)
2215 if (cmd
>= 0 && cmd
< 32)
2216 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;