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 "GitConfig.h"
26 #include "UnicodeUtils.h"
29 #include "FormatMessageWrapper.h"
31 int CGit::m_LogEncode
=CP_UTF8
;
32 typedef CComCritSecLock
<CComCriticalSection
> CAutoLocker
;
34 static LPTSTR
nextpath(wchar_t *path
, wchar_t *buf
, size_t buflen
)
36 wchar_t term
, *base
= path
;
38 if (path
== NULL
|| buf
== NULL
|| buflen
== 0)
41 term
= (*path
== L
'"') ? *path
++ : L
';';
43 for (buflen
--; *path
&& *path
!= term
&& buflen
; buflen
--)
46 *buf
= L
'\0'; /* reserved a byte via initial subtract */
48 while (*path
== term
|| *path
== L
';')
51 return (path
!= base
) ? path
: NULL
;
54 static inline BOOL
FileExists(LPCTSTR lpszFileName
)
57 return _tstat(lpszFileName
, &st
) == 0;
60 static BOOL
FindGitPath()
63 _tgetenv_s(&size
, NULL
, 0, _T("PATH"));
70 TCHAR
*env
= (TCHAR
*)alloca(size
* sizeof(TCHAR
));
71 _tgetenv_s(&size
, env
, size
, _T("PATH"));
73 TCHAR buf
[MAX_PATH
] = {0};
75 // search in all paths defined in PATH
76 while ((env
= nextpath(env
, buf
, MAX_PATH
- 1)) != NULL
&& *buf
)
78 TCHAR
*pfin
= buf
+ _tcslen(buf
)-1;
80 // ensure trailing slash
81 if (*pfin
!= _T('/') && *pfin
!= _T('\\'))
82 _tcscpy_s(++pfin
, 2, _T("\\")); // we have enough space left, MAX_PATH-1 is used in nextpath above
84 const size_t len
= _tcslen(buf
);
86 if ((len
+ 7) < MAX_PATH
)
87 _tcscpy_s(pfin
+ 1, MAX_PATH
- len
, _T("git.exe"));
91 if ( FileExists(buf
) )
95 CGit::ms_LastMsysGitDir
= buf
;
96 CGit::ms_LastMsysGitDir
.TrimRight(_T("\\"));
97 if (CGit::ms_LastMsysGitDir
.GetLength() > 4)
99 // often the msysgit\cmd folder is on the %PATH%, but
100 // that git.exe does not work, so try to guess the bin folder
101 CString binDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin\\git.exe");
102 if (FileExists(binDir
))
103 CGit::ms_LastMsysGitDir
= CGit::ms_LastMsysGitDir
.Mid(0, CGit::ms_LastMsysGitDir
.GetLength() - 4) + _T("\\bin");
112 static bool g_bSortLogical
;
113 static bool g_bSortLocalBranchesFirst
;
115 static void GetSortOptions()
117 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_CURRENT_USER
);
119 g_bSortLogical
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoStrCmpLogical", 0, false, HKEY_LOCAL_MACHINE
);
120 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_CURRENT_USER
);
121 if (g_bSortLocalBranchesFirst
)
122 g_bSortLocalBranchesFirst
= !CRegDWORD(L
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer\\NoSortLocalBranchesFirst", 0, false, HKEY_LOCAL_MACHINE
);
125 static int LogicalComparePredicate(const CString
&left
, const CString
&right
)
128 return StrCmpLogicalW(left
, right
) < 0;
129 return StrCmpI(left
, right
) < 0;
132 static int LogicalCompareBranchesPredicate(const CString
&left
, const CString
&right
)
134 if (g_bSortLocalBranchesFirst
)
136 int leftIsRemote
= left
.Find(_T("remotes/"));
137 int rightIsRemote
= right
.Find(_T("remotes/"));
139 if (leftIsRemote
== 0 && rightIsRemote
< 0)
141 else if (leftIsRemote
< 0 && rightIsRemote
== 0)
145 return StrCmpLogicalW(left
, right
) < 0;
146 return StrCmpI(left
, right
) < 0;
149 #define MAX_DIRBUFFER 1000
150 #define CALL_OUTPUT_READ_CHUNK_SIZE 1024
152 CString
CGit::ms_LastMsysGitDir
;
153 int CGit::ms_LastMsysGitVersion
= 0;
159 GetCurrentDirectory(MAX_DIRBUFFER
,m_CurrentDir
.GetBuffer(MAX_DIRBUFFER
));
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"), 0);
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 CStringA branchA
= CUnicodeUtils::GetUTF8(_T("refs/heads/") + branchname
);
193 return !!git_reference_is_valid_name(branchA
);
196 static char g_Buffer
[4096];
198 int CGit::RunAsync(CString cmd
, PROCESS_INFORMATION
*piOut
, HANDLE
*hReadOut
, HANDLE
*hErrReadOut
, CString
*StdioFile
)
200 SECURITY_ATTRIBUTES sa
;
201 HANDLE hRead
, hWrite
, hReadErr
= NULL
, hWriteErr
= NULL
;
202 HANDLE hStdioFile
= NULL
;
204 sa
.nLength
= sizeof(SECURITY_ATTRIBUTES
);
205 sa
.lpSecurityDescriptor
=NULL
;
206 sa
.bInheritHandle
=TRUE
;
207 if(!CreatePipe(&hRead
,&hWrite
,&sa
,0))
209 CString err
= CFormatMessageWrapper();
210 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
211 return TGIT_GIT_ERROR_OPEN_PIP
;
213 if (hErrReadOut
&& !CreatePipe(&hReadErr
, &hWriteErr
, &sa
, 0))
215 CString err
= CFormatMessageWrapper();
216 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
217 return TGIT_GIT_ERROR_OPEN_PIP
;
222 hStdioFile
=CreateFile(*StdioFile
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
223 &sa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
227 PROCESS_INFORMATION pi
;
228 si
.cb
=sizeof(STARTUPINFO
);
232 si
.hStdError
= hWriteErr
;
234 si
.hStdError
= hWrite
;
236 si
.hStdOutput
=hStdioFile
;
238 si
.hStdOutput
=hWrite
;
240 si
.wShowWindow
=SW_HIDE
;
241 si
.dwFlags
=STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
243 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
244 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
246 //DETACHED_PROCESS make ssh recognize that it has no console to launch askpass to input password.
247 dwFlags
|= DETACHED_PROCESS
| CREATE_NEW_PROCESS_GROUP
;
249 memset(&this->m_CurrentGitPi
,0,sizeof(PROCESS_INFORMATION
));
250 memset(&pi
, 0, sizeof(PROCESS_INFORMATION
));
252 if(cmd
.Find(_T("git")) == 0)
254 int firstSpace
= cmd
.Find(_T(" "));
256 cmd
= _T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+ cmd
.Left(firstSpace
) + _T('"')+ cmd
.Mid(firstSpace
);
258 cmd
=_T('"')+CGit::ms_LastMsysGitDir
+_T("\\")+cmd
+_T('"');
261 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
262 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
264 CString err
= CFormatMessageWrapper();
265 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": error while executing command: %s\n"), err
.Trim());
266 return TGIT_GIT_ERROR_CREATE_PROCESS
;
273 CloseHandle(hWriteErr
);
279 *hErrReadOut
= hReadErr
;
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 HANDLE hRead
, hReadErr
;
350 if(RunAsync(pcall
->GetCmd(),&pi
,&hRead
, &hReadErr
))
351 return TGIT_GIT_ERROR_CREATE_PROCESS
;
354 ASYNCREADSTDERRTHREADARGS threadArguments
;
355 threadArguments
.fileHandle
= hReadErr
;
356 threadArguments
.pcall
= pcall
;
357 thread
= CreateThread(NULL
, 0, AsyncReadStdErrThread
, &threadArguments
, 0, NULL
);
360 BYTE data
[CALL_OUTPUT_READ_CHUNK_SIZE
];
362 while(ReadFile(hRead
,data
,CALL_OUTPUT_READ_CHUNK_SIZE
,&readnumber
,NULL
))
364 // TODO: when OnOutputData() returns 'true', abort git-command. Send CTRL-C signal?
365 if(!bAborted
)//For now, flush output when command aborted.
366 if(pcall
->OnOutputData(data
,readnumber
))
373 WaitForSingleObject(thread
, INFINITE
);
375 CloseHandle(pi
.hThread
);
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
);
389 CloseHandle(pi
.hProcess
);
392 CloseHandle(hReadErr
);
395 class CGitCall_ByteVector
: public CGitCall
398 CGitCall_ByteVector(CString cmd
,BYTE_VECTOR
* pvector
, BYTE_VECTOR
* pvectorErr
= NULL
):CGitCall(cmd
),m_pvector(pvector
),m_pvectorErr(pvectorErr
){}
399 virtual bool OnOutputData(const BYTE
* data
, size_t size
)
401 if (!m_pvector
|| size
== 0)
403 size_t oldsize
=m_pvector
->size();
404 m_pvector
->resize(m_pvector
->size()+size
);
405 memcpy(&*(m_pvector
->begin()+oldsize
),data
,size
);
408 virtual bool OnOutputErrData(const BYTE
* data
, size_t size
)
410 if (!m_pvectorErr
|| size
== 0)
412 size_t oldsize
= m_pvectorErr
->size();
413 m_pvectorErr
->resize(m_pvectorErr
->size() + size
);
414 memcpy(&*(m_pvectorErr
->begin() + oldsize
), data
, size
);
417 BYTE_VECTOR
* m_pvector
;
418 BYTE_VECTOR
* m_pvectorErr
;
421 int CGit::Run(CString cmd
,BYTE_VECTOR
*vector
, BYTE_VECTOR
*vectorErr
)
423 CGitCall_ByteVector
call(cmd
, vector
, vectorErr
);
426 int CGit::Run(CString cmd
, CString
* output
, int code
)
430 ret
= Run(cmd
, output
, &err
, code
);
432 if (output
&& !err
.IsEmpty())
434 if (!output
->IsEmpty())
441 int CGit::Run(CString cmd
, CString
* output
, CString
* outputErr
, int code
)
443 BYTE_VECTOR vector
, vectorErr
;
446 ret
= Run(cmd
, &vector
, &vectorErr
);
448 ret
= Run(cmd
, &vector
);
451 StringAppend(output
, &(vector
[0]), code
);
455 vectorErr
.push_back(0);
456 StringAppend(outputErr
, &(vectorErr
[0]), code
);
462 CString
CGit::GetUserName(void)
465 env
.CopyProcessEnvironment();
466 CString envname
= env
.GetEnv(_T("GIT_AUTHOR_NAME"));
467 if (!envname
.IsEmpty())
469 return GetConfigValue(L
"user.name");
471 CString
CGit::GetUserEmail(void)
474 env
.CopyProcessEnvironment();
475 CString envmail
= env
.GetEnv(_T("GIT_AUTHOR_EMAIL"));
476 if (!envmail
.IsEmpty())
479 return GetConfigValue(L
"user.email");
482 CString
CGit::GetConfigValue(const CString
& name
, int encoding
, BOOL RemoveCR
)
486 if(this->m_IsUseGitDLL
)
488 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
497 key
= CUnicodeUtils::GetMulti(name
, encoding
);
501 if (git_get_config(key
, value
.GetBufferSetLength(4096), 4096))
504 catch (const char *msg
)
506 ::MessageBox(NULL
, _T("Could not get config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
510 StringAppend(&configValue
, (BYTE
*)(LPCSTR
)value
, encoding
);
512 return configValue
.Tokenize(_T("\n"),start
);
518 cmd
.Format(L
"git.exe config %s", name
);
519 Run(cmd
, &configValue
, NULL
, encoding
);
521 return configValue
.Tokenize(_T("\n"),start
);
526 bool CGit::GetConfigValueBool(const CString
& name
)
528 CString configValue
= GetConfigValue(name
);
529 configValue
.MakeLower();
531 if(configValue
== _T("true") || configValue
== _T("on") || configValue
== _T("yes") || StrToInt(configValue
) != 0)
537 int CGit::SetConfigValue(const CString
& key
, const CString
& value
, CONFIG_TYPE type
, int encoding
)
539 if(this->m_IsUseGitDLL
)
541 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
550 CStringA keya
, valuea
;
551 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
552 valuea
= CUnicodeUtils::GetMulti(value
, encoding
);
556 return get_set_config(keya
, valuea
, type
);
558 catch (const char *msg
)
560 ::MessageBox(NULL
, _T("Could not set config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
571 option
= _T("--global");
574 option
= _T("--system");
579 cmd
.Format(_T("git.exe config %s %s \"%s\""), option
, key
, value
);
581 if (Run(cmd
, &out
, NULL
, encoding
))
589 int CGit::UnsetConfigValue(const CString
& key
, CONFIG_TYPE type
, int encoding
)
591 if(this->m_IsUseGitDLL
)
593 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
602 keya
= CUnicodeUtils::GetMulti(key
, CP_UTF8
);
606 return get_set_config(keya
, nullptr, type
);
608 catch (const char *msg
)
610 ::MessageBox(NULL
, _T("Could not unset config.\nlibgit reports:\n") + CString(msg
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
621 option
= _T("--global");
624 option
= _T("--system");
629 cmd
.Format(_T("git.exe config %s --unset %s"), option
, key
);
631 if (Run(cmd
, &out
, NULL
, encoding
))
639 CString
CGit::GetCurrentBranch(bool fallback
)
642 //Run(_T("git.exe branch"),&branch);
644 int result
= GetCurrentBranchFromFile(m_CurrentDir
, output
, fallback
);
645 if (result
!= 0 && ((result
== 1 && !fallback
) || result
!= 1))
647 return _T("(no branch)");
654 CString
CGit::GetSymbolicRef(const wchar_t* symbolicRefName
, bool bStripRefsHeads
)
657 if(this->m_IsUseGitDLL
)
659 unsigned char sha1
[20] = { 0 };
662 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
663 const char *refs_heads_master
= nullptr;
666 refs_heads_master
= git_resolve_ref(CUnicodeUtils::GetUTF8(CString(symbolicRefName
)), sha1
, 0, &flag
);
668 catch (const char *err
)
670 ::MessageBox(NULL
, _T("Could not resolve ref ") + CString(symbolicRefName
) + _T(".\nlibgit reports:\n") + CString(err
), _T("TortoiseGit"), MB_OK
| MB_ICONERROR
);
672 if(refs_heads_master
&& (flag
&REF_ISSYMREF
))
674 StringAppend(&refName
,(BYTE
*)refs_heads_master
);
676 refName
= StripRefName(refName
);
683 cmd
.Format(L
"git.exe symbolic-ref %s", symbolicRefName
);
684 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
685 return CString();//Error
687 refName
= refName
.Tokenize(L
"\n", iStart
);
689 refName
= StripRefName(refName
);
694 CString
CGit::GetFullRefName(const CString
& shortRefName
)
698 cmd
.Format(L
"git.exe rev-parse --symbolic-full-name %s", shortRefName
);
699 if (Run(cmd
, &refName
, NULL
, CP_UTF8
) != 0)
700 return CString();//Error
702 return refName
.Tokenize(L
"\n", iStart
);
705 CString
CGit::StripRefName(CString refName
)
707 if(wcsncmp(refName
, L
"refs/heads/", 11) == 0)
708 refName
= refName
.Mid(11);
709 else if(wcsncmp(refName
, L
"refs/", 5) == 0)
710 refName
= refName
.Mid(5);
712 return refName
.Tokenize(_T("\n"),start
);
715 int CGit::GetCurrentBranchFromFile(const CString
&sProjectRoot
, CString
&sBranchOut
, bool fallback
)
717 // read current branch name like git-gui does, by parsing the .git/HEAD file directly
719 if ( sProjectRoot
.IsEmpty() )
723 if (!g_GitAdminDir
.GetAdminDirPath(sProjectRoot
, sDotGitPath
))
726 CString sHeadFile
= sDotGitPath
+ _T("HEAD");
729 _tfopen_s(&pFile
, sHeadFile
.GetString(), _T("r"));
737 fgets(s
, sizeof(s
), pFile
);
741 const char *pfx
= "ref: refs/heads/";
742 const int len
= 16;//strlen(pfx)
744 if ( !strncmp(s
, pfx
, len
) )
746 //# We're on a branch. It might not exist. But
747 //# HEAD looks good enough to be a branch.
748 CStringA
utf8Branch(s
+ len
);
749 sBranchOut
= CUnicodeUtils::GetUnicode(utf8Branch
);
750 sBranchOut
.TrimRight(_T(" \r\n\t"));
752 if ( sBranchOut
.IsEmpty() )
757 CStringA
utf8Hash(s
);
758 CString unicodeHash
= CUnicodeUtils::GetUnicode(utf8Hash
);
759 unicodeHash
.TrimRight(_T(" \r\n\t"));
760 if (CGitHash::IsValidSHA1(unicodeHash
))
761 sBranchOut
= unicodeHash
;
763 //# Assume this is a detached head.
764 sBranchOut
= _T("HEAD");
769 //# Assume this is a detached head.
778 int CGit::BuildOutputFormat(CString
&format
,bool IsFull
)
781 log
.Format(_T("#<%c>%%x00"),LOG_REV_ITEM_BEGIN
);
785 log
.Format(_T("#<%c>%%an%%x00"),LOG_REV_AUTHOR_NAME
);
787 log
.Format(_T("#<%c>%%ae%%x00"),LOG_REV_AUTHOR_EMAIL
);
789 log
.Format(_T("#<%c>%%ai%%x00"),LOG_REV_AUTHOR_DATE
);
791 log
.Format(_T("#<%c>%%cn%%x00"),LOG_REV_COMMIT_NAME
);
793 log
.Format(_T("#<%c>%%ce%%x00"),LOG_REV_COMMIT_EMAIL
);
795 log
.Format(_T("#<%c>%%ci%%x00"),LOG_REV_COMMIT_DATE
);
797 log
.Format(_T("#<%c>%%b%%x00"),LOG_REV_COMMIT_BODY
);
801 log
.Format(_T("#<%c>%%m%%H%%x00"),LOG_REV_COMMIT_HASH
);
803 log
.Format(_T("#<%c>%%P%%x00"),LOG_REV_COMMIT_PARENT
);
805 log
.Format(_T("#<%c>%%s%%x00"),LOG_REV_COMMIT_SUBJECT
);
810 log
.Format(_T("#<%c>%%x00"),LOG_REV_COMMIT_FILE
);
816 CString
CGit::GetLogCmd(const CString
&range
, const CTGitPath
*path
, int count
, int mask
, bool paramonly
,
823 CString file
= _T(" --");
826 file
.Format(_T(" -- \"%s\""),path
->GetGitPathString());
829 num
.Format(_T("-n%d"),count
);
833 if(mask
& LOG_INFO_STAT
)
834 param
+= _T(" --numstat ");
835 if(mask
& LOG_INFO_FILESTATE
)
836 param
+= _T(" --raw ");
838 if(mask
& LOG_INFO_FULLHISTORY
)
839 param
+= _T(" --full-history ");
841 if(mask
& LOG_INFO_BOUNDARY
)
842 param
+= _T(" --left-right --boundary ");
844 if(mask
& CGit::LOG_INFO_ALL_BRANCH
)
845 param
+= _T(" --all ");
847 if(mask
& CGit::LOG_INFO_LOCAL_BRANCHES
)
848 param
+= _T(" --branches ");
850 if(mask
& CGit::LOG_INFO_DETECT_COPYRENAME
)
853 if(mask
& CGit::LOG_INFO_DETECT_RENAME
)
856 if(mask
& CGit::LOG_INFO_FIRST_PARENT
)
857 param
+= _T(" --first-parent ");
859 if(mask
& CGit::LOG_INFO_NO_MERGE
)
860 param
+= _T(" --no-merges ");
862 if(mask
& CGit::LOG_INFO_FOLLOW
)
863 param
+= _T(" --follow ");
865 if(mask
& CGit::LOG_INFO_SHOW_MERGEDFILE
)
868 if(mask
& CGit::LOG_INFO_FULL_DIFF
)
869 param
+= _T(" --full-diff ");
871 if(mask
& CGit::LOG_INFO_SIMPILFY_BY_DECORATION
)
872 param
+= _T(" --simplify-by-decoration ");
878 if( Filter
&& (Filter
->m_From
!= -1))
880 st1
.Format(_T(" --max-age=%I64u "), Filter
->m_From
);
884 if( Filter
&& (Filter
->m_To
!= -1))
886 st2
.Format(_T(" --min-age=%I64u "), Filter
->m_To
);
891 if( Filter
&& (!Filter
->m_Author
.IsEmpty()))
893 st1
.Format(_T(" --author=\"%s\"" ),Filter
->m_Author
);
898 if( Filter
&& (!Filter
->m_Committer
.IsEmpty()))
900 st1
.Format(_T(" --committer=\"%s\"" ),Filter
->m_Author
);
905 if( Filter
&& (!Filter
->m_MessageFilter
.IsEmpty()))
907 st1
.Format(_T(" --grep=\"%s\"" ),Filter
->m_MessageFilter
);
914 if(!Filter
->m_IsRegex
)
915 param
+= _T(" --fixed-strings ");
917 param
+= _T(" --regexp-ignore-case --extended-regexp ");
920 DWORD logOrderBy
= CRegDWORD(_T("Software\\TortoiseGit\\LogOrderBy"), LOG_ORDER_TOPOORDER
);
921 if (logOrderBy
== LOG_ORDER_TOPOORDER
)
922 param
+= _T(" --topo-order");
923 else if (logOrderBy
== LOG_ORDER_DATEORDER
)
924 param
+= _T(" --date-order");
926 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
927 cmd
.Format(_T("--ignore-this-parameter %s -z %s --parents "), num
, param
);
931 BuildOutputFormat(log
,!(mask
&CGit::LOG_INFO_ONLY_HASH
));
932 cmd
.Format(_T("git.exe log %s -z %s --parents --pretty=format:\"%s\""),
941 void GetTempPath(CString
&path
)
943 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
945 DWORD dwBufSize
=BUFSIZE
;
946 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
947 lpPathBuffer
); // buffer for path
948 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
952 path
.Format(_T("%s"),lpPathBuffer
);
954 CString
GetTempFile()
956 TCHAR lpPathBuffer
[BUFSIZE
] = { 0 };
958 DWORD dwBufSize
=BUFSIZE
;
959 TCHAR szTempName
[BUFSIZE
] = { 0 };
962 dwRetVal
= GetTortoiseGitTempPath(dwBufSize
, // length of the buffer
963 lpPathBuffer
); // buffer for path
964 if (dwRetVal
> dwBufSize
|| (dwRetVal
== 0))
968 // Create a temporary file.
969 uRetVal
= GetTempFileName(lpPathBuffer
, // directory for tmp files
970 TEXT("Patch"), // temp file name prefix
971 0, // create unique name
972 szTempName
); // buffer for name
980 return CString(szTempName
);
984 DWORD
GetTortoiseGitTempPath(DWORD nBufferLength
, LPTSTR lpBuffer
)
986 DWORD result
= ::GetTempPath(nBufferLength
, lpBuffer
);
987 if (result
== 0) return 0;
988 if (lpBuffer
== NULL
|| (result
+ 13 > nBufferLength
))
995 _tcscat_s(lpBuffer
, nBufferLength
, _T("TortoiseGit\\"));
996 CreateDirectory(lpBuffer
, NULL
);
1001 int CGit::RunLogFile(CString cmd
, const CString
&filename
, CString
*stdErr
)
1004 PROCESS_INFORMATION pi
;
1005 si
.cb
=sizeof(STARTUPINFO
);
1006 GetStartupInfo(&si
);
1008 SECURITY_ATTRIBUTES psa
={sizeof(psa
),NULL
,TRUE
};;
1009 psa
.bInheritHandle
=TRUE
;
1011 HANDLE hReadErr
, hWriteErr
;
1012 if (!CreatePipe(&hReadErr
, &hWriteErr
, &psa
, 0))
1014 CString err
= CFormatMessageWrapper();
1015 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stderr pipe: %s\n"), err
.Trim());
1016 return TGIT_GIT_ERROR_OPEN_PIP
;
1019 HANDLE houtfile
=CreateFile(filename
,GENERIC_WRITE
,FILE_SHARE_READ
| FILE_SHARE_WRITE
,
1020 &psa
,CREATE_ALWAYS
,FILE_ATTRIBUTE_NORMAL
,NULL
);
1022 if (houtfile
== INVALID_HANDLE_VALUE
)
1024 CString err
= CFormatMessageWrapper();
1025 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not open stdout pipe: %s\n"), err
.Trim());
1026 return TGIT_GIT_ERROR_OPEN_PIP
;
1029 si
.wShowWindow
= SW_HIDE
;
1030 si
.dwFlags
= STARTF_USESTDHANDLES
|STARTF_USESHOWWINDOW
;
1031 si
.hStdOutput
= houtfile
;
1032 si
.hStdError
= hWriteErr
;
1034 LPTSTR pEnv
= (!m_Environment
.empty()) ? &m_Environment
[0]: NULL
;
1035 DWORD dwFlags
= pEnv
? CREATE_UNICODE_ENVIRONMENT
: 0;
1037 if(cmd
.Find(_T("git")) == 0)
1038 cmd
=CGit::ms_LastMsysGitDir
+_T("\\")+cmd
;
1040 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": executing %s\n"), cmd
);
1041 if(!CreateProcess(NULL
,(LPWSTR
)cmd
.GetString(), NULL
,NULL
,TRUE
,dwFlags
,pEnv
,(LPWSTR
)m_CurrentDir
.GetString(),&si
,&pi
))
1043 CString err
= CFormatMessageWrapper();
1044 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": failed to create Process: %s\n"), err
.Trim());
1046 return TGIT_GIT_ERROR_CREATE_PROCESS
;
1049 BYTE_VECTOR stderrVector
;
1050 CGitCall_ByteVector
pcall(L
"", nullptr, &stderrVector
);
1052 ASYNCREADSTDERRTHREADARGS threadArguments
;
1053 threadArguments
.fileHandle
= hReadErr
;
1054 threadArguments
.pcall
= &pcall
;
1055 thread
= CreateThread(nullptr, 0, AsyncReadStdErrThread
, &threadArguments
, 0, nullptr);
1057 WaitForSingleObject(pi
.hProcess
,INFINITE
);
1059 CloseHandle(hWriteErr
);
1060 CloseHandle(hReadErr
);
1063 WaitForSingleObject(thread
, INFINITE
);
1065 stderrVector
.push_back(0);
1066 StringAppend(stdErr
, &(stderrVector
[0]), CP_UTF8
);
1069 if (!GetExitCodeProcess(pi
.hProcess
, &exitcode
))
1071 CString err
= CFormatMessageWrapper();
1072 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": could not get exit code: %s\n"), err
.Trim());
1073 return TGIT_GIT_ERROR_GET_EXIT_CODE
;
1076 CTraceToOutputDebugString::Instance()(_T(__FUNCTION__
) _T(": process exited: %d\n"), exitcode
);
1078 CloseHandle(pi
.hThread
);
1079 CloseHandle(pi
.hProcess
);
1080 CloseHandle(houtfile
);
1084 int CGit::GetHash(CGitHash
&hash
, const CString
& friendname
)
1086 // no need to parse a ref if it's already a 40-byte hash
1087 if (CGitHash::IsValidSHA1(friendname
))
1089 CString
sHash(friendname
);
1090 hash
= CGitHash(sHash
);
1096 git_repository
*repo
= NULL
;
1097 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1098 if (git_repository_open(&repo
, gitdirA
))
1101 int isHeadOrphan
= git_repository_head_unborn(repo
);
1102 if (isHeadOrphan
!= 0)
1104 git_repository_free(repo
);
1106 if (isHeadOrphan
== 1)
1112 CStringA refnameA
= CUnicodeUtils::GetMulti(friendname
, CP_UTF8
);
1114 git_object
* gitObject
= NULL
;
1115 if (git_revparse_single(&gitObject
, repo
, refnameA
))
1117 git_repository_free(repo
);
1121 const git_oid
* oid
= git_object_id(gitObject
);
1124 git_object_free(gitObject
);
1125 git_repository_free(repo
);
1129 hash
= CGitHash((char *)oid
->id
);
1131 git_object_free(gitObject
); // also frees oid
1132 git_repository_free(repo
);
1139 cmd
.Format(_T("git.exe rev-parse %s" ),FixBranchName(friendname
));
1141 int ret
= Run(cmd
, &gitLastErr
, NULL
, CP_UTF8
);
1142 hash
= CGitHash(gitLastErr
.Trim());
1149 int CGit::GetInitAddList(CTGitPathList
&outputlist
)
1154 cmd
=_T("git.exe ls-files -s -t -z");
1156 if (Run(cmd
, &cmdout
))
1159 if (outputlist
.ParserFromLsFile(cmdout
))
1161 for(int i
= 0; i
< outputlist
.GetCount(); ++i
)
1162 const_cast<CTGitPath
&>(outputlist
[i
]).m_Action
= CTGitPath::LOGACTIONS_ADDED
;
1166 int CGit::GetCommitDiffList(const CString
&rev1
,const CString
&rev2
,CTGitPathList
&outputlist
)
1170 if(rev1
== GIT_REV_ZERO
|| rev2
== GIT_REV_ZERO
)
1173 if(rev1
== GIT_REV_ZERO
)
1174 cmd
.Format(_T("git.exe diff -r --raw -C -M --numstat -z %s --"), rev2
);
1176 cmd
.Format(_T("git.exe diff -r -R --raw -C -M --numstat -z %s --"), rev1
);
1180 cmd
.Format(_T("git.exe diff-tree -r --raw -C -M --numstat -z %s %s --"), rev2
, rev1
);
1187 outputlist
.ParserFromLog(out
);
1192 int addto_list_each_ref_fn(const char *refname
, const unsigned char * /*sha1*/, int /*flags*/, void *cb_data
)
1194 STRING_VECTOR
*list
= (STRING_VECTOR
*)cb_data
;
1196 g_Git
.StringAppend(&str
, (BYTE
*)refname
, CP_UTF8
);
1197 list
->push_back(str
);
1201 int CGit::GetTagList(STRING_VECTOR
&list
)
1203 if (this->m_IsUseLibGit2
)
1205 git_repository
*repo
= NULL
;
1207 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1208 if (git_repository_open(&repo
, gitdir
))
1211 git_strarray tag_names
;
1213 if (git_tag_list(&tag_names
, repo
))
1215 git_repository_free(repo
);
1219 for (size_t i
= 0; i
< tag_names
.count
; ++i
)
1221 CStringA
tagName(tag_names
.strings
[i
]);
1222 list
.push_back(CUnicodeUtils::GetUnicode(tagName
));
1225 git_strarray_free(&tag_names
);
1227 git_repository_free(repo
);
1229 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1235 CString cmd
, output
;
1236 cmd
=_T("git.exe tag -l");
1237 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1244 one
=output
.Tokenize(_T("\n"),pos
);
1246 list
.push_back(one
);
1248 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1255 Use this method only if m_IsUseLibGit2 is used for fallbacks.
1256 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
1258 CString
CGit::GetGitLastErr(const CString
& msg
)
1260 if (this->m_IsUseLibGit2
)
1261 return GetLibGit2LastErr(msg
);
1262 else if (gitLastErr
.IsEmpty())
1263 return msg
+ _T("\nUnknown git.exe error.");
1266 CString lastError
= gitLastErr
;
1268 return msg
+ _T("\n") + lastError
;
1272 CString
CGit::GetGitLastErr(const CString
& msg
, int cmd
)
1274 if (UsingLibGit2(cmd
))
1275 return GetLibGit2LastErr(msg
);
1276 else if (gitLastErr
.IsEmpty())
1277 return msg
+ _T("\nUnknown git.exe error.");
1280 CString lastError
= gitLastErr
;
1282 return msg
+ _T("\n") + lastError
;
1286 CString
CGit::GetLibGit2LastErr()
1288 const git_error
*libgit2err
= giterr_last();
1291 CString lastError
= CUnicodeUtils::GetUnicode(CStringA(libgit2err
->message
));
1293 return _T("libgit2 returned: ") + lastError
;
1296 return _T("An error occoured in libgit2, but no message is available.");
1299 CString
CGit::GetLibGit2LastErr(const CString
& msg
)
1302 return msg
+ _T("\n") + GetLibGit2LastErr();
1303 return GetLibGit2LastErr();
1306 CString
CGit::FixBranchName_Mod(CString
& branchName
)
1308 if(branchName
== "FETCH_HEAD")
1309 branchName
= DerefFetchHead();
1313 CString
CGit::FixBranchName(const CString
& branchName
)
1315 CString tempBranchName
= branchName
;
1316 FixBranchName_Mod(tempBranchName
);
1317 return tempBranchName
;
1320 bool CGit::IsBranchTagNameUnique(const CString
& name
)
1325 cmd
.Format(_T("git.exe show-ref --tags --heads refs/heads/%s refs/tags/%s"), name
, name
);
1326 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1332 if (!output
.Tokenize(_T("\n"), pos
).IsEmpty())
1343 Checks if a branch or tag with the given name exists
1344 isBranch is true -> branch, tag otherwise
1346 bool CGit::BranchTagExists(const CString
& name
, bool isBranch
/*= true*/)
1348 CString cmd
, output
;
1350 cmd
= _T("git.exe show-ref ");
1352 cmd
+= _T("--heads ");
1354 cmd
+= _T("--tags ");
1356 cmd
+= _T("refs/heads/") + name
;
1357 cmd
+= _T(" refs/tags/") + name
;
1359 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1362 if (!output
.IsEmpty())
1369 CString
CGit::DerefFetchHead()
1372 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, dotGitPath
);
1373 std::ifstream
fetchHeadFile((dotGitPath
+ L
"FETCH_HEAD").GetString(), std::ios::in
| std::ios::binary
);
1374 int forMergeLineCount
= 0;
1376 std::string hashToReturn
;
1377 while(getline(fetchHeadFile
, line
))
1379 //Tokenize this line
1380 std::string::size_type prevPos
= 0;
1381 std::string::size_type pos
= line
.find('\t');
1382 if(pos
== std::string::npos
) continue; //invalid line
1384 std::string hash
= line
.substr(0, pos
);
1385 ++pos
; prevPos
= pos
; pos
= line
.find('\t', pos
); if(pos
== std::string::npos
) continue;
1387 bool forMerge
= pos
== prevPos
;
1388 ++pos
; prevPos
= pos
; pos
= line
.size(); if(pos
== std::string::npos
) continue;
1390 std::string remoteBranch
= line
.substr(prevPos
, pos
- prevPos
);
1395 hashToReturn
= hash
;
1396 ++forMergeLineCount
;
1397 if(forMergeLineCount
> 1)
1398 return L
""; //More then 1 branch to merge found. Octopus merge needed. Cannot pick single ref from FETCH_HEAD
1402 return CUnicodeUtils::GetUnicode(hashToReturn
.c_str());
1405 int CGit::GetBranchList(STRING_VECTOR
&list
,int *current
,BRANCH_TYPE type
)
1408 CString cmd
, output
, cur
;
1409 cmd
= _T("git.exe branch --no-color");
1411 if((type
&BRANCH_ALL
) == BRANCH_ALL
)
1413 else if(type
&BRANCH_REMOTE
)
1416 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1423 one
=output
.Tokenize(_T("\n"),pos
);
1424 one
.Trim(L
" \r\n\t");
1425 if(one
.Find(L
" -> ") >= 0 || one
.IsEmpty())
1426 continue; // skip something like: refs/origin/HEAD -> refs/origin/master
1427 if(one
[0] == _T('*'))
1432 if (one
.Left(10) != _T("(no branch") && one
.Left(15) != _T("(detached from "))
1433 list
.push_back(one
);
1437 if(type
& BRANCH_FETCH_HEAD
&& !DerefFetchHead().IsEmpty())
1438 list
.push_back(L
"FETCH_HEAD");
1440 std::sort(list
.begin(), list
.end(), LogicalCompareBranchesPredicate
);
1442 if (current
&& cur
.Left(10) != _T("(no branch") && cur
.Left(15) != _T("(detached from "))
1444 for (unsigned int i
= 0; i
< list
.size(); ++i
)
1457 int CGit::GetRemoteList(STRING_VECTOR
&list
)
1459 if (this->m_IsUseLibGit2
)
1461 git_repository
*repo
= NULL
;
1463 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1464 if (git_repository_open(&repo
, gitdir
))
1467 git_strarray remotes
;
1469 if (git_remote_list(&remotes
, repo
))
1471 git_repository_free(repo
);
1475 for (size_t i
= 0; i
< remotes
.count
; ++i
)
1477 CStringA
remote(remotes
.strings
[i
]);
1478 list
.push_back(CUnicodeUtils::GetUnicode(remote
));
1481 git_strarray_free(&remotes
);
1483 git_repository_free(repo
);
1485 std::sort(list
.begin(), list
.end());
1492 CString cmd
, output
;
1493 cmd
=_T("git.exe remote");
1494 ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1501 one
=output
.Tokenize(_T("\n"),pos
);
1503 list
.push_back(one
);
1510 int CGit::GetRemoteTags(const CString
& remote
, STRING_VECTOR
&list
)
1512 CString cmd
, out
, err
;
1513 cmd
.Format(_T("git.exe ls-remote -t \"%s\""), remote
);
1514 if (Run(cmd
, &out
, &err
, CP_UTF8
))
1516 MessageBox(NULL
, err
, _T("TortoiseGit"), MB_ICONERROR
);
1523 CString one
= out
.Tokenize(_T("\n"), pos
).Mid(51).Trim(); // sha1, tab + refs/tags/
1524 // dot not include annotated tags twice; this works, because an annotated tag appears twice (one normal tag and one with ^{} at the end)
1525 if (one
.Find(_T("^{}")) >= 1)
1528 list
.push_back(one
);
1530 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1534 int libgit2_addto_list_each_ref_fn(git_reference
*ref
, void *payload
)
1536 STRING_VECTOR
*list
= (STRING_VECTOR
*)payload
;
1538 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1539 list
->push_back(str
);
1543 int CGit::GetRefList(STRING_VECTOR
&list
)
1545 if (this->m_IsUseLibGit2
)
1547 git_repository
*repo
= NULL
;
1549 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1550 if (git_repository_open(&repo
, gitdir
))
1553 if (git_reference_foreach(repo
, libgit2_addto_list_each_ref_fn
, &list
))
1555 git_repository_free(repo
);
1559 git_repository_free(repo
);
1561 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1567 CString cmd
, output
;
1568 cmd
=_T("git.exe show-ref -d");
1569 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1576 one
=output
.Tokenize(_T("\n"),pos
);
1577 int start
=one
.Find(_T(" "),0);
1581 name
=one
.Right(one
.GetLength()-start
-1);
1582 list
.push_back(name
);
1585 std::sort(list
.begin(), list
.end(), LogicalComparePredicate
);
1591 typedef struct map_each_ref_payload
{
1592 git_repository
* repo
;
1593 MAP_HASH_NAME
* map
;
1594 } map_each_ref_payload
;
1596 int libgit2_addto_map_each_ref_fn(git_reference
*ref
, void *payload
)
1598 map_each_ref_payload
*payloadContent
= (map_each_ref_payload
*)payload
;
1601 g_Git
.StringAppend(&str
, (BYTE
*)git_reference_name(ref
), CP_UTF8
);
1603 git_object
* gitObject
= NULL
;
1607 if (git_revparse_single(&gitObject
, payloadContent
->repo
, git_reference_name(ref
)))
1612 if (git_object_type(gitObject
) == GIT_OBJ_TAG
)
1614 str
+= _T("^{}"); // deref tag
1615 git_object
* derefedTag
= NULL
;
1616 if (git_object_peel(&derefedTag
, gitObject
, GIT_OBJ_ANY
))
1620 git_object_free(gitObject
);
1621 gitObject
= derefedTag
;
1624 const git_oid
* oid
= git_object_id(gitObject
);
1630 CGitHash
hash((char *)oid
->id
);
1631 (*payloadContent
->map
)[hash
].push_back(str
);
1636 git_object_free(gitObject
);
1643 int CGit::GetMapHashToFriendName(MAP_HASH_NAME
&map
)
1645 if (this->m_IsUseLibGit2
)
1647 git_repository
*repo
= NULL
;
1649 CStringA gitdir
= CUnicodeUtils::GetMulti(CTGitPath(m_CurrentDir
).GetGitPathString(), CP_UTF8
);
1650 if (git_repository_open(&repo
, gitdir
))
1653 map_each_ref_payload payloadContent
= { repo
, &map
};
1655 if (git_reference_foreach(repo
, libgit2_addto_map_each_ref_fn
, &payloadContent
))
1657 git_repository_free(repo
);
1661 git_repository_free(repo
);
1663 for (auto it
= map
.begin(); it
!= map
.end(); ++it
)
1665 std::sort(it
->second
.begin(), it
->second
.end());
1672 CString cmd
, output
;
1673 cmd
=_T("git.exe show-ref -d");
1674 int ret
= Run(cmd
, &output
, NULL
, CP_UTF8
);
1681 one
=output
.Tokenize(_T("\n"),pos
);
1682 int start
=one
.Find(_T(" "),0);
1686 name
=one
.Right(one
.GetLength()-start
-1);
1689 hash
=one
.Left(start
);
1691 map
[CGitHash(hash
)].push_back(name
);
1699 static void SetLibGit2SearchPath(int level
, const CString
&value
)
1701 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1702 git_libgit2_opts(GIT_OPT_SET_SEARCH_PATH
, level
, valueA
);
1705 static void SetLibGit2TemplatePath(const CString
&value
)
1707 CStringA valueA
= CUnicodeUtils::GetMulti(value
, CP_UTF8
);
1708 git_libgit2_opts(GIT_OPT_SET_TEMPLATE_PATH
, valueA
);
1711 BOOL
CGit::CheckMsysGitDir(BOOL bFallback
)
1718 this->m_Environment
.clear();
1719 m_Environment
.CopyProcessEnvironment();
1722 size_t homesize
,size
;
1724 // set HOME if not set already
1725 _tgetenv_s(&homesize
, NULL
, 0, _T("HOME"));
1728 CString home
= GetHomeDirectory();
1729 m_Environment
.SetEnv(_T("HOME"), home
);
1734 CString sshclient
=CRegString(_T("Software\\TortoiseGit\\SSH"));
1735 if (sshclient
.IsEmpty())
1736 sshclient
= CRegString(_T("Software\\TortoiseGit\\SSH"), _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1738 if(!sshclient
.IsEmpty())
1740 m_Environment
.SetEnv(_T("GIT_SSH"), sshclient
);
1741 m_Environment
.SetEnv(_T("SVN_SSH"), sshclient
);
1745 TCHAR sPlink
[MAX_PATH
] = {0};
1746 GetModuleFileName(NULL
, sPlink
, _countof(sPlink
));
1747 LPTSTR ptr
= _tcsrchr(sPlink
, _T('\\'));
1749 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sPlink
+ 1), _T("TortoiseGitPLink.exe"));
1750 m_Environment
.SetEnv(_T("GIT_SSH"), sPlink
);
1751 m_Environment
.SetEnv(_T("SVN_SSH"), sPlink
);
1756 TCHAR sAskPass
[MAX_PATH
] = {0};
1757 GetModuleFileName(NULL
, sAskPass
, _countof(sAskPass
));
1758 LPTSTR ptr
= _tcsrchr(sAskPass
, _T('\\'));
1761 _tcscpy_s(ptr
+ 1, MAX_PATH
- (ptr
- sAskPass
+ 1), _T("SshAskPass.exe"));
1762 m_Environment
.SetEnv(_T("DISPLAY"),_T(":9999"));
1763 m_Environment
.SetEnv(_T("SSH_ASKPASS"),sAskPass
);
1764 m_Environment
.SetEnv(_T("GIT_ASKPASS"),sAskPass
);
1768 // add git/bin path to PATH
1770 CRegString msysdir
=CRegString(REG_MSYSGIT_PATH
,_T(""),FALSE
);
1772 if(str
.IsEmpty() || !FileExists(str
+ _T("\\git.exe")))
1777 CRegString msyslocalinstalldir
= CRegString(REG_MSYSGIT_INSTALL_LOCAL
, _T(""), FALSE
, HKEY_CURRENT_USER
);
1778 str
= msyslocalinstalldir
;
1779 str
.TrimRight(_T("\\"));
1782 CRegString msysinstalldir
= CRegString(REG_MSYSGIT_INSTALL
, _T(""), FALSE
, HKEY_LOCAL_MACHINE
);
1783 str
= msysinstalldir
;
1784 str
.TrimRight(_T("\\"));
1786 if ( !str
.IsEmpty() )
1790 CGit::ms_LastMsysGitDir
= str
;
1795 // search PATH if git/bin directory is already present
1796 if ( FindGitPath() )
1798 m_bInitialized
= TRUE
;
1799 msysdir
= CGit::ms_LastMsysGitDir
;
1809 CGit::ms_LastMsysGitDir
= str
;
1812 // check for git.exe existance (maybe it was deinstalled in the meantime)
1813 if (!FileExists(CGit::ms_LastMsysGitDir
+ _T("\\git.exe")))
1816 // Configure libgit2 search paths
1818 PathCanonicalize(msysGitDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\etc"));
1819 msysGitDir
.ReleaseBuffer();
1820 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_SYSTEM
, msysGitDir
);
1821 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_GLOBAL
, g_Git
.GetHomeDirectory());
1822 SetLibGit2SearchPath(GIT_CONFIG_LEVEL_XDG
, g_Git
.GetGitGlobalXDGConfigPath());
1823 CString msysGitTemplateDir
;
1824 PathCanonicalize(msysGitTemplateDir
.GetBufferSetLength(MAX_PATH
), CGit::ms_LastMsysGitDir
+ _T("\\..\\share\\git-core\\templates"));
1825 msysGitTemplateDir
.ReleaseBuffer();
1826 SetLibGit2TemplatePath(msysGitTemplateDir
);
1829 _tdupenv_s(&oldpath
,&size
,_T("PATH"));
1832 path
.Format(_T("%s;%s"),oldpath
,str
+ _T(";")+ (CString
)CRegString(REG_MSYSGIT_EXTRA_PATH
,_T(""),FALSE
));
1834 m_Environment
.SetEnv(_T("PATH"), path
);
1836 CString str1
= m_Environment
.GetEnv(_T("PATH"));
1838 CString sOldPath
= oldpath
;
1841 m_bInitialized
= TRUE
;
1845 CString
CGit::GetHomeDirectory()
1847 const wchar_t * homeDir
= wget_windows_home_directory();
1848 return CString(homeDir
, (int)wcslen(homeDir
));
1851 CString
CGit::GetGitLocalConfig()
1854 g_GitAdminDir
.GetAdminDirPath(m_CurrentDir
, path
);
1855 path
+= _T("config");
1859 CStringA
CGit::GetGitPathStringA(const CString
&path
)
1861 return CUnicodeUtils::GetUTF8(CTGitPath(path
).GetGitPathString());
1864 CString
CGit::GetGitGlobalConfig()
1866 return g_Git
.GetHomeDirectory() + _T("\\.gitconfig");
1869 CString
CGit::GetGitGlobalXDGConfigPath()
1871 return g_Git
.GetHomeDirectory() + _T("\\.config\\git");
1874 CString
CGit::GetGitGlobalXDGConfig()
1876 return g_Git
.GetGitGlobalXDGConfigPath() + _T("\\config");
1879 CString
CGit::GetGitSystemConfig()
1881 const wchar_t * systemConfig
= wget_msysgit_etc();
1882 return CString(systemConfig
, (int)wcslen(systemConfig
));
1885 BOOL
CGit::CheckCleanWorkTree()
1889 cmd
=_T("git.exe rev-parse --verify HEAD");
1891 if(Run(cmd
,&out
,CP_UTF8
))
1894 cmd
=_T("git.exe update-index --ignore-submodules --refresh");
1895 if(Run(cmd
,&out
,CP_UTF8
))
1898 cmd
=_T("git.exe diff-files --quiet --ignore-submodules");
1899 if(Run(cmd
,&out
,CP_UTF8
))
1902 cmd
= _T("git.exe diff-index --cached --quiet HEAD --ignore-submodules --");
1903 if(Run(cmd
,&out
,CP_UTF8
))
1908 int CGit::Revert(const CString
& commit
, const CTGitPathList
&list
, bool)
1911 for (int i
= 0; i
< list
.GetCount(); ++i
)
1913 ret
= Revert(commit
, (CTGitPath
&)list
[i
]);
1919 int CGit::Revert(const CString
& commit
, const CTGitPath
&path
)
1923 if(path
.m_Action
& CTGitPath::LOGACTIONS_REPLACED
&& !path
.GetGitOldPathString().IsEmpty())
1925 if (CTGitPath(path
.GetGitOldPathString()).IsDirectory())
1928 err
.Format(_T("Cannot revert renaming of \"%s\". A directory with the old name \"%s\" exists."), path
.GetGitPathString(), path
.GetGitOldPathString());
1929 ::MessageBox(NULL
, err
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1933 // if the filenames only differ in case, we have to pass "-f"
1934 if (path
.GetGitPathString().CompareNoCase(path
.GetGitOldPathString()) == 0)
1936 cmd
.Format(_T("git.exe mv %s-- \"%s\" \"%s\""), force
, path
.GetGitPathString(), path
.GetGitOldPathString());
1937 if (Run(cmd
, &out
, CP_UTF8
))
1939 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1943 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitOldPathString());
1944 if (Run(cmd
, &out
, CP_UTF8
))
1946 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1951 else if(path
.m_Action
& CTGitPath::LOGACTIONS_ADDED
)
1952 { //To init git repository, there are not HEAD, so we can use git reset command
1953 cmd
.Format(_T("git.exe rm -f --cached -- \"%s\""),path
.GetGitPathString());
1955 if (Run(cmd
, &out
, CP_UTF8
))
1957 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1963 cmd
.Format(_T("git.exe checkout %s -f -- \"%s\""), commit
, path
.GetGitPathString());
1964 if (Run(cmd
, &out
, CP_UTF8
))
1966 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1971 if (path
.m_Action
& CTGitPath::LOGACTIONS_DELETED
)
1973 cmd
.Format(_T("git.exe add -f -- \"%s\""), path
.GetGitPathString());
1974 if (Run(cmd
, &out
, CP_UTF8
))
1976 ::MessageBox(NULL
, out
, _T("TortoiseGit"), MB_OK
|MB_ICONERROR
);
1984 int CGit::ListConflictFile(CTGitPathList
&list
, const CTGitPath
*path
)
1990 cmd
.Format(_T("git.exe ls-files -u -t -z -- \"%s\""),path
->GetGitPathString());
1992 cmd
=_T("git.exe ls-files -u -t -z");
1994 if (Run(cmd
, &vector
))
1999 if (list
.ParserFromLsFile(vector
))
2005 bool CGit::IsFastForward(const CString
&from
, const CString
&to
, CGitHash
* commonAncestor
)
2008 CGitHash basehash
,hash
;
2010 cmd
.Format(_T("git.exe merge-base %s %s"), FixBranchName(to
), FixBranchName(from
));
2012 if (Run(cmd
, &base
, &err
, CP_UTF8
))
2016 basehash
= base
.Trim();
2018 GetHash(hash
, from
);
2021 *commonAncestor
= basehash
;
2023 return hash
== basehash
;
2026 unsigned int CGit::Hash2int(const CGitHash
&hash
)
2029 for (int i
= 0; i
< 4; ++i
)
2032 ret
|= hash
.m_hash
[i
];
2037 int CGit::RefreshGitIndex()
2039 if(g_Git
.m_IsUseGitDLL
)
2041 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2044 return [] { return git_run_cmd("update-index","update-index -q --refresh"); }();
2055 cmd
=_T("git.exe update-index --refresh");
2056 return Run(cmd
, &output
, CP_UTF8
);
2060 int CGit::GetOneFile(const CString
&Refname
, const CTGitPath
&path
, const CString
&outputfile
)
2062 if(g_Git
.m_IsUseGitDLL
)
2064 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2067 g_Git
.CheckAndInitDll();
2068 CStringA ref
, patha
, outa
;
2069 ref
= CUnicodeUtils::GetMulti(Refname
, CP_UTF8
);
2070 patha
= CUnicodeUtils::GetMulti(path
.GetGitPathString(), CP_UTF8
);
2071 outa
= CUnicodeUtils::GetMulti(outputfile
, CP_UTF8
);
2072 ::DeleteFile(outputfile
);
2073 return git_checkout_file(ref
, patha
, outa
);
2083 cmd
.Format(_T("git.exe cat-file -p %s:\"%s\""), Refname
, path
.GetGitPathString());
2084 return RunLogFile(cmd
, outputfile
, &gitLastErr
);
2087 void CEnvironment::CopyProcessEnvironment()
2089 TCHAR
*porig
= GetEnvironmentStrings();
2091 while(*p
!=0 || *(p
+1) !=0)
2092 this->push_back(*p
++);
2094 push_back(_T('\0'));
2095 push_back(_T('\0'));
2097 FreeEnvironmentStrings(porig
);
2100 CString
CEnvironment::GetEnv(const TCHAR
*name
)
2103 for (size_t i
= 0; i
< size(); ++i
)
2107 CString sname
= str
.Tokenize(_T("="),start
);
2108 if(sname
.CompareNoCase(name
) == 0)
2110 return &(*this)[i
+start
];
2117 void CEnvironment::SetEnv(const TCHAR
*name
, const TCHAR
* value
)
2120 for (i
= 0; i
< size(); ++i
)
2122 CString str
= &(*this)[i
];
2124 CString sname
= str
.Tokenize(_T("="),start
);
2125 if(sname
.CompareNoCase(name
) == 0)
2134 i
-= 1; // roll back terminate \0\0
2135 this->push_back(_T('\0'));
2138 CEnvironment::iterator it
;
2142 while(*it
&& i
<size())
2151 this->insert(it
,*name
++);
2156 this->insert(it
, _T('='));
2162 this->insert(it
,*value
++);
2169 int CGit::GetGitEncode(TCHAR
* configkey
)
2171 CString str
=GetConfigValue(configkey
);
2176 return CUnicodeUtils::GetCPCode(str
);
2180 int CGit::GetDiffPath(CTGitPathList
*PathList
, CGitHash
*hash1
, CGitHash
*hash2
, char *arg
)
2186 CAutoLocker
lock(g_Git
.m_critGitDllSec
);
2189 diff
= GetGitDiff();
2191 git_open_diff(&diff
, arg
);
2200 isStat
= !!strstr(arg
, "stat");
2205 ret
= git_root_diff(diff
, hash1
->m_hash
, &file
, &count
,isStat
);
2207 ret
= git_do_diff(diff
,hash2
->m_hash
,hash1
->m_hash
,&file
,&count
,isStat
);
2216 for (int j
= 0; j
< count
; ++j
)
2225 int mode
=0,IsBin
=0,inc
=0,dec
=0;
2226 git_get_diff_file(diff
,file
,j
,&newname
,&oldname
,
2227 &mode
,&IsBin
,&inc
,&dec
);
2229 StringAppend(&strnewname
, (BYTE
*)newname
, CP_UTF8
);
2230 StringAppend(&stroldname
, (BYTE
*)oldname
, CP_UTF8
);
2232 path
.SetFromGit(strnewname
,&stroldname
);
2233 path
.ParserAction((BYTE
)mode
);
2237 path
.m_StatAdd
=_T("-");
2238 path
.m_StatDel
=_T("-");
2242 path
.m_StatAdd
.Format(_T("%d"),inc
);
2243 path
.m_StatDel
.Format(_T("%d"),dec
);
2245 PathList
->AddPath(path
);
2247 git_diff_flush(diff
);
2250 git_close_diff(diff
);
2255 int CGit::GetShortHASHLength()
2260 CString
CGit::GetShortName(const CString
& ref
, REF_TYPE
*out_type
)
2264 REF_TYPE type
= CGit::UNKNOWN
;
2266 if (CGit::GetShortName(str
, shortname
, _T("refs/heads/")))
2268 type
= CGit::LOCAL_BRANCH
;
2271 else if (CGit::GetShortName(str
, shortname
, _T("refs/remotes/")))
2273 type
= CGit::REMOTE_BRANCH
;
2275 else if (CGit::GetShortName(str
, shortname
, _T("refs/tags/")))
2279 else if (CGit::GetShortName(str
, shortname
, _T("refs/stash")))
2282 shortname
=_T("stash");
2284 else if (CGit::GetShortName(str
, shortname
, _T("refs/bisect/")))
2286 if (shortname
.Find(_T("good")) == 0)
2288 type
= CGit::BISECT_GOOD
;
2289 shortname
= _T("good");
2292 if (shortname
.Find(_T("bad")) == 0)
2294 type
= CGit::BISECT_BAD
;
2295 shortname
= _T("bad");
2298 else if (CGit::GetShortName(str
, shortname
, _T("refs/notes/")))
2302 else if (CGit::GetShortName(str
, shortname
, _T("refs/")))
2304 type
= CGit::UNKNOWN
;
2308 type
= CGit::UNKNOWN
;
2318 bool CGit::UsingLibGit2(int cmd
)
2320 if (cmd
>= 0 && cmd
< 32)
2321 return ((1 << cmd
) & m_IsUseLibGit2_mask
) ? true : false;
2325 CString
CGit::GetUnifiedDiffCmd(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, bool bMerge
, bool bCombine
, int diffContext
)
2328 if (rev2
== GitRev::GetWorkingCopy())
2329 cmd
.Format(_T("git.exe diff --stat -p %s --"), rev1
);
2330 else if (rev1
== GitRev::GetWorkingCopy())
2331 cmd
.Format(_T("git.exe diff -R --stat -p %s --"), rev2
);
2342 if (diffContext
> 0)
2343 unified
.Format(_T(" --unified=%d"), diffContext
);
2344 cmd
.Format(_T("git.exe diff-tree -r -p %s %s --stat %s %s --"), merge
, unified
, rev1
, rev2
);
2347 if (!path
.IsEmpty())
2350 cmd
+= path
.GetGitPathString();
2357 static int UnifiedDiffToFile(const git_diff_delta
* /* delta */, const git_diff_hunk
* /* hunk */, const git_diff_line
* line
, void *payload
)
2359 ATLASSERT(payload
&& line
);
2360 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2361 fwrite(&line
->origin
, 1, 1, (FILE *)payload
);
2362 fwrite(line
->content
, 1, line
->content_len
, (FILE *)payload
);
2366 static int resolve_to_tree(git_repository
*repo
, const char *identifier
, git_tree
**tree
)
2368 ATLASSERT(repo
&& identifier
&& tree
);
2370 /* try to resolve identifier */
2371 git_object
*obj
= nullptr;
2372 if (git_revparse_single(&obj
, repo
, identifier
))
2376 return GIT_ENOTFOUND
;
2379 switch (git_object_type(obj
))
2382 *tree
= (git_tree
*)obj
;
2384 case GIT_OBJ_COMMIT
:
2385 err
= git_commit_tree(tree
, (git_commit
*)obj
);
2386 git_object_free(obj
);
2389 err
= GIT_ENOTFOUND
;
2395 /* use libgit2 get unified diff */
2396 static int GetUnifiedDiffLibGit2(const CTGitPath
& /*path*/, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, git_diff_line_cb callback
, void *data
, bool /* bMerge */)
2398 git_repository
*repo
= nullptr;
2399 CStringA gitdirA
= CUnicodeUtils::GetMulti(CTGitPath(g_Git
.m_CurrentDir
).GetGitPathString(), CP_UTF8
);
2400 CStringA tree1
= CUnicodeUtils::GetMulti(rev1
, CP_UTF8
);
2401 CStringA tree2
= CUnicodeUtils::GetMulti(rev2
, CP_UTF8
);
2404 if (git_repository_open(&repo
, gitdirA
))
2407 int isHeadOrphan
= git_repository_head_unborn(repo
);
2408 if (isHeadOrphan
!= 0)
2410 git_repository_free(repo
);
2411 if (isHeadOrphan
== 1)
2417 git_diff_options opts
= GIT_DIFF_OPTIONS_INIT
;
2418 git_diff
*diff
= nullptr;
2420 if (rev1
== GitRev::GetWorkingCopy() || rev2
== GitRev::GetWorkingCopy())
2422 git_tree
*t1
= nullptr;
2423 git_diff
*diff2
= nullptr;
2427 if (rev1
!= GitRev::GetWorkingCopy())
2429 if (resolve_to_tree(repo
, tree1
, &t1
))
2435 if (rev2
!= GitRev::GetWorkingCopy())
2437 if (resolve_to_tree(repo
, tree2
, &t1
))
2444 ret
= git_diff_tree_to_index(&diff
, repo
, t1
, nullptr, &opts
);
2448 ret
= git_diff_index_to_workdir(&diff2
, repo
, nullptr, &opts
);
2452 ret
= git_diff_merge(diff
, diff2
);
2456 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2459 if (git_patch_from_diff(&patch
, diff
, i
))
2465 if (git_patch_print(patch
, callback
, data
))
2467 git_patch_free(patch
);
2472 git_patch_free(patch
);
2476 git_diff_free(diff
);
2478 git_diff_free(diff2
);
2484 git_tree
*t1
= nullptr, *t2
= nullptr;
2487 if (tree1
.IsEmpty() && tree2
.IsEmpty())
2493 if (tree1
.IsEmpty())
2499 if (!tree1
.IsEmpty() && resolve_to_tree(repo
, tree1
, &t1
))
2505 if (tree2
.IsEmpty())
2507 /* don't check return value, there are not parent commit at first commit*/
2508 resolve_to_tree(repo
, tree1
+ "~1", &t2
);
2510 else if (resolve_to_tree(repo
, tree2
, &t2
))
2515 if (git_diff_tree_to_tree(&diff
, repo
, t2
, t1
, &opts
))
2521 for (size_t i
= 0; i
< git_diff_num_deltas(diff
); ++i
)
2524 if (git_patch_from_diff(&patch
, diff
, i
))
2530 if (git_patch_print(patch
, callback
, data
))
2532 git_patch_free(patch
);
2537 git_patch_free(patch
);
2542 git_diff_free(diff
);
2548 git_repository_free(repo
);
2553 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CString patchfile
, bool bMerge
, bool bCombine
, int diffContext
)
2555 if (UsingLibGit2(GIT_CMD_DIFF
))
2557 FILE *file
= nullptr;
2558 _tfopen_s(&file
, patchfile
, _T("w"));
2559 if (file
== nullptr)
2561 int ret
= GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToFile
, file
, bMerge
);
2568 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2569 return g_Git
.RunLogFile(cmd
, patchfile
, &gitLastErr
);
2573 static int UnifiedDiffToStringA(const git_diff_delta
* /*delta*/, const git_diff_hunk
* /*hunk*/, const git_diff_line
*line
, void *payload
)
2575 ATLASSERT(payload
&& line
);
2576 CStringA
*str
= (CStringA
*) payload
;
2577 if (line
->origin
== GIT_DIFF_LINE_CONTEXT
|| line
->origin
== GIT_DIFF_LINE_ADDITION
|| line
->origin
== GIT_DIFF_LINE_DELETION
)
2578 str
->Append(&line
->origin
, 1);
2579 str
->Append(line
->content
, (int)line
->content_len
);
2583 int CGit::GetUnifiedDiff(const CTGitPath
& path
, const git_revnum_t
& rev1
, const git_revnum_t
& rev2
, CStringA
* buffer
, bool bMerge
, bool bCombine
, int diffContext
)
2585 if (UsingLibGit2(GIT_CMD_DIFF
))
2586 return GetUnifiedDiffLibGit2(path
, rev1
, rev2
, UnifiedDiffToStringA
, buffer
, bMerge
);
2590 cmd
= GetUnifiedDiffCmd(path
, rev1
, rev2
, bMerge
, bCombine
, diffContext
);
2592 int ret
= Run(cmd
, &vector
);
2593 if (!vector
.empty())
2594 buffer
->Append((char *)&vector
[0]);
2599 int CGit::GitRevert(int parent
, const CGitHash
&hash
)
2601 if (UsingLibGit2(GIT_CMD_REVERT
))
2603 git_repository
*repo
= nullptr;
2604 CStringA gitdirA
= CUnicodeUtils::GetUTF8(CTGitPath(m_CurrentDir
).GetGitPathString());
2605 if (git_repository_open(&repo
, gitdirA
))
2608 git_commit
*commit
= nullptr;
2609 if (git_commit_lookup(&commit
, repo
, (const git_oid
*)hash
.m_hash
))
2611 git_repository_free(repo
);
2615 git_revert_opts revert_opts
= GIT_REVERT_OPTS_INIT
;
2616 revert_opts
.mainline
= parent
;
2617 int result
= git_revert(repo
, commit
, &revert_opts
);
2619 git_commit_free(commit
);
2620 git_repository_free(repo
);
2621 return !result
? 0 : -1;
2625 CString cmd
, merge
, gitLastErr
;
2627 merge
.Format(_T("-m %d "), parent
);
2628 cmd
.Format(_T("git.exe revert --no-edit --no-commit %s%s"), merge
, hash
.ToString());
2629 gitLastErr
= cmd
+ _T("\n");
2630 if (g_Git
.Run(cmd
, &gitLastErr
, CP_UTF8
))