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"
32 int CGit::m_LogEncode
=CP_UTF8
;
33 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
35 static LPTSTR
nextpath(wchar_t *path
, wchar_t *buf
, size_t buflen
)
37 wchar_t term
, *base
= path
;
39 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
42 term
= (*path
== L
'"') ? *path
++ : L
';';
44 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
47 *buf
= L
'\0'; /* reserved a byte via initial subtract */
49 while (*path
== term
|| *path
== L
';')
52 return (path
!= base
) ? path
: NULL
;
55 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
58 return _tstat(lpszFileName
, &st
) == 0;
61 static BOOL
FindGitPath()
64 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
71 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
72 _tgetenv_s(&size
, env
, size
, _T("PATH"));
74 TCHAR buf
[MAX_PATH
] = {0};
76 // search in all paths defined in PATH
77 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
79 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
81 // ensure trailing slash
82 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
83 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
85 const size_t len
= _tcslen(buf
);
87 if ((len
+ 7) < MAX_PATH
)
88 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, _T("git.exe"));
92 if ( FileExists(buf
) )
96 CGit::ms_LastMsysGitDir
= buf
;
97 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
98 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
100 // often the msysgit\cmd folder is on the %PATH%, but
101 // that git.exe does not work, so try to guess the bin folder
102 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
103 if (FileExists(binDir
))
104 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
113 static bool g_bSortLogical
;
114 static bool g_bSortLocalBranchesFirst
;
115 static bool g_bSortTagsReversed
;
117 static void GetSortOptions()
119 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
121 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
122 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
123 if (g_bSortLocalBranchesFirst
)
124 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
125 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_LOCAL_MACHINE
);
126 if (!g_bSortTagsReversed
)
127 g_bSortTagsReversed
= !!CRegDWORD(L
"Software\\TortoiseGit\\SortTagsReversed", 0, false, HKEY_CURRENT_USER
);
130 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
133 return StrCmpLogicalW(left
, right
) < 0;
134 return StrCmpI(left
, right
) < 0;
137 static int LogicalCompareReversedPredicate(const CString
&left
, const CString
&right
)
140 return StrCmpLogicalW(left
, right
) > 0;
141 return StrCmpI(left
, right
) > 0;
144 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
146 if (g_bSortLocalBranchesFirst
)
148 int leftIsRemote
= left
.Find(_T("remotes/"));
149 int rightIsRemote
= right
.Find(_T("remotes/"));
151 if (leftIsRemote
== 0 && rightIsRemote
< 0)
153 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
157 return StrCmpLogicalW(left
, right
) < 0;
158 return StrCmpI(left
, right
) < 0;
161 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
163 CString
CGit::ms_LastMsysGitDir
;
164 int CGit::ms_LastMsysGitVersion
= 0;
170 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
171 m_CurrentDir
.ReleaseBuffer();
172 m_IsGitDllInited
= false;
174 m_GitSimpleListDiff
=0;
175 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
176 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
177 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
));
179 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
182 this->m_bInitialized
=false;
184 m_critGitDllSec
.Init();
191 git_close_diff(m_GitDiff
);
194 if(this->m_GitSimpleListDiff
)
196 git_close_diff(m_GitSimpleListDiff
);
197 m_GitSimpleListDiff
=0;
201 bool CGit::IsBranchNameValid(const CString
& branchname
)
203 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
205 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
207 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
208 return !!git_reference_is_valid_name(branchA
);
211 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
213 SECURITY_ATTRIBUTES sa
;
214 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
215 CAutoGeneralHandle hStdioFile
;
217 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
218 sa
.lpSecurityDescriptor
=NULL
;
219 sa
.bInheritHandle
=TRUE
;
220 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
222 CString err
= CFormatMessageWrapper();
223 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
224 return TGIT_GIT_ERROR_OPEN_PIP
;
226 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
228 CString err
= CFormatMessageWrapper();
229 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
230 return TGIT_GIT_ERROR_OPEN_PIP
;
235 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
236 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
240 PROCESS_INFORMATION pi
;
241 si
.cb
=sizeof(STARTUPINFO
);
245 si
.hStdError
= hWriteErr
;
247 si
.hStdError
= hWrite
;
249 si
.hStdOutput
=hStdioFile
;
251 si
.hStdOutput
=hWrite
;
253 si
.wShowWindow
=SW_HIDE
;
254 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
256 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
257 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
259 // CREATE_NEW_CONSOLE makes ssh recognize that it has no console in order to launch askpass to ask for the password.
260 // DETACHED_PROCESS which was originally used here has the same effect, however, it prevents PowerShell from working (cf. issue #2143)
261 dwFlags
|= CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
;
263 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
264 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
266 if(cmd
.Find(_T("git")) == 0)
268 int firstSpace
= cmd
.Find(_T(" "));
270 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
272 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
275 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
276 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
278 CString err
= CFormatMessageWrapper();
279 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
280 return TGIT_GIT_ERROR_CREATE_PROCESS
;
288 *hReadOut
= hRead
.Detach();
290 *hErrReadOut
= hReadErr
.Detach();
294 //Must use sperate function to convert ANSI str to union code string
295 //Becuase A2W use stack as internal convert buffer.
296 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
303 len
= (int)strlen((const char*)p
);
308 int currentContentLen
= str
->GetLength();
309 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
310 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
311 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
314 // This method was originally used to check for orphaned branches
315 BOOL
CGit::CanParseRev(CString ref
)
321 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
331 // Checks if we have an orphaned HEAD
332 BOOL
CGit::IsInitRepos()
335 // handle error on reading HEAD hash as init repo
336 if (GetHash(hash
, _T("HEAD")) != 0)
338 return hash
.IsEmpty() ? TRUE
: FALSE
;
341 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
343 PASYNCREADSTDERRTHREADARGS pDataArray
;
344 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
347 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
348 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
350 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
357 int CGit::Run(CGitCall
* pcall
)
359 PROCESS_INFORMATION pi
;
360 CAutoGeneralHandle hRead
, hReadErr
;
361 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
362 return TGIT_GIT_ERROR_CREATE_PROCESS
;
364 CAutoGeneralHandle
piThread(pi
.hThread
);
365 CAutoGeneralHandle
piProcess(pi
.hProcess
);
367 ASYNCREADSTDERRTHREADARGS threadArguments
;
368 threadArguments
.fileHandle
= hReadErr
;
369 threadArguments
.pcall
= pcall
;
370 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
373 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
375 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
377 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
378 if(!bAborted
)//For now, flush output when command aborted.
379 if(pcall
->OnOutputData(data
,readnumber
))
386 WaitForSingleObject(thread
, INFINITE
);
388 WaitForSingleObject(pi
.hProcess
, INFINITE
);
391 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
393 CString err
= CFormatMessageWrapper();
394 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
395 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
398 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
402 class CGitCall_ByteVector
: public CGitCall
405 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
406 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
408 if (!m_pvector
|| size
== 0)
410 size_t oldsize
=m_pvector
->size();
411 m_pvector
->resize(m_pvector
->size()+size
);
412 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
415 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
417 if (!m_pvectorErr
|| size
== 0)
419 size_t oldsize
= m_pvectorErr
->size();
420 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
421 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
424 BYTE_VECTOR
* m_pvector
;
425 BYTE_VECTOR
* m_pvectorErr
;
428 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
430 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
433 int CGit::Run(CString cmd
, CString
* output
, int code
)
437 ret
= Run(cmd
, output
, &err
, code
);
439 if (output
&& !err
.IsEmpty())
441 if (!output
->IsEmpty())
448 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
450 BYTE_VECTOR vector
, vectorErr
;
453 ret
= Run(cmd
, &vector
, &vectorErr
);
455 ret
= Run(cmd
, &vector
);
458 StringAppend(output
, &(vector
[0]), code
);
462 vectorErr
.push_back(0);
463 StringAppend(outputErr
, &(vectorErr
[0]), code
);
469 class CGitCallCb
: public CGitCall
472 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
474 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
479 int oldEndPos
= m_buffer
.GetLength();
480 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
481 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
483 // Break into lines and feed to m_recv
485 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
487 m_recv(m_buffer
.Left(eolPos
));
488 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
493 virtual bool OnOutputErrData(const BYTE
*, size_t) override
495 return false; // Ignore error output for now
498 virtual void OnEnd() override
500 if (!m_buffer
.IsEmpty())
502 m_buffer
.Empty(); // Just for sure
506 GitReceiverFunc m_recv
;
510 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
512 CGitCallCb
call(cmd
, recv
);
516 CString
CGit::GetUserName(void)
519 env
.CopyProcessEnvironment();
520 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
521 if (!envname
.IsEmpty())
523 return GetConfigValue(L
"user.name");
525 CString
CGit::GetUserEmail(void)
528 env
.CopyProcessEnvironment();
529 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
530 if (!envmail
.IsEmpty())
533 return GetConfigValue(L
"user.email");
536 CString
CGit::GetConfigValue(const CString
& name
)
540 if(this->m_IsUseGitDLL
)
542 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
551 key
= CUnicodeUtils::GetUTF8(name
);
555 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
558 catch (const char *msg
)
560 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
564 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
565 return configValue
.Tokenize(_T("\n"),start
);
570 cmd
.Format(L
"git.exe config %s", name
);
571 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
572 return configValue
.Tokenize(_T("\n"),start
);
576 bool CGit::GetConfigValueBool(const CString
& name
)
578 CString configValue
= GetConfigValue(name
);
579 configValue
.MakeLower();
581 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
587 int CGit::GetConfigValueInt32(const CString
& name
, int def
)
589 CString configValue
= GetConfigValue(name
);
591 if (!git_config_parse_int32(&value
, CUnicodeUtils::GetUTF8(configValue
)))
596 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
598 if(this->m_IsUseGitDLL
)
600 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
609 CStringA keya
, valuea
;
610 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
611 valuea
= CUnicodeUtils::GetUTF8(value
);
615 return [=]() { return get_set_config(keya
, valuea
, type
); }();
617 catch (const char *msg
)
619 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
630 option
= _T("--global");
633 option
= _T("--system");
638 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
640 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
648 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
650 if(this->m_IsUseGitDLL
)
652 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
661 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
665 return [=]() { return get_set_config(keya
, nullptr, type
); }();
667 catch (const char *msg
)
669 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
680 option
= _T("--global");
683 option
= _T("--system");
688 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
690 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
698 CString
CGit::GetCurrentBranch(bool fallback
)
701 //Run(_T("git.exe branch"),&branch);
703 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
704 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
706 return _T("(no branch)");
713 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
715 if (localBranch
.IsEmpty())
719 configName
.Format(L
"branch.%s.remote", localBranch
);
720 pullRemote
= GetConfigValue(configName
);
722 //Select pull-branch from current branch
723 configName
.Format(L
"branch.%s.merge", localBranch
);
724 pullBranch
= StripRefName(GetConfigValue(configName
));
727 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
730 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
732 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
735 CString
CGit::GetFullRefName(const CString
& shortRefName
)
739 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
740 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
741 return CString();//Error
743 return refName
.Tokenize(L
"\n", iStart
);
746 CString
CGit::StripRefName(CString refName
)
748 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
749 refName
= refName
.Mid(11);
750 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
751 refName
= refName
.Mid(5);
753 return refName
.Tokenize(_T("\n"),start
);
756 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
758 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
760 if ( sProjectRoot
.IsEmpty() )
764 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
767 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
770 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
778 fgets(s
, sizeof(s
), pFile
);
782 const char *pfx
= "ref: refs/heads/";
783 const int len
= 16;//strlen(pfx)
785 if ( !strncmp(s
, pfx
, len
) )
787 //# We're on a branch. It might not exist. But
788 //# HEAD looks good enough to be a branch.
789 CStringA
utf8Branch(s
+ len
);
790 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
791 sBranchOut
.TrimRight(_T(" \r\n\t"));
793 if ( sBranchOut
.IsEmpty() )
798 CStringA
utf8Hash(s
);
799 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
800 unicodeHash
.TrimRight(_T(" \r\n\t"));
801 if (CGitHash::IsValidSHA1(unicodeHash
))
802 sBranchOut
= unicodeHash
;
804 //# Assume this is a detached head.
805 sBranchOut
= _T("HEAD");
810 //# Assume this is a detached head.
819 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
822 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
826 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
828 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
830 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
832 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
834 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
836 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
838 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
842 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
844 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
846 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
851 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
857 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
864 CString file
= _T(" --");
867 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
870 num
.Format(_T("-n%d"),count
);
874 if(mask
& LOG_INFO_STAT
)
875 param
+= _T(" --numstat ");
876 if(mask
& LOG_INFO_FILESTATE
)
877 param
+= _T(" --raw ");
879 if(mask
& LOG_INFO_FULLHISTORY
)
880 param
+= _T(" --full-history ");
882 if(mask
& LOG_INFO_BOUNDARY
)
883 param
+= _T(" --left-right --boundary ");
885 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
886 param
+= _T(" --all ");
888 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
889 param
+= _T(" --branches ");
891 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
894 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
897 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
898 param
+= _T(" --first-parent ");
900 if(mask
& CGit::LOG_INFO_NO_MERGE
)
901 param
+= _T(" --no-merges ");
903 if(mask
& CGit::LOG_INFO_FOLLOW
)
904 param
+= _T(" --follow ");
906 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
909 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
910 param
+= _T(" --full-diff ");
912 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
913 param
+= _T(" --simplify-by-decoration ");
919 if( Filter
&& (Filter
->m_From
!= -1))
921 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
925 if( Filter
&& (Filter
->m_To
!= -1))
927 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
932 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
934 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
939 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
941 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
946 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
948 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
955 if(!Filter
->m_IsRegex
)
956 param
+= _T(" --fixed-strings ");
958 param
+= _T(" --regexp-ignore-case --extended-regexp ");
961 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
962 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
963 param
+= _T(" --topo-order");
964 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
965 param
+= _T(" --date-order");
967 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
968 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
972 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
973 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
982 void GetTempPath(CString
&path
)
984 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
986 DWORD dwBufSize
=BUFSIZE
;
987 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
988 lpPathBuffer
); // buffer for path
989 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
993 path
.Format(_T("%s"),lpPathBuffer
);
995 CString
GetTempFile()
997 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
999 DWORD dwBufSize
=BUFSIZE
;
1000 TCHAR szTempName
[BUFSIZE
] = { 0 };
1003 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
1004 lpPathBuffer
); // buffer for path
1005 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
1009 // Create a temporary file.
1010 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
1011 TEXT("Patch"), // temp file name prefix
1012 0, // create unique name
1013 szTempName
); // buffer for name
1021 return CString(szTempName
);
1025 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1027 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1028 if (result
== 0) return 0;
1029 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1036 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1037 CreateDirectory(lpBuffer
, NULL
);
1042 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1045 PROCESS_INFORMATION pi
;
1046 si
.cb
=sizeof(STARTUPINFO
);
1047 GetStartupInfo(&si
);
1049 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1050 psa
.bInheritHandle
=TRUE
;
1052 HANDLE hReadErr
, hWriteErr
;
1053 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1055 CString err
= CFormatMessageWrapper();
1056 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1057 return TGIT_GIT_ERROR_OPEN_PIP
;
1060 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1061 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1063 if (houtfile
== INVALID_HANDLE_VALUE
)
1065 CString err
= CFormatMessageWrapper();
1066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1067 CloseHandle(hReadErr
);
1068 CloseHandle(hWriteErr
);
1069 return TGIT_GIT_ERROR_OPEN_PIP
;
1072 si
.wShowWindow
= SW_HIDE
;
1073 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1074 si
.hStdOutput
= houtfile
;
1075 si
.hStdError
= hWriteErr
;
1077 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1078 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1080 if(cmd
.Find(_T("git")) == 0)
1081 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1083 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1084 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1086 CString err
= CFormatMessageWrapper();
1087 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1089 CloseHandle(hReadErr
);
1090 CloseHandle(hWriteErr
);
1091 CloseHandle(houtfile
);
1092 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1095 BYTE_VECTOR stderrVector
;
1096 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1098 ASYNCREADSTDERRTHREADARGS threadArguments
;
1099 threadArguments
.fileHandle
= hReadErr
;
1100 threadArguments
.pcall
= &pcall
;
1101 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1103 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1105 CloseHandle(hWriteErr
);
1106 CloseHandle(hReadErr
);
1109 WaitForSingleObject(thread
, INFINITE
);
1111 stderrVector
.push_back(0);
1112 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1115 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1117 CString err
= CFormatMessageWrapper();
1118 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1119 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1122 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1124 CloseHandle(pi
.hThread
);
1125 CloseHandle(pi
.hProcess
);
1126 CloseHandle(houtfile
);
1130 git_repository
* CGit::GetGitRepository() const
1132 git_repository
* repo
= nullptr;
1133 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1137 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1141 // no need to parse a ref if it's already a 40-byte hash
1142 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1144 hash
= CGitHash(friendname
);
1148 int isHeadOrphan
= git_repository_head_unborn(repo
);
1149 if (isHeadOrphan
!= 0)
1152 if (isHeadOrphan
== 1)
1158 CAutoObject gitObject
;
1159 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1162 const git_oid
* oid
= git_object_id(gitObject
);
1166 hash
= CGitHash((char *)oid
->id
);
1171 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1173 // no need to parse a ref if it's already a 40-byte hash
1174 if (CGitHash::IsValidSHA1(friendname
))
1176 hash
= CGitHash(friendname
);
1182 CAutoRepository
repo(GetGitRepository());
1186 return GetHash(repo
, hash
, friendname
, true);
1191 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1193 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1194 hash
= CGitHash(gitLastErr
.Trim());
1201 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1206 cmd
=_T("git.exe ls-files -s -t -z");
1208 if (Run(cmd
, &cmdout
))
1211 if (outputlist
.ParserFromLsFile(cmdout
))
1213 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1214 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1218 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1222 if (ignoreSpaceAtEol
)
1223 ignore
+= _T(" --ignore-space-at-eol");
1224 if (ignoreSpaceChange
)
1225 ignore
+= _T(" --ignore-space-change");
1227 ignore
+= _T(" --ignore-all-space");
1228 if (ignoreBlankLines
)
1229 ignore
+= _T(" --ignore-blank-lines");
1231 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1234 if(rev1
== GIT_REV_ZERO
)
1235 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1237 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1241 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1248 outputlist
.ParserFromLog(out
);
1253 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1255 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1257 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1258 list
->push_back(str
);
1262 int CGit::GetTagList(STRING_VECTOR
&list
)
1264 if (this->m_IsUseLibGit2
)
1266 CAutoRepository
repo(GetGitRepository());
1270 CAutoStrArray tag_names
;
1272 if (git_tag_list(tag_names
, repo
))
1275 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1277 CStringA
tagName(tag_names
->strings
[i
]);
1278 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1281 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1287 CString cmd
, output
;
1288 cmd
=_T("git.exe tag -l");
1289 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1296 one
=output
.Tokenize(_T("\n"),pos
);
1298 list
.push_back(one
);
1300 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1306 CString
CGit::GetGitLastErr(const CString
& msg
)
1308 if (this->m_IsUseLibGit2
)
1309 return GetLibGit2LastErr(msg
);
1310 else if (gitLastErr
.IsEmpty())
1311 return msg
+ _T("\nUnknown git.exe error.");
1314 CString lastError
= gitLastErr
;
1316 return msg
+ _T("\n") + lastError
;
1320 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1322 if (UsingLibGit2(cmd
))
1323 return GetLibGit2LastErr(msg
);
1324 else if (gitLastErr
.IsEmpty())
1325 return msg
+ _T("\nUnknown git.exe error.");
1328 CString lastError
= gitLastErr
;
1330 return msg
+ _T("\n") + lastError
;
1334 CString
CGit::GetLibGit2LastErr()
1336 const git_error
*libgit2err
= giterr_last();
1339 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1341 return _T("libgit2 returned: ") + lastError
;
1344 return _T("An error occoured in libgit2, but no message is available.");
1347 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1350 return msg
+ _T("\n") + GetLibGit2LastErr();
1351 return GetLibGit2LastErr();
1354 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1356 if(branchName
== "FETCH_HEAD")
1357 branchName
= DerefFetchHead();
1361 CString
CGit::FixBranchName(const CString
& branchName
)
1363 CString tempBranchName
= branchName
;
1364 FixBranchName_Mod(tempBranchName
);
1365 return tempBranchName
;
1368 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1372 CAutoRepository
repo(GetGitRepository());
1374 return true; // TODO: optimize error reporting
1376 CAutoReference tagRef
;
1377 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1380 CAutoReference branchRef
;
1381 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1390 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1391 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1397 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1407 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1411 CAutoRepository
repo(GetGitRepository());
1413 return false; // TODO: optimize error reporting
1417 prefix
= _T("refs/heads/");
1419 prefix
= _T("refs/tags/");
1422 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1428 CString cmd
, output
;
1430 cmd
= _T("git.exe show-ref ");
1432 cmd
+= _T("--heads ");
1434 cmd
+= _T("--tags ");
1436 cmd
+= _T("refs/heads/") + name
;
1437 cmd
+= _T(" refs/tags/") + name
;
1439 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1442 if (!output
.IsEmpty())
1449 CString
CGit::DerefFetchHead()
1452 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1453 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1454 int forMergeLineCount
= 0;
1456 std::string hashToReturn
;
1457 while(getline(fetchHeadFile
, line
))
1459 //Tokenize this line
1460 std::string::size_type prevPos
= 0;
1461 std::string::size_type pos
= line
.find('\t');
1462 if(pos
== std::string::npos
) continue; //invalid line
1464 std::string hash
= line
.substr(0, pos
);
1465 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1467 bool forMerge
= pos
== prevPos
;
1468 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1470 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1475 hashToReturn
= hash
;
1476 ++forMergeLineCount
;
1477 if(forMergeLineCount
> 1)
1478 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1482 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1485 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1491 CAutoRepository
repo(GetGitRepository());
1495 if (git_repository_head_detached(repo
) == 1)
1496 cur
= _T("(detached from ");
1498 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1500 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1501 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1502 flags
= GIT_BRANCH_ALL
;
1503 else if (type
& BRANCH_REMOTE
)
1504 flags
= GIT_BRANCH_REMOTE
;
1506 CAutoBranchIterator it
;
1507 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1510 git_reference
* ref
= nullptr;
1511 git_branch_t branchType
;
1512 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1514 CAutoReference
autoRef(ref
);
1515 const char * name
= nullptr;
1516 if (git_branch_name(&name
, ref
))
1519 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1520 if (branchType
& GIT_BRANCH_REMOTE
)
1521 list
.push_back(_T("remotes/") + branchname
);
1524 if (git_branch_is_head(ref
))
1526 list
.push_back(branchname
);
1533 CString cmd
, output
;
1534 cmd
= _T("git.exe branch --no-color");
1536 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1538 else if (type
& BRANCH_REMOTE
)
1541 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1548 one
= output
.Tokenize(_T("\n"), pos
);
1549 one
.Trim(L
" \r\n\t");
1550 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1551 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1552 if (one
[0] == _T('*'))
1557 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1558 list
.push_back(one
);
1563 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1564 list
.push_back(L
"FETCH_HEAD");
1566 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1568 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1570 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1583 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1585 if (this->m_IsUseLibGit2
)
1587 CAutoRepository
repo(GetGitRepository());
1591 CAutoStrArray remotes
;
1592 if (git_remote_list(remotes
, repo
))
1595 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1597 CStringA
remote(remotes
->strings
[i
]);
1598 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1601 std::sort(list
.begin(), list
.end());
1608 CString cmd
, output
;
1609 cmd
=_T("git.exe remote");
1610 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1617 one
=output
.Tokenize(_T("\n"),pos
);
1619 list
.push_back(one
);
1626 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1628 CString cmd
, out
, err
;
1629 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1630 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1632 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1639 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1640 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1641 if (one
.Find(_T("^{}")) >= 1)
1644 list
.push_back(one
);
1646 std::sort(list
.begin(), list
.end(), g_bSortTagsReversed
? LogicalCompareReversedPredicate
: LogicalComparePredicate
);
1650 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1652 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1654 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1655 list
->push_back(str
);
1659 int CGit::GetRefList(STRING_VECTOR
&list
)
1661 if (this->m_IsUseLibGit2
)
1663 CAutoRepository
repo(GetGitRepository());
1667 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1670 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1676 CString cmd
, output
;
1677 cmd
=_T("git.exe show-ref -d");
1678 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1685 one
=output
.Tokenize(_T("\n"),pos
);
1686 int start
=one
.Find(_T(" "),0);
1690 name
=one
.Right(one
.GetLength()-start
-1);
1691 list
.push_back(name
);
1694 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1700 typedef struct map_each_ref_payload
{
1701 git_repository
* repo
;
1702 MAP_HASH_NAME
* map
;
1703 } map_each_ref_payload
;
1705 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1707 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1710 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1712 CAutoObject gitObject
;
1713 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1716 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1718 str
+= _T("^{}"); // deref tag
1719 CAutoObject derefedTag
;
1720 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1722 gitObject
.Swap(derefedTag
);
1725 const git_oid
* oid
= git_object_id(gitObject
);
1729 CGitHash
hash((char *)oid
->id
);
1730 (*payloadContent
->map
)[hash
].push_back(str
);
1734 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1738 map_each_ref_payload payloadContent
= { repo
, &map
};
1740 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1743 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1745 std::sort(it
->second
.begin(), it
->second
.end());
1751 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1753 if (this->m_IsUseLibGit2
)
1755 CAutoRepository
repo(GetGitRepository());
1759 return GetMapHashToFriendName(repo
, map
);
1763 CString cmd
, output
;
1764 cmd
=_T("git.exe show-ref -d");
1765 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1772 one
=output
.Tokenize(_T("\n"),pos
);
1773 int start
=one
.Find(_T(" "),0);
1777 name
=one
.Right(one
.GetLength()-start
-1);
1780 hash
=one
.Left(start
);
1782 map
[CGitHash(hash
)].push_back(name
);
1790 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1792 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1793 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1796 static void SetLibGit2TemplatePath(const CString
&value
)
1798 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1799 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1802 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1809 this->m_Environment
.clear();
1810 m_Environment
.CopyProcessEnvironment();
1813 size_t homesize
,size
;
1815 // set HOME if not set already
1816 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1818 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1821 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1822 if (sshclient
.IsEmpty())
1823 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1825 if(!sshclient
.IsEmpty())
1827 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1828 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1832 TCHAR sPlink
[MAX_PATH
] = {0};
1833 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1834 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1836 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1837 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1838 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1843 TCHAR sAskPass
[MAX_PATH
] = {0};
1844 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1845 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1848 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1849 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1850 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1851 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1855 // add git/bin path to PATH
1857 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1858 CString str
= msysdir
;
1859 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1864 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1865 str
= msyslocalinstalldir
;
1866 str
.TrimRight(_T("\\"));
1869 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1870 str
= msysinstalldir
;
1871 str
.TrimRight(_T("\\"));
1873 if ( !str
.IsEmpty() )
1877 CGit::ms_LastMsysGitDir
= str
;
1882 // search PATH if git/bin directory is already present
1883 if ( FindGitPath() )
1885 m_bInitialized
= TRUE
;
1886 msysdir
= CGit::ms_LastMsysGitDir
;
1896 CGit::ms_LastMsysGitDir
= str
;
1899 // check for git.exe existance (maybe it was deinstalled in the meantime)
1900 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1903 // Configure libgit2 search paths
1905 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1906 msysGitDir
.ReleaseBuffer();
1907 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1908 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1909 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1910 CString msysGitTemplateDir
;
1911 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1912 msysGitTemplateDir
.ReleaseBuffer();
1913 SetLibGit2TemplatePath(msysGitTemplateDir
);
1916 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1919 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1921 m_Environment
.SetEnv(_T("PATH"), path
);
1923 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1925 CString sOldPath
= oldpath
;
1928 m_bInitialized
= TRUE
;
1932 CString
CGit::GetHomeDirectory() const
1934 const wchar_t * homeDir
= wget_windows_home_directory();
1935 return CString(homeDir
, (int)wcslen(homeDir
));
1938 CString
CGit::GetGitLocalConfig() const
1941 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1942 path
+= _T("config");
1946 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1948 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1951 CString
CGit::GetGitGlobalConfig() const
1953 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1956 CString
CGit::GetGitGlobalXDGConfigPath() const
1958 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1961 CString
CGit::GetGitGlobalXDGConfig() const
1963 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1966 CString
CGit::GetGitSystemConfig() const
1968 const wchar_t * systemConfig
= wget_msysgit_etc();
1969 return CString(systemConfig
, (int)wcslen(systemConfig
));
1972 BOOL
CGit::CheckCleanWorkTree()
1976 cmd
=_T("git.exe rev-parse --verify HEAD");
1978 if(Run(cmd
,&out
,CP_UTF8
))
1981 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1982 if(Run(cmd
,&out
,CP_UTF8
))
1985 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1986 if(Run(cmd
,&out
,CP_UTF8
))
1989 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1990 if(Run(cmd
,&out
,CP_UTF8
))
1995 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
1998 for (int i
= 0; i
< list
.GetCount(); ++i
)
2000 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
2006 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
2010 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
2012 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2015 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2016 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2020 // if the filenames only differ in case, we have to pass "-f"
2021 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2023 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2024 if (Run(cmd
, &out
, CP_UTF8
))
2026 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2030 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2031 if (Run(cmd
, &out
, CP_UTF8
))
2033 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2038 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2039 { //To init git repository, there are not HEAD, so we can use git reset command
2040 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2042 if (Run(cmd
, &out
, CP_UTF8
))
2044 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2050 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2051 if (Run(cmd
, &out
, CP_UTF8
))
2053 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2058 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2060 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2061 if (Run(cmd
, &out
, CP_UTF8
))
2063 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2071 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2077 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2079 cmd
=_T("git.exe ls-files -u -t -z");
2081 if (Run(cmd
, &vector
))
2086 if (list
.ParserFromLsFile(vector
))
2092 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2094 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2096 CAutoRepository
repo(GetGitRepository());
2100 CGitHash fromHash
, toHash
, baseHash
;
2101 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2104 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2108 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2111 baseHash
= baseOid
.id
;
2114 *commonAncestor
= baseHash
;
2116 return fromHash
== baseHash
;
2120 CGitHash basehash
,hash
;
2122 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2124 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2128 basehash
= base
.Trim();
2130 GetHash(hash
, from
);
2133 *commonAncestor
= basehash
;
2135 return hash
== basehash
;
2138 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2141 for (int i
= 0; i
< 4; ++i
)
2144 ret
|= hash
.m_hash
[i
];
2149 int CGit::RefreshGitIndex()
2151 if(g_Git
.m_IsUseGitDLL
)
2153 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2156 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2167 cmd
=_T("git.exe update-index --refresh");
2168 return Run(cmd
, &output
, CP_UTF8
);
2172 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2174 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2176 CAutoRepository
repo(GetGitRepository());
2181 if (GetHash(repo
, hash
, Refname
))
2185 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2189 if (git_commit_tree(tree
.GetPointer(), commit
))
2192 CAutoTreeEntry entry
;
2193 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2197 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2200 FILE *file
= nullptr;
2201 _tfopen_s(&file
, outputfile
, _T("w"));
2202 if (file
== nullptr)
2204 giterr_set_str(GITERR_NONE
, "Could not create file.");
2208 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2213 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2215 giterr_set_str(GITERR_OS
, "Could not write to file.");
2224 else if (g_Git
.m_IsUseGitDLL
)
2226 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2229 g_Git
.CheckAndInitDll();
2230 CStringA ref
, patha
, outa
;
2231 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2232 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2233 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2234 ::DeleteFile(outputfile
);
2235 return git_checkout_file(ref
, patha
, outa
);
2238 catch (const char * msg
)
2240 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2245 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2252 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2253 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2256 void CEnvironment::CopyProcessEnvironment()
2258 TCHAR
*porig
= GetEnvironmentStrings();
2260 while(*p
!=0 || *(p
+1) !=0)
2261 this->push_back(*p
++);
2263 push_back(_T('\0'));
2264 push_back(_T('\0'));
2266 FreeEnvironmentStrings(porig
);
2269 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2272 for (size_t i
= 0; i
< size(); ++i
)
2276 CString sname
= str
.Tokenize(_T("="),start
);
2277 if(sname
.CompareNoCase(name
) == 0)
2279 return &(*this)[i
+start
];
2286 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2289 for (i
= 0; i
< size(); ++i
)
2291 CString str
= &(*this)[i
];
2293 CString sname
= str
.Tokenize(_T("="),start
);
2294 if(sname
.CompareNoCase(name
) == 0)
2303 i
-= 1; // roll back terminate \0\0
2304 this->push_back(_T('\0'));
2307 CEnvironment::iterator it
;
2311 while(*it
&& i
<size())
2320 this->insert(it
,*name
++);
2325 this->insert(it
, _T('='));
2331 this->insert(it
,*value
++);
2338 int CGit::GetGitEncode(TCHAR
* configkey
)
2340 CString str
=GetConfigValue(configkey
);
2345 return CUnicodeUtils::GetCPCode(str
);
2349 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2355 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2358 diff
= GetGitDiff();
2360 git_open_diff(&diff
, arg
);
2369 isStat
= !!strstr(arg
, "stat");
2374 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2376 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2385 for (int j
= 0; j
< count
; ++j
)
2394 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2395 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2396 &mode
,&IsBin
,&inc
,&dec
);
2398 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2399 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2401 path
.SetFromGit(strnewname
,&stroldname
);
2402 path
.ParserAction((BYTE
)mode
);
2406 path
.m_StatAdd
=_T("-");
2407 path
.m_StatDel
=_T("-");
2411 path
.m_StatAdd
.Format(_T("%d"),inc
);
2412 path
.m_StatDel
.Format(_T("%d"),dec
);
2414 PathList
->AddPath(path
);
2416 git_diff_flush(diff
);
2419 git_close_diff(diff
);
2424 int CGit::GetShortHASHLength() const
2429 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2433 REF_TYPE type
= CGit::UNKNOWN
;
2435 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2437 type
= CGit::LOCAL_BRANCH
;
2440 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2442 type
= CGit::REMOTE_BRANCH
;
2444 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2448 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2451 shortname
=_T("stash");
2453 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2455 if (shortname
.Find(_T("good")) == 0)
2457 type
= CGit::BISECT_GOOD
;
2458 shortname
= _T("good");
2461 if (shortname
.Find(_T("bad")) == 0)
2463 type
= CGit::BISECT_BAD
;
2464 shortname
= _T("bad");
2467 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2471 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2473 type
= CGit::UNKNOWN
;
2477 type
= CGit::UNKNOWN
;
2487 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2489 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2492 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2495 if (rev2
== GitRev::GetWorkingCopy())
2496 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2497 else if (rev1
== GitRev::GetWorkingCopy())
2498 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2509 if (diffContext
>= 0)
2510 unified
.Format(_T(" --unified=%d"), diffContext
);
2511 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2514 if (!path
.IsEmpty())
2517 cmd
+= path
.GetGitPathString();
2524 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2526 ATLASSERT(payload
&& line
);
2527 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2528 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2529 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2533 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2535 ATLASSERT(repo
&& identifier
&& tree
);
2537 /* try to resolve identifier */
2539 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2543 return GIT_ENOTFOUND
;
2546 switch (git_object_type(obj
))
2549 *tree
= (git_tree
*)obj
.Detach();
2551 case GIT_OBJ_COMMIT
:
2552 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2555 err
= GIT_ENOTFOUND
;
2561 /* use libgit2 get unified diff */
2562 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 */)
2564 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2565 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2567 CAutoRepository
repo(g_Git
.GetGitRepository());
2571 int isHeadOrphan
= git_repository_head_unborn(repo
);
2572 if (isHeadOrphan
== 1)
2574 else if (isHeadOrphan
!= 0)
2577 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2578 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2579 char *buf
= pathA
.GetBuffer();
2580 if (!pathA
.IsEmpty())
2582 opts
.pathspec
.strings
= &buf
;
2583 opts
.pathspec
.count
= 1;
2587 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2592 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2595 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2598 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2601 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2604 if (git_diff_merge(diff
, diff2
))
2609 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2612 if (tree1
.IsEmpty())
2620 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2623 if (tree2
.IsEmpty())
2625 /* don't check return value, there are not parent commit at first commit*/
2626 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2628 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2630 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2634 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2637 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2640 if (git_patch_print(patch
, callback
, data
))
2644 pathA
.ReleaseBuffer();
2649 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2651 if (UsingLibGit2(GIT_CMD_DIFF
))
2653 FILE *file
= nullptr;
2654 _tfopen_s(&file
, patchfile
, _T("w"));
2655 if (file
== nullptr)
2657 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2664 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2665 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2669 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2671 ATLASSERT(payload
&& line
);
2672 CStringA
*str
= (CStringA
*) payload
;
2673 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2674 str
->Append(&line
->origin
, 1);
2675 str
->Append(line
->content
, (int)line
->content_len
);
2679 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2681 if (UsingLibGit2(GIT_CMD_DIFF
))
2682 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2686 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2688 int ret
= Run(cmd
, &vector
);
2689 if (!vector
.empty())
2691 vector
.push_back(0); // vector is not NUL terminated
2692 buffer
->Append((char *)&vector
[0]);
2698 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2700 if (UsingLibGit2(GIT_CMD_REVERT
))
2702 CAutoRepository
repo(GetGitRepository());
2707 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2710 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2711 revert_opts
.mainline
= parent
;
2712 int result
= git_revert(repo
, commit
, &revert_opts
);
2714 return !result
? 0 : -1;
2720 merge
.Format(_T("-m %d "), parent
);
2721 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2722 gitLastErr
= cmd
+ _T("\n");
2723 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2735 int CGit::DeleteRef(const CString
& reference
)
2737 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2739 CAutoRepository
repo(GetGitRepository());
2744 if (reference
.Right(3) == _T("^{}"))
2745 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2747 refA
= CUnicodeUtils::GetUTF8(reference
);
2750 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
2754 if (git_reference_is_tag(ref
))
2755 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2756 else if (git_reference_is_branch(ref
))
2757 result
= git_branch_delete(ref
);
2758 else if (git_reference_is_remote(ref
))
2759 result
= git_branch_delete(ref
);
2761 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2767 CString cmd
, shortname
;
2768 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2769 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2770 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2771 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2772 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2773 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2776 gitLastErr
= L
"unsupported reference type: " + reference
;
2780 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2788 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2790 if (PathFileExists(filename
))
2792 FILE *pFile
= nullptr;
2793 _tfopen_s(&pFile
, filename
, _T("r"));
2799 char s
[8196] = { 0 };
2800 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2803 str
+= CStringA(s
, read
);
2806 msg
= CUnicodeUtils::GetUnicode(str
);
2807 msg
.Replace(_T("\r\n"), _T("\n"));
2808 msg
.TrimRight(_T("\n"));
2812 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
2813 return true; // load no further files