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 LPTSTR
nextpath(wchar_t *path
, wchar_t *buf
, size_t buflen
)
41 wchar_t term
, *base
= path
;
43 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
46 term
= (*path
== L
'"') ? *path
++ : L
';';
48 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
51 *buf
= L
'\0'; /* reserved a byte via initial subtract */
53 while (*path
== term
|| *path
== L
';')
56 return (path
!= base
) ? path
: NULL
;
59 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
62 return _tstat(lpszFileName
, &st
) == 0;
65 static BOOL
FindGitPath()
68 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
75 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
76 _tgetenv_s(&size
, env
, size
, _T("PATH"));
78 TCHAR buf
[MAX_PATH
] = {0};
80 // search in all paths defined in PATH
81 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
83 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
85 // ensure trailing slash
86 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
87 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
89 const size_t len
= _tcslen(buf
);
91 if ((len
+ 7) < MAX_PATH
)
92 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, _T("git.exe"));
96 if ( FileExists(buf
) )
100 CGit::ms_LastMsysGitDir
= buf
;
101 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
102 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
104 // often the msysgit\cmd folder is on the %PATH%, but
105 // that git.exe does not work, so try to guess the bin folder
106 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
107 if (FileExists(binDir
))
108 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
117 static bool g_bSortLogical
;
118 static bool g_bSortLocalBranchesFirst
;
119 static bool g_bSortTagsReversed
;
121 static void GetSortOptions()
123 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
125 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
126 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
127 if (g_bSortLocalBranchesFirst
)
128 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
129 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
130 if (!g_bSortTagsReversed
)
131 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
134 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
137 return StrCmpLogicalW(left
, right
) < 0;
138 return StrCmpI(left
, right
) < 0;
141 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
144 return StrCmpLogicalW(left
, right
) > 0;
145 return StrCmpI(left
, right
) > 0;
148 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
150 if (g_bSortLocalBranchesFirst
)
152 int leftIsRemote
= left
.Find(_T("remotes/"));
153 int rightIsRemote
= right
.Find(_T("remotes/"));
155 if (leftIsRemote
== 0 && rightIsRemote
< 0)
157 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
161 return StrCmpLogicalW(left
, right
) < 0;
162 return StrCmpI(left
, right
) < 0;
165 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
167 CString
CGit::ms_LastMsysGitDir
;
168 int CGit::ms_LastMsysGitVersion
= 0;
174 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
175 m_CurrentDir
.ReleaseBuffer();
176 m_IsGitDllInited
= false;
178 m_GitSimpleListDiff
=0;
179 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
180 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
181 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
));
183 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
186 this->m_bInitialized
=false;
188 m_critGitDllSec
.Init();
195 git_close_diff(m_GitDiff
);
198 if(this->m_GitSimpleListDiff
)
200 git_close_diff(m_GitSimpleListDiff
);
201 m_GitSimpleListDiff
=0;
205 bool CGit::IsBranchNameValid(const CString
& branchname
)
207 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
209 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
211 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
212 return !!git_reference_is_valid_name(branchA
);
215 static bool IsPowerShell(CString cmd
)
218 int powerShellPos
= cmd
.Find(_T("powershell"));
219 if (powerShellPos
< 0)
222 // found the word powershell, check that it is the command and not any parameter
223 int end
= cmd
.GetLength();
224 if (cmd
.Find(_T('"')) == 0)
226 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
227 if (secondDoubleQuote
> 0)
228 end
= secondDoubleQuote
;
232 int firstSpace
= cmd
.Find(_T(' '));
237 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
240 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
242 SECURITY_ATTRIBUTES sa
;
243 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
244 CAutoGeneralHandle hStdioFile
;
246 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
247 sa
.lpSecurityDescriptor
=NULL
;
248 sa
.bInheritHandle
=TRUE
;
249 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
251 CString err
= CFormatMessageWrapper();
252 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
253 return TGIT_GIT_ERROR_OPEN_PIP
;
255 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
257 CString err
= CFormatMessageWrapper();
258 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
259 return TGIT_GIT_ERROR_OPEN_PIP
;
264 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
265 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
269 PROCESS_INFORMATION pi
;
270 si
.cb
=sizeof(STARTUPINFO
);
274 si
.hStdError
= hWriteErr
;
276 si
.hStdError
= hWrite
;
278 si
.hStdOutput
=hStdioFile
;
280 si
.hStdOutput
=hWrite
;
282 si
.wShowWindow
=SW_HIDE
;
283 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
285 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
286 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
288 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
290 // 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,
291 // 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)
292 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
293 if (IsPowerShell(cmd
))
294 dwFlags
|= CREATE_NEW_CONSOLE
;
296 dwFlags
|= DETACHED_PROCESS
;
298 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
299 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
301 if(cmd
.Find(_T("git")) == 0)
303 int firstSpace
= cmd
.Find(_T(" "));
305 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
307 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
310 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
311 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
313 CString err
= CFormatMessageWrapper();
314 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
315 return TGIT_GIT_ERROR_CREATE_PROCESS
;
323 *hReadOut
= hRead
.Detach();
325 *hErrReadOut
= hReadErr
.Detach();
329 //Must use sperate function to convert ANSI str to union code string
330 //Becuase A2W use stack as internal convert buffer.
331 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
338 len
= (int)strlen((const char*)p
);
343 int currentContentLen
= str
->GetLength();
344 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
345 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
346 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
349 // This method was originally used to check for orphaned branches
350 BOOL
CGit::CanParseRev(CString ref
)
356 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
366 // Checks if we have an orphaned HEAD
367 BOOL
CGit::IsInitRepos()
370 // handle error on reading HEAD hash as init repo
371 if (GetHash(hash
, _T("HEAD")) != 0)
373 return hash
.IsEmpty() ? TRUE
: FALSE
;
376 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
378 PASYNCREADSTDERRTHREADARGS pDataArray
;
379 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
382 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
383 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
385 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
392 int CGit::Run(CGitCall
* pcall
)
394 PROCESS_INFORMATION pi
;
395 CAutoGeneralHandle hRead
, hReadErr
;
396 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
397 return TGIT_GIT_ERROR_CREATE_PROCESS
;
399 CAutoGeneralHandle
piThread(pi
.hThread
);
400 CAutoGeneralHandle
piProcess(pi
.hProcess
);
402 ASYNCREADSTDERRTHREADARGS threadArguments
;
403 threadArguments
.fileHandle
= hReadErr
;
404 threadArguments
.pcall
= pcall
;
405 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
408 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
410 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
412 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
413 if(!bAborted
)//For now, flush output when command aborted.
414 if(pcall
->OnOutputData(data
,readnumber
))
421 WaitForSingleObject(thread
, INFINITE
);
423 WaitForSingleObject(pi
.hProcess
, INFINITE
);
426 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
428 CString err
= CFormatMessageWrapper();
429 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
430 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
433 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
437 class CGitCall_ByteVector
: public CGitCall
440 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
441 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
443 if (!m_pvector
|| size
== 0)
445 size_t oldsize
=m_pvector
->size();
446 m_pvector
->resize(m_pvector
->size()+size
);
447 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
450 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
452 if (!m_pvectorErr
|| size
== 0)
454 size_t oldsize
= m_pvectorErr
->size();
455 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
456 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
459 BYTE_VECTOR
* m_pvector
;
460 BYTE_VECTOR
* m_pvectorErr
;
463 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
465 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
468 int CGit::Run(CString cmd
, CString
* output
, int code
)
472 ret
= Run(cmd
, output
, &err
, code
);
474 if (output
&& !err
.IsEmpty())
476 if (!output
->IsEmpty())
483 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
485 BYTE_VECTOR vector
, vectorErr
;
488 ret
= Run(cmd
, &vector
, &vectorErr
);
490 ret
= Run(cmd
, &vector
);
493 StringAppend(output
, &(vector
[0]), code
);
497 vectorErr
.push_back(0);
498 StringAppend(outputErr
, &(vectorErr
[0]), code
);
504 class CGitCallCb
: public CGitCall
507 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
509 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
514 int oldEndPos
= m_buffer
.GetLength();
515 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
516 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
518 // Break into lines and feed to m_recv
520 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
522 m_recv(m_buffer
.Left(eolPos
));
523 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
528 virtual bool OnOutputErrData(const BYTE
*, size_t) override
530 return false; // Ignore error output for now
533 virtual void OnEnd() override
535 if (!m_buffer
.IsEmpty())
537 m_buffer
.Empty(); // Just for sure
541 GitReceiverFunc m_recv
;
545 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
547 CGitCallCb
call(cmd
, recv
);
551 CString
CGit::GetUserName(void)
554 env
.CopyProcessEnvironment();
555 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
556 if (!envname
.IsEmpty())
558 return GetConfigValue(L
"user.name");
560 CString
CGit::GetUserEmail(void)
563 env
.CopyProcessEnvironment();
564 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
565 if (!envmail
.IsEmpty())
568 return GetConfigValue(L
"user.email");
571 CString
CGit::GetConfigValue(const CString
& name
)
575 if(this->m_IsUseGitDLL
)
577 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
586 key
= CUnicodeUtils::GetUTF8(name
);
590 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
593 catch (const char *msg
)
595 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
599 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
600 return configValue
.Tokenize(_T("\n"),start
);
605 cmd
.Format(L
"git.exe config %s", name
);
606 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
607 return configValue
.Tokenize(_T("\n"),start
);
611 bool CGit::GetConfigValueBool(const CString
& name
)
613 CString configValue
= GetConfigValue(name
);
614 configValue
.MakeLower();
616 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
622 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
624 CString configValue
= GetConfigValue(name
);
626 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
631 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
633 if(this->m_IsUseGitDLL
)
635 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
644 CStringA keya
, valuea
;
645 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
646 valuea
= CUnicodeUtils::GetUTF8(value
);
650 return [=]() { return get_set_config(keya
, valuea
, type
); }();
652 catch (const char *msg
)
654 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
665 option
= _T("--global");
668 option
= _T("--system");
673 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
675 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
683 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
685 if(this->m_IsUseGitDLL
)
687 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
696 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
700 return [=]() { return get_set_config(keya
, nullptr, type
); }();
702 catch (const char *msg
)
704 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
715 option
= _T("--global");
718 option
= _T("--system");
723 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
725 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
733 CString
CGit::GetCurrentBranch(bool fallback
)
736 //Run(_T("git.exe branch"),&branch);
738 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
739 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
741 return _T("(no branch)");
748 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
750 if (localBranch
.IsEmpty())
754 configName
.Format(L
"branch.%s.remote", localBranch
);
755 pullRemote
= GetConfigValue(configName
);
757 //Select pull-branch from current branch
758 configName
.Format(L
"branch.%s.merge", localBranch
);
759 pullBranch
= StripRefName(GetConfigValue(configName
));
762 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
765 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
767 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
770 CString
CGit::GetFullRefName(const CString
& shortRefName
)
774 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
775 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
776 return CString();//Error
778 return refName
.Tokenize(L
"\n", iStart
);
781 CString
CGit::StripRefName(CString refName
)
783 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
784 refName
= refName
.Mid(11);
785 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
786 refName
= refName
.Mid(5);
788 return refName
.Tokenize(_T("\n"),start
);
791 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
793 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
795 if ( sProjectRoot
.IsEmpty() )
799 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
802 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
805 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
813 fgets(s
, sizeof(s
), pFile
);
817 const char *pfx
= "ref: refs/heads/";
818 const int len
= 16;//strlen(pfx)
820 if ( !strncmp(s
, pfx
, len
) )
822 //# We're on a branch. It might not exist. But
823 //# HEAD looks good enough to be a branch.
824 CStringA
utf8Branch(s
+ len
);
825 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
826 sBranchOut
.TrimRight(_T(" \r\n\t"));
828 if ( sBranchOut
.IsEmpty() )
833 CStringA
utf8Hash(s
);
834 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
835 unicodeHash
.TrimRight(_T(" \r\n\t"));
836 if (CGitHash::IsValidSHA1(unicodeHash
))
837 sBranchOut
= unicodeHash
;
839 //# Assume this is a detached head.
840 sBranchOut
= _T("HEAD");
845 //# Assume this is a detached head.
854 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
857 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
861 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
863 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
865 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
867 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
869 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
871 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
873 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
877 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
879 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
881 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
886 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
892 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
899 CString file
= _T(" --");
902 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
905 num
.Format(_T("-n%d"),count
);
909 if(mask
& LOG_INFO_STAT
)
910 param
+= _T(" --numstat ");
911 if(mask
& LOG_INFO_FILESTATE
)
912 param
+= _T(" --raw ");
914 if(mask
& LOG_INFO_FULLHISTORY
)
915 param
+= _T(" --full-history ");
917 if(mask
& LOG_INFO_BOUNDARY
)
918 param
+= _T(" --left-right --boundary ");
920 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
921 param
+= _T(" --all ");
923 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
924 param
+= _T(" --branches ");
926 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
929 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
932 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
933 param
+= _T(" --first-parent ");
935 if(mask
& CGit::LOG_INFO_NO_MERGE
)
936 param
+= _T(" --no-merges ");
938 if(mask
& CGit::LOG_INFO_FOLLOW
)
939 param
+= _T(" --follow ");
941 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
944 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
945 param
+= _T(" --full-diff ");
947 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
948 param
+= _T(" --simplify-by-decoration ");
954 if( Filter
&& (Filter
->m_From
!= -1))
956 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
960 if( Filter
&& (Filter
->m_To
!= -1))
962 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
967 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
969 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
974 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
976 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
981 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
983 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
990 if(!Filter
->m_IsRegex
)
991 param
+= _T(" --fixed-strings ");
993 param
+= _T(" --regexp-ignore-case --extended-regexp ");
996 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
997 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
998 param
+= _T(" --topo-order");
999 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1000 param
+= _T(" --date-order");
1002 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
1003 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1007 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1008 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1017 void GetTempPath(CString
&path
)
1019 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1021 DWORD dwBufSize
=BUFSIZE
;
1022 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1023 lpPathBuffer
); // buffer for path
1024 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1028 path
.Format(_T("%s"),lpPathBuffer
);
1030 CString
GetTempFile()
1032 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1034 DWORD dwBufSize
=BUFSIZE
;
1035 TCHAR szTempName
[BUFSIZE
] = { 0 };
1038 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1039 lpPathBuffer
); // buffer for path
1040 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1044 // Create a temporary file.
1045 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1046 TEXT("Patch"), // temp file name prefix
1047 0, // create unique name
1048 szTempName
); // buffer for name
1056 return CString(szTempName
);
1060 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1062 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1063 if (result
== 0) return 0;
1064 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1071 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1072 CreateDirectory(lpBuffer
, NULL
);
1077 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1080 PROCESS_INFORMATION pi
;
1081 si
.cb
=sizeof(STARTUPINFO
);
1082 GetStartupInfo(&si
);
1084 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1085 psa
.bInheritHandle
=TRUE
;
1087 HANDLE hReadErr
, hWriteErr
;
1088 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1090 CString err
= CFormatMessageWrapper();
1091 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1092 return TGIT_GIT_ERROR_OPEN_PIP
;
1095 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1096 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1098 if (houtfile
== INVALID_HANDLE_VALUE
)
1100 CString err
= CFormatMessageWrapper();
1101 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1102 CloseHandle(hReadErr
);
1103 CloseHandle(hWriteErr
);
1104 return TGIT_GIT_ERROR_OPEN_PIP
;
1107 si
.wShowWindow
= SW_HIDE
;
1108 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1109 si
.hStdOutput
= houtfile
;
1110 si
.hStdError
= hWriteErr
;
1112 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1113 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1115 if(cmd
.Find(_T("git")) == 0)
1116 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1118 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1119 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1121 CString err
= CFormatMessageWrapper();
1122 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1124 CloseHandle(hReadErr
);
1125 CloseHandle(hWriteErr
);
1126 CloseHandle(houtfile
);
1127 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1130 BYTE_VECTOR stderrVector
;
1131 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1133 ASYNCREADSTDERRTHREADARGS threadArguments
;
1134 threadArguments
.fileHandle
= hReadErr
;
1135 threadArguments
.pcall
= &pcall
;
1136 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1138 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1140 CloseHandle(hWriteErr
);
1141 CloseHandle(hReadErr
);
1144 WaitForSingleObject(thread
, INFINITE
);
1146 stderrVector
.push_back(0);
1147 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1150 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1152 CString err
= CFormatMessageWrapper();
1153 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1154 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1157 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1159 CloseHandle(pi
.hThread
);
1160 CloseHandle(pi
.hProcess
);
1161 CloseHandle(houtfile
);
1165 git_repository
* CGit::GetGitRepository() const
1167 git_repository
* repo
= nullptr;
1168 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1172 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1176 // no need to parse a ref if it's already a 40-byte hash
1177 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1179 hash
= CGitHash(friendname
);
1183 int isHeadOrphan
= git_repository_head_unborn(repo
);
1184 if (isHeadOrphan
!= 0)
1187 if (isHeadOrphan
== 1)
1193 CAutoObject gitObject
;
1194 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1197 const git_oid
* oid
= git_object_id(gitObject
);
1201 hash
= CGitHash((char *)oid
->id
);
1206 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1208 // no need to parse a ref if it's already a 40-byte hash
1209 if (CGitHash::IsValidSHA1(friendname
))
1211 hash
= CGitHash(friendname
);
1217 CAutoRepository
repo(GetGitRepository());
1221 return GetHash(repo
, hash
, friendname
, true);
1226 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1228 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1229 hash
= CGitHash(gitLastErr
.Trim());
1236 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1241 cmd
=_T("git.exe ls-files -s -t -z");
1243 if (Run(cmd
, &cmdout
))
1246 if (outputlist
.ParserFromLsFile(cmdout
))
1248 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1249 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1253 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1257 if (ignoreSpaceAtEol
)
1258 ignore
+= _T(" --ignore-space-at-eol");
1259 if (ignoreSpaceChange
)
1260 ignore
+= _T(" --ignore-space-change");
1262 ignore
+= _T(" --ignore-all-space");
1263 if (ignoreBlankLines
)
1264 ignore
+= _T(" --ignore-blank-lines");
1266 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1269 if(rev1
== GIT_REV_ZERO
)
1270 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1272 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1276 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1283 outputlist
.ParserFromLog(out
);
1288 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1290 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1292 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1293 list
->push_back(str
);
1297 int CGit::GetTagList(STRING_VECTOR
&list
)
1299 if (this->m_IsUseLibGit2
)
1301 CAutoRepository
repo(GetGitRepository());
1305 CAutoStrArray tag_names
;
1307 if (git_tag_list(tag_names
, repo
))
1310 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1312 CStringA
tagName(tag_names
->strings
[i
]);
1313 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1316 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1322 CString cmd
, output
;
1323 cmd
=_T("git.exe tag -l");
1324 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1331 one
=output
.Tokenize(_T("\n"),pos
);
1333 list
.push_back(one
);
1335 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1341 CString
CGit::GetGitLastErr(const CString
& msg
)
1343 if (this->m_IsUseLibGit2
)
1344 return GetLibGit2LastErr(msg
);
1345 else if (gitLastErr
.IsEmpty())
1346 return msg
+ _T("\nUnknown git.exe error.");
1349 CString lastError
= gitLastErr
;
1351 return msg
+ _T("\n") + lastError
;
1355 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1357 if (UsingLibGit2(cmd
))
1358 return GetLibGit2LastErr(msg
);
1359 else if (gitLastErr
.IsEmpty())
1360 return msg
+ _T("\nUnknown git.exe error.");
1363 CString lastError
= gitLastErr
;
1365 return msg
+ _T("\n") + lastError
;
1369 CString
CGit::GetLibGit2LastErr()
1371 const git_error
*libgit2err
= giterr_last();
1374 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1376 return _T("libgit2 returned: ") + lastError
;
1379 return _T("An error occoured in libgit2, but no message is available.");
1382 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1385 return msg
+ _T("\n") + GetLibGit2LastErr();
1386 return GetLibGit2LastErr();
1389 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1391 if(branchName
== "FETCH_HEAD")
1392 branchName
= DerefFetchHead();
1396 CString
CGit::FixBranchName(const CString
& branchName
)
1398 CString tempBranchName
= branchName
;
1399 FixBranchName_Mod(tempBranchName
);
1400 return tempBranchName
;
1403 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1407 CAutoRepository
repo(GetGitRepository());
1409 return true; // TODO: optimize error reporting
1411 CAutoReference tagRef
;
1412 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1415 CAutoReference branchRef
;
1416 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1425 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1426 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1432 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1442 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1446 CAutoRepository
repo(GetGitRepository());
1448 return false; // TODO: optimize error reporting
1452 prefix
= _T("refs/heads/");
1454 prefix
= _T("refs/tags/");
1457 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1463 CString cmd
, output
;
1465 cmd
= _T("git.exe show-ref ");
1467 cmd
+= _T("--heads ");
1469 cmd
+= _T("--tags ");
1471 cmd
+= _T("refs/heads/") + name
;
1472 cmd
+= _T(" refs/tags/") + name
;
1474 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1477 if (!output
.IsEmpty())
1484 CString
CGit::DerefFetchHead()
1487 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1488 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1489 int forMergeLineCount
= 0;
1491 std::string hashToReturn
;
1492 while(getline(fetchHeadFile
, line
))
1494 //Tokenize this line
1495 std::string::size_type prevPos
= 0;
1496 std::string::size_type pos
= line
.find('\t');
1497 if(pos
== std::string::npos
) continue; //invalid line
1499 std::string hash
= line
.substr(0, pos
);
1500 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1502 bool forMerge
= pos
== prevPos
;
1503 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1505 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1510 hashToReturn
= hash
;
1511 ++forMergeLineCount
;
1512 if(forMergeLineCount
> 1)
1513 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1517 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1520 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1526 CAutoRepository
repo(GetGitRepository());
1530 if (git_repository_head_detached(repo
) == 1)
1531 cur
= _T("(detached from ");
1533 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1535 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1536 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1537 flags
= GIT_BRANCH_ALL
;
1538 else if (type
& BRANCH_REMOTE
)
1539 flags
= GIT_BRANCH_REMOTE
;
1541 CAutoBranchIterator it
;
1542 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1545 git_reference
* ref
= nullptr;
1546 git_branch_t branchType
;
1547 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1549 CAutoReference
autoRef(ref
);
1550 const char * name
= nullptr;
1551 if (git_branch_name(&name
, ref
))
1554 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1555 if (branchType
& GIT_BRANCH_REMOTE
)
1556 list
.push_back(_T("remotes/") + branchname
);
1559 if (git_branch_is_head(ref
))
1561 list
.push_back(branchname
);
1568 CString cmd
, output
;
1569 cmd
= _T("git.exe branch --no-color");
1571 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1573 else if (type
& BRANCH_REMOTE
)
1576 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1583 one
= output
.Tokenize(_T("\n"), pos
);
1584 one
.Trim(L
" \r\n\t");
1585 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1586 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1587 if (one
[0] == _T('*'))
1592 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1593 list
.push_back(one
);
1598 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1599 list
.push_back(L
"FETCH_HEAD");
1601 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1603 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1605 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1618 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1620 if (this->m_IsUseLibGit2
)
1622 CAutoRepository
repo(GetGitRepository());
1626 CAutoStrArray remotes
;
1627 if (git_remote_list(remotes
, repo
))
1630 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1632 CStringA
remote(remotes
->strings
[i
]);
1633 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1636 std::sort(list
.begin(), list
.end());
1643 CString cmd
, output
;
1644 cmd
=_T("git.exe remote");
1645 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1652 one
=output
.Tokenize(_T("\n"),pos
);
1654 list
.push_back(one
);
1661 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1663 CString cmd
, out
, err
;
1664 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1665 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1667 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1674 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1675 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1676 if (one
.Find(_T("^{}")) >= 1)
1679 list
.push_back(one
);
1681 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1685 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1687 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1689 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1690 list
->push_back(str
);
1694 int CGit::GetRefList(STRING_VECTOR
&list
)
1696 if (this->m_IsUseLibGit2
)
1698 CAutoRepository
repo(GetGitRepository());
1702 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1705 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1711 CString cmd
, output
;
1712 cmd
=_T("git.exe show-ref -d");
1713 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1720 one
=output
.Tokenize(_T("\n"),pos
);
1721 int start
=one
.Find(_T(" "),0);
1725 name
=one
.Right(one
.GetLength()-start
-1);
1726 list
.push_back(name
);
1729 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1735 typedef struct map_each_ref_payload
{
1736 git_repository
* repo
;
1737 MAP_HASH_NAME
* map
;
1738 } map_each_ref_payload
;
1740 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1742 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1745 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1747 CAutoObject gitObject
;
1748 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1751 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1753 str
+= _T("^{}"); // deref tag
1754 CAutoObject derefedTag
;
1755 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1757 gitObject
.Swap(derefedTag
);
1760 const git_oid
* oid
= git_object_id(gitObject
);
1764 CGitHash
hash((char *)oid
->id
);
1765 (*payloadContent
->map
)[hash
].push_back(str
);
1769 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1773 map_each_ref_payload payloadContent
= { repo
, &map
};
1775 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1778 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1780 std::sort(it
->second
.begin(), it
->second
.end());
1786 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1788 if (this->m_IsUseLibGit2
)
1790 CAutoRepository
repo(GetGitRepository());
1794 return GetMapHashToFriendName(repo
, map
);
1798 CString cmd
, output
;
1799 cmd
=_T("git.exe show-ref -d");
1800 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1807 one
=output
.Tokenize(_T("\n"),pos
);
1808 int start
=one
.Find(_T(" "),0);
1812 name
=one
.Right(one
.GetLength()-start
-1);
1815 hash
=one
.Left(start
);
1817 map
[CGitHash(hash
)].push_back(name
);
1825 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1827 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1828 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1831 static void SetLibGit2TemplatePath(const CString
&value
)
1833 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1834 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1837 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1844 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
1845 this->m_Environment
.clear();
1846 m_Environment
.CopyProcessEnvironment();
1849 size_t homesize
,size
;
1851 // set HOME if not set already
1852 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1854 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1857 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1858 if (sshclient
.IsEmpty())
1859 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1861 if(!sshclient
.IsEmpty())
1863 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1864 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1868 TCHAR sPlink
[MAX_PATH
] = {0};
1869 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1870 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1872 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1873 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1874 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1879 TCHAR sAskPass
[MAX_PATH
] = {0};
1880 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1881 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1884 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1885 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1886 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1887 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1891 // add git/bin path to PATH
1893 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1894 CString str
= msysdir
;
1895 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1897 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
1901 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1902 str
= msyslocalinstalldir
;
1903 str
.TrimRight(_T("\\"));
1906 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1907 str
= msysinstalldir
;
1908 str
.TrimRight(_T("\\"));
1910 if ( !str
.IsEmpty() )
1914 CGit::ms_LastMsysGitDir
= str
;
1919 // search PATH if git/bin directory is already present
1920 if ( FindGitPath() )
1922 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
1923 m_bInitialized
= TRUE
;
1924 msysdir
= CGit::ms_LastMsysGitDir
;
1934 CGit::ms_LastMsysGitDir
= str
;
1937 // check for git.exe existance (maybe it was deinstalled in the meantime)
1938 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1940 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
1944 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
1945 // Configure libgit2 search paths
1947 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1948 msysGitDir
.ReleaseBuffer();
1949 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1950 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1951 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1952 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
, g_Git
.m_Environment
.GetEnv(_T("GIT_SSH")), &g_Git
.m_Environment
[0]); }, 0 };
1953 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
1954 CString msysGitTemplateDir
;
1955 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1956 msysGitTemplateDir
.ReleaseBuffer();
1957 SetLibGit2TemplatePath(msysGitTemplateDir
);
1960 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1963 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1965 m_Environment
.SetEnv(_T("PATH"), path
);
1967 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1969 CString sOldPath
= oldpath
;
1972 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
1973 // register filter only once
1974 if (!git_filter_lookup("filter"))
1976 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir
+ L
"\\sh.exe\"", &m_Environment
[0]), GIT_FILTER_DRIVER_PRIORITY
))
1981 m_bInitialized
= TRUE
;
1985 CString
CGit::GetHomeDirectory() const
1987 const wchar_t * homeDir
= wget_windows_home_directory();
1988 return CString(homeDir
, (int)wcslen(homeDir
));
1991 CString
CGit::GetGitLocalConfig() const
1994 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1995 path
+= _T("config");
1999 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2001 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2004 CString
CGit::GetGitGlobalConfig() const
2006 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2009 CString
CGit::GetGitGlobalXDGConfigPath() const
2011 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2014 CString
CGit::GetGitGlobalXDGConfig() const
2016 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2019 CString
CGit::GetGitSystemConfig() const
2021 const wchar_t * systemConfig
= wget_msysgit_etc();
2022 return CString(systemConfig
, (int)wcslen(systemConfig
));
2025 BOOL
CGit::CheckCleanWorkTree()
2029 cmd
=_T("git.exe rev-parse --verify HEAD");
2031 if(Run(cmd
,&out
,CP_UTF8
))
2034 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2035 if(Run(cmd
,&out
,CP_UTF8
))
2038 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2039 if(Run(cmd
,&out
,CP_UTF8
))
2042 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2043 if(Run(cmd
,&out
,CP_UTF8
))
2048 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2051 for (int i
= 0; i
< list
.GetCount(); ++i
)
2053 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2059 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2063 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2065 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2067 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2071 // if the filenames only differ in case, we have to pass "-f"
2072 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2074 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2075 if (Run(cmd
, &err
, CP_UTF8
))
2078 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2079 if (Run(cmd
, &err
, CP_UTF8
))
2082 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2083 { //To init git repository, there are not HEAD, so we can use git reset command
2084 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2086 if (Run(cmd
, &err
, CP_UTF8
))
2091 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2092 if (Run(cmd
, &err
, CP_UTF8
))
2096 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2098 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2099 if (Run(cmd
, &err
, CP_UTF8
))
2106 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2112 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2114 cmd
=_T("git.exe ls-files -u -t -z");
2116 if (Run(cmd
, &vector
))
2121 if (list
.ParserFromLsFile(vector
))
2127 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2129 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2131 CAutoRepository
repo(GetGitRepository());
2135 CGitHash fromHash
, toHash
, baseHash
;
2136 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2139 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2143 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2146 baseHash
= baseOid
.id
;
2149 *commonAncestor
= baseHash
;
2151 return fromHash
== baseHash
;
2155 CGitHash basehash
,hash
;
2157 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2159 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2163 basehash
= base
.Trim();
2165 GetHash(hash
, from
);
2168 *commonAncestor
= basehash
;
2170 return hash
== basehash
;
2173 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2176 for (int i
= 0; i
< 4; ++i
)
2179 ret
|= hash
.m_hash
[i
];
2184 int CGit::RefreshGitIndex()
2186 if(g_Git
.m_IsUseGitDLL
)
2188 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2191 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2202 cmd
=_T("git.exe update-index --refresh");
2203 return Run(cmd
, &output
, CP_UTF8
);
2207 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2209 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2211 CAutoRepository
repo(GetGitRepository());
2216 if (GetHash(repo
, hash
, Refname
))
2220 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2224 if (git_commit_tree(tree
.GetPointer(), commit
))
2227 CAutoTreeEntry entry
;
2228 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2232 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2235 FILE *file
= nullptr;
2236 _tfopen_s(&file
, outputfile
, _T("w"));
2237 if (file
== nullptr)
2239 giterr_set_str(GITERR_NONE
, "Could not create file.");
2243 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2248 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2250 giterr_set_str(GITERR_OS
, "Could not write to file.");
2259 else if (g_Git
.m_IsUseGitDLL
)
2261 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2264 g_Git
.CheckAndInitDll();
2265 CStringA ref
, patha
, outa
;
2266 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2267 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2268 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2269 ::DeleteFile(outputfile
);
2270 return git_checkout_file(ref
, patha
, outa
);
2273 catch (const char * msg
)
2275 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2280 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2287 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2288 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2291 void CEnvironment::CopyProcessEnvironment()
2293 TCHAR
*porig
= GetEnvironmentStrings();
2295 while(*p
!=0 || *(p
+1) !=0)
2296 this->push_back(*p
++);
2298 push_back(_T('\0'));
2299 push_back(_T('\0'));
2301 FreeEnvironmentStrings(porig
);
2304 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2307 for (size_t i
= 0; i
< size(); ++i
)
2311 CString sname
= str
.Tokenize(_T("="),start
);
2312 if(sname
.CompareNoCase(name
) == 0)
2314 return &(*this)[i
+start
];
2321 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2324 for (i
= 0; i
< size(); ++i
)
2326 CString str
= &(*this)[i
];
2328 CString sname
= str
.Tokenize(_T("="),start
);
2329 if(sname
.CompareNoCase(name
) == 0)
2338 i
-= 1; // roll back terminate \0\0
2339 this->push_back(_T('\0'));
2342 CEnvironment::iterator it
;
2346 while(*it
&& i
<size())
2355 this->insert(it
,*name
++);
2360 this->insert(it
, _T('='));
2366 this->insert(it
,*value
++);
2373 int CGit::GetGitEncode(TCHAR
* configkey
)
2375 CString str
=GetConfigValue(configkey
);
2380 return CUnicodeUtils::GetCPCode(str
);
2384 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2390 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2395 diff
= GetGitDiff();
2397 git_open_diff(&diff
, arg
);
2401 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2412 isStat
= !!strstr(arg
, "stat");
2417 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2419 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2428 for (int j
= 0; j
< count
; ++j
)
2437 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2438 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2439 &mode
,&IsBin
,&inc
,&dec
);
2441 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2442 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2444 path
.SetFromGit(strnewname
,&stroldname
);
2445 path
.ParserAction((BYTE
)mode
);
2449 path
.m_StatAdd
=_T("-");
2450 path
.m_StatDel
=_T("-");
2454 path
.m_StatAdd
.Format(_T("%d"),inc
);
2455 path
.m_StatDel
.Format(_T("%d"),dec
);
2457 PathList
->AddPath(path
);
2459 git_diff_flush(diff
);
2462 git_close_diff(diff
);
2467 int CGit::GetShortHASHLength() const
2472 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2476 REF_TYPE type
= CGit::UNKNOWN
;
2478 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2480 type
= CGit::LOCAL_BRANCH
;
2483 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2485 type
= CGit::REMOTE_BRANCH
;
2487 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2491 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2494 shortname
=_T("stash");
2496 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2498 if (shortname
.Find(_T("good")) == 0)
2500 type
= CGit::BISECT_GOOD
;
2501 shortname
= _T("good");
2504 if (shortname
.Find(_T("bad")) == 0)
2506 type
= CGit::BISECT_BAD
;
2507 shortname
= _T("bad");
2510 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2514 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2516 type
= CGit::UNKNOWN
;
2520 type
= CGit::UNKNOWN
;
2530 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2532 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2535 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2538 if (rev2
== GitRev::GetWorkingCopy())
2539 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2540 else if (rev1
== GitRev::GetWorkingCopy())
2541 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2552 if (diffContext
>= 0)
2553 unified
.Format(_T(" --unified=%d"), diffContext
);
2554 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2557 if (!path
.IsEmpty())
2560 cmd
+= path
.GetGitPathString();
2567 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2569 ATLASSERT(payload
&& line
);
2570 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2571 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2572 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2576 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2578 ATLASSERT(repo
&& identifier
&& tree
);
2580 /* try to resolve identifier */
2582 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2586 return GIT_ENOTFOUND
;
2589 switch (git_object_type(obj
))
2592 *tree
= (git_tree
*)obj
.Detach();
2594 case GIT_OBJ_COMMIT
:
2595 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2598 err
= GIT_ENOTFOUND
;
2604 /* use libgit2 get unified diff */
2605 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 */)
2607 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2608 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2610 CAutoRepository
repo(g_Git
.GetGitRepository());
2614 int isHeadOrphan
= git_repository_head_unborn(repo
);
2615 if (isHeadOrphan
== 1)
2617 else if (isHeadOrphan
!= 0)
2620 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2621 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2622 char *buf
= pathA
.GetBuffer();
2623 if (!pathA
.IsEmpty())
2625 opts
.pathspec
.strings
= &buf
;
2626 opts
.pathspec
.count
= 1;
2630 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2635 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2638 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2641 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2644 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2647 if (git_diff_merge(diff
, diff2
))
2652 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2655 if (tree1
.IsEmpty())
2663 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2666 if (tree2
.IsEmpty())
2668 /* don't check return value, there are not parent commit at first commit*/
2669 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2671 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2673 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2677 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2680 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2683 if (git_patch_print(patch
, callback
, data
))
2687 pathA
.ReleaseBuffer();
2692 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2694 if (UsingLibGit2(GIT_CMD_DIFF
))
2696 FILE *file
= nullptr;
2697 _tfopen_s(&file
, patchfile
, _T("w"));
2698 if (file
== nullptr)
2700 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2707 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2708 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2712 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2714 ATLASSERT(payload
&& line
);
2715 CStringA
*str
= (CStringA
*) payload
;
2716 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2717 str
->Append(&line
->origin
, 1);
2718 str
->Append(line
->content
, (int)line
->content_len
);
2722 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2724 if (UsingLibGit2(GIT_CMD_DIFF
))
2725 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2729 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2731 int ret
= Run(cmd
, &vector
);
2732 if (!vector
.empty())
2734 vector
.push_back(0); // vector is not NUL terminated
2735 buffer
->Append((char *)&vector
[0]);
2741 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2743 if (UsingLibGit2(GIT_CMD_REVERT
))
2745 CAutoRepository
repo(GetGitRepository());
2750 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2753 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2754 revert_opts
.mainline
= parent
;
2755 int result
= git_revert(repo
, commit
, &revert_opts
);
2757 return !result
? 0 : -1;
2763 merge
.Format(_T("-m %d "), parent
);
2764 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2765 gitLastErr
= cmd
+ _T("\n");
2766 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2778 int CGit::DeleteRef(const CString
& reference
)
2780 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2782 CAutoRepository
repo(GetGitRepository());
2787 if (reference
.Right(3) == _T("^{}"))
2788 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2790 refA
= CUnicodeUtils::GetUTF8(reference
);
2793 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
2797 if (git_reference_is_tag(ref
))
2798 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2799 else if (git_reference_is_branch(ref
))
2800 result
= git_branch_delete(ref
);
2801 else if (git_reference_is_remote(ref
))
2802 result
= git_branch_delete(ref
);
2804 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2810 CString cmd
, shortname
;
2811 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2812 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2813 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2814 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2815 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2816 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2819 gitLastErr
= L
"unsupported reference type: " + reference
;
2823 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2831 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2833 if (PathFileExists(filename
))
2835 FILE *pFile
= nullptr;
2836 _tfopen_s(&pFile
, filename
, _T("r"));
2842 char s
[8196] = { 0 };
2843 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2846 str
+= CStringA(s
, read
);
2849 msg
= CUnicodeUtils::GetUnicode(str
);
2850 msg
.Replace(_T("\r\n"), _T("\n"));
2851 msg
.TrimRight(_T("\n"));
2855 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
2856 return true; // load no further files