Avoid creation of intermediates
[TortoiseGit.git] / src / Git / Git.h
blobeb18a0906a0b60e75f5a2c1dd8614afa9931e641
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2016 - 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.
20 #pragma once
21 #include "GitType.h"
22 #include "GitRev.h"
23 #include "GitStatus.h"
24 #include "GitAdminDir.h"
25 #include "gitdll.h"
26 #include <functional>
27 #include "StringUtils.h"
29 #define REG_MSYSGIT_PATH _T("Software\\TortoiseGit\\MSysGit")
30 #define REG_SYSTEM_GITCONFIGPATH _T("Software\\TortoiseGit\\SystemConfig")
31 #define REG_MSYSGIT_EXTRA_PATH _T("Software\\TortoiseGit\\MSysGitExtra")
33 #define DEFAULT_USE_LIBGIT2_MASK (1 << CGit::GIT_CMD_MERGE_BASE) | (1 << CGit::GIT_CMD_DELETETAGBRANCH) | (1 << CGit::GIT_CMD_GETONEFILE) | (1 << CGit::GIT_CMD_ADD) | (1 << CGit::GIT_CMD_CHECKCONFLICTS) | (1 << CGit::GIT_CMD_GET_COMMIT)
35 struct git_repository;
37 class CFilterData
39 public:
41 enum
43 SHOW_NO_LIMIT, // NOTE: no limitation does not mean "without all limitations", it's just without the following limitations. That say, the log still could be limited by auther, committer, etc.
44 SHOW_LAST_SEL_DATE,
45 SHOW_LAST_N_COMMITS,
46 SHOW_LAST_N_YEARS,
47 SHOW_LAST_N_MONTHS,
48 SHOW_LAST_N_WEEKS,
51 CFilterData()
53 m_From=m_To=-1;
54 m_IsRegex=1;
55 m_NumberOfLogsScale = SHOW_NO_LIMIT;
56 m_NumberOfLogs = 1;
59 DWORD m_NumberOfLogsScale;
60 DWORD m_NumberOfLogs;
61 __time64_t m_From;
62 __time64_t m_To;
63 CString m_Author;
64 CString m_Committer;
65 CString m_MessageFilter;
66 BOOL m_IsRegex;
69 class CGitCall
71 public:
72 CGitCall(){}
73 CGitCall(CString cmd):m_Cmd(cmd){}
74 virtual ~CGitCall() {}
76 CString GetCmd()const{return m_Cmd;}
77 void SetCmd(CString cmd){m_Cmd=cmd;}
79 //This function is called when command output data is available.
80 //When this function returns 'true' the git command should be aborted.
81 //This behavior is not implemented yet.
82 virtual bool OnOutputData(const BYTE* data, size_t size)=0;
83 virtual bool OnOutputErrData(const BYTE* data, size_t size)=0;
84 virtual void OnEnd(){}
86 private:
87 CString m_Cmd;
90 typedef std::function<void (const CStringA&)> GitReceiverFunc;
92 class CTGitPath;
93 class CEnvironment : protected std::vector<TCHAR>
95 public:
96 CEnvironment() : baseptr(nullptr) {}
97 CEnvironment(const CEnvironment& env) : std::vector<TCHAR>(env)
99 baseptr = &__super::at(0);
101 CEnvironment& operator =(const CEnvironment& env)
103 __super::operator=(env);
104 if (empty())
105 baseptr = nullptr;
106 else
107 baseptr = &__super::at(0);
108 return *this;
110 void CopyProcessEnvironment();
111 CString GetEnv(const TCHAR *name);
112 void SetEnv(const TCHAR* name, const TCHAR* value);
113 void AddToPath(CString value);
114 void clear();
115 bool empty();
116 operator LPTSTR();
117 operator LPWSTR*();
118 LPWSTR baseptr;
119 CEnvironment(CEnvironment&& env) = delete;
120 CEnvironment& operator =(CEnvironment&& env) = delete;
122 class CGit
124 private:
125 CString gitLastErr;
126 protected:
127 GIT_DIFF m_GitDiff;
128 GIT_DIFF m_GitSimpleListDiff;
129 #ifdef GTEST_INCLUDE_GTEST_GTEST_H_
130 public:
131 #endif
132 bool m_IsGitDllInited;
133 public:
134 CComCriticalSection m_critGitDllSec;
135 bool m_IsUseGitDLL;
136 bool m_IsUseLibGit2;
137 DWORD m_IsUseLibGit2_mask;
139 CEnvironment m_Environment;
141 static BOOL GitPathFileExists(const CString &path)
143 if(path[0] == _T('\\') && path[1] == _T('\\'))
144 //it is netshare \\server\sharefoldername
145 // \\server\.git will create smb error log.
147 int length = path.GetLength();
149 if(length<2)
150 return false;
152 int start = path.Find(_T('\\'),2);
153 if(start<0)
154 return false;
156 start = path.Find(_T('\\'),start+1);
157 if(start<0)
158 return false;
160 return PathFileExists(path);
163 else
164 return PathFileExists(path);
166 void CheckAndInitDll()
168 if(!m_IsGitDllInited)
170 git_init();
171 m_IsGitDllInited=true;
175 GIT_DIFF GetGitDiff()
177 if(m_GitDiff)
178 return m_GitDiff;
179 else
181 git_open_diff(&m_GitDiff,"-C -M -r");
182 return m_GitDiff;
186 GIT_DIFF GetGitSimpleListDiff()
188 if(m_GitSimpleListDiff)
189 return m_GitSimpleListDiff;
190 else
192 git_open_diff(&m_GitSimpleListDiff,"-r -r");
193 return m_GitSimpleListDiff;
197 BOOL CheckMsysGitDir(BOOL bFallback = TRUE);
198 BOOL FindAndSetGitExePath(BOOL bFallback);
199 BOOL m_bInitialized;
201 typedef enum
203 GIT_CMD_CLONE,
204 GIT_CMD_FETCH,
205 GIT_CMD_COMMIT_UPDATE_INDEX,
206 GIT_CMD_DIFF,
207 GIT_CMD_RESET,
208 GIT_CMD_REVERT,
209 GIT_CMD_MERGE_BASE,
210 GIT_CMD_DELETETAGBRANCH,
211 GIT_CMD_GETONEFILE,
212 GIT_CMD_ADD,
213 GIT_CMD_PUSH,
214 GIT_CMD_CHECK_CLEAN_WT,
215 GIT_CMD_CHECKCONFLICTS,
216 GIT_CMD_GET_COMMIT,
217 GIT_CMD_LOGLISTDIFF,
218 } LIBGIT2_CMD;
219 bool UsingLibGit2(LIBGIT2_CMD cmd) const;
221 * callback type should be git_cred_acquire_cb
223 static void SetGit2CredentialCallback(void* callback);
224 static void SetGit2CertificateCheckCertificate(void* callback);
226 CString GetHomeDirectory() const;
227 CString GetGitLocalConfig() const;
228 CString GetGitGlobalConfig() const;
229 CString GetGitGlobalXDGConfigPath() const;
230 CString GetGitGlobalXDGConfig() const;
231 CString GetGitSystemConfig() const;
232 CString GetGitProgramDataConfig() const;
233 CAutoRepository GetGitRepository() const;
234 static CStringA GetGitPathStringA(const CString &path);
235 static CString ms_LastMsysGitDir; // the last msysgitdir added to the path, blank if none
236 static CString ms_MsysGitRootDir;
237 static int ms_LastMsysGitVersion;
238 static bool ms_bCygwinGit;
239 static bool ms_bMsys2Git;
240 static int m_LogEncode;
241 static bool IsBranchNameValid(const CString& branchname);
242 bool IsBranchTagNameUnique(const CString& name);
244 * Checks if a branch or tag with the given name exists
245 *isBranch is true -> branch, tag otherwise
247 bool BranchTagExists(const CString& name, bool isBranch = true);
248 unsigned int Hash2int(const CGitHash &hash);
250 PROCESS_INFORMATION m_CurrentGitPi;
252 CGit(void);
253 ~CGit(void);
255 int Run(CString cmd, CString* output, int code);
256 int Run(CString cmd, CString* output, CString* outputErr, int code);
257 int Run(CString cmd, BYTE_VECTOR* byte_array, BYTE_VECTOR* byte_arrayErr = nullptr);
258 int Run(CGitCall* pcall);
259 int Run(CString cmd, const GitReceiverFunc& recv, CString* outputErr = nullptr);
261 private:
262 CComCriticalSection m_critSecThreadMap;
263 std::map<DWORD, HANDLE> m_AsyncReadStdErrThreadMap;
264 static DWORD WINAPI AsyncReadStdErrThread(LPVOID lpParam);
265 typedef struct AsyncReadStdErrThreadArguments
267 HANDLE fileHandle;
268 CGitCall* pcall;
269 } ASYNCREADSTDERRTHREADARGS, *PASYNCREADSTDERRTHREADARGS;
270 CString GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix = false);
272 public:
273 #ifdef _MFC_VER
274 void KillRelatedThreads(CWinThread* thread);
275 #endif
276 int RunAsync(CString cmd, PROCESS_INFORMATION* pi, HANDLE* hRead, HANDLE* hErrReadOut, CString* StdioFile = nullptr);
277 int RunLogFile(CString cmd, const CString &filename, CString *stdErr);
279 int GetDiffPath(CTGitPathList* PathList, CGitHash* hash1, CGitHash* hash2, char* arg = nullptr);
281 int GetGitEncode(TCHAR* configkey);
283 bool IsFastForward(const CString& from, const CString& to, CGitHash* commonAncestor = nullptr);
284 CString GetConfigValue(const CString& name, const CString& def = CString(), bool wantBool = false);
285 bool GetConfigValueBool(const CString& name, const bool def = false);
286 int GetConfigValueInt32(const CString& name, const int def = 0);
288 int SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type = CONFIG_LOCAL);
289 int UnsetConfigValue(const CString& key, CONFIG_TYPE type = CONFIG_LOCAL);
291 CString GetUserName(void);
292 CString GetUserEmail(void);
293 CString GetCurrentBranch(bool fallback = false);
294 void GetRemoteTrackedBranch(const CString& localBranch, CString& remote, CString& branch);
295 void GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch);
296 void GetRemotePushBranch(const CString& localBranch, CString& pushRemote, CString& pushBranch);
297 // read current branch name from HEAD file, returns 0 on success, -1 on failure, 1 detached (branch name "HEAD" returned)
298 static int GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback = false);
300 Use this method only when the HEAD is exist.
302 BOOL CheckCleanWorkTree(bool stagedOk = false);
303 int Revert(const CString& commit, const CTGitPathList &list, CString& err);
304 int Revert(const CString& commit, const CTGitPath &path, CString& err);
305 int DeleteRef(const CString& reference);
307 Use this method only if m_IsUseLibGit2 is used for fallbacks.
308 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
310 CString GetGitLastErr(const CString& msg);
311 CString GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd);
312 static CString GetLibGit2LastErr();
313 static CString GetLibGit2LastErr(const CString& msg);
314 bool SetCurrentDir(CString path, bool submodule = false)
316 bool b = GitAdminDir::HasAdminDir(path, submodule ? false : !!PathIsDirectory(path), &m_CurrentDir);
317 if (!b && GitAdminDir::IsBareRepo(path))
319 m_CurrentDir = path;
320 b = true;
322 if(m_CurrentDir.GetLength() == 2 && m_CurrentDir[1] == _T(':')) //C: D:
323 m_CurrentDir += _T('\\');
324 return b;
326 CString m_CurrentDir;
328 enum
330 LOG_ORDER_CHRONOLOGIALREVERSED,
331 LOG_ORDER_TOPOORDER,
332 LOG_ORDER_DATEORDER,
335 typedef enum
337 BRANCH_LOCAL = 0x1,
338 BRANCH_REMOTE = 0x2,
339 BRANCH_FETCH_HEAD = 0x4,
340 BRANCH_LOCAL_F = BRANCH_LOCAL | BRANCH_FETCH_HEAD,
341 BRANCH_ALL = BRANCH_LOCAL | BRANCH_REMOTE,
342 BRANCH_ALL_F = BRANCH_ALL | BRANCH_FETCH_HEAD,
343 }BRANCH_TYPE;
345 typedef enum
347 LOG_INFO_STAT=0x1,
348 LOG_INFO_FILESTATE=0x2,
349 LOG_INFO_PATCH=0x4,
350 LOG_INFO_FULLHISTORY=0x8,
351 LOG_INFO_BOUNDARY=0x10,
352 LOG_INFO_ALL_BRANCH=0x20,
353 LOG_INFO_ONLY_HASH=0x40,
354 LOG_INFO_DETECT_RENAME=0x80,
355 LOG_INFO_DETECT_COPYRENAME=0x100,
356 LOG_INFO_FIRST_PARENT = 0x200,
357 LOG_INFO_NO_MERGE = 0x400,
358 LOG_INFO_FOLLOW = 0x800,
359 LOG_INFO_SHOW_MERGEDFILE=0x1000,
360 LOG_INFO_FULL_DIFF = 0x2000,
361 LOG_INFO_SIMPILFY_BY_DECORATION = 0x4000,
362 LOG_INFO_LOCAL_BRANCHES = 0x8000,
363 LOG_INFO_BASIC_REFS = 0x10000,
364 }LOG_INFO_MASK;
366 typedef enum
368 LOCAL_BRANCH,
369 REMOTE_BRANCH,
370 ANNOTATED_TAG,
371 TAG,
372 STASH,
373 BISECT_GOOD,
374 BISECT_BAD,
375 NOTES,
376 UNKNOWN,
378 }REF_TYPE;
380 int GetRemoteList(STRING_VECTOR &list);
381 int GetBranchList(STRING_VECTOR &list, int *Current,BRANCH_TYPE type=BRANCH_LOCAL);
382 int GetTagList(STRING_VECTOR &list);
383 int GetRemoteTags(const CString& remote, STRING_VECTOR& list);
384 int DeleteRemoteRefs(const CString& remote, const STRING_VECTOR& list);
385 int GetBranchDescriptions(MAP_STRING_STRING& map);
386 int GetMapHashToFriendName(MAP_HASH_NAME &map);
387 static int GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map);
389 CString DerefFetchHead();
391 // FixBranchName():
392 // When branchName == FETCH_HEAD, derefrence it.
393 // A selected branch name got from GetBranchList(), with flag BRANCH_FETCH_HEAD enabled,
394 // should go through this function before it is used.
395 CString FixBranchName_Mod(CString& branchName);
396 CString FixBranchName(const CString& branchName);
398 CString GetLogCmd(const CString& range, const CTGitPath* path, int InfoMask, CFilterData* filter, int logOrderBy);
400 int GetHash(CGitHash &hash, const CString& friendname);
401 static int GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck = false);
403 int BuildOutputFormat(CString &format,bool IsFull=TRUE);
404 static void StringAppend(CString *str, const BYTE *p, int code = CP_UTF8, int length = -1);
406 BOOL CanParseRev(CString ref);
408 Checks if HEAD points to an unborn branch
409 This method assumes, that we already know that we are in a working tree.
411 BOOL IsInitRepos();
412 /** Returns 0 if no conflict, if a conflict was found and -1 in case of a failure */
413 int HasWorkingTreeConflicts();
414 /** Returns 0 if no conflict, if a conflict was found and -1 in case of a failure */
415 int HasWorkingTreeConflicts(git_repository* repo);
416 int IsRebaseRunning();
417 void GetBisectTerms(CString* good, CString* bad);
418 int GetRefList(STRING_VECTOR &list);
420 int RefreshGitIndex();
421 int GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile);
423 //Example: master -> refs/heads/master
424 CString GetFullRefName(const CString& shortRefName);
425 //Removes 'refs/heads/' or just 'refs'. Example: refs/heads/master -> master
426 static CString StripRefName(CString refName);
428 int GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outpathlist, bool ignoreSpaceAtEol = false, bool ignoreSpaceChange = false, bool ignoreAllSpace = false, bool ignoreBlankLines = false);
429 int GetInitAddList(CTGitPathList &outpathlist);
430 int GetWorkingTreeChanges(CTGitPathList& result, bool amend = false, CTGitPathList* filterlist = nullptr);
432 static __int64 filetime_to_time_t(const FILETIME *ft)
434 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
435 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
436 winTime /= 10000000; /* Nano to seconds resolution */
437 return (time_t)winTime;
440 static int GetFileModifyTime(LPCTSTR filename, __int64* time, bool* isDir = nullptr, __int64* size = nullptr)
442 WIN32_FILE_ATTRIBUTE_DATA fdata;
443 if (GetFileAttributesEx(filename, GetFileExInfoStandard, &fdata))
445 if(time)
446 *time = filetime_to_time_t(&fdata.ftLastWriteTime);
448 if (size)
449 *size = ((__int64)fdata.nFileSizeHigh << 32) + fdata.nFileSizeLow;
451 if(isDir)
452 *isDir = !!( fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
454 return 0;
456 return -1;
459 int GetShortHASHLength() const;
461 static BOOL GetShortName(const CString& ref, CString& shortname, const CString& prefix)
463 //TRACE(_T("%s %s\r\n"),ref,prefix);
464 if (CStringUtils::StartsWith(ref, prefix))
466 shortname = ref.Right(ref.GetLength() - prefix.GetLength());
467 if (shortname.Right(3) == _T("^{}"))
468 shortname.Truncate(shortname.GetLength() - 3);
469 return TRUE;
471 return FALSE;
474 static CString GetShortName(const CString& ref, REF_TYPE *type);
476 static bool LoadTextFile(const CString &filename, CString &msg);
478 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext, bool bNoPrefix = false);
479 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext);
481 int GitRevert(int parent, const CGitHash &hash);
483 int GetGitVersion(CString* versiondebug, CString* errStr);
485 CString CombinePath(const CString &path) const
487 if (path.IsEmpty())
488 return m_CurrentDir;
489 if (m_CurrentDir.IsEmpty())
490 return path;
491 return m_CurrentDir + (m_CurrentDir.Right(1) == _T("\\") ? _T("") : _T("\\")) + path;
494 CString CombinePath(const CTGitPath &path) const
496 return CombinePath(path.GetWinPath());
499 CString CombinePath(const CTGitPath *path) const
501 ATLASSERT(path);
502 return CombinePath(path->GetWinPath());
505 extern void GetTempPath(CString &path);
506 extern CString GetTempFile();
507 extern DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer);
509 extern CGit g_Git;