1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2012 - 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("\\"));
105 static bool g_bSortLogical
;
107 static void GetSortLogicalEnabled()
109 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
111 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
114 static int LogicalComparePredicate(CString
&left
, CString
&right
)
117 return StrCmpLogicalW(left
, right
) < 0;
118 return StrCmpI(left
, right
) < 0;
121 #define MAX_DIRBUFFER 1000
122 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
124 CString
CGit::ms_LastMsysGitDir
;
130 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
131 m_CurrentDir
.ReleaseBuffer();
132 m_IsGitDllInited
= false;
134 m_GitSimpleListDiff
=0;
135 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
136 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
137 GetSortLogicalEnabled();
138 this->m_bInitialized
=false;
140 m_critGitDllSec
.Init();
147 git_close_diff(m_GitDiff
);
150 if(this->m_GitSimpleListDiff
)
152 git_close_diff(m_GitSimpleListDiff
);
153 m_GitSimpleListDiff
=0;
157 bool CGit::IsBranchNameValid(CString branchname
)
159 if (branchname
.IsEmpty())
162 for(int i
=0; i
< branchname
.GetLength(); i
++)
164 TCHAR c
= branchname
.GetAt(i
);
165 if (c
<= ' ' || c
== '~' || c
== '^' || c
== ':' || c
== '\\' || c
== '?' || c
== '[')
169 if (branchname
.Find(L
".") == 0 || branchname
.Find(L
"/.") >= 0 || branchname
.Find(L
"..") >= 0 || branchname
.Find(L
"@{") >= 0 || branchname
.ReverseFind('*') >= 0)
172 CString reverseBranchname
= branchname
.MakeReverse();
173 if (branchname
.Find(L
'.') == 0 || branchname
.Find(L
'/') == 0 || reverseBranchname
.Find(L
"kcol.") >= 0)
179 static char g_Buffer
[4096];
181 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
183 SECURITY_ATTRIBUTES sa
;
184 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
185 HANDLE hStdioFile
= NULL
;
187 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
188 sa
.lpSecurityDescriptor
=NULL
;
189 sa
.bInheritHandle
=TRUE
;
190 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
192 return TGIT_GIT_ERROR_OPEN_PIP
;
194 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
195 return TGIT_GIT_ERROR_OPEN_PIP
;
199 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
200 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
204 PROCESS_INFORMATION pi
;
205 si
.cb
=sizeof(STARTUPINFO
);
209 si
.hStdError
= hWriteErr
;
211 si
.hStdError
= hWrite
;
213 si
.hStdOutput
=hStdioFile
;
215 si
.hStdOutput
=hWrite
;
217 si
.wShowWindow
=SW_HIDE
;
218 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
220 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
221 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
223 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
224 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
226 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
227 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
229 if(cmd
.Find(_T("git")) == 0)
231 int firstSpace
= cmd
.Find(_T(" "));
233 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
235 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
238 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
241 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
| FORMAT_MESSAGE_FROM_SYSTEM
,
242 NULL
,GetLastError(), MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
245 return TGIT_GIT_ERROR_CREATE_PROCESS
;
252 CloseHandle(hWriteErr
);
258 *hErrReadOut
= hReadErr
;
262 //Must use sperate function to convert ANSI str to union code string
263 //Becuase A2W use stack as internal convert buffer.
264 void CGit::StringAppend(CString
*str
,BYTE
*p
,int code
,int length
)
267 //str->Append(A2W_CP((LPCSTR)p,code));
275 len
= (int)strlen((const char*)p
);
280 //buf = new WCHAR[len*4 + 1];
281 buf
= str
->GetBuffer(len
*4+1+str
->GetLength())+str
->GetLength();
282 SecureZeroMemory(buf
, (len
*4 + 1)*sizeof(WCHAR
));
283 MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
*4);
284 str
->ReleaseBuffer();
289 BOOL
CGit::IsOrphanBranch(CString ref
)
295 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
305 BOOL
CGit::IsInitRepos()
307 return IsOrphanBranch(_T("HEAD"));
310 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
312 PASYNCREADSTDERRTHREADARGS pDataArray
;
313 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
316 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
317 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
319 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
326 int CGit::Run(CGitCall
* pcall
)
328 PROCESS_INFORMATION pi
;
329 HANDLE hRead
, hReadErr
;
330 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
331 return TGIT_GIT_ERROR_CREATE_PROCESS
;
334 ASYNCREADSTDERRTHREADARGS threadArguments
;
335 threadArguments
.fileHandle
= hReadErr
;
336 threadArguments
.pcall
= pcall
;
337 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
340 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
342 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
344 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
345 if(!bAborted
)//For now, flush output when command aborted.
346 if(pcall
->OnOutputData(data
,readnumber
))
353 WaitForSingleObject(thread
, INFINITE
);
355 CloseHandle(pi
.hThread
);
357 WaitForSingleObject(pi
.hProcess
, INFINITE
);
360 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
362 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
365 CloseHandle(pi
.hProcess
);
368 CloseHandle(hReadErr
);
371 class CGitCall_ByteVector
: public CGitCall
374 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
375 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
379 size_t oldsize
=m_pvector
->size();
380 m_pvector
->resize(m_pvector
->size()+size
);
381 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
384 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
386 if (!m_pvectorErr
|| size
== 0)
388 size_t oldsize
= m_pvectorErr
->size();
389 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
390 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
393 BYTE_VECTOR
* m_pvector
;
394 BYTE_VECTOR
* m_pvectorErr
;
397 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
399 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
402 int CGit::Run(CString cmd
, CString
* output
, int code
)
406 ret
= Run(cmd
, output
, &err
, code
);
408 if (output
&& !err
.IsEmpty())
410 if (!output
->IsEmpty())
417 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
419 BYTE_VECTOR vector
, vectorErr
;
422 ret
= Run(cmd
, &vector
, &vectorErr
);
424 ret
= Run(cmd
, &vector
);
427 StringAppend(output
, &(vector
[0]), code
);
431 vectorErr
.push_back(0);
432 StringAppend(outputErr
, &(vectorErr
[0]), code
);
438 CString
CGit::GetUserName(void)
441 env
.CopyProcessEnvironment();
442 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
443 if (!envname
.IsEmpty())
445 return GetConfigValue(L
"user.name", this->GetGitEncode(L
"i18n.commitencoding"));
447 CString
CGit::GetUserEmail(void)
450 env
.CopyProcessEnvironment();
451 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
452 if (!envmail
.IsEmpty())
455 return GetConfigValue(L
"user.email");
458 CString
CGit::GetConfigValue(CString name
,int encoding
, CString
*GitPath
, BOOL RemoveCR
)
462 if(this->m_IsUseGitDLL
)
464 CString
*git_path
=NULL
;
466 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
479 key
= CUnicodeUtils::GetMulti(name
, encoding
);
482 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
484 if(git_get_config(key
.GetBuffer(), value
.GetBufferSetLength(4096), 4096, p
.GetBuffer()))
488 StringAppend(&configValue
,(BYTE
*)value
.GetBuffer(),encoding
);
490 return configValue
.Tokenize(_T("\n"),start
);
498 cmd
.Format(L
"git.exe config %s", name
);
499 Run(cmd
, &configValue
, NULL
, encoding
);
501 return configValue
.Tokenize(_T("\n"),start
);
506 int CGit::SetConfigValue(CString key
, CString value
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
508 if(this->m_IsUseGitDLL
)
510 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
519 CStringA keya
, valuea
;
520 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
521 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
524 p
= CUnicodeUtils::GetMulti(*GitPath
, CP_UTF8
);
526 return get_set_config(keya
.GetBuffer(), valuea
.GetBuffer(), type
, p
.GetBuffer());
536 option
= _T("--global");
539 option
= _T("--system");
544 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
546 if (Run(cmd
, &out
, NULL
, encoding
))
554 int CGit::UnsetConfigValue(CString key
, CONFIG_TYPE type
, int encoding
, CString
*GitPath
)
556 if(this->m_IsUseGitDLL
)
558 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
567 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
570 p
=CUnicodeUtils::GetMulti(*GitPath
,CP_ACP
);
572 return get_set_config(keya
.GetBuffer(), NULL
, type
, p
.GetBuffer());
581 option
= _T("--global");
584 option
= _T("--system");
589 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
591 if (Run(cmd
, &out
, NULL
, encoding
))
599 CString
CGit::GetCurrentBranch(void)
602 //Run(_T("git.exe branch"),&branch);
604 if(this->GetCurrentBranchFromFile(this->m_CurrentDir
,output
))
606 return _T("(no branch)");
613 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
616 if(this->m_IsUseGitDLL
)
618 unsigned char sha1
[20];
621 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
622 const char *refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
623 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
625 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
627 refName
= StripRefName(refName
);
634 cmd
.Format(L
"git symbolic-ref %s", symbolicRefName
);
635 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
636 return CString();//Error
638 refName
= refName
.Tokenize(L
"\n", iStart
);
640 refName
= StripRefName(refName
);
645 CString
CGit::GetFullRefName(CString shortRefName
)
649 cmd
.Format(L
"git rev-parse --symbolic-full-name %s", shortRefName
);
650 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
651 return CString();//Error
653 return refName
.Tokenize(L
"\n", iStart
);
656 CString
CGit::StripRefName(CString refName
)
658 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
659 refName
= refName
.Mid(11);
660 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
661 refName
= refName
.Mid(5);
663 return refName
.Tokenize(_T("\n"),start
);
666 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
)
668 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
670 if ( sProjectRoot
.IsEmpty() )
674 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
677 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
680 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
688 fgets(s
, sizeof(s
), pFile
);
692 const char *pfx
= "ref: refs/heads/";
693 const int len
= 16;//strlen(pfx)
695 if ( !strncmp(s
, pfx
, len
) )
697 //# We're on a branch. It might not exist. But
698 //# HEAD looks good enough to be a branch.
699 CStringA
utf8Branch(s
+ len
);
700 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
701 sBranchOut
.TrimRight(_T(" \r\n\t"));
703 if ( sBranchOut
.IsEmpty() )
708 //# Assume this is a detached head.
717 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
720 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
724 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
726 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
728 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
730 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
732 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
734 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
736 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
740 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
742 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
744 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
749 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
755 int CGit::GetLog(BYTE_VECTOR
& logOut
, const CString
&hash
, CTGitPath
*path
,int count
,int mask
,CString
*from
,CString
*to
)
757 CGitCall_ByteVector
gitCall(CString(), &logOut
, NULL
);
758 return GetLog(&gitCall
,hash
,path
,count
,mask
,from
,to
);
761 CString
CGit::GetLogCmd( const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
,bool paramonly
,
771 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
774 num
.Format(_T("-n%d"),count
);
778 if(mask
& LOG_INFO_STAT
)
779 param
+= _T(" --numstat ");
780 if(mask
& LOG_INFO_FILESTATE
)
781 param
+= _T(" --raw ");
783 if(mask
& LOG_INFO_FULLHISTORY
)
784 param
+= _T(" --full-history ");
786 if(mask
& LOG_INFO_BOUNDARY
)
787 param
+= _T(" --left-right --boundary ");
789 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
790 param
+= _T(" --all ");
792 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
795 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
798 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
799 param
+= _T(" --first-parent ");
801 if(mask
& CGit::LOG_INFO_NO_MERGE
)
802 param
+= _T(" --no-merges ");
804 if(mask
& CGit::LOG_INFO_FOLLOW
)
805 param
+= _T(" --follow ");
807 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
810 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
811 param
+= _T(" --full-diff ");
813 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
814 param
+= _T(" --simplify-by-decoration ");
816 if(from
!= NULL
&& to
!= NULL
)
819 range
.Format(_T(" %s..%s "),FixBranchName(*from
),FixBranchName(*to
));
822 else if(to
!= NULL
&& hash
.IsEmpty())
825 range
.Format(_T(" %s "), FixBranchName(*to
));
832 if( Filter
&& (Filter
->m_From
!= -1))
834 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
838 if( Filter
&& (Filter
->m_To
!= -1))
840 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
845 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
847 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
852 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
854 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
859 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
861 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
868 if(!Filter
->m_IsRegex
)
869 param
+= _T(" --fixed-strings ");
871 param
+= _T(" --regexp-ignore-case --extended-regexp ");
874 if (CRegDWORD(_T("Software\\TortoiseGit\\LogTopoOrder"), TRUE
))
875 param
+= _T(" --topo-order");
877 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
878 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
882 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
883 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
891 //int CGit::GetLog(CGitCall* pgitCall, const CString &hash, CTGitPath *path ,int count,int mask)
892 int CGit::GetLog(CGitCall
* pgitCall
, const CString
&hash
, CTGitPath
*path
, int count
, int mask
,CString
*from
,CString
*to
)
894 pgitCall
->SetCmd( GetLogCmd(hash
,path
,count
,mask
,from
,to
) );
896 return Run(pgitCall
);
897 // return Run(cmd,&logOut);
901 void GetTempPath(CString
&path
)
903 TCHAR lpPathBuffer
[BUFSIZE
];
905 DWORD dwBufSize
=BUFSIZE
;
906 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
907 lpPathBuffer
); // buffer for path
908 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
912 path
.Format(_T("%s"),lpPathBuffer
);
914 CString
GetTempFile()
916 TCHAR lpPathBuffer
[BUFSIZE
];
918 DWORD dwBufSize
=BUFSIZE
;
919 TCHAR szTempName
[BUFSIZE
];
922 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
923 lpPathBuffer
); // buffer for path
924 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
928 // Create a temporary file.
929 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
930 TEXT("Patch"), // temp file name prefix
931 0, // create unique name
932 szTempName
); // buffer for name
940 return CString(szTempName
);
944 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
946 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
947 if (result
== 0) return 0;
948 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
955 _tcscat(lpBuffer
, _T("TortoiseGit\\"));
956 CreateDirectory(lpBuffer
, NULL
);
961 int CGit::RunLogFile(CString cmd
,const CString
&filename
)
964 PROCESS_INFORMATION pi
;
965 si
.cb
=sizeof(STARTUPINFO
);
968 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
969 psa
.bInheritHandle
=TRUE
;
971 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
972 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
974 si
.wShowWindow
= SW_HIDE
;
975 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
976 si
.hStdOutput
= houtfile
;
978 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
979 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
981 if(cmd
.Find(_T("git")) == 0)
982 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
984 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
987 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER
|FORMAT_MESSAGE_FROM_SYSTEM
,
988 NULL
,GetLastError(),MAKELANGID(LANG_NEUTRAL
, SUBLANG_DEFAULT
),
991 return TGIT_GIT_ERROR_CREATE_PROCESS
;
994 WaitForSingleObject(pi
.hProcess
,INFINITE
);
996 CloseHandle(pi
.hThread
);
997 CloseHandle(pi
.hProcess
);
998 CloseHandle(houtfile
);
999 return TGIT_GIT_SUCCESS
;
1003 CGitHash
CGit::GetHash(TCHAR
* friendname
)
1005 // no need to parse a ref if it's already a 40-byte hash
1006 if (CGitHash::IsValidSHA1(friendname
))
1008 CString
sHash(friendname
);
1009 return CGitHash(sHash
);
1014 git_repository
*repo
= NULL
;
1015 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1016 if (git_repository_open(&repo
, gitdirA
.GetBuffer()))
1018 gitdirA
.ReleaseBuffer();
1021 gitdirA
.ReleaseBuffer();
1023 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1025 git_object
* gitObject
= NULL
;
1026 if (git_revparse_single(&gitObject
, repo
, refnameA
.GetBuffer()))
1028 refnameA
.ReleaseBuffer();
1029 git_repository_free(repo
);
1032 refnameA
.ReleaseBuffer();
1034 const git_oid
* oid
= git_object_id(gitObject
);
1037 git_object_free(gitObject
);
1038 git_repository_free(repo
);
1042 CGitHash
hash((char *)oid
->id
);
1044 git_object_free(gitObject
); // also frees oid
1045 git_repository_free(repo
);
1053 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1054 Run(cmd
, &out
, NULL
, CP_UTF8
);
1055 return CGitHash(out
.Trim());
1059 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1064 cmd
=_T("git.exe ls-files -s -t -z");
1066 if (Run(cmd
, &cmdout
))
1069 outputlist
.ParserFromLsFile(cmdout
);
1070 for(int i
=0;i
<outputlist
.GetCount();i
++)
1071 ((unsigned int)outputlist
[i
].m_Action
) = CTGitPath::LOGACTIONS_ADDED
;
1075 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1079 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1082 if(rev1
== GIT_REV_ZERO
)
1083 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s"),rev2
);
1085 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s"),rev1
);
1089 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s"),rev2
,rev1
);
1096 outputlist
.ParserFromLog(out
);
1101 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1103 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1105 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1106 list
->push_back(str
);
1110 int CGit::GetTagList(STRING_VECTOR
&list
)
1112 if (this->m_IsUseLibGit2
)
1114 git_repository
*repo
= NULL
;
1116 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1117 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1119 gitdir
.ReleaseBuffer();
1122 gitdir
.ReleaseBuffer();
1124 git_strarray tag_names
;
1126 if (git_tag_list(&tag_names
, repo
))
1128 git_repository_free(repo
);
1132 for (size_t i
= 0; i
< tag_names
.count
; i
++)
1134 CStringA
tagName(tag_names
.strings
[i
]);
1135 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1138 git_strarray_free(&tag_names
);
1140 git_repository_free(repo
);
1142 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1148 CString cmd
, output
;
1149 cmd
=_T("git.exe tag -l");
1150 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1157 one
=output
.Tokenize(_T("\n"),pos
);
1159 list
.push_back(one
);
1161 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1167 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1169 if(branchName
== "FETCH_HEAD")
1170 branchName
= DerefFetchHead();
1174 CString
CGit::FixBranchName(const CString
& branchName
)
1176 CString tempBranchName
= branchName
;
1177 FixBranchName_Mod(tempBranchName
);
1178 return tempBranchName
;
1181 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1186 cmd
.Format(_T("git show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1187 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1193 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1204 Checks if a branch or tag with the given name exists
1205 isBranch is true -> branch, tag otherwise
1207 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1209 CString cmd
, output
;
1211 cmd
= _T("git show-ref ");
1213 cmd
+= _T("--heads ");
1215 cmd
+= _T("--tags ");
1217 cmd
+= _T("refs/heads/") + name
;
1218 cmd
+= _T(" refs/tags/") + name
;
1220 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1223 if (!output
.IsEmpty())
1230 CString
CGit::DerefFetchHead()
1232 using namespace std
;
1234 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1235 ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), ios::in
| ios::binary
);
1236 int forMergeLineCount
= 0;
1238 string hashToReturn
;
1239 while(getline(fetchHeadFile
, line
))
1241 //Tokenize this line
1242 string::size_type prevPos
= 0;
1243 string::size_type pos
= line
.find('\t');
1244 if(pos
== string::npos
) continue; //invalid line
1246 string hash
= line
.substr(0, pos
);
1247 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== string::npos
) continue;
1249 bool forMerge
= pos
== prevPos
;
1250 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== string::npos
) continue;
1252 string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1257 hashToReturn
= hash
;
1258 ++forMergeLineCount
;
1259 if(forMergeLineCount
> 1)
1260 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1264 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1267 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1270 CString cmd
, output
, cur
;
1271 cmd
= _T("git.exe branch --no-color");
1273 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1275 else if(type
&BRANCH_REMOTE
)
1278 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1285 one
=output
.Tokenize(_T("\n"),pos
);
1286 one
.Trim(L
" \r\n\t");
1287 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1288 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1289 if(one
[0] == _T('*'))
1294 if (one
!= _T("(no branch)"))
1295 list
.push_back(one
);
1299 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1300 list
.push_back(L
"FETCH_HEAD");
1302 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1304 if (current
&& cur
!= _T("(no branch)"))
1306 for (unsigned int i
= 0; i
< list
.size(); i
++)
1319 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1321 if (this->m_IsUseLibGit2
)
1323 git_repository
*repo
= NULL
;
1325 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1326 if (git_repository_open(&repo
, gitdir
.GetBuffer()))
1328 gitdir
.ReleaseBuffer();
1331 gitdir
.ReleaseBuffer();
1333 git_strarray remotes
;
1335 if (git_remote_list(&remotes
, repo
))
1337 git_repository_free(repo
);
1341 for (size_t i
= 0; i
< remotes
.count
; i
++)
1343 CStringA
remote(remotes
.strings
[i
]);
1344 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1347 git_strarray_free(&remotes
);
1349 git_repository_free(repo
);
1351 std::sort(list
.begin(), list
.end());
1358 CString cmd
, output
;
1359 cmd
=_T("git.exe remote");
1360 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1367 one
=output
.Tokenize(_T("\n"),pos
);
1369 list
.push_back(one
);
1376 int CGit::GetRemoteTags(CString remote
, STRING_VECTOR
&list
)
1378 CString cmd
, out
, err
;
1379 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1380 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1382 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1389 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1390 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1391 if (one
.Find(_T("^{}")) >= 1)
1394 list
.push_back(one
);
1396 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1400 int CGit::GetRefList(STRING_VECTOR
&list
)
1403 if(this->m_IsUseGitDLL
)
1405 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1406 ret
= git_for_each_ref_in("",addto_list_each_ref_fn
, &list
);
1407 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1411 CString cmd
, output
;
1412 cmd
=_T("git.exe show-ref -d");
1413 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1420 one
=output
.Tokenize(_T("\n"),pos
);
1421 int start
=one
.Find(_T(" "),0);
1425 name
=one
.Right(one
.GetLength()-start
-1);
1426 list
.push_back(name
);
1429 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1435 int addto_map_each_ref_fn(const char *refname
, const unsigned char *sha1
, int /*flags*/, void *cb_data
)
1437 MAP_HASH_NAME
*map
= (MAP_HASH_NAME
*)cb_data
;
1439 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1440 CGitHash
hash((char*)sha1
);
1442 (*map
)[hash
].push_back(str
);
1444 if(strncmp(refname
, "refs/tags", 9) == 0)
1449 if(!git_deref_tag(sha1
, refhash
))
1451 (*map
)[(char*)refhash
].push_back(str
+_T("^{}"));
1457 ::MessageBox(NULL
, _T("Could not get (readable) reference for hash ") + hash
.ToString() + _T(".\nlibgit reports:\n") + err
, _T("TortoiseGit"), MB_ICONERROR
);
1463 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1466 if(this->m_IsUseGitDLL
)
1468 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1469 return git_for_each_ref_in("",addto_map_each_ref_fn
, &map
);
1474 CString cmd
, output
;
1475 cmd
=_T("git.exe show-ref -d");
1476 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1483 one
=output
.Tokenize(_T("\n"),pos
);
1484 int start
=one
.Find(_T(" "),0);
1488 name
=one
.Right(one
.GetLength()-start
-1);
1491 hash
=one
.Left(start
);
1493 map
[CGitHash(hash
)].push_back(name
);
1501 BOOL
CGit::CheckMsysGitDir()
1508 this->m_Environment
.clear();
1509 m_Environment
.CopyProcessEnvironment();
1512 size_t homesize
,size
;
1514 // set HOME if not set already
1515 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1518 CString home
= GetHomeDirectory();
1519 m_Environment
.SetEnv(_T("HOME"), home
.GetBuffer());
1520 home
.ReleaseBuffer();
1525 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1527 if(!sshclient
.IsEmpty())
1529 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
.GetBuffer());
1530 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
.GetBuffer());
1534 TCHAR sPlink
[MAX_PATH
];
1535 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1536 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1538 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1539 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1540 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1545 TCHAR sAskPass
[MAX_PATH
];
1546 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1547 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1550 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1551 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1552 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1553 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1557 // add git/bin path to PATH
1559 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1561 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1563 CRegString msysinstalldir
=CRegString(REG_MSYSGIT_INSTALL
,_T(""),FALSE
,HKEY_LOCAL_MACHINE
);
1565 str
.TrimRight(_T("\\"));
1566 if ( !str
.IsEmpty() )
1570 CGit::ms_LastMsysGitDir
= str
;
1575 // search PATH if git/bin directory is already present
1576 if ( FindGitPath() )
1578 m_bInitialized
= TRUE
;
1579 msysdir
= CGit::ms_LastMsysGitDir
;
1589 CGit::ms_LastMsysGitDir
= str
;
1592 // check for git.exe existance (maybe it was deinstalled in the meantime)
1593 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1597 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1600 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1602 m_Environment
.SetEnv(_T("PATH"),path
.GetBuffer());
1604 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1606 CString sOldPath
= oldpath
;
1609 m_bInitialized
= TRUE
;
1613 CString
CGit::GetHomeDirectory()
1615 const wchar_t * homeDir
= wget_windows_home_directory();
1616 return CString(homeDir
, (int)wcslen(homeDir
));
1619 CString
CGit::GetGitLocalConfig()
1622 g_GitAdminDir
.GetAdminDirPath(g_Git
.m_CurrentDir
, path
);
1623 path
+= _T("config");
1627 CString
CGit::GetGitGlobalConfig()
1629 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1632 CString
CGit::GetGitGlobalXDGConfigPath()
1634 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1637 CString
CGit::GetGitGlobalXDGConfig()
1639 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1642 CString
CGit::GetGitSystemConfig()
1644 const wchar_t * systemConfig
= wget_msysgit_etc();
1645 return CString(systemConfig
, (int)wcslen(systemConfig
));
1648 BOOL
CGit::CheckCleanWorkTree()
1652 cmd
=_T("git.exe rev-parse --verify HEAD");
1654 if(Run(cmd
,&out
,CP_UTF8
))
1657 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1658 if(Run(cmd
,&out
,CP_UTF8
))
1661 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1662 if(Run(cmd
,&out
,CP_UTF8
))
1665 cmd
=_T("git diff-index --cached --quiet HEAD --ignore-submodules");
1666 if(Run(cmd
,&out
,CP_UTF8
))
1671 int CGit::Revert(CString commit
, CTGitPathList
&list
, bool)
1674 for(int i
=0;i
<list
.GetCount();i
++)
1676 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1682 int CGit::Revert(CString commit
, CTGitPath
&path
)
1686 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1688 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1691 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1692 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1696 // if the filenames only differ in case, we have to pass "-f"
1697 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1699 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1700 if (Run(cmd
, &out
, CP_UTF8
))
1702 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1706 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1707 if (Run(cmd
, &out
, CP_UTF8
))
1709 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1714 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1715 { //To init git repository, there are not HEAD, so we can use git reset command
1716 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1718 if (Run(cmd
, &out
, CP_UTF8
))
1720 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1726 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1727 if (Run(cmd
, &out
, CP_UTF8
))
1729 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1734 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1736 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1737 if (Run(cmd
, &out
, CP_UTF8
))
1739 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1747 int CGit::ListConflictFile(CTGitPathList
&list
,CTGitPath
*path
)
1753 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1755 cmd
=_T("git.exe ls-files -u -t -z");
1757 if (Run(cmd
, &vector
))
1762 list
.ParserFromLsFile(vector
);
1767 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
1770 CGitHash basehash
,hash
;
1772 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
1774 if (Run(cmd
, &base
, &err
, CP_UTF8
))
1778 basehash
= base
.Trim();
1780 hash
= GetHash(from
);
1783 *commonAncestor
= basehash
;
1785 return hash
== basehash
;
1788 unsigned int CGit::Hash2int(CGitHash
&hash
)
1791 for(int i
=0;i
<4;i
++)
1794 ret
|= hash
.m_hash
[i
];
1799 int CGit::RefreshGitIndex()
1801 if(g_Git
.m_IsUseGitDLL
)
1803 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1806 return git_run_cmd("update-index","update-index -q --refresh");
1817 cmd
=_T("git.exe update-index --refresh");
1818 return Run(cmd
, &output
, CP_UTF8
);
1822 int CGit::GetOneFile(CString Refname
, CTGitPath
&path
, const CString
&outputfile
)
1824 if(g_Git
.m_IsUseGitDLL
)
1826 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1829 g_Git
.CheckAndInitDll();
1830 CStringA ref
, patha
, outa
;
1831 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
1832 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
1833 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
1834 ::DeleteFile(outputfile
);
1835 return git_checkout_file((const char*)ref
.GetBuffer(),(const char*)patha
.GetBuffer(),(const char*)outa
.GetBuffer());
1845 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
1846 return RunLogFile(cmd
,outputfile
);
1849 void CEnvironment::CopyProcessEnvironment()
1851 TCHAR
*p
= GetEnvironmentStrings();
1852 while(*p
!=0 || *(p
+1) !=0)
1853 this->push_back(*p
++);
1855 push_back(_T('\0'));
1856 push_back(_T('\0'));
1859 CString
CEnvironment::GetEnv(TCHAR
*name
)
1862 for (size_t i
= 0; i
< size(); i
++)
1866 CString sname
= str
.Tokenize(_T("="),start
);
1867 if(sname
.CompareNoCase(name
) == 0)
1869 return &(*this)[i
+start
];
1876 void CEnvironment::SetEnv(TCHAR
*name
, TCHAR
* value
)
1879 for( i
=0;i
<size();i
++)
1881 CString str
= &(*this)[i
];
1883 CString sname
= str
.Tokenize(_T("="),start
);
1884 if(sname
.CompareNoCase(name
) == 0)
1893 i
-= 1; // roll back terminate \0\0
1894 this->push_back(_T('\0'));
1897 CEnvironment::iterator it
;
1901 while(*it
&& i
<size())
1910 this->insert(it
,*name
++);
1915 this->insert(it
, _T('='));
1921 this->insert(it
,*value
++);
1928 int CGit::GetGitEncode(TCHAR
* configkey
)
1930 CString str
=GetConfigValue(configkey
);
1935 return CUnicodeUtils::GetCPCode(str
);
1939 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
1945 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
1948 diff
= GetGitDiff();
1950 git_open_diff(&diff
, arg
);
1959 isStat
= !!strstr(arg
, "stat");
1964 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
1966 ret
= git_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
1975 for(int j
=0;j
<count
;j
++)
1984 int mode
=0,IsBin
=0,inc
=0,dec
=0;
1985 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
1986 &mode
,&IsBin
,&inc
,&dec
);
1988 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
1989 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
1991 path
.SetFromGit(strnewname
,&stroldname
);
1992 path
.ParserAction((BYTE
)mode
);
1996 path
.m_StatAdd
=_T("-");
1997 path
.m_StatDel
=_T("-");
2001 path
.m_StatAdd
.Format(_T("%d"),inc
);
2002 path
.m_StatDel
.Format(_T("%d"),dec
);
2004 PathList
->AddPath(path
);
2006 git_diff_flush(diff
);
2009 git_close_diff(diff
);
2014 int CGit::GetShortHASHLength()
2019 CString
CGit::GetShortName(CString ref
, REF_TYPE
*out_type
)
2025 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2027 type
= CGit::LOCAL_BRANCH
;
2030 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2032 type
= CGit::REMOTE_BRANCH
;
2034 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2038 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2041 shortname
=_T("stash");
2043 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2045 if (shortname
.Find(_T("good")) == 0)
2047 type
= CGit::BISECT_GOOD
;
2048 shortname
= _T("good");
2051 if (shortname
.Find(_T("bad")) == 0)
2053 type
= CGit::BISECT_BAD
;
2054 shortname
= _T("bad");
2057 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2063 type
= CGit::UNKNOWN
;
2064 shortname
= _T("Unknown");