1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - 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.
23 #include "GitForWindows.h"
24 #include "UnicodeUtils.h"
28 #include "FormatMessageWrapper.h"
29 #include "SmartHandle.h"
30 #include "MassiveGitTaskBase.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 bool CGit::ms_bCygwinGit
= (CRegDWORD(_T("Software\\TortoiseGit\\CygwinHack"), FALSE
) == TRUE
);
37 int CGit::m_LogEncode
=CP_UTF8
;
38 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
40 static LPCTSTR
nextpath(const wchar_t* path
, wchar_t* buf
, size_t buflen
)
42 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
45 const wchar_t* base
= path
;
46 wchar_t 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 CString
FindFileOnPath(const CString
& filename
, LPCTSTR env
, bool wantDirectory
= false)
67 TCHAR buf
[MAX_PATH
] = { 0 };
69 // search in all paths defined in PATH
70 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
72 TCHAR
*pfin
= buf
+ _tcslen(buf
) - 1;
74 // ensure trailing slash
75 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
76 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
78 const size_t len
= _tcslen(buf
);
80 if ((len
+ filename
.GetLength()) < MAX_PATH
)
81 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, filename
);
96 static BOOL
FindGitPath()
99 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
103 TCHAR
* env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
106 _tgetenv_s(&size
, env
, size
, _T("PATH"));
108 CString gitExeDirectory
= FindFileOnPath(_T("git.exe"), env
, true);
109 if (!gitExeDirectory
.IsEmpty())
111 CGit::ms_LastMsysGitDir
= gitExeDirectory
;
112 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
113 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
115 // often the msysgit\cmd folder is on the %PATH%, but
116 // that git.exe does not work, so try to guess the bin folder
117 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
118 if (FileExists(binDir
))
119 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
127 static CString
FindExecutableOnPath(const CString
& executable
, LPCTSTR env
)
129 CString filename
= executable
;
131 if (executable
.GetLength() < 4 || executable
.Find(_T(".exe"), executable
.GetLength() - 4) != executable
.GetLength() - 4)
132 filename
+= _T(".exe");
134 if (FileExists(filename
))
137 filename
= FindFileOnPath(filename
, env
);
138 if (!filename
.IsEmpty())
144 static bool g_bSortLogical
;
145 static bool g_bSortLocalBranchesFirst
;
146 static bool g_bSortTagsReversed
;
147 static git_cred_acquire_cb g_Git2CredCallback
;
148 static git_transport_certificate_check_cb g_Git2CheckCertificateCallback
;
150 static void GetSortOptions()
152 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
154 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
155 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
156 if (g_bSortLocalBranchesFirst
)
157 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
158 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
159 if (!g_bSortTagsReversed
)
160 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
163 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
166 return StrCmpLogicalW(left
, right
) < 0;
167 return StrCmpI(left
, right
) < 0;
170 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
173 return StrCmpLogicalW(left
, right
) > 0;
174 return StrCmpI(left
, right
) > 0;
177 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
179 if (g_bSortLocalBranchesFirst
)
181 int leftIsRemote
= left
.Find(_T("remotes/"));
182 int rightIsRemote
= right
.Find(_T("remotes/"));
184 if (leftIsRemote
== 0 && rightIsRemote
< 0)
186 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
190 return StrCmpLogicalW(left
, right
) < 0;
191 return StrCmpI(left
, right
) < 0;
194 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
196 CString
CGit::ms_LastMsysGitDir
;
197 int CGit::ms_LastMsysGitVersion
= 0;
203 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
204 m_CurrentDir
.ReleaseBuffer();
205 m_IsGitDllInited
= false;
207 m_GitSimpleListDiff
=0;
208 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
209 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
210 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), DEFAULT_USE_LIBGIT2_MASK
);
212 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
215 this->m_bInitialized
=false;
217 m_critGitDllSec
.Init();
224 git_close_diff(m_GitDiff
);
227 if(this->m_GitSimpleListDiff
)
229 git_close_diff(m_GitSimpleListDiff
);
230 m_GitSimpleListDiff
=0;
234 bool CGit::IsBranchNameValid(const CString
& branchname
)
236 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
238 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
240 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
241 return !!git_reference_is_valid_name(branchA
);
244 static bool IsPowerShell(CString cmd
)
247 int powerShellPos
= cmd
.Find(_T("powershell"));
248 if (powerShellPos
< 0)
251 // found the word powershell, check that it is the command and not any parameter
252 int end
= cmd
.GetLength();
253 if (cmd
.Find(_T('"')) == 0)
255 int secondDoubleQuote
= cmd
.Find(_T('"'), 1);
256 if (secondDoubleQuote
> 0)
257 end
= secondDoubleQuote
;
261 int firstSpace
= cmd
.Find(_T(' '));
266 return (end
- 4 - 10 == powerShellPos
|| end
- 10 == powerShellPos
); // len(".exe")==4, len("powershell")==10
269 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
271 SECURITY_ATTRIBUTES sa
;
272 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
273 CAutoGeneralHandle hStdioFile
;
275 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
276 sa
.lpSecurityDescriptor
=NULL
;
277 sa
.bInheritHandle
=TRUE
;
278 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
280 CString err
= CFormatMessageWrapper();
281 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
282 return TGIT_GIT_ERROR_OPEN_PIP
;
284 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
286 CString err
= CFormatMessageWrapper();
287 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
288 return TGIT_GIT_ERROR_OPEN_PIP
;
293 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
294 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
297 STARTUPINFO si
= { 0 };
298 PROCESS_INFORMATION pi
;
299 si
.cb
=sizeof(STARTUPINFO
);
302 si
.hStdError
= hWriteErr
;
304 si
.hStdError
= hWrite
;
306 si
.hStdOutput
=hStdioFile
;
308 si
.hStdOutput
=hWrite
;
310 si
.wShowWindow
=SW_HIDE
;
311 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
313 LPTSTR pEnv
= m_Environment
;
314 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
316 dwFlags
|= CREATE_NEW_PROCESS_GROUP
;
318 // 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,
319 // 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)
320 // => we keep using DETACHED_PROCESS as the default, but if cmd contains pwershell we use CREATE_NEW_CONSOLE
321 if (IsPowerShell(cmd
))
322 dwFlags
|= CREATE_NEW_CONSOLE
;
324 dwFlags
|= DETACHED_PROCESS
;
326 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
327 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
329 if (ms_bCygwinGit
&& cmd
.Find(_T("git")) == 0)
331 cmd
.Replace(_T('\\'), _T('/'));
332 cmd
.Replace(_T("\""), _T("\\\""));
333 cmd
= _T('"') + CGit::ms_LastMsysGitDir
+ _T("\\bash.exe\" -c \"/bin/") + cmd
+ _T('"');
335 else if(cmd
.Find(_T("git")) == 0)
337 int firstSpace
= cmd
.Find(_T(" "));
339 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
341 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
344 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
345 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
347 CString err
= CFormatMessageWrapper();
348 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
349 return TGIT_GIT_ERROR_CREATE_PROCESS
;
357 *hReadOut
= hRead
.Detach();
359 *hErrReadOut
= hReadErr
.Detach();
363 //Must use sperate function to convert ANSI str to union code string
364 //Becuase A2W use stack as internal convert buffer.
365 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
372 len
= (int)strlen((const char*)p
);
377 int currentContentLen
= str
->GetLength();
378 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
379 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
380 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
383 // This method was originally used to check for orphaned branches
384 BOOL
CGit::CanParseRev(CString ref
)
390 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
400 // Checks if we have an orphaned HEAD
401 BOOL
CGit::IsInitRepos()
404 if (GetHash(hash
, _T("HEAD")) != 0)
406 return hash
.IsEmpty() ? TRUE
: FALSE
;
409 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
411 PASYNCREADSTDERRTHREADARGS pDataArray
;
412 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
415 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
416 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
418 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
425 int CGit::Run(CGitCall
* pcall
)
427 PROCESS_INFORMATION pi
;
428 CAutoGeneralHandle hRead
, hReadErr
;
429 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
430 return TGIT_GIT_ERROR_CREATE_PROCESS
;
432 CAutoGeneralHandle
piThread(pi
.hThread
);
433 CAutoGeneralHandle
piProcess(pi
.hProcess
);
435 ASYNCREADSTDERRTHREADARGS threadArguments
;
436 threadArguments
.fileHandle
= hReadErr
;
437 threadArguments
.pcall
= pcall
;
438 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
441 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
443 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
445 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
446 if(!bAborted
)//For now, flush output when command aborted.
447 if(pcall
->OnOutputData(data
,readnumber
))
454 WaitForSingleObject(thread
, INFINITE
);
456 WaitForSingleObject(pi
.hProcess
, INFINITE
);
459 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
461 CString err
= CFormatMessageWrapper();
462 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
463 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
466 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
470 class CGitCall_ByteVector
: public CGitCall
473 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
474 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
476 if (!m_pvector
|| size
== 0)
478 size_t oldsize
=m_pvector
->size();
479 m_pvector
->resize(m_pvector
->size()+size
);
480 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
483 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
485 if (!m_pvectorErr
|| size
== 0)
487 size_t oldsize
= m_pvectorErr
->size();
488 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
489 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
492 BYTE_VECTOR
* m_pvector
;
493 BYTE_VECTOR
* m_pvectorErr
;
496 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
498 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
501 int CGit::Run(CString cmd
, CString
* output
, int code
)
505 ret
= Run(cmd
, output
, &err
, code
);
507 if (output
&& !err
.IsEmpty())
509 if (!output
->IsEmpty())
516 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
518 BYTE_VECTOR vector
, vectorErr
;
521 ret
= Run(cmd
, &vector
, &vectorErr
);
523 ret
= Run(cmd
, &vector
);
526 StringAppend(output
, &(vector
[0]), code
);
530 vectorErr
.push_back(0);
531 StringAppend(outputErr
, &(vectorErr
[0]), code
);
537 class CGitCallCb
: public CGitCall
540 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
542 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
547 int oldEndPos
= m_buffer
.GetLength();
548 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
549 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
551 // Break into lines and feed to m_recv
553 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
555 m_recv(m_buffer
.Left(eolPos
));
556 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
561 virtual bool OnOutputErrData(const BYTE
*, size_t) override
563 return false; // Ignore error output for now
566 virtual void OnEnd() override
568 if (!m_buffer
.IsEmpty())
570 m_buffer
.Empty(); // Just for sure
574 GitReceiverFunc m_recv
;
578 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
580 CGitCallCb
call(cmd
, recv
);
584 CString
CGit::GetUserName(void)
587 env
.CopyProcessEnvironment();
588 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
589 if (!envname
.IsEmpty())
591 return GetConfigValue(L
"user.name");
593 CString
CGit::GetUserEmail(void)
596 env
.CopyProcessEnvironment();
597 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
598 if (!envmail
.IsEmpty())
601 return GetConfigValue(L
"user.email");
604 CString
CGit::GetConfigValue(const CString
& name
)
607 if(this->m_IsUseGitDLL
)
609 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
618 key
= CUnicodeUtils::GetUTF8(name
);
622 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
625 catch (const char *msg
)
627 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
631 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
637 cmd
.Format(L
"git.exe config %s", name
);
638 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
639 if (configValue
.IsEmpty())
641 return configValue
.Left(configValue
.GetLength() - 1); // strip last newline character
645 bool CGit::GetConfigValueBool(const CString
& name
)
647 CString configValue
= GetConfigValue(name
);
648 configValue
.MakeLower();
650 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
656 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
658 CString configValue
= GetConfigValue(name
);
660 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
665 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
667 if(this->m_IsUseGitDLL
)
669 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
678 CStringA keya
, valuea
;
679 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
680 valuea
= CUnicodeUtils::GetUTF8(value
);
684 return [=]() { return get_set_config(keya
, valuea
, type
); }();
686 catch (const char *msg
)
688 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
699 option
= _T("--global");
702 option
= _T("--system");
707 CString mangledValue
= value
;
708 mangledValue
.Replace(_T("\\\""), _T("\\\\\""));
709 mangledValue
.Replace(_T("\""), _T("\\\""));
710 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, mangledValue
);
712 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
720 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
722 if(this->m_IsUseGitDLL
)
724 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
733 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
737 return [=]() { return get_set_config(keya
, nullptr, type
); }();
739 catch (const char *msg
)
741 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
752 option
= _T("--global");
755 option
= _T("--system");
760 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
762 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
770 CString
CGit::GetCurrentBranch(bool fallback
)
773 //Run(_T("git.exe branch"),&branch);
775 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
776 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
778 return _T("(no branch)");
785 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
787 if (localBranch
.IsEmpty())
791 configName
.Format(L
"branch.%s.remote", localBranch
);
792 pullRemote
= GetConfigValue(configName
);
794 //Select pull-branch from current branch
795 configName
.Format(L
"branch.%s.merge", localBranch
);
796 pullBranch
= StripRefName(GetConfigValue(configName
));
799 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
802 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
804 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
807 CString
CGit::GetFullRefName(const CString
& shortRefName
)
811 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
812 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
813 return CString();//Error
815 return refName
.Tokenize(L
"\n", iStart
);
818 CString
CGit::StripRefName(CString refName
)
820 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
821 refName
= refName
.Mid(11);
822 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
823 refName
= refName
.Mid(5);
825 return refName
.Tokenize(_T("\n"),start
);
828 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
830 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
832 if ( sProjectRoot
.IsEmpty() )
836 if (!GitAdminDir::GetAdminDirPath(sProjectRoot
, sDotGitPath
))
839 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
842 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
850 fgets(s
, sizeof(s
), pFile
);
854 const char *pfx
= "ref: refs/heads/";
855 const int len
= 16;//strlen(pfx)
857 if ( !strncmp(s
, pfx
, len
) )
859 //# We're on a branch. It might not exist. But
860 //# HEAD looks good enough to be a branch.
861 CStringA
utf8Branch(s
+ len
);
862 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
863 sBranchOut
.TrimRight(_T(" \r\n\t"));
865 if ( sBranchOut
.IsEmpty() )
870 CStringA
utf8Hash(s
);
871 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
872 unicodeHash
.TrimRight(_T(" \r\n\t"));
873 if (CGitHash::IsValidSHA1(unicodeHash
))
874 sBranchOut
= unicodeHash
;
876 //# Assume this is a detached head.
877 sBranchOut
= _T("HEAD");
882 //# Assume this is a detached head.
891 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
894 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
898 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
900 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
902 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
904 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
906 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
908 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
910 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
914 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
916 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
918 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
923 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
929 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
936 CString file
= _T(" --");
939 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
942 num
.Format(_T("-n%d"),count
);
946 if(mask
& LOG_INFO_STAT
)
947 param
+= _T(" --numstat ");
948 if(mask
& LOG_INFO_FILESTATE
)
949 param
+= _T(" --raw ");
951 if(mask
& LOG_INFO_FULLHISTORY
)
952 param
+= _T(" --full-history ");
954 if(mask
& LOG_INFO_BOUNDARY
)
955 param
+= _T(" --left-right --boundary ");
957 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
958 param
+= _T(" --all ");
960 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
961 param
+= _T(" --branches ");
963 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
966 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
969 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
970 param
+= _T(" --first-parent ");
972 if(mask
& CGit::LOG_INFO_NO_MERGE
)
973 param
+= _T(" --no-merges ");
975 if(mask
& CGit::LOG_INFO_FOLLOW
)
976 param
+= _T(" --follow ");
978 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
981 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
982 param
+= _T(" --full-diff ");
984 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
985 param
+= _T(" --simplify-by-decoration ");
991 if( Filter
&& (Filter
->m_From
!= -1))
993 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
997 if( Filter
&& (Filter
->m_To
!= -1))
999 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
1003 bool isgrep
= false;
1004 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
1006 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
1011 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
1013 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
1018 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
1020 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
1025 if(Filter
&& isgrep
)
1027 if(!Filter
->m_IsRegex
)
1028 param
+= _T(" --fixed-strings ");
1030 param
+= _T(" --regexp-ignore-case --extended-regexp ");
1033 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
1034 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
1035 param
+= _T(" --topo-order");
1036 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
1037 param
+= _T(" --date-order");
1039 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
1040 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
1044 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
1045 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
1054 void GetTempPath(CString
&path
)
1056 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1058 DWORD dwBufSize
=BUFSIZE
;
1059 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1060 lpPathBuffer
); // buffer for path
1061 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1065 path
.Format(_T("%s"),lpPathBuffer
);
1067 CString
GetTempFile()
1069 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
1071 DWORD dwBufSize
=BUFSIZE
;
1072 TCHAR szTempName
[BUFSIZE
] = { 0 };
1075 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1076 lpPathBuffer
); // buffer for path
1077 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1081 // Create a temporary file.
1082 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1083 TEXT("Patch"), // temp file name prefix
1084 0, // create unique name
1085 szTempName
); // buffer for name
1093 return CString(szTempName
);
1097 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1099 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1100 if (result
== 0) return 0;
1101 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1108 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1109 CreateDirectory(lpBuffer
, NULL
);
1114 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1117 PROCESS_INFORMATION pi
;
1118 si
.cb
=sizeof(STARTUPINFO
);
1119 GetStartupInfo(&si
);
1121 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1122 psa
.bInheritHandle
=TRUE
;
1124 HANDLE hReadErr
, hWriteErr
;
1125 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1127 CString err
= CFormatMessageWrapper();
1128 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1129 return TGIT_GIT_ERROR_OPEN_PIP
;
1132 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1133 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1135 if (houtfile
== INVALID_HANDLE_VALUE
)
1137 CString err
= CFormatMessageWrapper();
1138 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1139 CloseHandle(hReadErr
);
1140 CloseHandle(hWriteErr
);
1141 return TGIT_GIT_ERROR_OPEN_PIP
;
1144 si
.wShowWindow
= SW_HIDE
;
1145 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1146 si
.hStdOutput
= houtfile
;
1147 si
.hStdError
= hWriteErr
;
1149 LPTSTR pEnv
= m_Environment
;
1150 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1152 if(cmd
.Find(_T("git")) == 0)
1153 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1155 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1156 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1158 CString err
= CFormatMessageWrapper();
1159 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1161 CloseHandle(hReadErr
);
1162 CloseHandle(hWriteErr
);
1163 CloseHandle(houtfile
);
1164 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1167 BYTE_VECTOR stderrVector
;
1168 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1170 ASYNCREADSTDERRTHREADARGS threadArguments
;
1171 threadArguments
.fileHandle
= hReadErr
;
1172 threadArguments
.pcall
= &pcall
;
1173 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1175 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1177 CloseHandle(hWriteErr
);
1178 CloseHandle(hReadErr
);
1181 WaitForSingleObject(thread
, INFINITE
);
1183 stderrVector
.push_back(0);
1184 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1187 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1189 CString err
= CFormatMessageWrapper();
1190 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1191 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1194 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1196 CloseHandle(pi
.hThread
);
1197 CloseHandle(pi
.hProcess
);
1198 CloseHandle(houtfile
);
1202 git_repository
* CGit::GetGitRepository() const
1204 git_repository
* repo
= nullptr;
1205 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1209 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1213 // no need to parse a ref if it's already a 40-byte hash
1214 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1216 hash
= CGitHash(friendname
);
1220 int isHeadOrphan
= git_repository_head_unborn(repo
);
1221 if (isHeadOrphan
!= 0)
1224 if (isHeadOrphan
== 1)
1230 CAutoObject gitObject
;
1231 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1234 const git_oid
* oid
= git_object_id(gitObject
);
1238 hash
= CGitHash((char *)oid
->id
);
1243 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1245 // no need to parse a ref if it's already a 40-byte hash
1246 if (CGitHash::IsValidSHA1(friendname
))
1248 hash
= CGitHash(friendname
);
1254 CAutoRepository
repo(GetGitRepository());
1258 return GetHash(repo
, hash
, friendname
, true);
1262 CString branch
= FixBranchName(friendname
);
1263 if (friendname
== _T("FETCH_HEAD") && branch
.IsEmpty())
1264 branch
= friendname
;
1266 cmd
.Format(_T("git.exe rev-parse %s"), branch
);
1268 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1269 hash
= CGitHash(gitLastErr
.Trim());
1272 else if (friendname
== _T("HEAD")) // special check for unborn branch
1274 CString currentbranch
;
1275 if (GetCurrentBranchFromFile(m_CurrentDir
, currentbranch
))
1284 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1289 cmd
=_T("git.exe ls-files -s -t -z");
1291 if (Run(cmd
, &cmdout
))
1294 if (outputlist
.ParserFromLsFile(cmdout
))
1296 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1297 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1301 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1305 if (ignoreSpaceAtEol
)
1306 ignore
+= _T(" --ignore-space-at-eol");
1307 if (ignoreSpaceChange
)
1308 ignore
+= _T(" --ignore-space-change");
1310 ignore
+= _T(" --ignore-all-space");
1311 if (ignoreBlankLines
)
1312 ignore
+= _T(" --ignore-blank-lines");
1314 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1317 if(rev1
== GIT_REV_ZERO
)
1318 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1320 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1324 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1331 return outputlist
.ParserFromLog(out
);
1334 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1336 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1337 list
->push_back(CUnicodeUtils::GetUnicode(refname
));
1341 int CGit::GetTagList(STRING_VECTOR
&list
)
1343 if (this->m_IsUseLibGit2
)
1345 CAutoRepository
repo(GetGitRepository());
1349 CAutoStrArray tag_names
;
1351 if (git_tag_list(tag_names
, repo
))
1354 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1356 CStringA
tagName(tag_names
->strings
[i
]);
1357 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1360 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1366 CString cmd
, output
;
1367 cmd
=_T("git.exe tag -l");
1368 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1375 one
=output
.Tokenize(_T("\n"),pos
);
1377 list
.push_back(one
);
1379 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1381 else if (ret
== 1 && IsInitRepos())
1387 CString
CGit::GetGitLastErr(const CString
& msg
)
1389 if (this->m_IsUseLibGit2
)
1390 return GetLibGit2LastErr(msg
);
1391 else if (gitLastErr
.IsEmpty())
1392 return msg
+ _T("\nUnknown git.exe error.");
1395 CString lastError
= gitLastErr
;
1397 return msg
+ _T("\n") + lastError
;
1401 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1403 if (UsingLibGit2(cmd
))
1404 return GetLibGit2LastErr(msg
);
1405 else if (gitLastErr
.IsEmpty())
1406 return msg
+ _T("\nUnknown git.exe error.");
1409 CString lastError
= gitLastErr
;
1411 return msg
+ _T("\n") + lastError
;
1415 CString
CGit::GetLibGit2LastErr()
1417 const git_error
*libgit2err
= giterr_last();
1420 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1422 return _T("libgit2 returned: ") + lastError
;
1425 return _T("An error occoured in libgit2, but no message is available.");
1428 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1431 return msg
+ _T("\n") + GetLibGit2LastErr();
1432 return GetLibGit2LastErr();
1435 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1437 if(branchName
== "FETCH_HEAD")
1438 branchName
= DerefFetchHead();
1442 CString
CGit::FixBranchName(const CString
& branchName
)
1444 CString tempBranchName
= branchName
;
1445 FixBranchName_Mod(tempBranchName
);
1446 return tempBranchName
;
1449 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1453 CAutoRepository
repo(GetGitRepository());
1455 return true; // TODO: optimize error reporting
1457 CAutoReference tagRef
;
1458 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1461 CAutoReference branchRef
;
1462 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1471 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1472 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1478 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1488 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1492 CAutoRepository
repo(GetGitRepository());
1494 return false; // TODO: optimize error reporting
1498 prefix
= _T("refs/heads/");
1500 prefix
= _T("refs/tags/");
1503 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1509 CString cmd
, output
;
1511 cmd
= _T("git.exe show-ref ");
1513 cmd
+= _T("--heads ");
1515 cmd
+= _T("--tags ");
1517 cmd
+= _T("refs/heads/") + name
;
1518 cmd
+= _T(" refs/tags/") + name
;
1520 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1523 if (!output
.IsEmpty())
1530 CString
CGit::DerefFetchHead()
1533 GitAdminDir::GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1534 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1535 int forMergeLineCount
= 0;
1537 std::string hashToReturn
;
1538 while(getline(fetchHeadFile
, line
))
1540 //Tokenize this line
1541 std::string::size_type prevPos
= 0;
1542 std::string::size_type pos
= line
.find('\t');
1543 if(pos
== std::string::npos
) continue; //invalid line
1545 std::string hash
= line
.substr(0, pos
);
1546 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1548 bool forMerge
= pos
== prevPos
;
1549 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1551 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1556 hashToReturn
= hash
;
1557 ++forMergeLineCount
;
1558 if(forMergeLineCount
> 1)
1559 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1563 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1566 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1572 CAutoRepository
repo(GetGitRepository());
1576 if (git_repository_head_detached(repo
) == 1)
1577 cur
= _T("(detached from ");
1579 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1581 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1582 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1583 flags
= GIT_BRANCH_ALL
;
1584 else if (type
& BRANCH_REMOTE
)
1585 flags
= GIT_BRANCH_REMOTE
;
1587 CAutoBranchIterator it
;
1588 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1591 git_reference
* ref
= nullptr;
1592 git_branch_t branchType
;
1593 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1595 CAutoReference
autoRef(ref
);
1596 const char * name
= nullptr;
1597 if (git_branch_name(&name
, ref
))
1600 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1601 if (branchType
& GIT_BRANCH_REMOTE
)
1602 list
.push_back(_T("remotes/") + branchname
);
1605 if (git_branch_is_head(ref
))
1607 list
.push_back(branchname
);
1614 CString cmd
, output
;
1615 cmd
= _T("git.exe branch --no-color");
1617 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1619 else if (type
& BRANCH_REMOTE
)
1622 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1629 one
= output
.Tokenize(_T("\n"), pos
);
1630 one
.Trim(L
" \r\n\t");
1631 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1632 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1633 if (one
[0] == _T('*'))
1638 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1640 if ((type
& BRANCH_REMOTE
) != 0 && (type
& BRANCH_LOCAL
) == 0)
1641 one
= _T("remotes/") + one
;
1642 list
.push_back(one
);
1646 else if (ret
== 1 && IsInitRepos())
1650 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1651 list
.push_back(L
"FETCH_HEAD");
1653 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1655 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1657 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1670 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1672 if (this->m_IsUseLibGit2
)
1674 CAutoRepository
repo(GetGitRepository());
1678 CAutoStrArray remotes
;
1679 if (git_remote_list(remotes
, repo
))
1682 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1684 CStringA
remote(remotes
->strings
[i
]);
1685 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1688 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1695 CString cmd
, output
;
1696 cmd
=_T("git.exe remote");
1697 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1704 one
=output
.Tokenize(_T("\n"),pos
);
1706 list
.push_back(one
);
1713 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
& list
)
1715 if (UsingLibGit2(GIT_CMD_FETCH
))
1717 CAutoRepository
repo(GetGitRepository());
1721 CStringA remoteA
= CUnicodeUtils::GetUTF8(remote
);
1722 CAutoRemote gitremote
;
1723 if (git_remote_lookup(gitremote
.GetPointer(), repo
, remoteA
) < 0)
1726 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1727 callbacks
.credentials
= g_Git2CredCallback
;
1728 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1729 git_remote_set_callbacks(gitremote
, &callbacks
);
1730 if (git_remote_connect(gitremote
, GIT_DIRECTION_FETCH
) < 0)
1733 const git_remote_head
** heads
= nullptr;
1735 if (git_remote_ls(&heads
, &size
, gitremote
) < 0)
1738 for (size_t i
= 0; i
< size
; i
++)
1740 CString ref
= CUnicodeUtils::GetUnicode(heads
[i
]->name
);
1742 if (!GetShortName(ref
, shortname
, _T("refs/tags/")))
1744 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1745 if (shortname
.Find(_T("^{}")) >= 1)
1747 list
.push_back(shortname
);
1749 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1753 CString cmd
, out
, err
;
1754 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1755 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1757 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1764 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1765 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1766 if (one
.Find(_T("^{}")) >= 1)
1769 list
.push_back(one
);
1771 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1775 int CGit::DeleteRemoteRefs(const CString
& sRemote
, const STRING_VECTOR
& list
)
1777 if (UsingLibGit2(GIT_CMD_PUSH
))
1779 CAutoRepository
repo(GetGitRepository());
1783 CStringA remoteA
= CUnicodeUtils::GetUTF8(sRemote
);
1785 if (git_remote_lookup(remote
.GetPointer(), repo
, remoteA
) < 0)
1788 git_remote_callbacks callbacks
= GIT_REMOTE_CALLBACKS_INIT
;
1789 callbacks
.credentials
= g_Git2CredCallback
;
1790 callbacks
.certificate_check
= g_Git2CheckCertificateCallback
;
1791 git_remote_set_callbacks(remote
, &callbacks
);
1792 if (git_remote_connect(remote
, GIT_DIRECTION_PUSH
) < 0)
1795 std::vector
<CStringA
> refspecs
;
1796 for (auto ref
: list
)
1797 refspecs
.push_back(CUnicodeUtils::GetUTF8(_T(":") + ref
));
1799 std::vector
<char*> vc
;
1800 vc
.reserve(refspecs
.size());
1801 std::transform(refspecs
.begin(), refspecs
.end(), std::back_inserter(vc
), [](CStringA
& s
) -> char* { return s
.GetBuffer(); });
1802 git_strarray specs
= { &vc
[0], vc
.size() };
1804 if (git_remote_push(remote
, &specs
, nullptr) < 0)
1809 CMassiveGitTaskBase
mgtPush(_T("push ") + sRemote
, FALSE
);
1810 for (auto ref
: list
)
1812 CString refspec
= _T(":") + ref
;
1813 mgtPush
.AddFile(refspec
);
1816 BOOL cancel
= FALSE
;
1817 mgtPush
.Execute(cancel
);
1823 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1825 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1826 list
->push_back(CUnicodeUtils::GetUnicode(git_reference_name(ref
)));
1830 int CGit::GetRefList(STRING_VECTOR
&list
)
1832 if (this->m_IsUseLibGit2
)
1834 CAutoRepository
repo(GetGitRepository());
1838 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1841 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1847 CString cmd
, output
;
1848 cmd
=_T("git.exe show-ref -d");
1849 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1856 one
=output
.Tokenize(_T("\n"),pos
);
1857 int start
=one
.Find(_T(" "),0);
1861 name
=one
.Right(one
.GetLength()-start
-1);
1862 if (list
.empty() || name
!= *list
.crbegin() + _T("^{}"))
1863 list
.push_back(name
);
1866 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1868 else if (ret
== 1 && IsInitRepos())
1874 typedef struct map_each_ref_payload
{
1875 git_repository
* repo
;
1876 MAP_HASH_NAME
* map
;
1877 } map_each_ref_payload
;
1879 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1881 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1883 CString str
= CUnicodeUtils::GetUnicode(git_reference_name(ref
));
1885 CAutoObject gitObject
;
1886 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1889 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1891 str
+= _T("^{}"); // deref tag
1892 CAutoObject derefedTag
;
1893 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1895 gitObject
.Swap(derefedTag
);
1898 const git_oid
* oid
= git_object_id(gitObject
);
1902 CGitHash
hash((char *)oid
->id
);
1903 (*payloadContent
->map
)[hash
].push_back(str
);
1907 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1911 map_each_ref_payload payloadContent
= { repo
, &map
};
1913 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1916 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1918 std::sort(it
->second
.begin(), it
->second
.end());
1924 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1926 if (this->m_IsUseLibGit2
)
1928 CAutoRepository
repo(GetGitRepository());
1932 return GetMapHashToFriendName(repo
, map
);
1936 CString cmd
, output
;
1937 cmd
=_T("git.exe show-ref -d");
1938 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1945 one
=output
.Tokenize(_T("\n"),pos
);
1946 int start
=one
.Find(_T(" "),0);
1950 name
=one
.Right(one
.GetLength()-start
-1);
1953 hash
=one
.Left(start
);
1955 map
[CGitHash(hash
)].push_back(name
);
1959 else if (ret
== 1 && IsInitRepos())
1965 int CGit::GetBranchDescriptions(MAP_STRING_STRING
& map
)
1967 CAutoConfig
config(true);
1968 if (git_config_add_file_ondisk(config
, CGit::GetGitPathStringA(GetGitLocalConfig()), GIT_CONFIG_LEVEL_LOCAL
, FALSE
) < 0)
1970 return git_config_foreach_match(config
, "^branch\\..*\\.description$", [](const git_config_entry
* entry
, void* data
)
1972 MAP_STRING_STRING
* descriptions
= (MAP_STRING_STRING
*)data
;
1973 CString key
= CUnicodeUtils::GetUnicode(entry
->name
);
1974 key
= key
.Mid(7, key
.GetLength() - 7 - 12); // 7: branch., 12: .description
1975 descriptions
->insert(std::make_pair(key
, CUnicodeUtils::GetUnicode(entry
->value
)));
1980 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1982 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1983 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1986 static void SetLibGit2TemplatePath(const CString
&value
)
1988 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1989 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1992 int CGit::FindAndSetGitExePath(BOOL bFallback
)
1994 CRegString msysdir
= CRegString(REG_MSYSGIT_PATH
, _T(""), FALSE
);
1995 CString str
= msysdir
;
1996 if (str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1998 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2002 // first, search PATH if git/bin directory is already present
2005 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": FindGitPath() => %s\n"), CGit::ms_LastMsysGitDir
);
2006 msysdir
= CGit::ms_LastMsysGitDir
;
2011 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
2012 str
= msyslocalinstalldir
;
2013 str
.TrimRight(_T("\\"));
2016 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2017 str
= msysinstalldir
;
2018 str
.TrimRight(_T("\\"));
2024 CGit::ms_LastMsysGitDir
= str
;
2033 CGit::ms_LastMsysGitDir
= str
;
2038 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
2045 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": CheckMsysGitDir(%d)\n"), bFallback
);
2046 this->m_Environment
.clear();
2047 m_Environment
.CopyProcessEnvironment();
2048 m_Environment
.SetEnv(_T("GIT_DIR"), nullptr); // Remove %GIT_DIR% before executing git.exe
2051 size_t homesize
,size
;
2053 // set HOME if not set already
2054 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
2056 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
2059 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
2060 if (sshclient
.IsEmpty())
2061 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
2063 if(!sshclient
.IsEmpty())
2065 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
2066 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
2070 TCHAR sPlink
[MAX_PATH
] = {0};
2071 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
2072 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
2074 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
2075 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
2076 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
2081 TCHAR sAskPass
[MAX_PATH
] = {0};
2082 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
2083 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
2086 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
2087 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
2088 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
2089 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
2093 if (!FindAndSetGitExePath(bFallback
))
2096 // check for git.exe existance (maybe it was deinstalled in the meantime)
2097 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
2099 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": git.exe not exists: %s\n"), CGit::ms_LastMsysGitDir
);
2103 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": ms_LastMsysGitDir = %s\n"), CGit::ms_LastMsysGitDir
);
2104 // Configure libgit2 search paths
2106 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
2107 msysGitDir
.ReleaseBuffer();
2108 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
2109 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
2110 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
2111 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 };
2112 git_transport_register("ssh", git_transport_smart
, &ssh_wintunnel_subtransport_definition
);
2113 CString msysGitTemplateDir
;
2115 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
2117 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\usr\\share\\git-core\\templates"));
2118 msysGitTemplateDir
.ReleaseBuffer();
2119 SetLibGit2TemplatePath(msysGitTemplateDir
);
2122 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
2125 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
2127 m_Environment
.SetEnv(_T("PATH"), path
);
2129 CString str1
= m_Environment
.GetEnv(_T("PATH"));
2131 CString sOldPath
= oldpath
;
2134 #if !defined(TGITCACHE) && !defined(TORTOISESHELL)
2135 // register filter only once
2136 if (!git_filter_lookup("filter"))
2138 if (git_filter_register("filter", git_filter_filter_new(_T("\"") + CGit::ms_LastMsysGitDir
+ L
"\\sh.exe\"", m_Environment
), GIT_FILTER_DRIVER_PRIORITY
))
2143 m_bInitialized
= TRUE
;
2147 CString
CGit::GetHomeDirectory() const
2149 const wchar_t * homeDir
= wget_windows_home_directory();
2150 return CString(homeDir
, (int)wcslen(homeDir
));
2153 CString
CGit::GetGitLocalConfig() const
2156 GitAdminDir::GetAdminDirPath(m_CurrentDir
, path
);
2157 path
+= _T("config");
2161 CStringA
CGit::GetGitPathStringA(const CString
&path
)
2163 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
2166 CString
CGit::GetGitGlobalConfig() const
2168 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
2171 CString
CGit::GetGitGlobalXDGConfigPath() const
2173 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
2176 CString
CGit::GetGitGlobalXDGConfig() const
2178 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
2181 CString
CGit::GetGitSystemConfig() const
2183 const wchar_t * systemConfig
= wget_msysgit_etc();
2184 return CString(systemConfig
, (int)wcslen(systemConfig
));
2187 BOOL
CGit::CheckCleanWorkTree(bool stagedOk
/* false */)
2189 if (UsingLibGit2(GIT_CMD_CHECK_CLEAN_WT
))
2191 CAutoRepository repo
= GetGitRepository();
2195 if (git_repository_head_unborn(repo
))
2198 git_status_options statusopt
= GIT_STATUS_OPTIONS_INIT
;
2199 statusopt
.show
= stagedOk
? GIT_STATUS_SHOW_WORKDIR_ONLY
: GIT_STATUS_SHOW_INDEX_AND_WORKDIR
;
2200 statusopt
.flags
= GIT_STATUS_OPT_UPDATE_INDEX
| GIT_STATUS_OPT_EXCLUDE_SUBMODULES
;
2202 CAutoStatusList status
;
2203 if (git_status_list_new(status
.GetPointer(), repo
, &statusopt
))
2206 return (0 == git_status_list_entrycount(status
));
2211 cmd
=_T("git.exe rev-parse --verify HEAD");
2213 if(Run(cmd
,&out
,CP_UTF8
))
2216 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
2217 if(Run(cmd
,&out
,CP_UTF8
))
2220 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
2221 if(Run(cmd
,&out
,CP_UTF8
))
2224 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
2225 if (!stagedOk
&& Run(cmd
, &out
, CP_UTF8
))
2230 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, CString
& err
)
2233 for (int i
= 0; i
< list
.GetCount(); ++i
)
2235 ret
= Revert(commit
, (CTGitPath
&)list
[i
], err
);
2241 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
, CString
& err
)
2245 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2247 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2249 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2253 // if the filenames only differ in case, we have to pass "-f"
2254 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2256 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2257 if (Run(cmd
, &err
, CP_UTF8
))
2260 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2261 if (Run(cmd
, &err
, CP_UTF8
))
2264 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2265 { //To init git repository, there are not HEAD, so we can use git reset command
2266 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2268 if (Run(cmd
, &err
, CP_UTF8
))
2273 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2274 if (Run(cmd
, &err
, CP_UTF8
))
2278 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2280 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2281 if (Run(cmd
, &err
, CP_UTF8
))
2288 int CGit::HasWorkingTreeConflicts(git_repository
* repo
)
2293 if (git_repository_index(index
.GetPointer(), repo
))
2296 return git_index_has_conflicts(index
);
2299 int CGit::HasWorkingTreeConflicts()
2301 if (UsingLibGit2(GIT_CMD_CHECKCONFLICTS
))
2303 CAutoRepository
repo(GetGitRepository());
2307 return HasWorkingTreeConflicts(repo
);
2310 CString cmd
= _T("git.exe ls-files -u -t -z");
2313 if (Run(cmd
, &output
, &gitLastErr
, CP_UTF8
))
2316 return output
.IsEmpty() ? 0 : 1;
2319 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2321 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2323 CAutoRepository
repo(GetGitRepository());
2327 CGitHash fromHash
, toHash
, baseHash
;
2328 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2331 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2335 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2338 baseHash
= baseOid
.id
;
2341 *commonAncestor
= baseHash
;
2343 return fromHash
== baseHash
;
2347 CGitHash basehash
,hash
;
2349 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2351 if (Run(cmd
, &base
, &gitLastErr
, CP_UTF8
))
2355 basehash
= base
.Trim();
2357 GetHash(hash
, from
);
2360 *commonAncestor
= basehash
;
2362 return hash
== basehash
;
2365 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2368 for (int i
= 0; i
< 4; ++i
)
2371 ret
|= hash
.m_hash
[i
];
2376 int CGit::RefreshGitIndex()
2378 if(g_Git
.m_IsUseGitDLL
)
2380 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2383 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2394 cmd
=_T("git.exe update-index --refresh");
2395 return Run(cmd
, &output
, CP_UTF8
);
2399 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2401 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2403 CAutoRepository
repo(GetGitRepository());
2408 if (GetHash(repo
, hash
, Refname
))
2412 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2416 if (git_commit_tree(tree
.GetPointer(), commit
))
2419 CAutoTreeEntry entry
;
2420 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2424 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2427 FILE *file
= nullptr;
2428 _tfopen_s(&file
, outputfile
, _T("wb"));
2429 if (file
== nullptr)
2431 giterr_set_str(GITERR_NONE
, "Could not create file.");
2435 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2440 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2442 giterr_set_str(GITERR_OS
, "Could not write to file.");
2451 else if (g_Git
.m_IsUseGitDLL
)
2453 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2456 g_Git
.CheckAndInitDll();
2457 CStringA ref
, patha
, outa
;
2458 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2459 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2460 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2461 ::DeleteFile(outputfile
);
2462 int ret
= git_checkout_file(ref
, patha
, outa
.GetBuffer());
2463 outa
.ReleaseBuffer();
2467 catch (const char * msg
)
2469 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2474 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2481 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2482 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2486 void CEnvironment::clear()
2491 bool CEnvironment::empty()
2493 return size() < 3; // three is minimum for an empty environment with an empty key and empty value: "=\0\0"
2496 CEnvironment::operator LPTSTR()
2500 return &__super::at(0);
2503 void CEnvironment::CopyProcessEnvironment()
2507 TCHAR
*porig
= GetEnvironmentStrings();
2509 while(*p
!=0 || *(p
+1) !=0)
2510 this->push_back(*p
++);
2512 push_back(_T('\0'));
2513 push_back(_T('\0'));
2515 FreeEnvironmentStrings(porig
);
2518 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2521 for (size_t i
= 0; i
< size(); ++i
)
2525 CString sname
= str
.Tokenize(_T("="),start
);
2526 if(sname
.CompareNoCase(name
) == 0)
2528 return &(*this)[i
+start
];
2535 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2538 for (i
= 0; i
< size(); ++i
)
2540 CString str
= &(*this)[i
];
2542 CString sname
= str
.Tokenize(_T("="),start
);
2543 if(sname
.CompareNoCase(name
) == 0)
2552 if (!value
) // as we haven't found the variable we want to remove, just return
2554 if (i
== 0) // make inserting into an empty environment work
2556 this->push_back(_T('\0'));
2559 i
-= 1; // roll back terminate \0\0
2560 this->push_back(_T('\0'));
2563 CEnvironment::iterator it
;
2567 while(*it
&& i
<size())
2574 if (value
== nullptr) // remove the variable
2582 this->insert(it
,*name
++);
2587 this->insert(it
, _T('='));
2593 this->insert(it
,*value
++);
2600 int CGit::GetGitEncode(TCHAR
* configkey
)
2602 CString str
=GetConfigValue(configkey
);
2607 return CUnicodeUtils::GetCPCode(str
);
2611 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2617 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2622 diff
= GetGitDiff();
2624 git_open_diff(&diff
, arg
);
2628 MessageBox(nullptr, _T("Could not get diff.\nlibgit reported:\n") + CString(e
), _T("TortoiseGit"), MB_OK
);
2639 isStat
= !!strstr(arg
, "stat");
2644 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2646 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2655 for (int j
= 0; j
< count
; ++j
)
2664 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2665 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2666 &mode
,&IsBin
,&inc
,&dec
);
2668 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2669 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2671 path
.SetFromGit(strnewname
,&stroldname
);
2672 path
.ParserAction((BYTE
)mode
);
2676 path
.m_StatAdd
=_T("-");
2677 path
.m_StatDel
=_T("-");
2681 path
.m_StatAdd
.Format(_T("%d"),inc
);
2682 path
.m_StatDel
.Format(_T("%d"),dec
);
2684 PathList
->AddPath(path
);
2686 git_diff_flush(diff
);
2689 git_close_diff(diff
);
2694 int CGit::GetShortHASHLength() const
2699 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2703 REF_TYPE type
= CGit::UNKNOWN
;
2705 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2707 type
= CGit::LOCAL_BRANCH
;
2710 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2712 type
= CGit::REMOTE_BRANCH
;
2714 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2718 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2721 shortname
=_T("stash");
2723 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2725 if (shortname
.Find(_T("good")) == 0)
2727 type
= CGit::BISECT_GOOD
;
2728 shortname
= _T("good");
2731 if (shortname
.Find(_T("bad")) == 0)
2733 type
= CGit::BISECT_BAD
;
2734 shortname
= _T("bad");
2737 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2741 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2743 type
= CGit::UNKNOWN
;
2747 type
= CGit::UNKNOWN
;
2757 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2759 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2762 void CGit::SetGit2CredentialCallback(void* callback
)
2764 g_Git2CredCallback
= (git_cred_acquire_cb
)callback
;
2767 void CGit::SetGit2CertificateCheckCertificate(void* callback
)
2769 g_Git2CheckCertificateCallback
= (git_transport_certificate_check_cb
)callback
;
2772 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2775 if (rev2
== GitRev::GetWorkingCopy())
2776 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2777 else if (rev1
== GitRev::GetWorkingCopy())
2778 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2789 if (diffContext
>= 0)
2790 unified
.Format(_T(" --unified=%d"), diffContext
);
2791 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2794 if (!path
.IsEmpty())
2797 cmd
+= path
.GetGitPathString();
2804 static void UnifiedDiffStatToFile(const git_buf
* text
, void* payload
)
2806 ATLASSERT(payload
&& text
);
2807 fwrite(text
->ptr
, 1, text
->size
, (FILE *)payload
);
2808 fwrite("\n", 1, 1, (FILE *)payload
);
2811 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2813 ATLASSERT(payload
&& line
);
2814 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2815 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2816 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2820 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2822 ATLASSERT(repo
&& identifier
&& tree
);
2824 /* try to resolve identifier */
2826 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2830 return GIT_ENOTFOUND
;
2833 switch (git_object_type(obj
))
2836 *tree
= (git_tree
*)obj
.Detach();
2838 case GIT_OBJ_COMMIT
:
2839 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2842 err
= GIT_ENOTFOUND
;
2848 /* use libgit2 get unified diff */
2849 static int GetUnifiedDiffLibGit2(const CTGitPath
& path
, const git_revnum_t
& revOld
, const git_revnum_t
& revNew
, std::function
<void(const git_buf
*, void*)> statCallback
, git_diff_line_cb callback
, void *data
, bool /* bMerge */)
2851 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2852 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2854 CAutoRepository
repo(g_Git
.GetGitRepository());
2858 int isHeadOrphan
= git_repository_head_unborn(repo
);
2859 if (isHeadOrphan
== 1)
2861 else if (isHeadOrphan
!= 0)
2864 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2865 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2866 char *buf
= pathA
.GetBuffer();
2867 if (!pathA
.IsEmpty())
2869 opts
.pathspec
.strings
= &buf
;
2870 opts
.pathspec
.count
= 1;
2874 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2879 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2882 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2885 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2888 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2891 if (git_diff_merge(diff
, diff2
))
2896 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2899 if (tree1
.IsEmpty())
2907 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2910 if (tree2
.IsEmpty())
2912 /* don't check return value, there are not parent commit at first commit*/
2913 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2915 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2917 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2921 CAutoDiffStats stats
;
2922 if (git_diff_get_stats(stats
.GetPointer(), diff
))
2925 if (git_diff_stats_to_buf(statBuf
, stats
, GIT_DIFF_STATS_FULL
, 0))
2927 statCallback(statBuf
, data
);
2929 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2932 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2935 if (git_patch_print(patch
, callback
, data
))
2939 pathA
.ReleaseBuffer();
2944 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2946 if (UsingLibGit2(GIT_CMD_DIFF
))
2948 FILE *file
= nullptr;
2949 _tfopen_s(&file
, patchfile
, _T("w"));
2950 if (file
== nullptr)
2952 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToFile
, UnifiedDiffToFile
, file
, bMerge
);
2959 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2960 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2964 static void UnifiedDiffStatToStringA(const git_buf
* text
, void* payload
)
2966 ATLASSERT(payload
&& text
);
2967 CStringA
*str
= (CStringA
*) payload
;
2968 str
->Append(text
->ptr
, (int)text
->size
);
2969 str
->AppendChar('\n');
2972 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2974 ATLASSERT(payload
&& line
);
2975 CStringA
*str
= (CStringA
*) payload
;
2976 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2977 str
->Append(&line
->origin
, 1);
2978 str
->Append(line
->content
, (int)line
->content_len
);
2982 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2984 if (UsingLibGit2(GIT_CMD_DIFF
))
2985 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffStatToStringA
, UnifiedDiffToStringA
, buffer
, bMerge
);
2989 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2991 int ret
= Run(cmd
, &vector
);
2992 if (!vector
.empty())
2994 vector
.push_back(0); // vector is not NUL terminated
2995 buffer
->Append((char *)&vector
[0]);
3001 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
3003 if (UsingLibGit2(GIT_CMD_REVERT
))
3005 CAutoRepository
repo(GetGitRepository());
3010 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
3013 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
3014 revert_opts
.mainline
= parent
;
3015 int result
= git_revert(repo
, commit
, &revert_opts
);
3017 return !result
? 0 : -1;
3023 merge
.Format(_T("-m %d "), parent
);
3024 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
3025 gitLastErr
= cmd
+ _T("\n");
3026 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3038 int CGit::DeleteRef(const CString
& reference
)
3040 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
3042 CAutoRepository
repo(GetGitRepository());
3047 if (reference
.Right(3) == _T("^{}"))
3048 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
3050 refA
= CUnicodeUtils::GetUTF8(reference
);
3053 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
3057 if (git_reference_is_tag(ref
))
3058 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
3059 else if (git_reference_is_branch(ref
))
3060 result
= git_branch_delete(ref
);
3061 else if (git_reference_is_remote(ref
))
3062 result
= git_branch_delete(ref
);
3064 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
3070 CString cmd
, shortname
;
3071 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
3072 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
3073 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
3074 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
3075 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
3076 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
3079 gitLastErr
= L
"unsupported reference type: " + reference
;
3083 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
3091 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
3093 if (PathFileExists(filename
))
3095 FILE *pFile
= nullptr;
3096 _tfopen_s(&pFile
, filename
, _T("r"));
3102 char s
[8196] = { 0 };
3103 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
3106 str
+= CStringA(s
, read
);
3109 msg
= CUnicodeUtils::GetUnicode(str
);
3110 msg
.Replace(_T("\r\n"), _T("\n"));
3111 msg
.TrimRight(_T("\n"));
3115 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
3116 return true; // load no further files
3121 int CGit::GetWorkingTreeChanges(CTGitPathList
& result
, bool amend
, CTGitPathList
* filterlist
)
3124 return GetInitAddList(result
);
3130 count
= filterlist
->GetCount();
3132 CString head
= _T("HEAD");
3134 head
= _T("HEAD~1");
3136 for (int i
= 0; i
< count
; ++i
)
3142 // Prevent showing all files as modified when using cygwin's git
3144 cmd
= _T("git.exe status --");
3146 cmd
.Format(_T("git.exe status -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3151 // also list staged files which will be in the commit
3152 Run(_T("git.exe diff-index --cached --raw ") + head
+ _T(" --numstat -C -M -z --"), &cmdout
);
3155 cmd
= (_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z --"));
3157 cmd
.Format(_T("git.exe diff-index --raw ") + head
+ _T(" --numstat -C -M -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3160 if (Run(cmd
, &cmdout
, &cmdErr
))
3162 int last
= cmdErr
.RevertFind(0, -1);
3164 CGit::StringAppend(&str
, &cmdErr
[last
+ 1], CP_UTF8
, (int)cmdErr
.size() - last
- 1);
3165 MessageBox(nullptr, str
, _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
3168 out
.append(cmdout
, 0);
3170 result
.ParserFromLog(out
);
3172 // handle delete conflict case, when remote : modified, local : deleted.
3173 for (int i
= 0; i
< count
; ++i
)
3179 cmd
= _T("git.exe ls-files -u -t -z");
3181 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3185 CTGitPathList conflictlist
;
3186 conflictlist
.ParserFromLog(cmdout
);
3187 for (int j
= 0; j
< conflictlist
.GetCount(); ++j
)
3189 CTGitPath
* p
= result
.LookForGitPath(conflictlist
[j
].GetGitPathString());
3191 p
->m_Action
|= CTGitPath::LOGACTIONS_UNMERGED
;
3193 result
.AddPath(conflictlist
[j
]);
3197 // handle source files of file renames/moves (issue #860)
3198 // if a file gets renamed and the new file "git add"ed, diff-index doesn't list the source file anymore
3199 for (int i
= 0; i
< count
; ++i
)
3205 cmd
= _T("git.exe ls-files -d -z");
3207 cmd
.Format(_T("git.exe ls-files -d -z -- \"%s\""), (*filterlist
)[i
].GetGitPathString());
3211 CTGitPathList deletelist
;
3212 deletelist
.ParserFromLog(cmdout
, true);
3213 for (int j
= 0; j
< deletelist
.GetCount(); ++j
)
3215 CTGitPath
* p
= result
.LookForGitPath(deletelist
[j
].GetGitPathString());
3217 result
.AddPath(deletelist
[j
]);