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
);
167 this->m_bInitialized
=false;
169 m_critGitDllSec
.Init();
176 git_close_diff(m_GitDiff
);
179 if(this->m_GitSimpleListDiff
)
181 git_close_diff(m_GitSimpleListDiff
);
182 m_GitSimpleListDiff
=0;
186 bool CGit::IsBranchNameValid(CString branchname
)
188 if (branchname
.IsEmpty())
191 for(int i
=0; i
< branchname
.GetLength(); i
++)
193 TCHAR c
= branchname
.GetAt(i
);
194 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
198 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
201 CString reverseBranchname
= branchname
.MakeReverse();
202 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
208 static char g_Buffer
[4096];
210 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
212 SECURITY_ATTRIBUTES sa
;
213 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
214 HANDLE hStdioFile
= NULL
;
216 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
217 sa
.lpSecurityDescriptor
=NULL
;
218 sa
.bInheritHandle
=TRUE
;
219 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
221 return TGIT_GIT_ERROR_OPEN_PIP
;
223 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
224 return TGIT_GIT_ERROR_OPEN_PIP
;
228 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
229 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
233 PROCESS_INFORMATION pi
;
234 si
.cb
=sizeof(STARTUPINFO
);
238 si
.hStdError
= hWriteErr
;
240 si
.hStdError
= hWrite
;
242 si
.hStdOutput
=hStdioFile
;
244 si
.hStdOutput
=hWrite
;
246 si
.wShowWindow
=SW_HIDE
;
247 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
249 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
250 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
252 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
253 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
255 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
256 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
258 if(cmd
.Find(_T("git")) == 0)
260 int firstSpace
= cmd
.Find(_T(" "));
262 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
264 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
267 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
270 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
271 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
274 return TGIT_GIT_ERROR_CREATE_PROCESS
;
281 CloseHandle(hWriteErr
);
287 *hErrReadOut
= hReadErr
;
291 //Must use sperate function to convert ANSI str to union code string
292 //Becuase A2W use stack as internal convert buffer.
293 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
296 //str->Append(A2W_CP((LPCSTR)p,code));
304 len
= (int)strlen((const char*)p
);
309 //buf = new WCHAR[len*4 + 1];
310 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
311 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
312 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
313 str
->ReleaseBuffer();
318 BOOL
CGit::IsOrphanBranch(CString ref
)
324 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
334 BOOL
CGit::IsInitRepos()
336 return IsOrphanBranch(_T("HEAD"));
339 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
341 PASYNCREADSTDERRTHREADARGS pDataArray
;
342 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
345 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
346 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
348 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
355 int CGit::Run(CGitCall
* pcall
)
357 PROCESS_INFORMATION pi
;
358 HANDLE hRead
, hReadErr
;
359 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
360 return TGIT_GIT_ERROR_CREATE_PROCESS
;
363 ASYNCREADSTDERRTHREADARGS threadArguments
;
364 threadArguments
.fileHandle
= hReadErr
;
365 threadArguments
.pcall
= pcall
;
366 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
369 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
371 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
373 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
374 if(!bAborted
)//For now, flush output when command aborted.
375 if(pcall
->OnOutputData(data
,readnumber
))
382 WaitForSingleObject(thread
, INFINITE
);
384 CloseHandle(pi
.hThread
);
386 WaitForSingleObject(pi
.hProcess
, INFINITE
);
389 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
391 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
394 CloseHandle(pi
.hProcess
);
397 CloseHandle(hReadErr
);
400 class CGitCall_ByteVector
: public CGitCall
403 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
404 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
408 size_t oldsize
=m_pvector
->size();
409 m_pvector
->resize(m_pvector
->size()+size
);
410 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
413 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
415 if (!m_pvectorErr
|| size
== 0)
417 size_t oldsize
= m_pvectorErr
->size();
418 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
419 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
422 BYTE_VECTOR
* m_pvector
;
423 BYTE_VECTOR
* m_pvectorErr
;
426 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
428 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
431 int CGit::Run(CString cmd
, CString
* output
, int code
)
435 ret
= Run(cmd
, output
, &err
, code
);
437 if (output
&& !err
.IsEmpty())
439 if (!output
->IsEmpty())
446 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
448 BYTE_VECTOR vector
, vectorErr
;
451 ret
= Run(cmd
, &vector
, &vectorErr
);
453 ret
= Run(cmd
, &vector
);
456 StringAppend(output
, &(vector
[0]), code
);
460 vectorErr
.push_back(0);
461 StringAppend(outputErr
, &(vectorErr
[0]), code
);
467 CString
CGit::GetUserName(void)
470 env
.CopyProcessEnvironment();
471 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
472 if (!envname
.IsEmpty())
474 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
476 CString
CGit::GetUserEmail(void)
479 env
.CopyProcessEnvironment();
480 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
481 if (!envmail
.IsEmpty())
484 return GetConfigValue(L
"user.email");
487 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
491 if(this->m_IsUseGitDLL
)
493 CString
*git_path
=NULL
;
495 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
508 key
= CUnicodeUtils::GetMulti(name
, encoding
);
511 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
513 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
517 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
519 return configValue
.Tokenize(_T("\n"),start
);
527 cmd
.Format(L
"git.exe config %s", name
);
528 Run(cmd
, &configValue
, NULL
, encoding
);
530 return configValue
.Tokenize(_T("\n"),start
);
535 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
537 if(this->m_IsUseGitDLL
)
539 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
548 CStringA keya
, valuea
;
549 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
550 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
553 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
555 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
565 option
= _T("--global");
568 option
= _T("--system");
573 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
575 if (Run(cmd
, &out
, NULL
, encoding
))
583 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
585 if(this->m_IsUseGitDLL
)
587 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
596 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
599 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
601 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
610 option
= _T("--global");
613 option
= _T("--system");
618 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
620 if (Run(cmd
, &out
, NULL
, encoding
))
628 CString
CGit::GetCurrentBranch(void)
631 //Run(_T("git.exe branch"),&branch);
633 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
635 return _T("(no branch)");
642 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
645 if(this->m_IsUseGitDLL
)
647 unsigned char sha1
[20];
650 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
651 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
652 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
654 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
656 refName
= StripRefName(refName
);
663 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
664 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
665 return CString();//Error
667 refName
= refName
.Tokenize(L
"\n", iStart
);
669 refName
= StripRefName(refName
);
674 CString
CGit::GetFullRefName(CString shortRefName
)
678 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
679 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
680 return CString();//Error
682 return refName
.Tokenize(L
"\n", iStart
);
685 CString
CGit::StripRefName(CString refName
)
687 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
688 refName
= refName
.Mid(11);
689 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
690 refName
= refName
.Mid(5);
692 return refName
.Tokenize(_T("\n"),start
);
695 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
697 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
699 if ( sProjectRoot
.IsEmpty() )
703 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
706 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
709 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
717 fgets(s
, sizeof(s
), pFile
);
721 const char *pfx
= "ref: refs/heads/";
722 const int len
= 16;//strlen(pfx)
724 if ( !strncmp(s
, pfx
, len
) )
726 //# We're on a branch. It might not exist. But
727 //# HEAD looks good enough to be a branch.
728 CStringA
utf8Branch(s
+ len
);
729 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
730 sBranchOut
.TrimRight(_T(" \r\n\t"));
732 if ( sBranchOut
.IsEmpty() )
737 //# Assume this is a detached head.
746 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
749 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
753 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
755 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
757 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
759 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
761 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
763 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
765 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
769 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
771 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
773 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
778 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
784 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
786 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
787 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
790 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
800 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
803 num
.Format(_T("-n%d"),count
);
807 if(mask
& LOG_INFO_STAT
)
808 param
+= _T(" --numstat ");
809 if(mask
& LOG_INFO_FILESTATE
)
810 param
+= _T(" --raw ");
812 if(mask
& LOG_INFO_FULLHISTORY
)
813 param
+= _T(" --full-history ");
815 if(mask
& LOG_INFO_BOUNDARY
)
816 param
+= _T(" --left-right --boundary ");
818 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
819 param
+= _T(" --all ");
821 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
824 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
827 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
828 param
+= _T(" --first-parent ");
830 if(mask
& CGit::LOG_INFO_NO_MERGE
)
831 param
+= _T(" --no-merges ");
833 if(mask
& CGit::LOG_INFO_FOLLOW
)
834 param
+= _T(" --follow ");
836 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
839 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
840 param
+= _T(" --full-diff ");
842 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
843 param
+= _T(" --simplify-by-decoration ");
845 if(from
!= NULL
&& to
!= NULL
)
848 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
851 else if(to
!= NULL
&& hash
.IsEmpty())
854 range
.Format(_T(" %s "), FixBranchName(*to
));
861 if( Filter
&& (Filter
->m_From
!= -1))
863 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
867 if( Filter
&& (Filter
->m_To
!= -1))
869 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
874 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
876 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
881 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
883 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
888 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
890 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
897 if(!Filter
->m_IsRegex
)
898 param
+= _T(" --fixed-strings ");
900 param
+= _T(" --regexp-ignore-case --extended-regexp ");
903 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
904 param
+= _T(" --topo-order");
906 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
907 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
911 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
912 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
920 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
921 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
923 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
925 return Run(pgitCall
);
926 // return Run(cmd,&logOut);
930 void GetTempPath(CString
&path
)
932 TCHAR lpPathBuffer
[BUFSIZE
];
934 DWORD dwBufSize
=BUFSIZE
;
935 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
936 lpPathBuffer
); // buffer for path
937 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
941 path
.Format(_T("%s"),lpPathBuffer
);
943 CString
GetTempFile()
945 TCHAR lpPathBuffer
[BUFSIZE
];
947 DWORD dwBufSize
=BUFSIZE
;
948 TCHAR szTempName
[BUFSIZE
];
951 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
952 lpPathBuffer
); // buffer for path
953 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
957 // Create a temporary file.
958 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
959 TEXT("Patch"), // temp file name prefix
960 0, // create unique name
961 szTempName
); // buffer for name
969 return CString(szTempName
);
973 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
975 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
976 if (result
== 0) return 0;
977 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
984 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
985 CreateDirectory(lpBuffer
, NULL
);
990 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
993 PROCESS_INFORMATION pi
;
994 si
.cb
=sizeof(STARTUPINFO
);
997 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
998 psa
.bInheritHandle
=TRUE
;
1000 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1001 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1003 si
.wShowWindow
= SW_HIDE
;
1004 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1005 si
.hStdOutput
= houtfile
;
1007 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1008 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1010 if(cmd
.Find(_T("git")) == 0)
1011 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1013 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1016 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
1017 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
1020 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1023 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1025 CloseHandle(pi
.hThread
);
1026 CloseHandle(pi
.hProcess
);
1027 CloseHandle(houtfile
);
1028 return TGIT_GIT_SUCCESS
;
1032 int CGit::GetHash(CGitHash
&hash
, TCHAR
* friendname
)
1034 // no need to parse a ref if it's already a 40-byte hash
1035 if (CGitHash::IsValidSHA1(friendname
))
1037 CString
sHash(friendname
);
1038 hash
= CGitHash(sHash
);
1044 git_repository
*repo
= NULL
;
1045 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1046 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1048 gitdirA
.ReleaseBuffer();
1051 gitdirA
.ReleaseBuffer();
1053 int isHeadOrphan
= git_repository_head_orphan(repo
);
1054 if (isHeadOrphan
!= 0)
1056 git_repository_free(repo
);
1058 if (isHeadOrphan
== 1)
1064 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1066 git_object
* gitObject
= NULL
;
1067 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1069 refnameA
.ReleaseBuffer();
1070 git_repository_free(repo
);
1073 refnameA
.ReleaseBuffer();
1075 const git_oid
* oid
= git_object_id(gitObject
);
1078 git_object_free(gitObject
);
1079 git_repository_free(repo
);
1083 hash
= CGitHash((char *)oid
->id
);
1085 git_object_free(gitObject
); // also frees oid
1086 git_repository_free(repo
);
1093 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1094 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1095 hash
= CGitHash(gitLastErr
.Trim());
1100 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1105 cmd
=_T("git.exe ls-files -s -t -z");
1107 if (Run(cmd
, &cmdout
))
1110 outputlist
.ParserFromLsFile(cmdout
);
1111 for(int i
=0;i
<outputlist
.GetCount();i
++)
1112 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1116 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1120 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1123 if(rev1
== GIT_REV_ZERO
)
1124 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1126 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1130 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1137 outputlist
.ParserFromLog(out
);
1142 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1144 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1146 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1147 list
->push_back(str
);
1151 int CGit::GetTagList(STRING_VECTOR
&list
)
1153 if (this->m_IsUseLibGit2
)
1155 git_repository
*repo
= NULL
;
1157 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1158 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1160 gitdir
.ReleaseBuffer();
1163 gitdir
.ReleaseBuffer();
1165 git_strarray tag_names
;
1167 if (git_tag_list(&tag_names
, repo
))
1169 git_repository_free(repo
);
1173 for (size_t i
= 0; i
< tag_names
.count
; i
++)
1175 CStringA
tagName(tag_names
.strings
[i
]);
1176 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1179 git_strarray_free(&tag_names
);
1181 git_repository_free(repo
);
1183 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1189 CString cmd
, output
;
1190 cmd
=_T("git.exe tag -l");
1191 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1198 one
=output
.Tokenize(_T("\n"),pos
);
1200 list
.push_back(one
);
1202 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1208 CString
CGit::GetGitLastErr(CString msg
)
1210 if (this->m_IsUseLibGit2
)
1212 const git_error
*libgit2err
= giterr_last();
1215 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1217 return msg
+ _T("\nlibgit2 returned: ") + lastError
;
1221 return msg
+ _T("\nUnknown libgit2 error.");
1224 else if (gitLastErr
.IsEmpty())
1225 return msg
+ _T("\nUnknown git.exe error.");
1228 CString lastError
= gitLastErr
;
1230 return msg
+ _T("\n") + lastError
;
1234 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1236 if(branchName
== "FETCH_HEAD")
1237 branchName
= DerefFetchHead();
1241 CString
CGit::FixBranchName(const CString
& branchName
)
1243 CString tempBranchName
= branchName
;
1244 FixBranchName_Mod(tempBranchName
);
1245 return tempBranchName
;
1248 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1253 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1254 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1260 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1271 Checks if a branch or tag with the given name exists
1272 isBranch is true -> branch, tag otherwise
1274 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1276 CString cmd
, output
;
1278 cmd
= _T("git show-ref ");
1280 cmd
+= _T("--heads ");
1282 cmd
+= _T("--tags ");
1284 cmd
+= _T("refs/heads/") + name
;
1285 cmd
+= _T(" refs/tags/") + name
;
1287 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1290 if (!output
.IsEmpty())
1297 CString
CGit::DerefFetchHead()
1299 using namespace std
;
1301 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1302 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1303 int forMergeLineCount
= 0;
1305 string hashToReturn
;
1306 while(getline(fetchHeadFile
, line
))
1308 //Tokenize this line
1309 string::size_type prevPos
= 0;
1310 string::size_type pos
= line
.find('\t');
1311 if(pos
== string::npos
) continue; //invalid line
1313 string hash
= line
.substr(0, pos
);
1314 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1316 bool forMerge
= pos
== prevPos
;
1317 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1319 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1324 hashToReturn
= hash
;
1325 ++forMergeLineCount
;
1326 if(forMergeLineCount
> 1)
1327 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1331 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1334 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1337 CString cmd
, output
, cur
;
1338 cmd
= _T("git.exe branch --no-color");
1340 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1342 else if(type
&BRANCH_REMOTE
)
1345 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1352 one
=output
.Tokenize(_T("\n"),pos
);
1353 one
.Trim(L
" \r\n\t");
1354 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1355 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1356 if(one
[0] == _T('*'))
1361 if (one
!= _T("(no branch)"))
1362 list
.push_back(one
);
1366 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1367 list
.push_back(L
"FETCH_HEAD");
1369 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1371 if (current
&& cur
!= _T("(no branch)"))
1373 for (unsigned int i
= 0; i
< list
.size(); i
++)
1386 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1388 if (this->m_IsUseLibGit2
)
1390 git_repository
*repo
= NULL
;
1392 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1393 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1395 gitdir
.ReleaseBuffer();
1398 gitdir
.ReleaseBuffer();
1400 git_strarray remotes
;
1402 if (git_remote_list(&remotes
, repo
))
1404 git_repository_free(repo
);
1408 for (size_t i
= 0; i
< remotes
.count
; i
++)
1410 CStringA
remote(remotes
.strings
[i
]);
1411 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1414 git_strarray_free(&remotes
);
1416 git_repository_free(repo
);
1418 std::sort(list
.begin(), list
.end());
1425 CString cmd
, output
;
1426 cmd
=_T("git.exe remote");
1427 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1434 one
=output
.Tokenize(_T("\n"),pos
);
1436 list
.push_back(one
);
1443 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1445 CString cmd
, out
, err
;
1446 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1447 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1449 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1456 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1457 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1458 if (one
.Find(_T("^{}")) >= 1)
1461 list
.push_back(one
);
1463 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1467 int libgit2_addto_list_each_ref_fn(const char *refname
, void *payload
)
1469 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1471 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1472 list
->push_back(str
);
1476 int CGit::GetRefList(STRING_VECTOR
&list
)
1478 if (this->m_IsUseLibGit2
)
1480 git_repository
*repo
= NULL
;
1482 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1483 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1485 gitdir
.ReleaseBuffer();
1488 gitdir
.ReleaseBuffer();
1490 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_list_each_ref_fn
, &list
))
1492 git_repository_free(repo
);
1496 git_repository_free(repo
);
1498 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1504 CString cmd
, output
;
1505 cmd
=_T("git.exe show-ref -d");
1506 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1513 one
=output
.Tokenize(_T("\n"),pos
);
1514 int start
=one
.Find(_T(" "),0);
1518 name
=one
.Right(one
.GetLength()-start
-1);
1519 list
.push_back(name
);
1522 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1528 typedef struct map_each_ref_payload
{
1529 git_repository
* repo
;
1530 MAP_HASH_NAME
* map
;
1531 } map_each_ref_payload
;
1533 int libgit2_addto_map_each_ref_fn(const char *refname
, void *payload
)
1535 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1538 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1540 git_object
* gitObject
= NULL
;
1544 if (git_revparse_single(&gitObject
, payloadContent
->repo
, refname
))
1549 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1551 str
+= _T("^{}"); // deref tag
1552 git_object
* derefedTag
= NULL
;
1553 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1557 git_object_free(gitObject
);
1558 gitObject
= derefedTag
;
1561 const git_oid
* oid
= git_object_id(gitObject
);
1567 CGitHash
hash((char *)oid
->id
);
1568 (*payloadContent
->map
)[hash
].push_back(str
);
1573 git_object_free(gitObject
);
1580 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1582 if (this->m_IsUseLibGit2
)
1584 git_repository
*repo
= NULL
;
1586 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1587 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1589 gitdir
.ReleaseBuffer();
1592 gitdir
.ReleaseBuffer();
1594 map_each_ref_payload payloadContent
= { repo
, &map
};
1596 if (git_reference_foreach(repo
, GIT_REF_LISTALL
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1598 git_repository_free(repo
);
1602 git_repository_free(repo
);
1604 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1606 std::sort(it
->second
.begin(), it
->second
.end());
1613 CString cmd
, output
;
1614 cmd
=_T("git.exe show-ref -d");
1615 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1622 one
=output
.Tokenize(_T("\n"),pos
);
1623 int start
=one
.Find(_T(" "),0);
1627 name
=one
.Right(one
.GetLength()-start
-1);
1630 hash
=one
.Left(start
);
1632 map
[CGitHash(hash
)].push_back(name
);
1640 BOOL
CGit::CheckMsysGitDir()
1647 this->m_Environment
.clear();
1648 m_Environment
.CopyProcessEnvironment();
1651 size_t homesize
,size
;
1653 // set HOME if not set already
1654 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1657 CString home
= GetHomeDirectory();
1658 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1659 home
.ReleaseBuffer();
1664 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1666 if(!sshclient
.IsEmpty())
1668 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1669 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1673 TCHAR sPlink
[MAX_PATH
];
1674 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1675 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1677 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1678 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1679 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1684 TCHAR sAskPass
[MAX_PATH
];
1685 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1686 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1689 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1690 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1691 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1692 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1696 // add git/bin path to PATH
1698 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1700 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1702 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL32
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1703 str
= msyslocalinstalldir
;
1704 str
.TrimRight(_T("\\"));
1707 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1708 str
= msysinstalldir
;
1709 str
.TrimRight(_T("\\"));
1711 if ( !str
.IsEmpty() )
1715 CGit::ms_LastMsysGitDir
= str
;
1720 // search PATH if git/bin directory is already present
1721 if ( FindGitPath() )
1723 m_bInitialized
= TRUE
;
1724 msysdir
= CGit::ms_LastMsysGitDir
;
1734 CGit::ms_LastMsysGitDir
= str
;
1737 // check for git.exe existance (maybe it was deinstalled in the meantime)
1738 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1742 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1745 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1747 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1749 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1751 CString sOldPath
= oldpath
;
1754 m_bInitialized
= TRUE
;
1758 CString
CGit::GetHomeDirectory()
1760 const wchar_t * homeDir
= wget_windows_home_directory();
1761 return CString(homeDir
, (int)wcslen(homeDir
));
1764 CString
CGit::GetGitLocalConfig()
1767 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1768 path
+= _T("config");
1772 CString
CGit::GetGitGlobalConfig()
1774 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1777 CString
CGit::GetGitGlobalXDGConfigPath()
1779 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1782 CString
CGit::GetGitGlobalXDGConfig()
1784 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1787 CString
CGit::GetGitSystemConfig()
1789 const wchar_t * systemConfig
= wget_msysgit_etc();
1790 return CString(systemConfig
, (int)wcslen(systemConfig
));
1793 BOOL
CGit::CheckCleanWorkTree()
1797 cmd
=_T("git.exe rev-parse --verify HEAD");
1799 if(Run(cmd
,&out
,CP_UTF8
))
1802 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1803 if(Run(cmd
,&out
,CP_UTF8
))
1806 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1807 if(Run(cmd
,&out
,CP_UTF8
))
1810 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1811 if(Run(cmd
,&out
,CP_UTF8
))
1816 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1819 for(int i
=0;i
<list
.GetCount();i
++)
1821 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1827 int CGit::Revert(CString commit
, CTGitPath
&path
)
1831 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1833 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1836 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1837 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1841 // if the filenames only differ in case, we have to pass "-f"
1842 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1844 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1845 if (Run(cmd
, &out
, CP_UTF8
))
1847 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1851 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1852 if (Run(cmd
, &out
, CP_UTF8
))
1854 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1859 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1860 { //To init git repository, there are not HEAD, so we can use git reset command
1861 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1863 if (Run(cmd
, &out
, CP_UTF8
))
1865 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1871 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1872 if (Run(cmd
, &out
, CP_UTF8
))
1874 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1879 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1881 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1882 if (Run(cmd
, &out
, CP_UTF8
))
1884 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1892 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1898 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1900 cmd
=_T("git.exe ls-files -u -t -z");
1902 if (Run(cmd
, &vector
))
1907 list
.ParserFromLsFile(vector
);
1912 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1915 CGitHash basehash
,hash
;
1917 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1919 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1923 basehash
= base
.Trim();
1925 GetHash(hash
, from
);
1928 *commonAncestor
= basehash
;
1930 return hash
== basehash
;
1933 unsigned int CGit::Hash2int(CGitHash
&hash
)
1936 for(int i
=0;i
<4;i
++)
1939 ret
|= hash
.m_hash
[i
];
1944 int CGit::RefreshGitIndex()
1946 if(g_Git
.m_IsUseGitDLL
)
1948 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1951 return git_run_cmd("update-index","update-index -q --refresh");
1962 cmd
=_T("git.exe update-index --refresh");
1963 return Run(cmd
, &output
, CP_UTF8
);
1967 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1969 if(g_Git
.m_IsUseGitDLL
)
1971 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1974 g_Git
.CheckAndInitDll();
1975 CStringA ref
, patha
, outa
;
1976 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1977 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1978 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1979 ::DeleteFile(outputfile
);
1980 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1990 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1991 return RunLogFile(cmd
,outputfile
);
1994 void CEnvironment::CopyProcessEnvironment()
1996 TCHAR
*p
= GetEnvironmentStrings();
1997 while(*p
!=0 || *(p
+1) !=0)
1998 this->push_back(*p
++);
2000 push_back(_T('\0'));
2001 push_back(_T('\0'));
2004 CString
CEnvironment::GetEnv(TCHAR
*name
)
2007 for (size_t i
= 0; i
< size(); i
++)
2011 CString sname
= str
.Tokenize(_T("="),start
);
2012 if(sname
.CompareNoCase(name
) == 0)
2014 return &(*this)[i
+start
];
2021 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
2024 for( i
=0;i
<size();i
++)
2026 CString str
= &(*this)[i
];
2028 CString sname
= str
.Tokenize(_T("="),start
);
2029 if(sname
.CompareNoCase(name
) == 0)
2038 i
-= 1; // roll back terminate \0\0
2039 this->push_back(_T('\0'));
2042 CEnvironment::iterator it
;
2046 while(*it
&& i
<size())
2055 this->insert(it
,*name
++);
2060 this->insert(it
, _T('='));
2066 this->insert(it
,*value
++);
2073 int CGit::GetGitEncode(TCHAR
* configkey
)
2075 CString str
=GetConfigValue(configkey
);
2080 return CUnicodeUtils::GetCPCode(str
);
2084 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2090 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2093 diff
= GetGitDiff();
2095 git_open_diff(&diff
, arg
);
2104 isStat
= !!strstr(arg
, "stat");
2109 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2111 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2120 for(int j
=0;j
<count
;j
++)
2129 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2130 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2131 &mode
,&IsBin
,&inc
,&dec
);
2133 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2134 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2136 path
.SetFromGit(strnewname
,&stroldname
);
2137 path
.ParserAction((BYTE
)mode
);
2141 path
.m_StatAdd
=_T("-");
2142 path
.m_StatDel
=_T("-");
2146 path
.m_StatAdd
.Format(_T("%d"),inc
);
2147 path
.m_StatDel
.Format(_T("%d"),dec
);
2149 PathList
->AddPath(path
);
2151 git_diff_flush(diff
);
2154 git_close_diff(diff
);
2159 int CGit::GetShortHASHLength()
2164 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2168 REF_TYPE type
= CGit::UNKNOWN
;
2170 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2172 type
= CGit::LOCAL_BRANCH
;
2175 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2177 type
= CGit::REMOTE_BRANCH
;
2179 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2183 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2186 shortname
=_T("stash");
2188 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2190 if (shortname
.Find(_T("good")) == 0)
2192 type
= CGit::BISECT_GOOD
;
2193 shortname
= _T("good");
2196 if (shortname
.Find(_T("bad")) == 0)
2198 type
= CGit::BISECT_BAD
;
2199 shortname
= _T("bad");
2202 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2208 type
= CGit::UNKNOWN
;
2209 shortname
= _T("Unknown");