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
;
116 static void GetSortOptions()
118 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
120 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
121 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
122 if (g_bSortLocalBranchesFirst
)
123 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"Software\\TortoiseGit\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
126 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
129 return StrCmpLogicalW(left
, right
) < 0;
130 return StrCmpI(left
, right
) < 0;
133 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
135 if (g_bSortLocalBranchesFirst
)
137 int leftIsRemote
= left
.Find(_T("remotes/"));
138 int rightIsRemote
= right
.Find(_T("remotes/"));
140 if (leftIsRemote
== 0 && rightIsRemote
< 0)
142 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
146 return StrCmpLogicalW(left
, right
) < 0;
147 return StrCmpI(left
, right
) < 0;
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString
CGit::ms_LastMsysGitDir
;
153 int CGit::ms_LastMsysGitVersion
= 0;
159 GetCurrentDirectory(MAX_PATH
, m_CurrentDir
.GetBuffer(MAX_PATH
));
160 m_CurrentDir
.ReleaseBuffer();
161 m_IsGitDllInited
= false;
163 m_GitSimpleListDiff
=0;
164 m_IsUseGitDLL
= !!CRegDWORD(_T("Software\\TortoiseGit\\UsingGitDLL"),1);
165 m_IsUseLibGit2
= !!CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2"), TRUE
);
166 m_IsUseLibGit2_mask
= CRegDWORD(_T("Software\\TortoiseGit\\UseLibgit2_mask"), (1 << GIT_CMD_MERGE_BASE
) | (1 << GIT_CMD_DELETETAGBRANCH
) | (1 << GIT_CMD_GETONEFILE
));
168 SecureZeroMemory(&m_CurrentGitPi
, sizeof(PROCESS_INFORMATION
));
171 this->m_bInitialized
=false;
173 m_critGitDllSec
.Init();
180 git_close_diff(m_GitDiff
);
183 if(this->m_GitSimpleListDiff
)
185 git_close_diff(m_GitSimpleListDiff
);
186 m_GitSimpleListDiff
=0;
190 bool CGit::IsBranchNameValid(const CString
& branchname
)
192 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
194 if (branchname
.FindOneOf(_T("\"|<>")) >= 0) // not valid on Windows
196 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
197 return !!git_reference_is_valid_name(branchA
);
200 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
202 SECURITY_ATTRIBUTES sa
;
203 CAutoGeneralHandle hRead
, hWrite
, hReadErr
, hWriteErr
;
204 CAutoGeneralHandle hStdioFile
;
206 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
207 sa
.lpSecurityDescriptor
=NULL
;
208 sa
.bInheritHandle
=TRUE
;
209 if (!CreatePipe(hRead
.GetPointer(), hWrite
.GetPointer(), &sa
, 0))
211 CString err
= CFormatMessageWrapper();
212 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
213 return TGIT_GIT_ERROR_OPEN_PIP
;
215 if (hErrReadOut
&& !CreatePipe(hReadErr
.GetPointer(), hWriteErr
.GetPointer(), &sa
, 0))
217 CString err
= CFormatMessageWrapper();
218 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
219 return TGIT_GIT_ERROR_OPEN_PIP
;
224 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
225 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
229 PROCESS_INFORMATION pi
;
230 si
.cb
=sizeof(STARTUPINFO
);
234 si
.hStdError
= hWriteErr
;
236 si
.hStdError
= hWrite
;
238 si
.hStdOutput
=hStdioFile
;
240 si
.hStdOutput
=hWrite
;
242 si
.wShowWindow
=SW_HIDE
;
243 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
245 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
246 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
248 // CREATE_NEW_CONSOLE makes ssh recognize that it has no console in order to launch askpass to ask for the password.
249 // DETACHED_PROCESS which was originally used here has the same effect, however, it prevents PowerShell from working (cf. issue #2143)
250 dwFlags
|= CREATE_NEW_PROCESS_GROUP
| CREATE_NEW_CONSOLE
;
252 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
253 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
255 if(cmd
.Find(_T("git")) == 0)
257 int firstSpace
= cmd
.Find(_T(" "));
259 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
261 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
264 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
265 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
267 CString err
= CFormatMessageWrapper();
268 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
269 return TGIT_GIT_ERROR_CREATE_PROCESS
;
277 *hReadOut
= hRead
.Detach();
279 *hErrReadOut
= hReadErr
.Detach();
283 //Must use sperate function to convert ANSI str to union code string
284 //Becuase A2W use stack as internal convert buffer.
285 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
292 len
= (int)strlen((const char*)p
);
297 int currentContentLen
= str
->GetLength();
298 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
299 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
300 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
303 // This method was originally used to check for orphaned branches
304 BOOL
CGit::CanParseRev(CString ref
)
310 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
320 // Checks if we have an orphaned HEAD
321 BOOL
CGit::IsInitRepos()
324 // handle error on reading HEAD hash as init repo
325 if (GetHash(hash
, _T("HEAD")) != 0)
327 return hash
.IsEmpty() ? TRUE
: FALSE
;
330 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
332 PASYNCREADSTDERRTHREADARGS pDataArray
;
333 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
336 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
337 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
339 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
346 int CGit::Run(CGitCall
* pcall
)
348 PROCESS_INFORMATION pi
;
349 CAutoGeneralHandle hRead
, hReadErr
;
350 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
351 return TGIT_GIT_ERROR_CREATE_PROCESS
;
353 CAutoGeneralHandle
piThread(pi
.hThread
);
354 CAutoGeneralHandle
piProcess(pi
.hProcess
);
356 ASYNCREADSTDERRTHREADARGS threadArguments
;
357 threadArguments
.fileHandle
= hReadErr
;
358 threadArguments
.pcall
= pcall
;
359 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
362 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
364 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
366 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
367 if(!bAborted
)//For now, flush output when command aborted.
368 if(pcall
->OnOutputData(data
,readnumber
))
375 WaitForSingleObject(thread
, INFINITE
);
377 WaitForSingleObject(pi
.hProcess
, INFINITE
);
380 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
382 CString err
= CFormatMessageWrapper();
383 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
384 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
387 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
391 class CGitCall_ByteVector
: public CGitCall
394 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
395 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
397 if (!m_pvector
|| size
== 0)
399 size_t oldsize
=m_pvector
->size();
400 m_pvector
->resize(m_pvector
->size()+size
);
401 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
404 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
406 if (!m_pvectorErr
|| size
== 0)
408 size_t oldsize
= m_pvectorErr
->size();
409 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
410 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
413 BYTE_VECTOR
* m_pvector
;
414 BYTE_VECTOR
* m_pvectorErr
;
417 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
419 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
422 int CGit::Run(CString cmd
, CString
* output
, int code
)
426 ret
= Run(cmd
, output
, &err
, code
);
428 if (output
&& !err
.IsEmpty())
430 if (!output
->IsEmpty())
437 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
439 BYTE_VECTOR vector
, vectorErr
;
442 ret
= Run(cmd
, &vector
, &vectorErr
);
444 ret
= Run(cmd
, &vector
);
447 StringAppend(output
, &(vector
[0]), code
);
451 vectorErr
.push_back(0);
452 StringAppend(outputErr
, &(vectorErr
[0]), code
);
458 class CGitCallCb
: public CGitCall
461 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
463 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
468 int oldEndPos
= m_buffer
.GetLength();
469 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
470 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
472 // Break into lines and feed to m_recv
474 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
476 m_recv(m_buffer
.Left(eolPos
));
477 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
482 virtual bool OnOutputErrData(const BYTE
*, size_t) override
484 return false; // Ignore error output for now
487 virtual void OnEnd() override
489 if (!m_buffer
.IsEmpty())
491 m_buffer
.Empty(); // Just for sure
495 GitReceiverFunc m_recv
;
499 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
501 CGitCallCb
call(cmd
, recv
);
505 CString
CGit::GetUserName(void)
508 env
.CopyProcessEnvironment();
509 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
510 if (!envname
.IsEmpty())
512 return GetConfigValue(L
"user.name");
514 CString
CGit::GetUserEmail(void)
517 env
.CopyProcessEnvironment();
518 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
519 if (!envmail
.IsEmpty())
522 return GetConfigValue(L
"user.email");
525 CString
CGit::GetConfigValue(const CString
& name
)
529 if(this->m_IsUseGitDLL
)
531 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
540 key
= CUnicodeUtils::GetUTF8(name
);
544 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
547 catch (const char *msg
)
549 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
553 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
554 return configValue
.Tokenize(_T("\n"),start
);
559 cmd
.Format(L
"git.exe config %s", name
);
560 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
561 return configValue
.Tokenize(_T("\n"),start
);
565 bool CGit::GetConfigValueBool(const CString
& name
)
567 CString configValue
= GetConfigValue(name
);
568 configValue
.MakeLower();
570 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
576 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
578 if(this->m_IsUseGitDLL
)
580 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
589 CStringA keya
, valuea
;
590 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
591 valuea
= CUnicodeUtils::GetUTF8(value
);
595 return [=]() { return get_set_config(keya
, valuea
, type
); }();
597 catch (const char *msg
)
599 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
610 option
= _T("--global");
613 option
= _T("--system");
618 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
620 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
628 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
630 if(this->m_IsUseGitDLL
)
632 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
641 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
645 return [=]() { return get_set_config(keya
, nullptr, type
); }();
647 catch (const char *msg
)
649 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
660 option
= _T("--global");
663 option
= _T("--system");
668 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
670 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
678 CString
CGit::GetCurrentBranch(bool fallback
)
681 //Run(_T("git.exe branch"),&branch);
683 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
684 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
686 return _T("(no branch)");
693 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
695 if (localBranch
.IsEmpty())
699 configName
.Format(L
"branch.%s.remote", localBranch
);
700 pullRemote
= GetConfigValue(configName
);
702 //Select pull-branch from current branch
703 configName
.Format(L
"branch.%s.merge", localBranch
);
704 pullBranch
= StripRefName(GetConfigValue(configName
));
707 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
710 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
712 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
715 CString
CGit::GetFullRefName(const CString
& shortRefName
)
719 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
720 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
721 return CString();//Error
723 return refName
.Tokenize(L
"\n", iStart
);
726 CString
CGit::StripRefName(CString refName
)
728 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
729 refName
= refName
.Mid(11);
730 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
731 refName
= refName
.Mid(5);
733 return refName
.Tokenize(_T("\n"),start
);
736 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
738 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
740 if ( sProjectRoot
.IsEmpty() )
744 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
747 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
750 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
758 fgets(s
, sizeof(s
), pFile
);
762 const char *pfx
= "ref: refs/heads/";
763 const int len
= 16;//strlen(pfx)
765 if ( !strncmp(s
, pfx
, len
) )
767 //# We're on a branch. It might not exist. But
768 //# HEAD looks good enough to be a branch.
769 CStringA
utf8Branch(s
+ len
);
770 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
771 sBranchOut
.TrimRight(_T(" \r\n\t"));
773 if ( sBranchOut
.IsEmpty() )
778 CStringA
utf8Hash(s
);
779 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
780 unicodeHash
.TrimRight(_T(" \r\n\t"));
781 if (CGitHash::IsValidSHA1(unicodeHash
))
782 sBranchOut
= unicodeHash
;
784 //# Assume this is a detached head.
785 sBranchOut
= _T("HEAD");
790 //# Assume this is a detached head.
799 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
802 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
806 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
808 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
810 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
812 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
814 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
816 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
818 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
822 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
824 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
826 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
831 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
837 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
844 CString file
= _T(" --");
847 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
850 num
.Format(_T("-n%d"),count
);
854 if(mask
& LOG_INFO_STAT
)
855 param
+= _T(" --numstat ");
856 if(mask
& LOG_INFO_FILESTATE
)
857 param
+= _T(" --raw ");
859 if(mask
& LOG_INFO_FULLHISTORY
)
860 param
+= _T(" --full-history ");
862 if(mask
& LOG_INFO_BOUNDARY
)
863 param
+= _T(" --left-right --boundary ");
865 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
866 param
+= _T(" --all ");
868 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
869 param
+= _T(" --branches ");
871 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
874 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
877 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
878 param
+= _T(" --first-parent ");
880 if(mask
& CGit::LOG_INFO_NO_MERGE
)
881 param
+= _T(" --no-merges ");
883 if(mask
& CGit::LOG_INFO_FOLLOW
)
884 param
+= _T(" --follow ");
886 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
889 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
890 param
+= _T(" --full-diff ");
892 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
893 param
+= _T(" --simplify-by-decoration ");
899 if( Filter
&& (Filter
->m_From
!= -1))
901 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
905 if( Filter
&& (Filter
->m_To
!= -1))
907 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
912 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
914 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
919 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
921 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
926 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
928 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
935 if(!Filter
->m_IsRegex
)
936 param
+= _T(" --fixed-strings ");
938 param
+= _T(" --regexp-ignore-case --extended-regexp ");
941 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
942 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
943 param
+= _T(" --topo-order");
944 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
945 param
+= _T(" --date-order");
947 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
948 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
952 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
953 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
962 void GetTempPath(CString
&path
)
964 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
966 DWORD dwBufSize
=BUFSIZE
;
967 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
968 lpPathBuffer
); // buffer for path
969 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
973 path
.Format(_T("%s"),lpPathBuffer
);
975 CString
GetTempFile()
977 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
979 DWORD dwBufSize
=BUFSIZE
;
980 TCHAR szTempName
[BUFSIZE
] = { 0 };
983 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
984 lpPathBuffer
); // buffer for path
985 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
989 // Create a temporary file.
990 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
991 TEXT("Patch"), // temp file name prefix
992 0, // create unique name
993 szTempName
); // buffer for name
1001 return CString(szTempName
);
1005 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1007 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1008 if (result
== 0) return 0;
1009 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1016 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1017 CreateDirectory(lpBuffer
, NULL
);
1022 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1025 PROCESS_INFORMATION pi
;
1026 si
.cb
=sizeof(STARTUPINFO
);
1027 GetStartupInfo(&si
);
1029 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1030 psa
.bInheritHandle
=TRUE
;
1032 HANDLE hReadErr
, hWriteErr
;
1033 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1035 CString err
= CFormatMessageWrapper();
1036 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1037 return TGIT_GIT_ERROR_OPEN_PIP
;
1040 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1041 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1043 if (houtfile
== INVALID_HANDLE_VALUE
)
1045 CString err
= CFormatMessageWrapper();
1046 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1047 CloseHandle(hReadErr
);
1048 CloseHandle(hWriteErr
);
1049 return TGIT_GIT_ERROR_OPEN_PIP
;
1052 si
.wShowWindow
= SW_HIDE
;
1053 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1054 si
.hStdOutput
= houtfile
;
1055 si
.hStdError
= hWriteErr
;
1057 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1058 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1060 if(cmd
.Find(_T("git")) == 0)
1061 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1063 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1064 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1066 CString err
= CFormatMessageWrapper();
1067 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1069 CloseHandle(hReadErr
);
1070 CloseHandle(hWriteErr
);
1071 CloseHandle(houtfile
);
1072 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1075 BYTE_VECTOR stderrVector
;
1076 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1078 ASYNCREADSTDERRTHREADARGS threadArguments
;
1079 threadArguments
.fileHandle
= hReadErr
;
1080 threadArguments
.pcall
= &pcall
;
1081 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1083 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1085 CloseHandle(hWriteErr
);
1086 CloseHandle(hReadErr
);
1089 WaitForSingleObject(thread
, INFINITE
);
1091 stderrVector
.push_back(0);
1092 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1095 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1097 CString err
= CFormatMessageWrapper();
1098 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1099 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1102 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1104 CloseHandle(pi
.hThread
);
1105 CloseHandle(pi
.hProcess
);
1106 CloseHandle(houtfile
);
1110 git_repository
* CGit::GetGitRepository() const
1112 git_repository
* repo
= nullptr;
1113 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1117 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1121 // no need to parse a ref if it's already a 40-byte hash
1122 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1124 hash
= CGitHash(friendname
);
1128 int isHeadOrphan
= git_repository_head_unborn(repo
);
1129 if (isHeadOrphan
!= 0)
1132 if (isHeadOrphan
== 1)
1138 CAutoObject gitObject
;
1139 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1142 const git_oid
* oid
= git_object_id(gitObject
);
1146 hash
= CGitHash((char *)oid
->id
);
1151 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1153 // no need to parse a ref if it's already a 40-byte hash
1154 if (CGitHash::IsValidSHA1(friendname
))
1156 hash
= CGitHash(friendname
);
1162 CAutoRepository
repo(GetGitRepository());
1166 return GetHash(repo
, hash
, friendname
, true);
1171 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1173 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1174 hash
= CGitHash(gitLastErr
.Trim());
1181 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1186 cmd
=_T("git.exe ls-files -s -t -z");
1188 if (Run(cmd
, &cmdout
))
1191 if (outputlist
.ParserFromLsFile(cmdout
))
1193 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1194 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1198 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1202 if (ignoreSpaceAtEol
)
1203 ignore
+= _T(" --ignore-space-at-eol");
1204 if (ignoreSpaceChange
)
1205 ignore
+= _T(" --ignore-space-change");
1207 ignore
+= _T(" --ignore-all-space");
1208 if (ignoreBlankLines
)
1209 ignore
+= _T(" --ignore-blank-lines");
1211 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1214 if(rev1
== GIT_REV_ZERO
)
1215 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1217 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1221 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1228 outputlist
.ParserFromLog(out
);
1233 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1235 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1237 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1238 list
->push_back(str
);
1242 int CGit::GetTagList(STRING_VECTOR
&list
)
1244 if (this->m_IsUseLibGit2
)
1246 CAutoRepository
repo(GetGitRepository());
1250 CAutoStrArray tag_names
;
1252 if (git_tag_list(tag_names
, repo
))
1255 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1257 CStringA
tagName(tag_names
->strings
[i
]);
1258 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1261 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1267 CString cmd
, output
;
1268 cmd
=_T("git.exe tag -l");
1269 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1276 one
=output
.Tokenize(_T("\n"),pos
);
1278 list
.push_back(one
);
1280 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1286 CString
CGit::GetGitLastErr(const CString
& msg
)
1288 if (this->m_IsUseLibGit2
)
1289 return GetLibGit2LastErr(msg
);
1290 else if (gitLastErr
.IsEmpty())
1291 return msg
+ _T("\nUnknown git.exe error.");
1294 CString lastError
= gitLastErr
;
1296 return msg
+ _T("\n") + lastError
;
1300 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1302 if (UsingLibGit2(cmd
))
1303 return GetLibGit2LastErr(msg
);
1304 else if (gitLastErr
.IsEmpty())
1305 return msg
+ _T("\nUnknown git.exe error.");
1308 CString lastError
= gitLastErr
;
1310 return msg
+ _T("\n") + lastError
;
1314 CString
CGit::GetLibGit2LastErr()
1316 const git_error
*libgit2err
= giterr_last();
1319 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1321 return _T("libgit2 returned: ") + lastError
;
1324 return _T("An error occoured in libgit2, but no message is available.");
1327 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1330 return msg
+ _T("\n") + GetLibGit2LastErr();
1331 return GetLibGit2LastErr();
1334 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1336 if(branchName
== "FETCH_HEAD")
1337 branchName
= DerefFetchHead();
1341 CString
CGit::FixBranchName(const CString
& branchName
)
1343 CString tempBranchName
= branchName
;
1344 FixBranchName_Mod(tempBranchName
);
1345 return tempBranchName
;
1348 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1352 CAutoRepository
repo(GetGitRepository());
1354 return true; // TODO: optimize error reporting
1356 CAutoReference tagRef
;
1357 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1360 CAutoReference branchRef
;
1361 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1370 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1371 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1377 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1387 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1391 CAutoRepository
repo(GetGitRepository());
1393 return false; // TODO: optimize error reporting
1397 prefix
= _T("refs/heads/");
1399 prefix
= _T("refs/tags/");
1402 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1408 CString cmd
, output
;
1410 cmd
= _T("git.exe show-ref ");
1412 cmd
+= _T("--heads ");
1414 cmd
+= _T("--tags ");
1416 cmd
+= _T("refs/heads/") + name
;
1417 cmd
+= _T(" refs/tags/") + name
;
1419 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1422 if (!output
.IsEmpty())
1429 CString
CGit::DerefFetchHead()
1432 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1433 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1434 int forMergeLineCount
= 0;
1436 std::string hashToReturn
;
1437 while(getline(fetchHeadFile
, line
))
1439 //Tokenize this line
1440 std::string::size_type prevPos
= 0;
1441 std::string::size_type pos
= line
.find('\t');
1442 if(pos
== std::string::npos
) continue; //invalid line
1444 std::string hash
= line
.substr(0, pos
);
1445 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1447 bool forMerge
= pos
== prevPos
;
1448 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1450 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1455 hashToReturn
= hash
;
1456 ++forMergeLineCount
;
1457 if(forMergeLineCount
> 1)
1458 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1462 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1465 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1471 CAutoRepository
repo(GetGitRepository());
1475 if (git_repository_head_detached(repo
) == 1)
1476 cur
= _T("(detached from ");
1478 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1480 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1481 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1482 flags
= GIT_BRANCH_ALL
;
1483 else if (type
& BRANCH_REMOTE
)
1484 flags
= GIT_BRANCH_REMOTE
;
1486 CAutoBranchIterator it
;
1487 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1490 git_reference
* ref
= nullptr;
1491 git_branch_t branchType
;
1492 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1494 CAutoReference
autoRef(ref
);
1495 const char * name
= nullptr;
1496 if (git_branch_name(&name
, ref
))
1499 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1500 if (branchType
& GIT_BRANCH_REMOTE
)
1501 list
.push_back(_T("remotes/") + branchname
);
1504 if (git_branch_is_head(ref
))
1506 list
.push_back(branchname
);
1513 CString cmd
, output
;
1514 cmd
= _T("git.exe branch --no-color");
1516 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1518 else if (type
& BRANCH_REMOTE
)
1521 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1528 one
= output
.Tokenize(_T("\n"), pos
);
1529 one
.Trim(L
" \r\n\t");
1530 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1531 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1532 if (one
[0] == _T('*'))
1537 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1538 list
.push_back(one
);
1543 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1544 list
.push_back(L
"FETCH_HEAD");
1546 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1548 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1550 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1563 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1565 if (this->m_IsUseLibGit2
)
1567 CAutoRepository
repo(GetGitRepository());
1571 CAutoStrArray remotes
;
1572 if (git_remote_list(remotes
, repo
))
1575 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1577 CStringA
remote(remotes
->strings
[i
]);
1578 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1581 std::sort(list
.begin(), list
.end());
1588 CString cmd
, output
;
1589 cmd
=_T("git.exe remote");
1590 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1597 one
=output
.Tokenize(_T("\n"),pos
);
1599 list
.push_back(one
);
1606 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1608 CString cmd
, out
, err
;
1609 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1610 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1612 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1619 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1620 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1621 if (one
.Find(_T("^{}")) >= 1)
1624 list
.push_back(one
);
1626 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1630 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1632 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1634 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1635 list
->push_back(str
);
1639 int CGit::GetRefList(STRING_VECTOR
&list
)
1641 if (this->m_IsUseLibGit2
)
1643 CAutoRepository
repo(GetGitRepository());
1647 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1650 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1656 CString cmd
, output
;
1657 cmd
=_T("git.exe show-ref -d");
1658 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1665 one
=output
.Tokenize(_T("\n"),pos
);
1666 int start
=one
.Find(_T(" "),0);
1670 name
=one
.Right(one
.GetLength()-start
-1);
1671 list
.push_back(name
);
1674 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1680 typedef struct map_each_ref_payload
{
1681 git_repository
* repo
;
1682 MAP_HASH_NAME
* map
;
1683 } map_each_ref_payload
;
1685 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1687 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1690 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1692 CAutoObject gitObject
;
1693 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1696 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1698 str
+= _T("^{}"); // deref tag
1699 CAutoObject derefedTag
;
1700 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1702 gitObject
.Swap(derefedTag
);
1705 const git_oid
* oid
= git_object_id(gitObject
);
1709 CGitHash
hash((char *)oid
->id
);
1710 (*payloadContent
->map
)[hash
].push_back(str
);
1714 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1718 map_each_ref_payload payloadContent
= { repo
, &map
};
1720 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1723 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1725 std::sort(it
->second
.begin(), it
->second
.end());
1731 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1733 if (this->m_IsUseLibGit2
)
1735 CAutoRepository
repo(GetGitRepository());
1739 return GetMapHashToFriendName(repo
, map
);
1743 CString cmd
, output
;
1744 cmd
=_T("git.exe show-ref -d");
1745 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1752 one
=output
.Tokenize(_T("\n"),pos
);
1753 int start
=one
.Find(_T(" "),0);
1757 name
=one
.Right(one
.GetLength()-start
-1);
1760 hash
=one
.Left(start
);
1762 map
[CGitHash(hash
)].push_back(name
);
1770 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1772 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1773 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1776 static void SetLibGit2TemplatePath(const CString
&value
)
1778 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1779 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1782 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1789 this->m_Environment
.clear();
1790 m_Environment
.CopyProcessEnvironment();
1793 size_t homesize
,size
;
1795 // set HOME if not set already
1796 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1798 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1801 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1802 if (sshclient
.IsEmpty())
1803 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1805 if(!sshclient
.IsEmpty())
1807 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1808 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1812 TCHAR sPlink
[MAX_PATH
] = {0};
1813 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1814 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1816 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1817 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1818 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1823 TCHAR sAskPass
[MAX_PATH
] = {0};
1824 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1825 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1828 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1829 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1830 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1831 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1835 // add git/bin path to PATH
1837 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1838 CString str
= msysdir
;
1839 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1844 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1845 str
= msyslocalinstalldir
;
1846 str
.TrimRight(_T("\\"));
1849 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1850 str
= msysinstalldir
;
1851 str
.TrimRight(_T("\\"));
1853 if ( !str
.IsEmpty() )
1857 CGit::ms_LastMsysGitDir
= str
;
1862 // search PATH if git/bin directory is already present
1863 if ( FindGitPath() )
1865 m_bInitialized
= TRUE
;
1866 msysdir
= CGit::ms_LastMsysGitDir
;
1876 CGit::ms_LastMsysGitDir
= str
;
1879 // check for git.exe existance (maybe it was deinstalled in the meantime)
1880 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1883 // Configure libgit2 search paths
1885 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1886 msysGitDir
.ReleaseBuffer();
1887 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1888 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1889 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1890 CString msysGitTemplateDir
;
1891 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1892 msysGitTemplateDir
.ReleaseBuffer();
1893 SetLibGit2TemplatePath(msysGitTemplateDir
);
1896 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1899 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1901 m_Environment
.SetEnv(_T("PATH"), path
);
1903 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1905 CString sOldPath
= oldpath
;
1908 m_bInitialized
= TRUE
;
1912 CString
CGit::GetHomeDirectory() const
1914 const wchar_t * homeDir
= wget_windows_home_directory();
1915 return CString(homeDir
, (int)wcslen(homeDir
));
1918 CString
CGit::GetGitLocalConfig() const
1921 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1922 path
+= _T("config");
1926 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1928 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1931 CString
CGit::GetGitGlobalConfig() const
1933 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1936 CString
CGit::GetGitGlobalXDGConfigPath() const
1938 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1941 CString
CGit::GetGitGlobalXDGConfig() const
1943 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1946 CString
CGit::GetGitSystemConfig() const
1948 const wchar_t * systemConfig
= wget_msysgit_etc();
1949 return CString(systemConfig
, (int)wcslen(systemConfig
));
1952 BOOL
CGit::CheckCleanWorkTree()
1956 cmd
=_T("git.exe rev-parse --verify HEAD");
1958 if(Run(cmd
,&out
,CP_UTF8
))
1961 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1962 if(Run(cmd
,&out
,CP_UTF8
))
1965 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1966 if(Run(cmd
,&out
,CP_UTF8
))
1969 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1970 if(Run(cmd
,&out
,CP_UTF8
))
1975 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
1978 for (int i
= 0; i
< list
.GetCount(); ++i
)
1980 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1986 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
1990 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1992 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1995 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1996 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2000 // if the filenames only differ in case, we have to pass "-f"
2001 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2003 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2004 if (Run(cmd
, &out
, CP_UTF8
))
2006 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2010 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2011 if (Run(cmd
, &out
, CP_UTF8
))
2013 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2018 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2019 { //To init git repository, there are not HEAD, so we can use git reset command
2020 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2022 if (Run(cmd
, &out
, CP_UTF8
))
2024 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2030 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2031 if (Run(cmd
, &out
, CP_UTF8
))
2033 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2038 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2040 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2041 if (Run(cmd
, &out
, CP_UTF8
))
2043 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2051 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2057 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2059 cmd
=_T("git.exe ls-files -u -t -z");
2061 if (Run(cmd
, &vector
))
2066 if (list
.ParserFromLsFile(vector
))
2072 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2074 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2076 CAutoRepository
repo(GetGitRepository());
2080 CGitHash fromHash
, toHash
, baseHash
;
2081 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2084 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2088 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2091 baseHash
= baseOid
.id
;
2094 *commonAncestor
= baseHash
;
2096 return fromHash
== baseHash
;
2100 CGitHash basehash
,hash
;
2102 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2104 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2108 basehash
= base
.Trim();
2110 GetHash(hash
, from
);
2113 *commonAncestor
= basehash
;
2115 return hash
== basehash
;
2118 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2121 for (int i
= 0; i
< 4; ++i
)
2124 ret
|= hash
.m_hash
[i
];
2129 int CGit::RefreshGitIndex()
2131 if(g_Git
.m_IsUseGitDLL
)
2133 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2136 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2147 cmd
=_T("git.exe update-index --refresh");
2148 return Run(cmd
, &output
, CP_UTF8
);
2152 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2154 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2156 CAutoRepository
repo(GetGitRepository());
2161 if (GetHash(repo
, hash
, Refname
))
2165 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2169 if (git_commit_tree(tree
.GetPointer(), commit
))
2172 CAutoTreeEntry entry
;
2173 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2177 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2180 FILE *file
= nullptr;
2181 _tfopen_s(&file
, outputfile
, _T("w"));
2182 if (file
== nullptr)
2184 giterr_set_str(GITERR_NONE
, "Could not create file.");
2188 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2193 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2195 giterr_set_str(GITERR_OS
, "Could not write to file.");
2204 else if (g_Git
.m_IsUseGitDLL
)
2206 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2209 g_Git
.CheckAndInitDll();
2210 CStringA ref
, patha
, outa
;
2211 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2212 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2213 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2214 ::DeleteFile(outputfile
);
2215 return git_checkout_file(ref
, patha
, outa
);
2218 catch (const char * msg
)
2220 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2225 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2232 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2233 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2236 void CEnvironment::CopyProcessEnvironment()
2238 TCHAR
*porig
= GetEnvironmentStrings();
2240 while(*p
!=0 || *(p
+1) !=0)
2241 this->push_back(*p
++);
2243 push_back(_T('\0'));
2244 push_back(_T('\0'));
2246 FreeEnvironmentStrings(porig
);
2249 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2252 for (size_t i
= 0; i
< size(); ++i
)
2256 CString sname
= str
.Tokenize(_T("="),start
);
2257 if(sname
.CompareNoCase(name
) == 0)
2259 return &(*this)[i
+start
];
2266 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2269 for (i
= 0; i
< size(); ++i
)
2271 CString str
= &(*this)[i
];
2273 CString sname
= str
.Tokenize(_T("="),start
);
2274 if(sname
.CompareNoCase(name
) == 0)
2283 i
-= 1; // roll back terminate \0\0
2284 this->push_back(_T('\0'));
2287 CEnvironment::iterator it
;
2291 while(*it
&& i
<size())
2300 this->insert(it
,*name
++);
2305 this->insert(it
, _T('='));
2311 this->insert(it
,*value
++);
2318 int CGit::GetGitEncode(TCHAR
* configkey
)
2320 CString str
=GetConfigValue(configkey
);
2325 return CUnicodeUtils::GetCPCode(str
);
2329 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2335 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2338 diff
= GetGitDiff();
2340 git_open_diff(&diff
, arg
);
2349 isStat
= !!strstr(arg
, "stat");
2354 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2356 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2365 for (int j
= 0; j
< count
; ++j
)
2374 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2375 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2376 &mode
,&IsBin
,&inc
,&dec
);
2378 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2379 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2381 path
.SetFromGit(strnewname
,&stroldname
);
2382 path
.ParserAction((BYTE
)mode
);
2386 path
.m_StatAdd
=_T("-");
2387 path
.m_StatDel
=_T("-");
2391 path
.m_StatAdd
.Format(_T("%d"),inc
);
2392 path
.m_StatDel
.Format(_T("%d"),dec
);
2394 PathList
->AddPath(path
);
2396 git_diff_flush(diff
);
2399 git_close_diff(diff
);
2404 int CGit::GetShortHASHLength() const
2409 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2413 REF_TYPE type
= CGit::UNKNOWN
;
2415 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2417 type
= CGit::LOCAL_BRANCH
;
2420 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2422 type
= CGit::REMOTE_BRANCH
;
2424 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2428 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2431 shortname
=_T("stash");
2433 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2435 if (shortname
.Find(_T("good")) == 0)
2437 type
= CGit::BISECT_GOOD
;
2438 shortname
= _T("good");
2441 if (shortname
.Find(_T("bad")) == 0)
2443 type
= CGit::BISECT_BAD
;
2444 shortname
= _T("bad");
2447 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2451 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2453 type
= CGit::UNKNOWN
;
2457 type
= CGit::UNKNOWN
;
2467 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2469 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2472 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2475 if (rev2
== GitRev::GetWorkingCopy())
2476 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2477 else if (rev1
== GitRev::GetWorkingCopy())
2478 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2489 if (diffContext
> 0)
2490 unified
.Format(_T(" --unified=%d"), diffContext
);
2491 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2494 if (!path
.IsEmpty())
2497 cmd
+= path
.GetGitPathString();
2504 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2506 ATLASSERT(payload
&& line
);
2507 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2508 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2509 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2513 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2515 ATLASSERT(repo
&& identifier
&& tree
);
2517 /* try to resolve identifier */
2519 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2523 return GIT_ENOTFOUND
;
2526 switch (git_object_type(obj
))
2529 *tree
= (git_tree
*)obj
.Detach();
2531 case GIT_OBJ_COMMIT
:
2532 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2535 err
= GIT_ENOTFOUND
;
2541 /* use libgit2 get unified diff */
2542 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 */)
2544 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2545 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2547 CAutoRepository
repo(g_Git
.GetGitRepository());
2551 int isHeadOrphan
= git_repository_head_unborn(repo
);
2552 if (isHeadOrphan
== 1)
2554 else if (isHeadOrphan
!= 0)
2557 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2558 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2559 char *buf
= pathA
.GetBuffer();
2560 if (!pathA
.IsEmpty())
2562 opts
.pathspec
.strings
= &buf
;
2563 opts
.pathspec
.count
= 1;
2567 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2572 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2575 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2578 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2581 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2584 if (git_diff_merge(diff
, diff2
))
2589 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2592 if (tree1
.IsEmpty())
2600 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2603 if (tree2
.IsEmpty())
2605 /* don't check return value, there are not parent commit at first commit*/
2606 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2608 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2610 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2614 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2617 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2620 if (git_patch_print(patch
, callback
, data
))
2624 pathA
.ReleaseBuffer();
2629 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2631 if (UsingLibGit2(GIT_CMD_DIFF
))
2633 FILE *file
= nullptr;
2634 _tfopen_s(&file
, patchfile
, _T("w"));
2635 if (file
== nullptr)
2637 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2644 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2645 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2649 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2651 ATLASSERT(payload
&& line
);
2652 CStringA
*str
= (CStringA
*) payload
;
2653 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2654 str
->Append(&line
->origin
, 1);
2655 str
->Append(line
->content
, (int)line
->content_len
);
2659 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2661 if (UsingLibGit2(GIT_CMD_DIFF
))
2662 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2666 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2668 int ret
= Run(cmd
, &vector
);
2669 if (!vector
.empty())
2671 vector
.push_back(0); // vector is not NUL terminated
2672 buffer
->Append((char *)&vector
[0]);
2678 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2680 if (UsingLibGit2(GIT_CMD_REVERT
))
2682 CAutoRepository
repo(GetGitRepository());
2687 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2690 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2691 revert_opts
.mainline
= parent
;
2692 int result
= git_revert(repo
, commit
, &revert_opts
);
2694 return !result
? 0 : -1;
2700 merge
.Format(_T("-m %d "), parent
);
2701 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2702 gitLastErr
= cmd
+ _T("\n");
2703 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2715 int CGit::DeleteRef(const CString
& reference
)
2717 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2719 CAutoRepository
repo(GetGitRepository());
2724 if (reference
.Right(3) == _T("^{}"))
2725 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2727 refA
= CUnicodeUtils::GetUTF8(reference
);
2730 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
2734 if (git_reference_is_tag(ref
))
2735 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2736 else if (git_reference_is_branch(ref
))
2737 result
= git_branch_delete(ref
);
2738 else if (git_reference_is_remote(ref
))
2739 result
= git_branch_delete(ref
);
2741 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2747 CString cmd
, shortname
;
2748 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2749 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2750 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2751 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2752 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2753 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2756 gitLastErr
= L
"unsupported reference type: " + reference
;
2760 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2768 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2770 if (PathFileExists(filename
))
2772 FILE *pFile
= nullptr;
2773 _tfopen_s(&pFile
, filename
, _T("r"));
2779 char s
[8196] = { 0 };
2780 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2783 str
+= CStringA(s
, read
);
2786 msg
= CUnicodeUtils::GetUnicode(str
);
2787 msg
.Replace(_T("\r\n"), _T("\n"));
2788 msg
.TrimRight(_T("\n"));
2792 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
2793 return true; // load no further files