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 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
249 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
251 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
252 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
254 if(cmd
.Find(_T("git")) == 0)
256 int firstSpace
= cmd
.Find(_T(" "));
258 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
260 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
263 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
264 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
266 CString err
= CFormatMessageWrapper();
267 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
268 return TGIT_GIT_ERROR_CREATE_PROCESS
;
276 *hReadOut
= hRead
.Detach();
278 *hErrReadOut
= hReadErr
.Detach();
282 //Must use sperate function to convert ANSI str to union code string
283 //Becuase A2W use stack as internal convert buffer.
284 void CGit::StringAppend(CString
*str
, const BYTE
*p
, int code
,int length
)
291 len
= (int)strlen((const char*)p
);
296 int currentContentLen
= str
->GetLength();
297 WCHAR
* buf
= str
->GetBuffer(len
* 4 + 1 + currentContentLen
) + currentContentLen
;
298 int appendedLen
= MultiByteToWideChar(code
, 0, (LPCSTR
)p
, len
, buf
, len
* 4);
299 str
->ReleaseBuffer(currentContentLen
+ appendedLen
); // no - 1 because MultiByteToWideChar is called with a fixed length (thus no nul char included)
302 // This method was originally used to check for orphaned branches
303 BOOL
CGit::CanParseRev(CString ref
)
309 if (Run(_T("git.exe rev-parse --revs-only ") + ref
, &cmdout
, CP_UTF8
))
319 // Checks if we have an orphaned HEAD
320 BOOL
CGit::IsInitRepos()
323 // handle error on reading HEAD hash as init repo
324 if (GetHash(hash
, _T("HEAD")) != 0)
326 return hash
.IsEmpty() ? TRUE
: FALSE
;
329 DWORD WINAPI
CGit::AsyncReadStdErrThread(LPVOID lpParam
)
331 PASYNCREADSTDERRTHREADARGS pDataArray
;
332 pDataArray
= (PASYNCREADSTDERRTHREADARGS
)lpParam
;
335 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
336 while (ReadFile(pDataArray
->fileHandle
, data
, CALL_OUTPUT_READ_CHUNK_SIZE
, &readnumber
, NULL
))
338 if (pDataArray
->pcall
->OnOutputErrData(data
,readnumber
))
345 int CGit::Run(CGitCall
* pcall
)
347 PROCESS_INFORMATION pi
;
348 CAutoGeneralHandle hRead
, hReadErr
;
349 if (RunAsync(pcall
->GetCmd(), &pi
, hRead
.GetPointer(), hReadErr
.GetPointer()))
350 return TGIT_GIT_ERROR_CREATE_PROCESS
;
352 CAutoGeneralHandle
piThread(pi
.hThread
);
353 CAutoGeneralHandle
piProcess(pi
.hProcess
);
355 ASYNCREADSTDERRTHREADARGS threadArguments
;
356 threadArguments
.fileHandle
= hReadErr
;
357 threadArguments
.pcall
= pcall
;
358 CAutoGeneralHandle thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
361 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
363 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
365 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
366 if(!bAborted
)//For now, flush output when command aborted.
367 if(pcall
->OnOutputData(data
,readnumber
))
374 WaitForSingleObject(thread
, INFINITE
);
376 WaitForSingleObject(pi
.hProcess
, INFINITE
);
379 if(!GetExitCodeProcess(pi
.hProcess
,&exitcode
))
381 CString err
= CFormatMessageWrapper();
382 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
383 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
386 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
390 class CGitCall_ByteVector
: public CGitCall
393 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
394 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
396 if (!m_pvector
|| size
== 0)
398 size_t oldsize
=m_pvector
->size();
399 m_pvector
->resize(m_pvector
->size()+size
);
400 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
403 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
405 if (!m_pvectorErr
|| size
== 0)
407 size_t oldsize
= m_pvectorErr
->size();
408 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
409 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
412 BYTE_VECTOR
* m_pvector
;
413 BYTE_VECTOR
* m_pvectorErr
;
416 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
418 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
421 int CGit::Run(CString cmd
, CString
* output
, int code
)
425 ret
= Run(cmd
, output
, &err
, code
);
427 if (output
&& !err
.IsEmpty())
429 if (!output
->IsEmpty())
436 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
438 BYTE_VECTOR vector
, vectorErr
;
441 ret
= Run(cmd
, &vector
, &vectorErr
);
443 ret
= Run(cmd
, &vector
);
446 StringAppend(output
, &(vector
[0]), code
);
450 vectorErr
.push_back(0);
451 StringAppend(outputErr
, &(vectorErr
[0]), code
);
457 class CGitCallCb
: public CGitCall
460 CGitCallCb(CString cmd
, const GitReceiverFunc
& recv
): CGitCall(cmd
), m_recv(recv
) {}
462 virtual bool OnOutputData(const BYTE
* data
, size_t size
) override
467 int oldEndPos
= m_buffer
.GetLength();
468 memcpy(m_buffer
.GetBufferSetLength(oldEndPos
+ (int)size
) + oldEndPos
, data
, size
);
469 m_buffer
.ReleaseBuffer(oldEndPos
+ (int)size
);
471 // Break into lines and feed to m_recv
473 while ((eolPos
= m_buffer
.Find('\n')) >= 0)
475 m_recv(m_buffer
.Left(eolPos
));
476 m_buffer
= m_buffer
.Mid(eolPos
+ 1);
481 virtual bool OnOutputErrData(const BYTE
*, size_t) override
483 return false; // Ignore error output for now
486 virtual void OnEnd() override
488 if (!m_buffer
.IsEmpty())
490 m_buffer
.Empty(); // Just for sure
494 GitReceiverFunc m_recv
;
498 int CGit::Run(CString cmd
, const GitReceiverFunc
& recv
)
500 CGitCallCb
call(cmd
, recv
);
504 CString
CGit::GetUserName(void)
507 env
.CopyProcessEnvironment();
508 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
509 if (!envname
.IsEmpty())
511 return GetConfigValue(L
"user.name");
513 CString
CGit::GetUserEmail(void)
516 env
.CopyProcessEnvironment();
517 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
518 if (!envmail
.IsEmpty())
521 return GetConfigValue(L
"user.email");
524 CString
CGit::GetConfigValue(const CString
& name
)
528 if(this->m_IsUseGitDLL
)
530 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
539 key
= CUnicodeUtils::GetUTF8(name
);
543 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
546 catch (const char *msg
)
548 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
552 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
);
553 return configValue
.Tokenize(_T("\n"),start
);
558 cmd
.Format(L
"git.exe config %s", name
);
559 Run(cmd
, &configValue
, nullptr, CP_UTF8
);
560 return configValue
.Tokenize(_T("\n"),start
);
564 bool CGit::GetConfigValueBool(const CString
& name
)
566 CString configValue
= GetConfigValue(name
);
567 configValue
.MakeLower();
569 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
575 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
)
577 if(this->m_IsUseGitDLL
)
579 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
588 CStringA keya
, valuea
;
589 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
590 valuea
= CUnicodeUtils::GetUTF8(value
);
594 return [=]() { return get_set_config(keya
, valuea
, type
); }();
596 catch (const char *msg
)
598 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
609 option
= _T("--global");
612 option
= _T("--system");
617 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
619 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
627 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
)
629 if(this->m_IsUseGitDLL
)
631 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
640 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
644 return [=]() { return get_set_config(keya
, nullptr, type
); }();
646 catch (const char *msg
)
648 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
659 option
= _T("--global");
662 option
= _T("--system");
667 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
669 if (Run(cmd
, &out
, nullptr, CP_UTF8
))
677 CString
CGit::GetCurrentBranch(bool fallback
)
680 //Run(_T("git.exe branch"),&branch);
682 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
683 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
685 return _T("(no branch)");
692 void CGit::GetRemoteTrackedBranch(const CString
& localBranch
, CString
& pullRemote
, CString
& pullBranch
)
694 if (localBranch
.IsEmpty())
698 configName
.Format(L
"branch.%s.remote", localBranch
);
699 pullRemote
= GetConfigValue(configName
);
701 //Select pull-branch from current branch
702 configName
.Format(L
"branch.%s.merge", localBranch
);
703 pullBranch
= StripRefName(GetConfigValue(configName
));
706 void CGit::GetRemoteTrackedBranchForHEAD(CString
& remote
, CString
& branch
)
709 if (GetCurrentBranchFromFile(m_CurrentDir
, refName
))
711 GetRemoteTrackedBranch(StripRefName(refName
), remote
, branch
);
714 CString
CGit::GetFullRefName(const CString
& shortRefName
)
718 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
719 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
720 return CString();//Error
722 return refName
.Tokenize(L
"\n", iStart
);
725 CString
CGit::StripRefName(CString refName
)
727 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
728 refName
= refName
.Mid(11);
729 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
730 refName
= refName
.Mid(5);
732 return refName
.Tokenize(_T("\n"),start
);
735 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
737 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
739 if ( sProjectRoot
.IsEmpty() )
743 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
746 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
749 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
757 fgets(s
, sizeof(s
), pFile
);
761 const char *pfx
= "ref: refs/heads/";
762 const int len
= 16;//strlen(pfx)
764 if ( !strncmp(s
, pfx
, len
) )
766 //# We're on a branch. It might not exist. But
767 //# HEAD looks good enough to be a branch.
768 CStringA
utf8Branch(s
+ len
);
769 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
770 sBranchOut
.TrimRight(_T(" \r\n\t"));
772 if ( sBranchOut
.IsEmpty() )
777 CStringA
utf8Hash(s
);
778 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
779 unicodeHash
.TrimRight(_T(" \r\n\t"));
780 if (CGitHash::IsValidSHA1(unicodeHash
))
781 sBranchOut
= unicodeHash
;
783 //# Assume this is a detached head.
784 sBranchOut
= _T("HEAD");
789 //# Assume this is a detached head.
798 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
801 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
805 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
807 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
809 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
811 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
813 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
815 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
817 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
821 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
823 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
825 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
830 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
836 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
843 CString file
= _T(" --");
846 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
849 num
.Format(_T("-n%d"),count
);
853 if(mask
& LOG_INFO_STAT
)
854 param
+= _T(" --numstat ");
855 if(mask
& LOG_INFO_FILESTATE
)
856 param
+= _T(" --raw ");
858 if(mask
& LOG_INFO_FULLHISTORY
)
859 param
+= _T(" --full-history ");
861 if(mask
& LOG_INFO_BOUNDARY
)
862 param
+= _T(" --left-right --boundary ");
864 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
865 param
+= _T(" --all ");
867 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
868 param
+= _T(" --branches ");
870 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
873 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
876 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
877 param
+= _T(" --first-parent ");
879 if(mask
& CGit::LOG_INFO_NO_MERGE
)
880 param
+= _T(" --no-merges ");
882 if(mask
& CGit::LOG_INFO_FOLLOW
)
883 param
+= _T(" --follow ");
885 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
888 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
889 param
+= _T(" --full-diff ");
891 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
892 param
+= _T(" --simplify-by-decoration ");
898 if( Filter
&& (Filter
->m_From
!= -1))
900 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
904 if( Filter
&& (Filter
->m_To
!= -1))
906 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
911 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
913 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
918 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
920 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
925 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
927 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
934 if(!Filter
->m_IsRegex
)
935 param
+= _T(" --fixed-strings ");
937 param
+= _T(" --regexp-ignore-case --extended-regexp ");
940 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
941 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
942 param
+= _T(" --topo-order");
943 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
944 param
+= _T(" --date-order");
946 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
947 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
951 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
952 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
961 void GetTempPath(CString
&path
)
963 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
965 DWORD dwBufSize
=BUFSIZE
;
966 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
967 lpPathBuffer
); // buffer for path
968 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
972 path
.Format(_T("%s"),lpPathBuffer
);
974 CString
GetTempFile()
976 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
978 DWORD dwBufSize
=BUFSIZE
;
979 TCHAR szTempName
[BUFSIZE
] = { 0 };
982 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
983 lpPathBuffer
); // buffer for path
984 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
988 // Create a temporary file.
989 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
990 TEXT("Patch"), // temp file name prefix
991 0, // create unique name
992 szTempName
); // buffer for name
1000 return CString(szTempName
);
1004 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
1006 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
1007 if (result
== 0) return 0;
1008 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
1015 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
1016 CreateDirectory(lpBuffer
, NULL
);
1021 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1024 PROCESS_INFORMATION pi
;
1025 si
.cb
=sizeof(STARTUPINFO
);
1026 GetStartupInfo(&si
);
1028 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1029 psa
.bInheritHandle
=TRUE
;
1031 HANDLE hReadErr
, hWriteErr
;
1032 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1034 CString err
= CFormatMessageWrapper();
1035 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1036 return TGIT_GIT_ERROR_OPEN_PIP
;
1039 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1040 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1042 if (houtfile
== INVALID_HANDLE_VALUE
)
1044 CString err
= CFormatMessageWrapper();
1045 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1046 CloseHandle(hReadErr
);
1047 CloseHandle(hWriteErr
);
1048 return TGIT_GIT_ERROR_OPEN_PIP
;
1051 si
.wShowWindow
= SW_HIDE
;
1052 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1053 si
.hStdOutput
= houtfile
;
1054 si
.hStdError
= hWriteErr
;
1056 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1057 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1059 if(cmd
.Find(_T("git")) == 0)
1060 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1062 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1063 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1065 CString err
= CFormatMessageWrapper();
1066 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1068 CloseHandle(hReadErr
);
1069 CloseHandle(hWriteErr
);
1070 CloseHandle(houtfile
);
1071 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1074 BYTE_VECTOR stderrVector
;
1075 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1077 ASYNCREADSTDERRTHREADARGS threadArguments
;
1078 threadArguments
.fileHandle
= hReadErr
;
1079 threadArguments
.pcall
= &pcall
;
1080 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1082 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1084 CloseHandle(hWriteErr
);
1085 CloseHandle(hReadErr
);
1088 WaitForSingleObject(thread
, INFINITE
);
1090 stderrVector
.push_back(0);
1091 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1094 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1096 CString err
= CFormatMessageWrapper();
1097 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1098 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1101 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1103 CloseHandle(pi
.hThread
);
1104 CloseHandle(pi
.hProcess
);
1105 CloseHandle(houtfile
);
1109 git_repository
* CGit::GetGitRepository() const
1111 git_repository
* repo
= nullptr;
1112 git_repository_open(&repo
, GetGitPathStringA(m_CurrentDir
));
1116 int CGit::GetHash(git_repository
* repo
, CGitHash
&hash
, const CString
& friendname
, bool skipFastCheck
/* = false */)
1120 // no need to parse a ref if it's already a 40-byte hash
1121 if (!skipFastCheck
&& CGitHash::IsValidSHA1(friendname
))
1123 hash
= CGitHash(friendname
);
1127 int isHeadOrphan
= git_repository_head_unborn(repo
);
1128 if (isHeadOrphan
!= 0)
1131 if (isHeadOrphan
== 1)
1137 CAutoObject gitObject
;
1138 if (git_revparse_single(gitObject
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(friendname
)))
1141 const git_oid
* oid
= git_object_id(gitObject
);
1145 hash
= CGitHash((char *)oid
->id
);
1150 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1152 // no need to parse a ref if it's already a 40-byte hash
1153 if (CGitHash::IsValidSHA1(friendname
))
1155 hash
= CGitHash(friendname
);
1161 CAutoRepository
repo(GetGitRepository());
1165 return GetHash(repo
, hash
, friendname
, true);
1170 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1172 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1173 hash
= CGitHash(gitLastErr
.Trim());
1180 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1185 cmd
=_T("git.exe ls-files -s -t -z");
1187 if (Run(cmd
, &cmdout
))
1190 if (outputlist
.ParserFromLsFile(cmdout
))
1192 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1193 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1197 int CGit::GetCommitDiffList(const CString
&rev1
, const CString
&rev2
, CTGitPathList
&outputlist
, bool ignoreSpaceAtEol
, bool ignoreSpaceChange
, bool ignoreAllSpace
, bool ignoreBlankLines
)
1201 if (ignoreSpaceAtEol
)
1202 ignore
+= _T(" --ignore-space-at-eol");
1203 if (ignoreSpaceChange
)
1204 ignore
+= _T(" --ignore-space-change");
1206 ignore
+= _T(" --ignore-all-space");
1207 if (ignoreBlankLines
)
1208 ignore
+= _T(" --ignore-blank-lines");
1210 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1213 if(rev1
== GIT_REV_ZERO
)
1214 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s %s --"), ignore
, rev2
);
1216 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s %s --"), ignore
, rev1
);
1220 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s %s --"), ignore
, rev2
, rev1
);
1227 outputlist
.ParserFromLog(out
);
1232 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1234 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1236 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1237 list
->push_back(str
);
1241 int CGit::GetTagList(STRING_VECTOR
&list
)
1243 if (this->m_IsUseLibGit2
)
1245 CAutoRepository
repo(GetGitRepository());
1249 CAutoStrArray tag_names
;
1251 if (git_tag_list(tag_names
, repo
))
1254 for (size_t i
= 0; i
< tag_names
->count
; ++i
)
1256 CStringA
tagName(tag_names
->strings
[i
]);
1257 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1260 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1266 CString cmd
, output
;
1267 cmd
=_T("git.exe tag -l");
1268 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1275 one
=output
.Tokenize(_T("\n"),pos
);
1277 list
.push_back(one
);
1279 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1286 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1287 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1289 CString
CGit::GetGitLastErr(const CString
& msg
)
1291 if (this->m_IsUseLibGit2
)
1292 return GetLibGit2LastErr(msg
);
1293 else if (gitLastErr
.IsEmpty())
1294 return msg
+ _T("\nUnknown git.exe error.");
1297 CString lastError
= gitLastErr
;
1299 return msg
+ _T("\n") + lastError
;
1303 CString
CGit::GetGitLastErr(const CString
& msg
, LIBGIT2_CMD cmd
)
1305 if (UsingLibGit2(cmd
))
1306 return GetLibGit2LastErr(msg
);
1307 else if (gitLastErr
.IsEmpty())
1308 return msg
+ _T("\nUnknown git.exe error.");
1311 CString lastError
= gitLastErr
;
1313 return msg
+ _T("\n") + lastError
;
1317 CString
CGit::GetLibGit2LastErr()
1319 const git_error
*libgit2err
= giterr_last();
1322 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1324 return _T("libgit2 returned: ") + lastError
;
1327 return _T("An error occoured in libgit2, but no message is available.");
1330 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1333 return msg
+ _T("\n") + GetLibGit2LastErr();
1334 return GetLibGit2LastErr();
1337 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1339 if(branchName
== "FETCH_HEAD")
1340 branchName
= DerefFetchHead();
1344 CString
CGit::FixBranchName(const CString
& branchName
)
1346 CString tempBranchName
= branchName
;
1347 FixBranchName_Mod(tempBranchName
);
1348 return tempBranchName
;
1351 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1355 CAutoRepository
repo(GetGitRepository());
1357 return true; // TODO: optimize error reporting
1359 CAutoReference tagRef
;
1360 if (git_reference_lookup(tagRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/tags/" + name
)))
1363 CAutoReference branchRef
;
1364 if (git_reference_lookup(branchRef
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(L
"refs/heads/" + name
)))
1373 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1374 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1380 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1391 Checks if a branch or tag with the given name exists
1392 isBranch is true -> branch, tag otherwise
1394 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1398 CAutoRepository
repo(GetGitRepository());
1400 return false; // TODO: optimize error reporting
1404 prefix
= _T("refs/heads/");
1406 prefix
= _T("refs/tags/");
1409 if (git_reference_lookup(ref
.GetPointer(), repo
, CUnicodeUtils::GetUTF8(prefix
+ name
)))
1415 CString cmd
, output
;
1417 cmd
= _T("git.exe show-ref ");
1419 cmd
+= _T("--heads ");
1421 cmd
+= _T("--tags ");
1423 cmd
+= _T("refs/heads/") + name
;
1424 cmd
+= _T(" refs/tags/") + name
;
1426 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1429 if (!output
.IsEmpty())
1436 CString
CGit::DerefFetchHead()
1439 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1440 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1441 int forMergeLineCount
= 0;
1443 std::string hashToReturn
;
1444 while(getline(fetchHeadFile
, line
))
1446 //Tokenize this line
1447 std::string::size_type prevPos
= 0;
1448 std::string::size_type pos
= line
.find('\t');
1449 if(pos
== std::string::npos
) continue; //invalid line
1451 std::string hash
= line
.substr(0, pos
);
1452 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1454 bool forMerge
= pos
== prevPos
;
1455 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1457 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1462 hashToReturn
= hash
;
1463 ++forMergeLineCount
;
1464 if(forMergeLineCount
> 1)
1465 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1469 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1472 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1478 CAutoRepository
repo(GetGitRepository());
1482 if (git_repository_head_detached(repo
) == 1)
1483 cur
= _T("(detached from ");
1485 if ((type
& (BRANCH_LOCAL
| BRANCH_REMOTE
)) != 0)
1487 git_branch_t flags
= GIT_BRANCH_LOCAL
;
1488 if ((type
& BRANCH_LOCAL
) && (type
& BRANCH_REMOTE
))
1489 flags
= GIT_BRANCH_ALL
;
1490 else if (type
& BRANCH_REMOTE
)
1491 flags
= GIT_BRANCH_REMOTE
;
1493 CAutoBranchIterator it
;
1494 if (git_branch_iterator_new(it
.GetPointer(), repo
, flags
))
1497 git_reference
* ref
= nullptr;
1498 git_branch_t branchType
;
1499 while (git_branch_next(&ref
, &branchType
, it
) == 0)
1501 CAutoReference
autoRef(ref
);
1502 const char * name
= nullptr;
1503 if (git_branch_name(&name
, ref
))
1506 CString branchname
= CUnicodeUtils::GetUnicode(name
);
1507 if (branchType
& GIT_BRANCH_REMOTE
)
1508 list
.push_back(_T("remotes/") + branchname
);
1511 if (git_branch_is_head(ref
))
1513 list
.push_back(branchname
);
1520 CString cmd
, output
;
1521 cmd
= _T("git.exe branch --no-color");
1523 if ((type
& BRANCH_ALL
) == BRANCH_ALL
)
1525 else if (type
& BRANCH_REMOTE
)
1528 ret
= Run(cmd
, &output
, nullptr, CP_UTF8
);
1535 one
= output
.Tokenize(_T("\n"), pos
);
1536 one
.Trim(L
" \r\n\t");
1537 if (one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1538 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1539 if (one
[0] == _T('*'))
1544 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1545 list
.push_back(one
);
1550 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1551 list
.push_back(L
"FETCH_HEAD");
1553 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1555 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1557 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1570 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1572 if (this->m_IsUseLibGit2
)
1574 CAutoRepository
repo(GetGitRepository());
1578 CAutoStrArray remotes
;
1579 if (git_remote_list(remotes
, repo
))
1582 for (size_t i
= 0; i
< remotes
->count
; ++i
)
1584 CStringA
remote(remotes
->strings
[i
]);
1585 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1588 std::sort(list
.begin(), list
.end());
1595 CString cmd
, output
;
1596 cmd
=_T("git.exe remote");
1597 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1604 one
=output
.Tokenize(_T("\n"),pos
);
1606 list
.push_back(one
);
1613 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1615 CString cmd
, out
, err
;
1616 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1617 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1619 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1626 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1627 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1628 if (one
.Find(_T("^{}")) >= 1)
1631 list
.push_back(one
);
1633 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1637 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1639 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1641 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1642 list
->push_back(str
);
1646 int CGit::GetRefList(STRING_VECTOR
&list
)
1648 if (this->m_IsUseLibGit2
)
1650 CAutoRepository
repo(GetGitRepository());
1654 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1657 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1663 CString cmd
, output
;
1664 cmd
=_T("git.exe show-ref -d");
1665 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1672 one
=output
.Tokenize(_T("\n"),pos
);
1673 int start
=one
.Find(_T(" "),0);
1677 name
=one
.Right(one
.GetLength()-start
-1);
1678 list
.push_back(name
);
1681 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1687 typedef struct map_each_ref_payload
{
1688 git_repository
* repo
;
1689 MAP_HASH_NAME
* map
;
1690 } map_each_ref_payload
;
1692 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1694 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1697 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1699 CAutoObject gitObject
;
1700 if (git_revparse_single(gitObject
.GetPointer(), payloadContent
->repo
, git_reference_name(ref
)))
1703 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1705 str
+= _T("^{}"); // deref tag
1706 CAutoObject derefedTag
;
1707 if (git_object_peel(derefedTag
.GetPointer(), gitObject
, GIT_OBJ_ANY
))
1709 gitObject
.Swap(derefedTag
);
1712 const git_oid
* oid
= git_object_id(gitObject
);
1716 CGitHash
hash((char *)oid
->id
);
1717 (*payloadContent
->map
)[hash
].push_back(str
);
1721 int CGit::GetMapHashToFriendName(git_repository
* repo
, MAP_HASH_NAME
&map
)
1725 map_each_ref_payload payloadContent
= { repo
, &map
};
1727 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1730 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1732 std::sort(it
->second
.begin(), it
->second
.end());
1738 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1740 if (this->m_IsUseLibGit2
)
1742 CAutoRepository
repo(GetGitRepository());
1746 return GetMapHashToFriendName(repo
, map
);
1750 CString cmd
, output
;
1751 cmd
=_T("git.exe show-ref -d");
1752 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1759 one
=output
.Tokenize(_T("\n"),pos
);
1760 int start
=one
.Find(_T(" "),0);
1764 name
=one
.Right(one
.GetLength()-start
-1);
1767 hash
=one
.Left(start
);
1769 map
[CGitHash(hash
)].push_back(name
);
1777 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1779 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1780 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1783 static void SetLibGit2TemplatePath(const CString
&value
)
1785 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1786 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1789 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1796 this->m_Environment
.clear();
1797 m_Environment
.CopyProcessEnvironment();
1800 size_t homesize
,size
;
1802 // set HOME if not set already
1803 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1805 m_Environment
.SetEnv(_T("HOME"), GetHomeDirectory());
1808 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1809 if (sshclient
.IsEmpty())
1810 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1812 if(!sshclient
.IsEmpty())
1814 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1815 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1819 TCHAR sPlink
[MAX_PATH
] = {0};
1820 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1821 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1823 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1824 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1825 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1830 TCHAR sAskPass
[MAX_PATH
] = {0};
1831 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1832 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1835 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1836 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1837 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1838 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1842 // add git/bin path to PATH
1844 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1845 CString str
= msysdir
;
1846 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1851 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1852 str
= msyslocalinstalldir
;
1853 str
.TrimRight(_T("\\"));
1856 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1857 str
= msysinstalldir
;
1858 str
.TrimRight(_T("\\"));
1860 if ( !str
.IsEmpty() )
1864 CGit::ms_LastMsysGitDir
= str
;
1869 // search PATH if git/bin directory is already present
1870 if ( FindGitPath() )
1872 m_bInitialized
= TRUE
;
1873 msysdir
= CGit::ms_LastMsysGitDir
;
1883 CGit::ms_LastMsysGitDir
= str
;
1886 // check for git.exe existance (maybe it was deinstalled in the meantime)
1887 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1890 // Configure libgit2 search paths
1892 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1893 msysGitDir
.ReleaseBuffer();
1894 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1895 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1896 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1897 CString msysGitTemplateDir
;
1898 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1899 msysGitTemplateDir
.ReleaseBuffer();
1900 SetLibGit2TemplatePath(msysGitTemplateDir
);
1903 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1906 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1908 m_Environment
.SetEnv(_T("PATH"), path
);
1910 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1912 CString sOldPath
= oldpath
;
1915 m_bInitialized
= TRUE
;
1919 CString
CGit::GetHomeDirectory() const
1921 const wchar_t * homeDir
= wget_windows_home_directory();
1922 return CString(homeDir
, (int)wcslen(homeDir
));
1925 CString
CGit::GetGitLocalConfig() const
1928 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1929 path
+= _T("config");
1933 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1935 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1938 CString
CGit::GetGitGlobalConfig() const
1940 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1943 CString
CGit::GetGitGlobalXDGConfigPath() const
1945 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1948 CString
CGit::GetGitGlobalXDGConfig() const
1950 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1953 CString
CGit::GetGitSystemConfig() const
1955 const wchar_t * systemConfig
= wget_msysgit_etc();
1956 return CString(systemConfig
, (int)wcslen(systemConfig
));
1959 BOOL
CGit::CheckCleanWorkTree()
1963 cmd
=_T("git.exe rev-parse --verify HEAD");
1965 if(Run(cmd
,&out
,CP_UTF8
))
1968 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1969 if(Run(cmd
,&out
,CP_UTF8
))
1972 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1973 if(Run(cmd
,&out
,CP_UTF8
))
1976 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1977 if(Run(cmd
,&out
,CP_UTF8
))
1982 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
1985 for (int i
= 0; i
< list
.GetCount(); ++i
)
1987 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1993 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
1997 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1999 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
2002 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
2003 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2007 // if the filenames only differ in case, we have to pass "-f"
2008 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
2010 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
2011 if (Run(cmd
, &out
, CP_UTF8
))
2013 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2017 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
2018 if (Run(cmd
, &out
, CP_UTF8
))
2020 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2025 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
2026 { //To init git repository, there are not HEAD, so we can use git reset command
2027 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
2029 if (Run(cmd
, &out
, CP_UTF8
))
2031 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2037 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
2038 if (Run(cmd
, &out
, CP_UTF8
))
2040 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2045 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
2047 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
2048 if (Run(cmd
, &out
, CP_UTF8
))
2050 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
2058 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
2064 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
2066 cmd
=_T("git.exe ls-files -u -t -z");
2068 if (Run(cmd
, &vector
))
2073 if (list
.ParserFromLsFile(vector
))
2079 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2081 if (UsingLibGit2(GIT_CMD_MERGE_BASE
))
2083 CAutoRepository
repo(GetGitRepository());
2087 CGitHash fromHash
, toHash
, baseHash
;
2088 if (GetHash(repo
, toHash
, FixBranchName(to
)))
2091 if (GetHash(repo
, fromHash
, FixBranchName(from
)))
2095 if (git_merge_base(&baseOid
, repo
, (const git_oid
*)toHash
.m_hash
, (const git_oid
*)fromHash
.m_hash
))
2098 baseHash
= baseOid
.id
;
2101 *commonAncestor
= baseHash
;
2103 return fromHash
== baseHash
;
2107 CGitHash basehash
,hash
;
2109 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2111 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2115 basehash
= base
.Trim();
2117 GetHash(hash
, from
);
2120 *commonAncestor
= basehash
;
2122 return hash
== basehash
;
2125 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2128 for (int i
= 0; i
< 4; ++i
)
2131 ret
|= hash
.m_hash
[i
];
2136 int CGit::RefreshGitIndex()
2138 if(g_Git
.m_IsUseGitDLL
)
2140 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2143 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2154 cmd
=_T("git.exe update-index --refresh");
2155 return Run(cmd
, &output
, CP_UTF8
);
2159 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2161 if (UsingLibGit2(GIT_CMD_GETONEFILE
))
2163 CAutoRepository
repo(GetGitRepository());
2168 if (GetHash(repo
, hash
, Refname
))
2172 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2176 if (git_commit_tree(tree
.GetPointer(), commit
))
2179 CAutoTreeEntry entry
;
2180 if (git_tree_entry_bypath(entry
.GetPointer(), tree
, CUnicodeUtils::GetUTF8(path
.GetGitPathString())))
2184 if (git_tree_entry_to_object((git_object
**)blob
.GetPointer(), repo
, entry
))
2187 FILE *file
= nullptr;
2188 _tfopen_s(&file
, outputfile
, _T("w"));
2189 if (file
== nullptr)
2191 giterr_set_str(GITERR_NONE
, "Could not create file.");
2195 if (git_blob_filtered_content(buf
, blob
, CUnicodeUtils::GetUTF8(path
.GetGitPathString()), 0))
2200 if (fwrite(buf
->ptr
, sizeof(char), buf
->size
, file
) != buf
->size
)
2202 giterr_set_str(GITERR_OS
, "Could not write to file.");
2211 else if (g_Git
.m_IsUseGitDLL
)
2213 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2216 g_Git
.CheckAndInitDll();
2217 CStringA ref
, patha
, outa
;
2218 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2219 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2220 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2221 ::DeleteFile(outputfile
);
2222 return git_checkout_file(ref
, patha
, outa
);
2225 catch (const char * msg
)
2227 gitLastErr
= L
"gitdll.dll reports: " + CString(msg
);
2232 gitLastErr
= L
"An unknown gitdll.dll error occurred.";
2239 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2240 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2243 void CEnvironment::CopyProcessEnvironment()
2245 TCHAR
*porig
= GetEnvironmentStrings();
2247 while(*p
!=0 || *(p
+1) !=0)
2248 this->push_back(*p
++);
2250 push_back(_T('\0'));
2251 push_back(_T('\0'));
2253 FreeEnvironmentStrings(porig
);
2256 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2259 for (size_t i
= 0; i
< size(); ++i
)
2263 CString sname
= str
.Tokenize(_T("="),start
);
2264 if(sname
.CompareNoCase(name
) == 0)
2266 return &(*this)[i
+start
];
2273 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2276 for (i
= 0; i
< size(); ++i
)
2278 CString str
= &(*this)[i
];
2280 CString sname
= str
.Tokenize(_T("="),start
);
2281 if(sname
.CompareNoCase(name
) == 0)
2290 i
-= 1; // roll back terminate \0\0
2291 this->push_back(_T('\0'));
2294 CEnvironment::iterator it
;
2298 while(*it
&& i
<size())
2307 this->insert(it
,*name
++);
2312 this->insert(it
, _T('='));
2318 this->insert(it
,*value
++);
2325 int CGit::GetGitEncode(TCHAR
* configkey
)
2327 CString str
=GetConfigValue(configkey
);
2332 return CUnicodeUtils::GetCPCode(str
);
2336 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2342 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2345 diff
= GetGitDiff();
2347 git_open_diff(&diff
, arg
);
2356 isStat
= !!strstr(arg
, "stat");
2361 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2363 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2372 for (int j
= 0; j
< count
; ++j
)
2381 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2382 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2383 &mode
,&IsBin
,&inc
,&dec
);
2385 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2386 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2388 path
.SetFromGit(strnewname
,&stroldname
);
2389 path
.ParserAction((BYTE
)mode
);
2393 path
.m_StatAdd
=_T("-");
2394 path
.m_StatDel
=_T("-");
2398 path
.m_StatAdd
.Format(_T("%d"),inc
);
2399 path
.m_StatDel
.Format(_T("%d"),dec
);
2401 PathList
->AddPath(path
);
2403 git_diff_flush(diff
);
2406 git_close_diff(diff
);
2411 int CGit::GetShortHASHLength() const
2416 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2420 REF_TYPE type
= CGit::UNKNOWN
;
2422 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2424 type
= CGit::LOCAL_BRANCH
;
2427 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2429 type
= CGit::REMOTE_BRANCH
;
2431 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2435 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2438 shortname
=_T("stash");
2440 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2442 if (shortname
.Find(_T("good")) == 0)
2444 type
= CGit::BISECT_GOOD
;
2445 shortname
= _T("good");
2448 if (shortname
.Find(_T("bad")) == 0)
2450 type
= CGit::BISECT_BAD
;
2451 shortname
= _T("bad");
2454 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2458 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2460 type
= CGit::UNKNOWN
;
2464 type
= CGit::UNKNOWN
;
2474 bool CGit::UsingLibGit2(LIBGIT2_CMD cmd
) const
2476 return m_IsUseLibGit2
&& ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2479 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2482 if (rev2
== GitRev::GetWorkingCopy())
2483 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2484 else if (rev1
== GitRev::GetWorkingCopy())
2485 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2496 if (diffContext
> 0)
2497 unified
.Format(_T(" --unified=%d"), diffContext
);
2498 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2501 if (!path
.IsEmpty())
2504 cmd
+= path
.GetGitPathString();
2511 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2513 ATLASSERT(payload
&& line
);
2514 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2515 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2516 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2520 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2522 ATLASSERT(repo
&& identifier
&& tree
);
2524 /* try to resolve identifier */
2526 if (git_revparse_single(obj
.GetPointer(), repo
, identifier
))
2530 return GIT_ENOTFOUND
;
2533 switch (git_object_type(obj
))
2536 *tree
= (git_tree
*)obj
.Detach();
2538 case GIT_OBJ_COMMIT
:
2539 err
= git_commit_tree(tree
, (git_commit
*)(git_object
*)obj
);
2542 err
= GIT_ENOTFOUND
;
2548 /* use libgit2 get unified diff */
2549 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 */)
2551 CStringA tree1
= CUnicodeUtils::GetMulti(revNew
, CP_UTF8
);
2552 CStringA tree2
= CUnicodeUtils::GetMulti(revOld
, CP_UTF8
);
2554 CAutoRepository
repo(g_Git
.GetGitRepository());
2558 int isHeadOrphan
= git_repository_head_unborn(repo
);
2559 if (isHeadOrphan
== 1)
2561 else if (isHeadOrphan
!= 0)
2564 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2565 CStringA pathA
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2566 char *buf
= pathA
.GetBuffer();
2567 if (!pathA
.IsEmpty())
2569 opts
.pathspec
.strings
= &buf
;
2570 opts
.pathspec
.count
= 1;
2574 if (revNew
== GitRev::GetWorkingCopy() || revOld
== GitRev::GetWorkingCopy())
2579 if (revNew
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2582 if (revOld
!= GitRev::GetWorkingCopy() && resolve_to_tree(repo
, tree2
, t1
.GetPointer()))
2585 if (git_diff_tree_to_index(diff
.GetPointer(), repo
, t1
, nullptr, &opts
))
2588 if (git_diff_index_to_workdir(diff2
.GetPointer(), repo
, nullptr, &opts
))
2591 if (git_diff_merge(diff
, diff2
))
2596 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2599 if (tree1
.IsEmpty())
2607 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, t1
.GetPointer()))
2610 if (tree2
.IsEmpty())
2612 /* don't check return value, there are not parent commit at first commit*/
2613 resolve_to_tree(repo
, tree1
+ "~1", t2
.GetPointer());
2615 else if (resolve_to_tree(repo
, tree2
, t2
.GetPointer()))
2617 if (git_diff_tree_to_tree(diff
.GetPointer(), repo
, t2
, t1
, &opts
))
2621 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2624 if (git_patch_from_diff(patch
.GetPointer(), diff
, i
))
2627 if (git_patch_print(patch
, callback
, data
))
2631 pathA
.ReleaseBuffer();
2636 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2638 if (UsingLibGit2(GIT_CMD_DIFF
))
2640 FILE *file
= nullptr;
2641 _tfopen_s(&file
, patchfile
, _T("w"));
2642 if (file
== nullptr)
2644 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2651 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2652 return RunLogFile(cmd
, patchfile
, &gitLastErr
);
2656 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2658 ATLASSERT(payload
&& line
);
2659 CStringA
*str
= (CStringA
*) payload
;
2660 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2661 str
->Append(&line
->origin
, 1);
2662 str
->Append(line
->content
, (int)line
->content_len
);
2666 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2668 if (UsingLibGit2(GIT_CMD_DIFF
))
2669 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2673 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2675 int ret
= Run(cmd
, &vector
);
2676 if (!vector
.empty())
2678 vector
.push_back(0); // vector is not NUL terminated
2679 buffer
->Append((char *)&vector
[0]);
2685 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2687 if (UsingLibGit2(GIT_CMD_REVERT
))
2689 CAutoRepository
repo(GetGitRepository());
2694 if (git_commit_lookup(commit
.GetPointer(), repo
, (const git_oid
*)hash
.m_hash
))
2697 git_revert_options revert_opts
= GIT_REVERT_OPTIONS_INIT
;
2698 revert_opts
.mainline
= parent
;
2699 int result
= git_revert(repo
, commit
, &revert_opts
);
2701 return !result
? 0 : -1;
2707 merge
.Format(_T("-m %d "), parent
);
2708 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2709 gitLastErr
= cmd
+ _T("\n");
2710 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2722 int CGit::DeleteRef(const CString
& reference
)
2724 if (UsingLibGit2(GIT_CMD_DELETETAGBRANCH
))
2726 CAutoRepository
repo(GetGitRepository());
2731 if (reference
.Right(3) == _T("^{}"))
2732 refA
= CUnicodeUtils::GetUTF8(reference
.Left(reference
.GetLength() - 3));
2734 refA
= CUnicodeUtils::GetUTF8(reference
);
2737 if (git_reference_lookup(ref
.GetPointer(), repo
, refA
))
2741 if (git_reference_is_tag(ref
))
2742 result
= git_tag_delete(repo
, git_reference_shorthand(ref
));
2743 else if (git_reference_is_branch(ref
))
2744 result
= git_branch_delete(ref
);
2745 else if (git_reference_is_remote(ref
))
2746 result
= git_branch_delete(ref
);
2748 giterr_set_str(GITERR_REFERENCE
, CUnicodeUtils::GetUTF8(L
"unsupported reference type: " + reference
));
2754 CString cmd
, shortname
;
2755 if (GetShortName(reference
, shortname
, _T("refs/heads/")))
2756 cmd
.Format(_T("git.exe branch -D -- %s"), shortname
);
2757 else if (GetShortName(reference
, shortname
, _T("refs/tags/")))
2758 cmd
.Format(_T("git.exe tag -d -- %s"), shortname
);
2759 else if (GetShortName(reference
, shortname
, _T("refs/remotes/")))
2760 cmd
.Format(_T("git.exe branch -r -D -- %s"), shortname
);
2763 gitLastErr
= L
"unsupported reference type: " + reference
;
2767 if (Run(cmd
, &gitLastErr
, CP_UTF8
))
2775 bool CGit::LoadTextFile(const CString
&filename
, CString
&msg
)
2777 if (PathFileExists(filename
))
2779 FILE *pFile
= nullptr;
2780 _tfopen_s(&pFile
, filename
, _T("r"));
2786 char s
[8196] = { 0 };
2787 int read
= (int)fread(s
, sizeof(char), sizeof(s
), pFile
);
2790 str
+= CStringA(s
, read
);
2793 msg
= CUnicodeUtils::GetUnicode(str
);
2794 msg
.Replace(_T("\r\n"), _T("\n"));
2795 msg
.TrimRight(_T("\n"));
2799 ::MessageBox(nullptr, _T("Could not open ") + filename
, _T("TortoiseGit"), MB_ICONERROR
);
2800 return true; // load no further files