1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2014 - 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.
24 #include "GitForWindows.h"
26 #include "UnicodeUtils.h"
29 #include "FormatMessageWrapper.h"
30 #include "SmartHandle.h"
31 #include "git2/sys/filter.h"
32 #include "git2/sys/transport.h"
33 #include "../libgit2/filter-filter.h"
34 #include "../libgit2/ssh-wintunnel.h"
36 int CGit::m_LogEncode
=CP_UTF8
;
37 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
39 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
41 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
44 const wchar_t* base
= path
;
45 wchar_t term
= (*path
== L
'"') ? *path
++ : L
';';
47 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
50 *buf
= L
'\0'; /* reserved a byte via initial subtract */
52 while (*path
== term
|| *path
== L
';')
55 return (path
!= base
) ? path
: NULL
;
58 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
61 return _tstat(lpszFileName
, &st
) == 0;
64 static CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
66 TCHAR buf
[MAX_PATH
] = { 0 };
68 // search in all paths defined in PATH
69 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
71 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
73 // ensure trailing slash
74 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
75 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
77 const size_t len
= _tcslen(buf
);
79 if ((len
+ filename
.GetLength()) < MAX_PATH
)
80 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
95 static BOOL
FindGitPath()
98 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
102 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
105 _tgetenv_s(&size
, env
, size
, _T("PATH"));
107 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
108 if (!gitExeDirectory
.IsEmpty())
110 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
111 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
112 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
114 // often the msysgit\cmd folder is on the %PATH%, but
115 // that git.exe does not work, so try to guess the bin folder
116 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
117 if (FileExists(binDir
))
118 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
126 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
128 CString filename
= executable
;
130 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
131 filename
+= _T(".exe");
133 if (FileExists(filename
))
136 filename
= FindFileOnPath(filename
, env
);
137 if (!filename
.IsEmpty())
143 static bool g_bSortLogical
;
144 static bool g_bSortLocalBranchesFirst
;
145 static bool g_bSortTagsReversed
;
147 static void GetSortOptions()
149 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
151 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
152 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
153 if (g_bSortLocalBranchesFirst
)
154 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
155 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
156 if (!g_bSortTagsReversed
)
157 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
160 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
163 return StrCmpLogicalW(left
, right
) < 0;
164 return StrCmpI(left
, right
) < 0;
167 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
170 return StrCmpLogicalW(left
, right
) > 0;
171 return StrCmpI(left
, right
) > 0;
174 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
176 if (g_bSortLocalBranchesFirst
)
178 int leftIsRemote
= left
.Find(_T("remotes/"));
179 int rightIsRemote
= right
.Find(_T("remotes/"));
181 if (leftIsRemote
== 0 && rightIsRemote
< 0)
183 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
187 return StrCmpLogicalW(left
, right
) < 0;
188 return StrCmpI(left
, right
) < 0;
191 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
193 CString
CGit::ms_LastMsysGitDir
;
194 int CGit::ms_LastMsysGitVersion
= 0;
200 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
201 m_CurrentDir
.ReleaseBuffer();
202 m_IsGitDllInited
= false;
204 m_GitSimpleListDiff
=0;
205 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
206 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
207 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), (1 << GIT_CMD_MERGE_BASE
) | (1 << GIT_CMD_DELETETAGBRANCH
) | (1 << GIT_CMD_GETONEFILE
) | (1 << GIT_CMD_ADD
));
209 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
212 this->m_bInitialized
=false;
214 m_critGitDllSec
.Init();
221 git_close_diff(m_GitDiff
);
224 if(this->m_GitSimpleListDiff
)
226 git_close_diff(m_GitSimpleListDiff
);
227 m_GitSimpleListDiff
=0;
231 bool CGit::IsBranchNameValid(const CString
& branchname
)
233 if (branchname
.Left(1) == _T("-")) // branch names starting with a dash are discouraged when used with git.exe, see https://github.com/git/git/commit/6348624010888bd2353e5cebdc2b5329490b0f6d
235 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
237 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
238 return !!git_reference_is_valid_name(branchA
);
241 static bool IsPowerShell(CString cmd
)
244 int powerShellPos
= cmd
.Find(_T("powershell"));
245 if (powerShellPos
< 0)
248 // found the word powershell, check that it is the command and not any parameter
249 int end
= cmd
.GetLength();
250 if (cmd
.Find(_T('"')) == 0)
252 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
253 if (secondDoubleQuote
> 0)
254 end
= secondDoubleQuote
;
258 int firstSpace
= cmd
.Find(_T(' '));
263 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
266 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
268 SECURITY_ATTRIBUTES sa
;
269 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
270 CAutoGeneralHandle hStdioFile
;
272 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
273 sa
.lpSecurityDescriptor
=NULL
;
274 sa
.bInheritHandle
=TRUE
;
275 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
277 CString err
= CFormatMessageWrapper();
278 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
279 return TGIT_GIT_ERROR_OPEN_PIP
;
281 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
283 CString err
= CFormatMessageWrapper();
284 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
285 return TGIT_GIT_ERROR_OPEN_PIP
;
290 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
291 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
295 PROCESS_INFORMATION pi
;
296 si
.cb
=sizeof(STARTUPINFO
);
300 si
.hStdError
= hWriteErr
;
302 si
.hStdError
= hWrite
;
304 si
.hStdOutput
=hStdioFile
;
306 si
.hStdOutput
=hWrite
;
308 si
.wShowWindow
=SW_HIDE
;
309 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
311 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
312 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
314 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
316 // CREATE_NEW_CONSOLE makes git (but not ssh.exe, see issue #2257) recognize that it has no console in order to launch askpass to ask for the password,
317 // DETACHED_PROCESS which was originally used here has the same effect (but works with git.exe AND ssh.exe), however, it prevents PowerShell from working (cf. issue #2143)
318 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
319 if (IsPowerShell(cmd
))
320 dwFlags
|= CREATE_NEW_CONSOLE
;
322 dwFlags
|= DETACHED_PROCESS
;
324 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
325 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
327 if(cmd
.Find(_T("git")) == 0)
329 int firstSpace
= cmd
.Find(_T(" "));
331 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
333 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
336 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
337 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
339 CString err
= CFormatMessageWrapper();
340 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
341 return TGIT_GIT_ERROR_CREATE_PROCESS
;
349 *hReadOut
= hRead
.Detach();
351 *hErrReadOut
= hReadErr
.Detach();
355 //Must use sperate function to convert ANSI str to union code string
356 //Becuase A2W use stack as internal convert buffer.
357 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
364 len
= (int)strlen((const char*)p
);
369 int currentContentLen
= str
->GetLength();
370 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
371 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
372 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
375 // This method was originally used to check for orphaned branches
376 BOOL
CGit::CanParseRev(CString ref
)
382 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
392 // Checks if we have an orphaned HEAD
393 BOOL
CGit::IsInitRepos()
396 // handle error on reading HEAD hash as init repo
397 if (GetHash(hash
, _T("HEAD")) != 0)
399 return hash
.IsEmpty() ? TRUE
: FALSE
;
402 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
404 PASYNCREADSTDERRTHREADARGS pDataArray
;
405 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
408 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
409 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
411 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
418 int CGit::Run(CGitCall
* pcall
)
420 PROCESS_INFORMATION pi
;
421 CAutoGeneralHandle hRead
, hReadErr
;
422 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
423 return TGIT_GIT_ERROR_CREATE_PROCESS
;
425 CAutoGeneralHandle
piThread(pi
.hThread
);
426 CAutoGeneralHandle
piProcess(pi
.hProcess
);
428 ASYNCREADSTDERRTHREADARGS threadArguments
;
429 threadArguments
.fileHandle
= hReadErr
;
430 threadArguments
.pcall
= pcall
;
431 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
434 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
436 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
438 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
439 if(!bAborted
)//For now, flush output when command aborted.
440 if(pcall
->OnOutputData(data
,readnumber
))
447 WaitForSingleObject(thread
, INFINITE
);
449 WaitForSingleObject(pi
.hProcess
, INFINITE
);
452 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
454 CString err
= CFormatMessageWrapper();
455 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
456 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
459 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
463 class CGitCall_ByteVector
: public CGitCall
466 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
467 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
469 if (!m_pvector
|| size
== 0)
471 size_t oldsize
=m_pvector
->size();
472 m_pvector
->resize(m_pvector
->size()+size
);
473 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
476 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
478 if (!m_pvectorErr
|| size
== 0)
480 size_t oldsize
= m_pvectorErr
->size();
481 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
482 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
485 BYTE_VECTOR
* m_pvector
;
486 BYTE_VECTOR
* m_pvectorErr
;
489 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
491 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
494 int CGit::Run(CString cmd
, CString
* output
, int code
)
498 ret
= Run(cmd
, output
, &err
, code
);
500 if (output
&& !err
.IsEmpty())
502 if (!output
->IsEmpty())
509 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
511 BYTE_VECTOR vector
, vectorErr
;
514 ret
= Run(cmd
, &vector
, &vectorErr
);
516 ret
= Run(cmd
, &vector
);
519 StringAppend(output
, &(vector
[0]), code
);
523 vectorErr
.push_back(0);
524 StringAppend(outputErr
, &(vectorErr
[0]), code
);
530 class CGitCallCb
: public CGitCall
533 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
535 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
540 int oldEndPos
= m_buffer
.GetLength();
541 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
542 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
544 // Break into lines and feed to m_recv
546 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
548 m_recv(m_buffer
.Left(eolPos
));
549 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
554 virtual bool OnOutputErrData(const BYTE
*, size_t) override
556 return false; // Ignore error output for now
559 virtual void OnEnd() override
561 if (!m_buffer
.IsEmpty())
563 m_buffer
.Empty(); // Just for sure
567 GitReceiverFunc m_recv
;
571 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
573 CGitCallCb
call(cmd
, recv
);
577 CString
CGit::GetUserName(void)
580 env
.CopyProcessEnvironment();
581 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
582 if (!envname
.IsEmpty())
584 return GetConfigValue(L
"user.name");
586 CString
CGit::GetUserEmail(void)
589 env
.CopyProcessEnvironment();
590 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
591 if (!envmail
.IsEmpty())
594 return GetConfigValue(L
"user.email");
597 CString
CGit::GetConfigValue(const CString
& name
)
601 if(this->m_IsUseGitDLL
)
603 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
612 key
= CUnicodeUtils::GetUTF8(name
);
616 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
619 catch (const char *msg
)
621 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
625 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
626 return configValue
.Tokenize(_T("\n"),start
);
631 cmd
.Format(L
"git.exe config %s", name
);
632 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
633 return configValue
.Tokenize(_T("\n"),start
);
637 bool CGit::GetConfigValueBool(const CString
& name
)
639 CString configValue
= GetConfigValue(name
);
640 configValue
.MakeLower();
642 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
648 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
650 CString configValue
= GetConfigValue(name
);
652 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
657 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
659 if(this->m_IsUseGitDLL
)
661 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
670 CStringA keya
, valuea
;
671 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
672 valuea
= CUnicodeUtils::GetUTF8(value
);
676 return [=]() { return get_set_config(keya
, valuea
, type
); }();
678 catch (const char *msg
)
680 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
691 option
= _T("--global");
694 option
= _T("--system");
699 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
701 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
709 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
711 if(this->m_IsUseGitDLL
)
713 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
722 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
726 return [=]() { return get_set_config(keya
, nullptr, type
); }();
728 catch (const char *msg
)
730 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
741 option
= _T("--global");
744 option
= _T("--system");
749 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
751 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
759 CString
CGit::GetCurrentBranch(bool fallback
)
762 //Run(_T("git.exe branch"),&branch);
764 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
765 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
767 return _T("(no branch)");
774 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
776 if (localBranch
.IsEmpty())
780 configName
.Format(L
"branch.%s.remote", localBranch
);
781 pullRemote
= GetConfigValue(configName
);
783 //Select pull-branch from current branch
784 configName
.Format(L
"branch.%s.merge", localBranch
);
785 pullBranch
= StripRefName(GetConfigValue(configName
));
788 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
791 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
793 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
796 CString
CGit::GetFullRefName(const CString
& shortRefName
)
800 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
801 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
802 return CString();//Error
804 return refName
.Tokenize(L
"\n", iStart
);
807 CString
CGit::StripRefName(CString refName
)
809 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
810 refName
= refName
.Mid(11);
811 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
812 refName
= refName
.Mid(5);
814 return refName
.Tokenize(_T("\n"),start
);
817 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
819 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
821 if ( sProjectRoot
.IsEmpty() )
825 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
828 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
831 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
839 fgets(s
, sizeof(s
), pFile
);
843 const char *pfx
= "ref: refs/heads/";
844 const int len
= 16;//strlen(pfx)
846 if ( !strncmp(s
, pfx
, len
) )
848 //# We're on a branch. It might not exist. But
849 //# HEAD looks good enough to be a branch.
850 CStringA
utf8Branch(s
+ len
);
851 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
852 sBranchOut
.TrimRight(_T(" \r\n\t"));
854 if ( sBranchOut
.IsEmpty() )
859 CStringA
utf8Hash(s
);
860 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
861 unicodeHash
.TrimRight(_T(" \r\n\t"));
862 if (CGitHash::IsValidSHA1(unicodeHash
))
863 sBranchOut
= unicodeHash
;
865 //# Assume this is a detached head.
866 sBranchOut
= _T("HEAD");
871 //# Assume this is a detached head.
880 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
883 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
887 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
889 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
891 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
893 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
895 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
897 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
899 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
903 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
905 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
907 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
912 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
918 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
925 CString file
= _T(" --");
928 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
931 num
.Format(_T("-n%d"),count
);
935 if(mask
& LOG_INFO_STAT
)
936 param
+= _T(" --numstat ");
937 if(mask
& LOG_INFO_FILESTATE
)
938 param
+= _T(" --raw ");
940 if(mask
& LOG_INFO_FULLHISTORY
)
941 param
+= _T(" --full-history ");
943 if(mask
& LOG_INFO_BOUNDARY
)
944 param
+= _T(" --left-right --boundary ");
946 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
947 param
+= _T(" --all ");
949 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
950 param
+= _T(" --branches ");
952 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
955 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
958 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
959 param
+= _T(" --first-parent ");
961 if(mask
& CGit::LOG_INFO_NO_MERGE
)
962 param
+= _T(" --no-merges ");
964 if(mask
& CGit::LOG_INFO_FOLLOW
)
965 param
+= _T(" --follow ");
967 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
970 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
971 param
+= _T(" --full-diff ");
973 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
974 param
+= _T(" --simplify-by-decoration ");
980 if( Filter
&& (Filter
->m_From
!= -1))
982 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
986 if( Filter
&& (Filter
->m_To
!= -1))
988 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
993 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
995 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
1000 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1002 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
1007 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1009 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
1014 if(Filter
&& isgrep
)
1016 if(!Filter
->m_IsRegex
)
1017 param
+= _T(" --fixed-strings ");
1019 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1022 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1023 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1024 param
+= _T(" --topo-order");
1025 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1026 param
+= _T(" --date-order");
1028 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
1029 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1033 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1034 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1043 void GetTempPath(CString
&path
)
1045 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1047 DWORD dwBufSize
=BUFSIZE
;
1048 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1049 lpPathBuffer
); // buffer for path
1050 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1054 path
.Format(_T("%s"),lpPathBuffer
);
1056 CString
GetTempFile()
1058 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1060 DWORD dwBufSize
=BUFSIZE
;
1061 TCHAR szTempName
[BUFSIZE
] = { 0 };
1064 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1065 lpPathBuffer
); // buffer for path
1066 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1070 // Create a temporary file.
1071 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1072 TEXT("Patch"), // temp file name prefix
1073 0, // create unique name
1074 szTempName
); // buffer for name
1082 return CString(szTempName
);
1086 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1088 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1089 if (result
== 0) return 0;
1090 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1097 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1098 CreateDirectory(lpBuffer
, NULL
);
1103 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1106 PROCESS_INFORMATION pi
;
1107 si
.cb
=sizeof(STARTUPINFO
);
1108 GetStartupInfo(&si
);
1110 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1111 psa
.bInheritHandle
=TRUE
;
1113 HANDLE hReadErr
, hWriteErr
;
1114 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1116 CString err
= CFormatMessageWrapper();
1117 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1118 return TGIT_GIT_ERROR_OPEN_PIP
;
1121 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1122 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1124 if (houtfile
== INVALID_HANDLE_VALUE
)
1126 CString err
= CFormatMessageWrapper();
1127 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1128 CloseHandle(hReadErr
);
1129 CloseHandle(hWriteErr
);
1130 return TGIT_GIT_ERROR_OPEN_PIP
;
1133 si
.wShowWindow
= SW_HIDE
;
1134 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1135 si
.hStdOutput
= houtfile
;
1136 si
.hStdError
= hWriteErr
;
1138 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1139 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1141 if(cmd
.Find(_T("git")) == 0)
1142 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1144 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1145 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1147 CString err
= CFormatMessageWrapper();
1148 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1150 CloseHandle(hReadErr
);
1151 CloseHandle(hWriteErr
);
1152 CloseHandle(houtfile
);
1153 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1156 BYTE_VECTOR stderrVector
;
1157 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1159 ASYNCREADSTDERRTHREADARGS threadArguments
;
1160 threadArguments
.fileHandle
= hReadErr
;
1161 threadArguments
.pcall
= &pcall
;
1162 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1164 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1166 CloseHandle(hWriteErr
);
1167 CloseHandle(hReadErr
);
1170 WaitForSingleObject(thread
, INFINITE
);
1172 stderrVector
.push_back(0);
1173 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1176 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1178 CString err
= CFormatMessageWrapper();
1179 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1180 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1183 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1185 CloseHandle(pi
.hThread
);
1186 CloseHandle(pi
.hProcess
);
1187 CloseHandle(houtfile
);
1191 git_repository
* CGit::GetGitRepository() const
1193 git_repository
* repo
= nullptr;
1194 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1198 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1202 // no need to parse a ref if it's already a 40-byte hash
1203 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1205 hash
= CGitHash(friendname
);
1209 int isHeadOrphan
= git_repository_head_unborn(repo
);
1210 if (isHeadOrphan
!= 0)
1213 if (isHeadOrphan
== 1)
1219 CAutoObject gitObject
;
1220 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1223 const git_oid
* oid
= git_object_id(gitObject
);
1227 hash
= CGitHash((char *)oid
->id
);
1232 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1234 // no need to parse a ref if it's already a 40-byte hash
1235 if (CGitHash::IsValidSHA1(friendname
))
1237 hash
= CGitHash(friendname
);
1243 CAutoRepository
repo(GetGitRepository());
1247 return GetHash(repo
, hash
, friendname
, true);
1252 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1254 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1255 hash
= CGitHash(gitLastErr
.Trim());
1262 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1267 cmd
=_T("git.exe ls-files -s -t -z");
1269 if (Run(cmd
, &cmdout
))
1272 if (outputlist
.ParserFromLsFile(cmdout
))
1274 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1275 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1279 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1283 if (ignoreSpaceAtEol
)
1284 ignore
+= _T(" --ignore-space-at-eol");
1285 if (ignoreSpaceChange
)
1286 ignore
+= _T(" --ignore-space-change");
1288 ignore
+= _T(" --ignore-all-space");
1289 if (ignoreBlankLines
)
1290 ignore
+= _T(" --ignore-blank-lines");
1292 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1295 if(rev1
== GIT_REV_ZERO
)
1296 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1298 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1302 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1309 outputlist
.ParserFromLog(out
);
1314 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1316 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1318 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1319 list
->push_back(str
);
1323 int CGit::GetTagList(STRING_VECTOR
&list
)
1325 if (this->m_IsUseLibGit2
)
1327 CAutoRepository
repo(GetGitRepository());
1331 CAutoStrArray tag_names
;
1333 if (git_tag_list(tag_names
, repo
))
1336 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1338 CStringA
tagName(tag_names
->strings
[i
]);
1339 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1342 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1348 CString cmd
, output
;
1349 cmd
=_T("git.exe tag -l");
1350 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1357 one
=output
.Tokenize(_T("\n"),pos
);
1359 list
.push_back(one
);
1361 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1367 CString
CGit::GetGitLastErr(const CString
& msg
)
1369 if (this->m_IsUseLibGit2
)
1370 return GetLibGit2LastErr(msg
);
1371 else if (gitLastErr
.IsEmpty())
1372 return msg
+ _T("\nUnknown git.exe error.");
1375 CString lastError
= gitLastErr
;
1377 return msg
+ _T("\n") + lastError
;
1381 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1383 if (UsingLibGit2(cmd
))
1384 return GetLibGit2LastErr(msg
);
1385 else if (gitLastErr
.IsEmpty())
1386 return msg
+ _T("\nUnknown git.exe error.");
1389 CString lastError
= gitLastErr
;
1391 return msg
+ _T("\n") + lastError
;
1395 CString
CGit::GetLibGit2LastErr()
1397 const git_error
*libgit2err
= giterr_last();
1400 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1402 return _T("libgit2 returned: ") + lastError
;
1405 return _T("An error occoured in libgit2, but no message is available.");
1408 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1411 return msg
+ _T("\n") + GetLibGit2LastErr();
1412 return GetLibGit2LastErr();
1415 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1417 if(branchName
== "FETCH_HEAD")
1418 branchName
= DerefFetchHead();
1422 CString
CGit::FixBranchName(const CString
& branchName
)
1424 CString tempBranchName
= branchName
;
1425 FixBranchName_Mod(tempBranchName
);
1426 return tempBranchName
;
1429 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1433 CAutoRepository
repo(GetGitRepository());
1435 return true; // TODO: optimize error reporting
1437 CAutoReference tagRef
;
1438 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1441 CAutoReference branchRef
;
1442 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1451 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1452 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1458 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1468 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1472 CAutoRepository
repo(GetGitRepository());
1474 return false; // TODO: optimize error reporting
1478 prefix
= _T("refs/heads/");
1480 prefix
= _T("refs/tags/");
1483 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1489 CString cmd
, output
;
1491 cmd
= _T("git.exe show-ref ");
1493 cmd
+= _T("--heads ");
1495 cmd
+= _T("--tags ");
1497 cmd
+= _T("refs/heads/") + name
;
1498 cmd
+= _T(" refs/tags/") + name
;
1500 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1503 if (!output
.IsEmpty())
1510 CString
CGit::DerefFetchHead()
1513 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1514 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1515 int forMergeLineCount
= 0;
1517 std::string hashToReturn
;
1518 while(getline(fetchHeadFile
, line
))
1520 //Tokenize this line
1521 std::string::size_type prevPos
= 0;
1522 std::string::size_type pos
= line
.find('\t');
1523 if(pos
== std::string::npos
) continue; //invalid line
1525 std::string hash
= line
.substr(0, pos
);
1526 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1528 bool forMerge
= pos
== prevPos
;
1529 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1531 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1536 hashToReturn
= hash
;
1537 ++forMergeLineCount
;
1538 if(forMergeLineCount
> 1)
1539 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1543 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1546 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1552 CAutoRepository
repo(GetGitRepository());
1556 if (git_repository_head_detached(repo
) == 1)
1557 cur
= _T("(detached from ");
1559 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1561 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1562 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1563 flags
= GIT_BRANCH_ALL
;
1564 else if (type
& BRANCH_REMOTE
)
1565 flags
= GIT_BRANCH_REMOTE
;
1567 CAutoBranchIterator it
;
1568 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1571 git_reference
* ref
= nullptr;
1572 git_branch_t branchType
;
1573 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1575 CAutoReference
autoRef(ref
);
1576 const char * name
= nullptr;
1577 if (git_branch_name(&name
, ref
))
1580 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1581 if (branchType
& GIT_BRANCH_REMOTE
)
1582 list
.push_back(_T("remotes/") + branchname
);
1585 if (git_branch_is_head(ref
))
1587 list
.push_back(branchname
);
1594 CString cmd
, output
;
1595 cmd
= _T("git.exe branch --no-color");
1597 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1599 else if (type
& BRANCH_REMOTE
)
1602 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1609 one
= output
.Tokenize(_T("\n"), pos
);
1610 one
.Trim(L
" \r\n\t");
1611 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1612 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1613 if (one
[0] == _T('*'))
1618 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1619 list
.push_back(one
);
1624 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1625 list
.push_back(L
"FETCH_HEAD");
1627 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1629 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1631 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1644 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1646 if (this->m_IsUseLibGit2
)
1648 CAutoRepository
repo(GetGitRepository());
1652 CAutoStrArray remotes
;
1653 if (git_remote_list(remotes
, repo
))
1656 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1658 CStringA
remote(remotes
->strings
[i
]);
1659 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1662 std::sort(list
.begin(), list
.end());
1669 CString cmd
, output
;
1670 cmd
=_T("git.exe remote");
1671 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1678 one
=output
.Tokenize(_T("\n"),pos
);
1680 list
.push_back(one
);
1687 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1689 CString cmd
, out
, err
;
1690 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1691 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1693 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1700 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1701 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1702 if (one
.Find(_T("^{}")) >= 1)
1705 list
.push_back(one
);
1707 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1711 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1713 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1715 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1716 list
->push_back(str
);
1720 int CGit::GetRefList(STRING_VECTOR
&list
)
1722 if (this->m_IsUseLibGit2
)
1724 CAutoRepository
repo(GetGitRepository());
1728 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1731 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1737 CString cmd
, output
;
1738 cmd
=_T("git.exe show-ref -d");
1739 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1746 one
=output
.Tokenize(_T("\n"),pos
);
1747 int start
=one
.Find(_T(" "),0);
1751 name
=one
.Right(one
.GetLength()-start
-1);
1752 list
.push_back(name
);
1755 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1761 typedef struct map_each_ref_payload
{
1762 git_repository
* repo
;
1763 MAP_HASH_NAME
* map
;
1764 } map_each_ref_payload
;
1766 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1768 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1771 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1773 CAutoObject gitObject
;
1774 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1777 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1779 str
+= _T("^{}"); // deref tag
1780 CAutoObject derefedTag
;
1781 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1783 gitObject
.Swap(derefedTag
);
1786 const git_oid
* oid
= git_object_id(gitObject
);
1790 CGitHash
hash((char *)oid
->id
);
1791 (*payloadContent
->map
)[hash
].push_back(str
);
1795 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1799 map_each_ref_payload payloadContent
= { repo
, &map
};
1801 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1804 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1806 std::sort(it
->second
.begin(), it
->second
.end());
1812 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1814 if (this->m_IsUseLibGit2
)
1816 CAutoRepository
repo(GetGitRepository());
1820 return GetMapHashToFriendName(repo
, map
);
1824 CString cmd
, output
;
1825 cmd
=_T("git.exe show-ref -d");
1826 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1833 one
=output
.Tokenize(_T("\n"),pos
);
1834 int start
=one
.Find(_T(" "),0);
1838 name
=one
.Right(one
.GetLength()-start
-1);
1841 hash
=one
.Left(start
);
1843 map
[CGitHash(hash
)].push_back(name
);
1851 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1853 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1854 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1857 static void SetLibGit2TemplatePath(const CString
&value
)
1859 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1860 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1863 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1870 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
1871 this->m_Environment
.clear();
1872 m_Environment
.CopyProcessEnvironment();
1875 size_t homesize
,size
;
1877 // set HOME if not set already
1878 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1880 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1883 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1884 if (sshclient
.IsEmpty())
1885 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1887 if(!sshclient
.IsEmpty())
1889 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1890 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1894 TCHAR sPlink
[MAX_PATH
] = {0};
1895 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1896 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1898 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1899 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1900 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1905 TCHAR sAskPass
[MAX_PATH
] = {0};
1906 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1907 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1910 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1911 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1912 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1913 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1917 // add git/bin path to PATH
1919 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1920 CString str
= msysdir
;
1921 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1923 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
1927 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1928 str
= msyslocalinstalldir
;
1929 str
.TrimRight(_T("\\"));
1932 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1933 str
= msysinstalldir
;
1934 str
.TrimRight(_T("\\"));
1936 if ( !str
.IsEmpty() )
1940 CGit::ms_LastMsysGitDir
= str
;
1945 // search PATH if git/bin directory is already present
1946 if ( FindGitPath() )
1948 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
1949 m_bInitialized
= TRUE
;
1950 msysdir
= CGit::ms_LastMsysGitDir
;
1960 CGit::ms_LastMsysGitDir
= str
;
1963 // check for git.exe existance (maybe it was deinstalled in the meantime)
1964 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1966 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
1970 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
1971 // Configure libgit2 search paths
1973 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1974 msysGitDir
.ReleaseBuffer();
1975 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1976 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1977 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1978 static git_smart_subtransport_definition ssh_wintunnel_subtransport_definition
= { [](git_smart_subtransport
**out
, git_transport
* owner
) -> int { return git_smart_subtransport_ssh_wintunnel(out
, owner
, FindExecutableOnPath(g_Git
.m_Environment
.GetEnv(_T("GIT_SSH")), g_Git
.m_Environment
.GetEnv(_T("PATH"))), &g_Git
.m_Environment
[0]); }, 0 };
1979 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
1980 CString msysGitTemplateDir
;
1981 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1982 msysGitTemplateDir
.ReleaseBuffer();
1983 SetLibGit2TemplatePath(msysGitTemplateDir
);
1986 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1989 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1991 m_Environment
.SetEnv(_T("PATH"), path
);
1993 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1995 CString sOldPath
= oldpath
;
1998 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
1999 // register filter only once
2000 if (!git_filter_lookup("filter"))
2002 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir
+ L
"\\sh.exe\"", &m_Environment
[0]), GIT_FILTER_DRIVER_PRIORITY
))
2007 m_bInitialized
= TRUE
;
2011 CString
CGit::GetHomeDirectory() const
2013 const wchar_t * homeDir
= wget_windows_home_directory();
2014 return CString(homeDir
, (int)wcslen(homeDir
));
2017 CString
CGit::GetGitLocalConfig() const
2020 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
2021 path
+= _T("config");
2025 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2027 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2030 CString
CGit::GetGitGlobalConfig() const
2032 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2035 CString
CGit::GetGitGlobalXDGConfigPath() const
2037 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2040 CString
CGit::GetGitGlobalXDGConfig() const
2042 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2045 CString
CGit::GetGitSystemConfig() const
2047 const wchar_t * systemConfig
= wget_msysgit_etc();
2048 return CString(systemConfig
, (int)wcslen(systemConfig
));
2051 BOOL
CGit::CheckCleanWorkTree()
2055 cmd
=_T("git.exe rev-parse --verify HEAD");
2057 if(Run(cmd
,&out
,CP_UTF8
))
2060 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2061 if(Run(cmd
,&out
,CP_UTF8
))
2064 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2065 if(Run(cmd
,&out
,CP_UTF8
))
2068 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2069 if(Run(cmd
,&out
,CP_UTF8
))
2074 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2077 for (int i
= 0; i
< list
.GetCount(); ++i
)
2079 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2085 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2089 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2091 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2093 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2097 // if the filenames only differ in case, we have to pass "-f"
2098 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2100 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2101 if (Run(cmd
, &err
, CP_UTF8
))
2104 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2105 if (Run(cmd
, &err
, CP_UTF8
))
2108 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2109 { //To init git repository, there are not HEAD, so we can use git reset command
2110 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2112 if (Run(cmd
, &err
, CP_UTF8
))
2117 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2118 if (Run(cmd
, &err
, CP_UTF8
))
2122 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2124 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2125 if (Run(cmd
, &err
, CP_UTF8
))
2132 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2138 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2140 cmd
=_T("git.exe ls-files -u -t -z");
2142 if (Run(cmd
, &vector
))
2147 if (list
.ParserFromLsFile(vector
))
2153 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2155 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2157 CAutoRepository
repo(GetGitRepository());
2161 CGitHash fromHash
, toHash
, baseHash
;
2162 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2165 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2169 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2172 baseHash
= baseOid
.id
;
2175 *commonAncestor
= baseHash
;
2177 return fromHash
== baseHash
;
2181 CGitHash basehash
,hash
;
2183 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2185 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2189 basehash
= base
.Trim();
2191 GetHash(hash
, from
);
2194 *commonAncestor
= basehash
;
2196 return hash
== basehash
;
2199 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2202 for (int i
= 0; i
< 4; ++i
)
2205 ret
|= hash
.m_hash
[i
];
2210 int CGit::RefreshGitIndex()
2212 if(g_Git
.m_IsUseGitDLL
)
2214 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2217 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2228 cmd
=_T("git.exe update-index --refresh");
2229 return Run(cmd
, &output
, CP_UTF8
);
2233 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2235 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2237 CAutoRepository
repo(GetGitRepository());
2242 if (GetHash(repo
, hash
, Refname
))
2246 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2250 if (git_commit_tree(tree
.GetPointer(), commit
))
2253 CAutoTreeEntry entry
;
2254 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2258 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2261 FILE *file
= nullptr;
2262 _tfopen_s(&file
, outputfile
, _T("w"));
2263 if (file
== nullptr)
2265 giterr_set_str(GITERR_NONE
, "Could not create file.");
2269 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2274 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2276 giterr_set_str(GITERR_OS
, "Could not write to file.");
2285 else if (g_Git
.m_IsUseGitDLL
)
2287 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2290 g_Git
.CheckAndInitDll();
2291 CStringA ref
, patha
, outa
;
2292 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2293 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2294 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2295 ::DeleteFile(outputfile
);
2296 return git_checkout_file(ref
, patha
, outa
);
2299 catch (const char * msg
)
2301 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2306 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2313 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2314 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2317 void CEnvironment::CopyProcessEnvironment()
2319 TCHAR
*porig
= GetEnvironmentStrings();
2321 while(*p
!=0 || *(p
+1) !=0)
2322 this->push_back(*p
++);
2324 push_back(_T('\0'));
2325 push_back(_T('\0'));
2327 FreeEnvironmentStrings(porig
);
2330 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2333 for (size_t i
= 0; i
< size(); ++i
)
2337 CString sname
= str
.Tokenize(_T("="),start
);
2338 if(sname
.CompareNoCase(name
) == 0)
2340 return &(*this)[i
+start
];
2347 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2350 for (i
= 0; i
< size(); ++i
)
2352 CString str
= &(*this)[i
];
2354 CString sname
= str
.Tokenize(_T("="),start
);
2355 if(sname
.CompareNoCase(name
) == 0)
2364 i
-= 1; // roll back terminate \0\0
2365 this->push_back(_T('\0'));
2368 CEnvironment::iterator it
;
2372 while(*it
&& i
<size())
2381 this->insert(it
,*name
++);
2386 this->insert(it
, _T('='));
2392 this->insert(it
,*value
++);
2399 int CGit::GetGitEncode(TCHAR
* configkey
)
2401 CString str
=GetConfigValue(configkey
);
2406 return CUnicodeUtils::GetCPCode(str
);
2410 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2416 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2421 diff
= GetGitDiff();
2423 git_open_diff(&diff
, arg
);
2427 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2438 isStat
= !!strstr(arg
, "stat");
2443 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2445 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2454 for (int j
= 0; j
< count
; ++j
)
2463 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2464 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2465 &mode
,&IsBin
,&inc
,&dec
);
2467 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2468 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2470 path
.SetFromGit(strnewname
,&stroldname
);
2471 path
.ParserAction((BYTE
)mode
);
2475 path
.m_StatAdd
=_T("-");
2476 path
.m_StatDel
=_T("-");
2480 path
.m_StatAdd
.Format(_T("%d"),inc
);
2481 path
.m_StatDel
.Format(_T("%d"),dec
);
2483 PathList
->AddPath(path
);
2485 git_diff_flush(diff
);
2488 git_close_diff(diff
);
2493 int CGit::GetShortHASHLength() const
2498 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2502 REF_TYPE type
= CGit::UNKNOWN
;
2504 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2506 type
= CGit::LOCAL_BRANCH
;
2509 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2511 type
= CGit::REMOTE_BRANCH
;
2513 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2517 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2520 shortname
=_T("stash");
2522 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2524 if (shortname
.Find(_T("good")) == 0)
2526 type
= CGit::BISECT_GOOD
;
2527 shortname
= _T("good");
2530 if (shortname
.Find(_T("bad")) == 0)
2532 type
= CGit::BISECT_BAD
;
2533 shortname
= _T("bad");
2536 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2540 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2542 type
= CGit::UNKNOWN
;
2546 type
= CGit::UNKNOWN
;
2556 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2558 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2561 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2564 if (rev2
== GitRev::GetWorkingCopy())
2565 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2566 else if (rev1
== GitRev::GetWorkingCopy())
2567 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2578 if (diffContext
>= 0)
2579 unified
.Format(_T(" --unified=%d"), diffContext
);
2580 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2583 if (!path
.IsEmpty())
2586 cmd
+= path
.GetGitPathString();
2593 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2595 ATLASSERT(payload
&& line
);
2596 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2597 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2598 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2602 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2604 ATLASSERT(repo
&& identifier
&& tree
);
2606 /* try to resolve identifier */
2608 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2612 return GIT_ENOTFOUND
;
2615 switch (git_object_type(obj
))
2618 *tree
= (git_tree
*)obj
.Detach();
2620 case GIT_OBJ_COMMIT
:
2621 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2624 err
= GIT_ENOTFOUND
;
2630 /* use libgit2 get unified diff */
2631 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const git_revnum_t
& revOld
, const git_revnum_t
& revNew
, git_diff_line_cb callback
, void *data
, bool /* bMerge */)
2633 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2634 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2636 CAutoRepository
repo(g_Git
.GetGitRepository());
2640 int isHeadOrphan
= git_repository_head_unborn(repo
);
2641 if (isHeadOrphan
== 1)
2643 else if (isHeadOrphan
!= 0)
2646 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2647 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2648 char *buf
= pathA
.GetBuffer();
2649 if (!pathA
.IsEmpty())
2651 opts
.pathspec
.strings
= &buf
;
2652 opts
.pathspec
.count
= 1;
2656 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2661 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2664 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2667 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2670 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2673 if (git_diff_merge(diff
, diff2
))
2678 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2681 if (tree1
.IsEmpty())
2689 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2692 if (tree2
.IsEmpty())
2694 /* don't check return value, there are not parent commit at first commit*/
2695 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2697 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2699 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2703 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2706 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2709 if (git_patch_print(patch
, callback
, data
))
2713 pathA
.ReleaseBuffer();
2718 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2720 if (UsingLibGit2(GIT_CMD_DIFF
))
2722 FILE *file
= nullptr;
2723 _tfopen_s(&file
, patchfile
, _T("w"));
2724 if (file
== nullptr)
2726 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2733 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2734 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2738 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2740 ATLASSERT(payload
&& line
);
2741 CStringA
*str
= (CStringA
*) payload
;
2742 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2743 str
->Append(&line
->origin
, 1);
2744 str
->Append(line
->content
, (int)line
->content_len
);
2748 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2750 if (UsingLibGit2(GIT_CMD_DIFF
))
2751 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2755 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2757 int ret
= Run(cmd
, &vector
);
2758 if (!vector
.empty())
2760 vector
.push_back(0); // vector is not NUL terminated
2761 buffer
->Append((char *)&vector
[0]);
2767 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2769 if (UsingLibGit2(GIT_CMD_REVERT
))
2771 CAutoRepository
repo(GetGitRepository());
2776 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2779 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2780 revert_opts
.mainline
= parent
;
2781 int result
= git_revert(repo
, commit
, &revert_opts
);
2783 return !result
? 0 : -1;
2789 merge
.Format(_T("-m %d "), parent
);
2790 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2791 gitLastErr
= cmd
+ _T("\n");
2792 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2804 int CGit::DeleteRef(const CString
& reference
)
2806 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2808 CAutoRepository
repo(GetGitRepository());
2813 if (reference
.Right(3) == _T("^{}"))
2814 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2816 refA
= CUnicodeUtils::GetUTF8(reference
);
2819 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
2823 if (git_reference_is_tag(ref
))
2824 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2825 else if (git_reference_is_branch(ref
))
2826 result
= git_branch_delete(ref
);
2827 else if (git_reference_is_remote(ref
))
2828 result
= git_branch_delete(ref
);
2830 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2836 CString cmd
, shortname
;
2837 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2838 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2839 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2840 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2841 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2842 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2845 gitLastErr
= L
"unsupported reference type: " + reference
;
2849 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2857 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2859 if (PathFileExists(filename
))
2861 FILE *pFile
= nullptr;
2862 _tfopen_s(&pFile
, filename
, _T("r"));
2868 char s
[8196] = { 0 };
2869 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2872 str
+= CStringA(s
, read
);
2875 msg
= CUnicodeUtils::GetUnicode(str
);
2876 msg
.Replace(_T("\r\n"), _T("\n"));
2877 msg
.TrimRight(_T("\n"));
2881 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
2882 return true; // load no further files