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"
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)
42 term
= (*path
== L
'"') ? *path
++ : L
';';
44 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
47 *buf
= L
'\0'; /* reserved a byte via initial subtract */
49 while (*path
== term
|| *path
== L
';')
52 return (path
!= base
) ? path
: NULL
;
55 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
58 return _tstat(lpszFileName
, &st
) == 0;
61 static BOOL
FindGitPath()
64 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
71 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
72 _tgetenv_s(&size
, env
, size
, _T("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"));
92 if ( FileExists(buf
) )
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");
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
);
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
)
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)
142 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
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
;
159 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
160 m_CurrentDir
.ReleaseBuffer();
161 m_IsGitDllInited
= false;
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);
169 this->m_bInitialized
=false;
171 m_critGitDllSec
.Init();
178 git_close_diff(m_GitDiff
);
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())
193 for (int i
= 0; i
< branchname
.GetLength(); ++i
)
195 TCHAR c
= branchname
.GetAt(i
);
196 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
200 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
203 CString reverseBranchname
= branchname
.MakeReverse();
204 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
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
;
230 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
231 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
235 PROCESS_INFORMATION pi
;
236 si
.cb
=sizeof(STARTUPINFO
);
240 si
.hStdError
= hWriteErr
;
242 si
.hStdError
= hWrite
;
244 si
.hStdOutput
=hStdioFile
;
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(" "));
264 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
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
))
272 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
273 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
276 return TGIT_GIT_ERROR_CREATE_PROCESS
;
283 CloseHandle(hWriteErr
);
289 *hErrReadOut
= hReadErr
;
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
)
298 //str->Append(A2W_CP((LPCSTR)p,code));
306 len
= (int)strlen((const char*)p
);
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();
320 BOOL
CGit::IsOrphanBranch(CString ref
)
326 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
336 BOOL
CGit::IsInitRepos()
338 return IsOrphanBranch(_T("HEAD"));
341 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
343 PASYNCREADSTDERRTHREADARGS pDataArray
;
344 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
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
))
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
;
365 ASYNCREADSTDERRTHREADARGS threadArguments
;
366 threadArguments
.fileHandle
= hReadErr
;
367 threadArguments
.pcall
= pcall
;
368 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
371 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
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
))
384 WaitForSingleObject(thread
, INFINITE
);
386 CloseHandle(pi
.hThread
);
388 WaitForSingleObject(pi
.hProcess
, INFINITE
);
391 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
393 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
396 CloseHandle(pi
.hProcess
);
399 CloseHandle(hReadErr
);
402 class CGitCall_ByteVector
: public CGitCall
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
)
410 size_t oldsize
=m_pvector
->size();
411 m_pvector
->resize(m_pvector
->size()+size
);
412 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
415 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
417 if (!m_pvectorErr
|| size
== 0)
419 size_t oldsize
= m_pvectorErr
->size();
420 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
421 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
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
);
433 int CGit::Run(CString cmd
, CString
* output
, int code
)
437 ret
= Run(cmd
, output
, &err
, code
);
439 if (output
&& !err
.IsEmpty())
441 if (!output
->IsEmpty())
448 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
450 BYTE_VECTOR vector
, vectorErr
;
453 ret
= Run(cmd
, &vector
, &vectorErr
);
455 ret
= Run(cmd
, &vector
);
458 StringAppend(output
, &(vector
[0]), code
);
462 vectorErr
.push_back(0);
463 StringAppend(outputErr
, &(vectorErr
[0]), code
);
469 CString
CGit::GetUserName(void)
472 env
.CopyProcessEnvironment();
473 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
474 if (!envname
.IsEmpty())
476 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
478 CString
CGit::GetUserEmail(void)
481 env
.CopyProcessEnvironment();
482 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
483 if (!envmail
.IsEmpty())
486 return GetConfigValue(L
"user.email");
489 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
493 if(this->m_IsUseGitDLL
)
495 CString
*git_path
=NULL
;
497 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
510 key
= CUnicodeUtils::GetMulti(name
, encoding
);
513 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
515 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
519 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
521 return configValue
.Tokenize(_T("\n"),start
);
529 cmd
.Format(L
"git.exe config %s", name
);
530 Run(cmd
, &configValue
, NULL
, encoding
);
532 return configValue
.Tokenize(_T("\n"),start
);
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
);
550 CStringA keya
, valuea
;
551 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
552 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
555 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
557 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
567 option
= _T("--global");
570 option
= _T("--system");
575 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
577 if (Run(cmd
, &out
, NULL
, encoding
))
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
);
598 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
601 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
603 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
612 option
= _T("--global");
615 option
= _T("--system");
620 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
622 if (Run(cmd
, &out
, NULL
, encoding
))
630 CString
CGit::GetCurrentBranch(void)
633 //Run(_T("git.exe branch"),&branch);
635 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
637 return _T("(no branch)");
644 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
647 if(this->m_IsUseGitDLL
)
649 unsigned char sha1
[20];
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
);
658 refName
= StripRefName(refName
);
665 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
666 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
667 return CString();//Error
669 refName
= refName
.Tokenize(L
"\n", iStart
);
671 refName
= StripRefName(refName
);
676 CString
CGit::GetFullRefName(CString shortRefName
)
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
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);
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() )
705 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
708 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
711 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
719 fgets(s
, sizeof(s
), 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() )
739 //# Assume this is a detached head.
748 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
751 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
755 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
757 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
759 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
761 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
763 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
765 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
767 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
771 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
773 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
775 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
780 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
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
,
802 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
805 num
.Format(_T("-n%d"),count
);
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
)
826 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
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
)
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
)
850 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
853 else if(to
!= NULL
&& hash
.IsEmpty())
856 range
.Format(_T(" %s "), FixBranchName(*to
));
863 if( Filter
&& (Filter
->m_From
!= -1))
865 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
869 if( Filter
&& (Filter
->m_To
!= -1))
871 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
876 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
878 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
883 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
885 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
890 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
892 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
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
);
913 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
914 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
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);
932 void GetTempPath(CString
&path
)
934 TCHAR lpPathBuffer
[BUFSIZE
];
936 DWORD dwBufSize
=BUFSIZE
;
937 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
938 lpPathBuffer
); // buffer for path
939 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
943 path
.Format(_T("%s"),lpPathBuffer
);
945 CString
GetTempFile()
947 TCHAR lpPathBuffer
[BUFSIZE
];
949 DWORD dwBufSize
=BUFSIZE
;
950 TCHAR szTempName
[BUFSIZE
];
953 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
954 lpPathBuffer
); // buffer for path
955 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
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
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
))
986 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
987 CreateDirectory(lpBuffer
, NULL
);
992 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
995 PROCESS_INFORMATION pi
;
996 si
.cb
=sizeof(STARTUPINFO
);
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
))
1018 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
1019 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
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
;
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
);
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();
1053 gitdirA
.ReleaseBuffer();
1055 int isHeadOrphan
= git_repository_head_orphan(repo
);
1056 if (isHeadOrphan
!= 0)
1058 git_repository_free(repo
);
1060 if (isHeadOrphan
== 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
);
1075 refnameA
.ReleaseBuffer();
1077 const git_oid
* oid
= git_object_id(gitObject
);
1080 git_object_free(gitObject
);
1081 git_repository_free(repo
);
1085 hash
= CGitHash((char *)oid
->id
);
1087 git_object_free(gitObject
); // also frees oid
1088 git_repository_free(repo
);
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());
1102 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1107 cmd
=_T("git.exe ls-files -s -t -z");
1109 if (Run(cmd
, &cmdout
))
1112 outputlist
.ParserFromLsFile(cmdout
);
1113 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1114 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1118 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1122 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1125 if(rev1
== GIT_REV_ZERO
)
1126 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1128 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1132 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1139 outputlist
.ParserFromLog(out
);
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
;
1148 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1149 list
->push_back(str
);
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();
1165 gitdir
.ReleaseBuffer();
1167 git_strarray tag_names
;
1169 if (git_tag_list(&tag_names
, repo
))
1171 git_repository_free(repo
);
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
);
1191 CString cmd
, output
;
1192 cmd
=_T("git.exe tag -l");
1193 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1200 one
=output
.Tokenize(_T("\n"),pos
);
1202 list
.push_back(one
);
1204 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1211 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1212 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1214 CString
CGit::GetGitLastErr(CString msg
)
1216 if (this->m_IsUseLibGit2
)
1217 return GetLibGit2LastErr(msg
);
1218 else if (gitLastErr
.IsEmpty())
1219 return msg
+ _T("\nUnknown git.exe error.");
1222 CString lastError
= gitLastErr
;
1224 return msg
+ _T("\n") + lastError
;
1228 CString
CGit::GetLibGit2LastErr()
1230 const git_error
*libgit2err
= giterr_last();
1233 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1235 return _T("libgit2 returned: ") + lastError
;
1238 return _T("An error occoured in libgit2, but no message is available.");
1241 CString
CGit::GetLibGit2LastErr(CString msg
)
1244 return msg
+ _T("\n") + GetLibGit2LastErr();
1245 return GetLibGit2LastErr();
1248 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1250 if(branchName
== "FETCH_HEAD")
1251 branchName
= DerefFetchHead();
1255 CString
CGit::FixBranchName(const CString
& branchName
)
1257 CString tempBranchName
= branchName
;
1258 FixBranchName_Mod(tempBranchName
);
1259 return tempBranchName
;
1262 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1267 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1268 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1274 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1285 Checks if a branch or tag with the given name exists
1286 isBranch is true -> branch, tag otherwise
1288 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1290 CString cmd
, output
;
1292 cmd
= _T("git show-ref ");
1294 cmd
+= _T("--heads ");
1296 cmd
+= _T("--tags ");
1298 cmd
+= _T("refs/heads/") + name
;
1299 cmd
+= _T(" refs/tags/") + name
;
1301 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1304 if (!output
.IsEmpty())
1311 CString
CGit::DerefFetchHead()
1313 using namespace std
;
1315 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1316 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1317 int forMergeLineCount
= 0;
1319 string hashToReturn
;
1320 while(getline(fetchHeadFile
, line
))
1322 //Tokenize this line
1323 string::size_type prevPos
= 0;
1324 string::size_type pos
= line
.find('\t');
1325 if(pos
== string::npos
) continue; //invalid line
1327 string hash
= line
.substr(0, pos
);
1328 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1330 bool forMerge
= pos
== prevPos
;
1331 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1333 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1338 hashToReturn
= hash
;
1339 ++forMergeLineCount
;
1340 if(forMergeLineCount
> 1)
1341 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1345 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1348 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1351 CString cmd
, output
, cur
;
1352 cmd
= _T("git.exe branch --no-color");
1354 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1356 else if(type
&BRANCH_REMOTE
)
1359 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1366 one
=output
.Tokenize(_T("\n"),pos
);
1367 one
.Trim(L
" \r\n\t");
1368 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1369 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1370 if(one
[0] == _T('*'))
1375 if (one
!= _T("(no branch)"))
1376 list
.push_back(one
);
1380 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1381 list
.push_back(L
"FETCH_HEAD");
1383 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1385 if (current
&& cur
!= _T("(no branch)"))
1387 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1400 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1402 if (this->m_IsUseLibGit2
)
1404 git_repository
*repo
= NULL
;
1406 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1407 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1409 gitdir
.ReleaseBuffer();
1412 gitdir
.ReleaseBuffer();
1414 git_strarray remotes
;
1416 if (git_remote_list(&remotes
, repo
))
1418 git_repository_free(repo
);
1422 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1424 CStringA
remote(remotes
.strings
[i
]);
1425 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1428 git_strarray_free(&remotes
);
1430 git_repository_free(repo
);
1432 std::sort(list
.begin(), list
.end());
1439 CString cmd
, output
;
1440 cmd
=_T("git.exe remote");
1441 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1448 one
=output
.Tokenize(_T("\n"),pos
);
1450 list
.push_back(one
);
1457 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1459 CString cmd
, out
, err
;
1460 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1461 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1463 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1470 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1471 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1472 if (one
.Find(_T("^{}")) >= 1)
1475 list
.push_back(one
);
1477 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1481 int libgit2_addto_list_each_ref_fn(const char *refname
, void *payload
)
1483 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1485 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1486 list
->push_back(str
);
1490 int CGit::GetRefList(STRING_VECTOR
&list
)
1492 if (this->m_IsUseLibGit2
)
1494 git_repository
*repo
= NULL
;
1496 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1497 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1499 gitdir
.ReleaseBuffer();
1502 gitdir
.ReleaseBuffer();
1504 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_list_each_ref_fn
, &list
))
1506 git_repository_free(repo
);
1510 git_repository_free(repo
);
1512 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1518 CString cmd
, output
;
1519 cmd
=_T("git.exe show-ref -d");
1520 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1527 one
=output
.Tokenize(_T("\n"),pos
);
1528 int start
=one
.Find(_T(" "),0);
1532 name
=one
.Right(one
.GetLength()-start
-1);
1533 list
.push_back(name
);
1536 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1542 typedef struct map_each_ref_payload
{
1543 git_repository
* repo
;
1544 MAP_HASH_NAME
* map
;
1545 } map_each_ref_payload
;
1547 int libgit2_addto_map_each_ref_fn(const char *refname
, void *payload
)
1549 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1552 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1554 git_object
* gitObject
= NULL
;
1558 if (git_revparse_single(&gitObject
, payloadContent
->repo
, refname
))
1563 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1565 str
+= _T("^{}"); // deref tag
1566 git_object
* derefedTag
= NULL
;
1567 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1571 git_object_free(gitObject
);
1572 gitObject
= derefedTag
;
1575 const git_oid
* oid
= git_object_id(gitObject
);
1581 CGitHash
hash((char *)oid
->id
);
1582 (*payloadContent
->map
)[hash
].push_back(str
);
1587 git_object_free(gitObject
);
1594 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1596 if (this->m_IsUseLibGit2
)
1598 git_repository
*repo
= NULL
;
1600 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1601 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1603 gitdir
.ReleaseBuffer();
1606 gitdir
.ReleaseBuffer();
1608 map_each_ref_payload payloadContent
= { repo
, &map
};
1610 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1612 git_repository_free(repo
);
1616 git_repository_free(repo
);
1618 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1620 std::sort(it
->second
.begin(), it
->second
.end());
1627 CString cmd
, output
;
1628 cmd
=_T("git.exe show-ref -d");
1629 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1636 one
=output
.Tokenize(_T("\n"),pos
);
1637 int start
=one
.Find(_T(" "),0);
1641 name
=one
.Right(one
.GetLength()-start
-1);
1644 hash
=one
.Left(start
);
1646 map
[CGitHash(hash
)].push_back(name
);
1654 BOOL
CGit::CheckMsysGitDir()
1661 this->m_Environment
.clear();
1662 m_Environment
.CopyProcessEnvironment();
1665 size_t homesize
,size
;
1667 // set HOME if not set already
1668 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1671 CString home
= GetHomeDirectory();
1672 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1673 home
.ReleaseBuffer();
1678 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1680 if(!sshclient
.IsEmpty())
1682 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1683 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1687 TCHAR sPlink
[MAX_PATH
];
1688 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1689 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1691 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1692 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1693 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1698 TCHAR sAskPass
[MAX_PATH
];
1699 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1700 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1703 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1704 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1705 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1706 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1710 // add git/bin path to PATH
1712 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1714 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1716 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1717 str
= msyslocalinstalldir
;
1718 str
.TrimRight(_T("\\"));
1721 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1722 str
= msysinstalldir
;
1723 str
.TrimRight(_T("\\"));
1725 if ( !str
.IsEmpty() )
1729 CGit::ms_LastMsysGitDir
= str
;
1734 // search PATH if git/bin directory is already present
1735 if ( FindGitPath() )
1737 m_bInitialized
= TRUE
;
1738 msysdir
= CGit::ms_LastMsysGitDir
;
1748 CGit::ms_LastMsysGitDir
= str
;
1751 // check for git.exe existance (maybe it was deinstalled in the meantime)
1752 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1756 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1759 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1761 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1763 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1765 CString sOldPath
= oldpath
;
1768 m_bInitialized
= TRUE
;
1772 CString
CGit::GetHomeDirectory()
1774 const wchar_t * homeDir
= wget_windows_home_directory();
1775 return CString(homeDir
, (int)wcslen(homeDir
));
1778 CString
CGit::GetGitLocalConfig()
1781 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1782 path
+= _T("config");
1786 CString
CGit::GetGitGlobalConfig()
1788 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1791 CString
CGit::GetGitGlobalXDGConfigPath()
1793 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1796 CString
CGit::GetGitGlobalXDGConfig()
1798 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1801 CString
CGit::GetGitSystemConfig()
1803 const wchar_t * systemConfig
= wget_msysgit_etc();
1804 return CString(systemConfig
, (int)wcslen(systemConfig
));
1807 BOOL
CGit::CheckCleanWorkTree()
1811 cmd
=_T("git.exe rev-parse --verify HEAD");
1813 if(Run(cmd
,&out
,CP_UTF8
))
1816 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1817 if(Run(cmd
,&out
,CP_UTF8
))
1820 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1821 if(Run(cmd
,&out
,CP_UTF8
))
1824 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1825 if(Run(cmd
,&out
,CP_UTF8
))
1830 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1833 for (int i
= 0; i
< list
.GetCount(); ++i
)
1835 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1841 int CGit::Revert(CString commit
, CTGitPath
&path
)
1845 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1847 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1850 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1851 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1855 // if the filenames only differ in case, we have to pass "-f"
1856 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1858 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1859 if (Run(cmd
, &out
, CP_UTF8
))
1861 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1865 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1866 if (Run(cmd
, &out
, CP_UTF8
))
1868 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1873 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1874 { //To init git repository, there are not HEAD, so we can use git reset command
1875 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1877 if (Run(cmd
, &out
, CP_UTF8
))
1879 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1885 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1886 if (Run(cmd
, &out
, CP_UTF8
))
1888 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1893 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1895 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1896 if (Run(cmd
, &out
, CP_UTF8
))
1898 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1906 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1912 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1914 cmd
=_T("git.exe ls-files -u -t -z");
1916 if (Run(cmd
, &vector
))
1921 list
.ParserFromLsFile(vector
);
1926 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1929 CGitHash basehash
,hash
;
1931 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1933 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1937 basehash
= base
.Trim();
1939 GetHash(hash
, from
);
1942 *commonAncestor
= basehash
;
1944 return hash
== basehash
;
1947 unsigned int CGit::Hash2int(CGitHash
&hash
)
1950 for (int i
= 0; i
< 4; ++i
)
1953 ret
|= hash
.m_hash
[i
];
1958 int CGit::RefreshGitIndex()
1960 if(g_Git
.m_IsUseGitDLL
)
1962 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1965 return git_run_cmd("update-index","update-index -q --refresh");
1976 cmd
=_T("git.exe update-index --refresh");
1977 return Run(cmd
, &output
, CP_UTF8
);
1981 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1983 if(g_Git
.m_IsUseGitDLL
)
1985 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1988 g_Git
.CheckAndInitDll();
1989 CStringA ref
, patha
, outa
;
1990 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1991 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1992 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1993 ::DeleteFile(outputfile
);
1994 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
2004 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2005 return RunLogFile(cmd
,outputfile
);
2008 void CEnvironment::CopyProcessEnvironment()
2010 TCHAR
*p
= GetEnvironmentStrings();
2011 while(*p
!=0 || *(p
+1) !=0)
2012 this->push_back(*p
++);
2014 push_back(_T('\0'));
2015 push_back(_T('\0'));
2018 CString
CEnvironment::GetEnv(TCHAR
*name
)
2021 for (size_t i
= 0; i
< size(); ++i
)
2025 CString sname
= str
.Tokenize(_T("="),start
);
2026 if(sname
.CompareNoCase(name
) == 0)
2028 return &(*this)[i
+start
];
2035 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2038 for (i
= 0; i
< size(); ++i
)
2040 CString str
= &(*this)[i
];
2042 CString sname
= str
.Tokenize(_T("="),start
);
2043 if(sname
.CompareNoCase(name
) == 0)
2052 i
-= 1; // roll back terminate \0\0
2053 this->push_back(_T('\0'));
2056 CEnvironment::iterator it
;
2060 while(*it
&& i
<size())
2069 this->insert(it
,*name
++);
2074 this->insert(it
, _T('='));
2080 this->insert(it
,*value
++);
2087 int CGit::GetGitEncode(TCHAR
* configkey
)
2089 CString str
=GetConfigValue(configkey
);
2094 return CUnicodeUtils::GetCPCode(str
);
2098 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2104 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2107 diff
= GetGitDiff();
2109 git_open_diff(&diff
, arg
);
2118 isStat
= !!strstr(arg
, "stat");
2123 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2125 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2134 for (int j
= 0; j
< count
; ++j
)
2143 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2144 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2145 &mode
,&IsBin
,&inc
,&dec
);
2147 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2148 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2150 path
.SetFromGit(strnewname
,&stroldname
);
2151 path
.ParserAction((BYTE
)mode
);
2155 path
.m_StatAdd
=_T("-");
2156 path
.m_StatDel
=_T("-");
2160 path
.m_StatAdd
.Format(_T("%d"),inc
);
2161 path
.m_StatDel
.Format(_T("%d"),dec
);
2163 PathList
->AddPath(path
);
2165 git_diff_flush(diff
);
2168 git_close_diff(diff
);
2173 int CGit::GetShortHASHLength()
2178 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2182 REF_TYPE type
= CGit::UNKNOWN
;
2184 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2186 type
= CGit::LOCAL_BRANCH
;
2189 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2191 type
= CGit::REMOTE_BRANCH
;
2193 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2197 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2200 shortname
=_T("stash");
2202 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2204 if (shortname
.Find(_T("good")) == 0)
2206 type
= CGit::BISECT_GOOD
;
2207 shortname
= _T("good");
2210 if (shortname
.Find(_T("bad")) == 0)
2212 type
= CGit::BISECT_BAD
;
2213 shortname
= _T("bad");
2216 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2222 type
= CGit::UNKNOWN
;
2223 shortname
= _T("Unknown");
2232 BOOL
CGit::UsingLibGit2(int cmd
)
2234 if (cmd
>= 0 && cmd
< 32)
2235 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? FALSE
: TRUE
;