Do not use GitAdminDir objects
[TortoiseGit.git] / src / Git / Git.h
blob7ea161b0f1cc3c8898e9c5df05b302ad4963d141
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2015 - 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>
28 #define REG_MSYSGIT_PATH _T("Software\\TortoiseGit\\MSysGit")
29 #define REG_MSYSGIT_EXTRA_PATH _T("Software\\TortoiseGit\\MSysGitExtra")
31 struct git_repository;
33 class CFilterData
35 public:
36 CFilterData()
38 m_From=m_To=-1;
39 m_IsRegex=1;
41 __time64_t m_From;
42 __time64_t m_To;
43 CString m_Author;
44 CString m_Committer;
45 CString m_MessageFilter;
46 BOOL m_IsRegex;
49 class CGitCall
51 public:
52 CGitCall(){}
53 CGitCall(CString cmd):m_Cmd(cmd){}
55 CString GetCmd()const{return m_Cmd;}
56 void SetCmd(CString cmd){m_Cmd=cmd;}
58 //This function is called when command output data is available.
59 //When this function returns 'true' the git command should be aborted.
60 //This behavior is not implemented yet.
61 virtual bool OnOutputData(const BYTE* data, size_t size)=0;
62 virtual bool OnOutputErrData(const BYTE* data, size_t size)=0;
63 virtual void OnEnd(){}
65 private:
66 CString m_Cmd;
69 typedef std::function<void (const CStringA&)> GitReceiverFunc;
71 class CTGitPath;
72 class CEnvironment:public std::vector<TCHAR>
74 public:
75 void CopyProcessEnvironment();
76 CString GetEnv(const TCHAR *name);
77 void SetEnv(const TCHAR* name, const TCHAR* value);
79 class CGit
81 private:
82 CString gitLastErr;
83 protected:
84 bool m_IsGitDllInited;
85 GIT_DIFF m_GitDiff;
86 GIT_DIFF m_GitSimpleListDiff;
87 public:
88 CComCriticalSection m_critGitDllSec;
89 bool m_IsUseGitDLL;
90 bool m_IsUseLibGit2;
91 DWORD m_IsUseLibGit2_mask;
93 CEnvironment m_Environment;
95 static BOOL GitPathFileExists(const CString &path)
97 if(path[0] == _T('\\') && path[1] == _T('\\'))
98 //it is netshare \\server\sharefoldername
99 // \\server\.git will create smb error log.
101 int length = path.GetLength();
103 if(length<2)
104 return false;
106 int start = path.Find(_T('\\'),2);
107 if(start<0)
108 return false;
110 start = path.Find(_T('\\'),start+1);
111 if(start<0)
112 return false;
114 return PathFileExists(path);
117 else
118 return PathFileExists(path);
120 void CheckAndInitDll()
122 if(!m_IsGitDllInited)
124 git_init();
125 m_IsGitDllInited=true;
129 GIT_DIFF GetGitDiff()
131 if(m_GitDiff)
132 return m_GitDiff;
133 else
135 git_open_diff(&m_GitDiff,"-C -M -r");
136 return m_GitDiff;
140 GIT_DIFF GetGitSimpleListDiff()
142 if(m_GitSimpleListDiff)
143 return m_GitSimpleListDiff;
144 else
146 git_open_diff(&m_GitSimpleListDiff,"-r -r");
147 return m_GitSimpleListDiff;
151 BOOL CheckMsysGitDir(BOOL bFallback = TRUE);
152 BOOL m_bInitialized;
154 typedef enum
156 GIT_CMD_CLONE,
157 GIT_CMD_FETCH,
158 GIT_CMD_COMMIT_UPDATE_INDEX,
159 GIT_CMD_DIFF,
160 GIT_CMD_RESET,
161 GIT_CMD_REVERT,
162 GIT_CMD_MERGE_BASE,
163 GIT_CMD_DELETETAGBRANCH,
164 GIT_CMD_GETONEFILE,
165 GIT_CMD_ADD,
166 GIT_CMD_PUSH,
167 } LIBGIT2_CMD;
168 bool UsingLibGit2(LIBGIT2_CMD cmd) const;
170 * callback type should be git_cred_acquire_cb
172 static void SetGit2CredentialCallback(void* callback);
173 static void SetGit2CertificateCheckCertificate(void* callback);
175 CString GetHomeDirectory() const;
176 CString GetGitLocalConfig() const;
177 CString GetGitGlobalConfig() const;
178 CString GetGitGlobalXDGConfigPath() const;
179 CString GetGitGlobalXDGConfig() const;
180 CString GetGitSystemConfig() const;
181 git_repository * GetGitRepository() const;
182 static CStringA GetGitPathStringA(const CString &path);
183 static CString ms_LastMsysGitDir; // the last msysgitdir added to the path, blank if none
184 static int ms_LastMsysGitVersion;
185 static bool ms_bCygwinGit;
186 static int m_LogEncode;
187 static bool IsBranchNameValid(const CString& branchname);
188 bool IsBranchTagNameUnique(const CString& name);
190 * Checks if a branch or tag with the given name exists
191 *isBranch is true -> branch, tag otherwise
193 bool BranchTagExists(const CString& name, bool isBranch = true);
194 unsigned int Hash2int(const CGitHash &hash);
196 PROCESS_INFORMATION m_CurrentGitPi;
198 CGit(void);
199 ~CGit(void);
201 int Run(CString cmd, CString* output, int code);
202 int Run(CString cmd, CString* output, CString* outputErr, int code);
203 int Run(CString cmd, BYTE_VECTOR *byte_array, BYTE_VECTOR *byte_arrayErr = NULL);
204 int Run(CGitCall* pcall);
205 int Run(CString cmd, const GitReceiverFunc& recv);
207 private:
208 static DWORD WINAPI AsyncReadStdErrThread(LPVOID lpParam);
209 typedef struct AsyncReadStdErrThreadArguments
211 HANDLE fileHandle;
212 CGitCall* pcall;
213 } ASYNCREADSTDERRTHREADARGS, *PASYNCREADSTDERRTHREADARGS;
214 CString GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext);
216 public:
217 int RunAsync(CString cmd, PROCESS_INFORMATION *pi, HANDLE* hRead, HANDLE *hErrReadOut, CString *StdioFile = NULL);
218 int RunLogFile(CString cmd, const CString &filename, CString *stdErr);
220 int GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg=NULL);
222 int GetGitEncode(TCHAR* configkey);
224 bool IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor = NULL);
225 CString GetConfigValue(const CString& name);
226 bool GetConfigValueBool(const CString& name);
227 int GetConfigValueInt32(const CString& name, int def = 0);
229 int SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type = CONFIG_LOCAL);
230 int UnsetConfigValue(const CString& key, CONFIG_TYPE type = CONFIG_LOCAL);
232 CString GetUserName(void);
233 CString GetUserEmail(void);
234 CString GetCurrentBranch(bool fallback = false);
235 void GetRemoteTrackedBranch(const CString& localBranch, CString& remote, CString& branch);
236 void GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch);
237 // read current branch name from HEAD file, returns 0 on success, -1 on failure, 1 detached (branch name "HEAD" returned)
238 static int GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback = false);
239 BOOL CheckCleanWorkTree(bool stagedOk = false);
240 int Revert(const CString& commit, const CTGitPathList &list, CString& err);
241 int Revert(const CString& commit, const CTGitPath &path, CString& err);
242 int DeleteRef(const CString& reference);
244 Use this method only if m_IsUseLibGit2 is used for fallbacks.
245 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
247 CString GetGitLastErr(const CString& msg);
248 CString GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd);
249 static CString GetLibGit2LastErr();
250 static CString GetLibGit2LastErr(const CString& msg);
251 bool SetCurrentDir(CString path, bool submodule = false)
253 bool b = GitAdminDir::HasAdminDir(path, submodule ? false : !!PathIsDirectory(path), &m_CurrentDir);
254 if (!b && GitAdminDir::IsBareRepo(path))
256 m_CurrentDir = path;
257 b = true;
259 if(m_CurrentDir.GetLength() == 2 && m_CurrentDir[1] == _T(':')) //C: D:
261 m_CurrentDir += _T('\\');
263 return b;
265 CString m_CurrentDir;
267 enum
269 LOG_ORDER_CHRONOLOGIALREVERSED,
270 LOG_ORDER_TOPOORDER,
271 LOG_ORDER_DATEORDER,
274 typedef enum
276 BRANCH_LOCAL = 0x1,
277 BRANCH_REMOTE = 0x2,
278 BRANCH_FETCH_HEAD = 0x4,
279 BRANCH_LOCAL_F = BRANCH_LOCAL | BRANCH_FETCH_HEAD,
280 BRANCH_ALL = BRANCH_LOCAL | BRANCH_REMOTE,
281 BRANCH_ALL_F = BRANCH_ALL | BRANCH_FETCH_HEAD,
282 }BRANCH_TYPE;
284 typedef enum
286 LOG_INFO_STAT=0x1,
287 LOG_INFO_FILESTATE=0x2,
288 LOG_INFO_PATCH=0x4,
289 LOG_INFO_FULLHISTORY=0x8,
290 LOG_INFO_BOUNDARY=0x10,
291 LOG_INFO_ALL_BRANCH=0x20,
292 LOG_INFO_ONLY_HASH=0x40,
293 LOG_INFO_DETECT_RENAME=0x80,
294 LOG_INFO_DETECT_COPYRENAME=0x100,
295 LOG_INFO_FIRST_PARENT = 0x200,
296 LOG_INFO_NO_MERGE = 0x400,
297 LOG_INFO_FOLLOW = 0x800,
298 LOG_INFO_SHOW_MERGEDFILE=0x1000,
299 LOG_INFO_FULL_DIFF = 0x2000,
300 LOG_INFO_SIMPILFY_BY_DECORATION = 0x4000,
301 LOG_INFO_LOCAL_BRANCHES = 0x8000,
302 }LOG_INFO_MASK;
304 typedef enum
306 LOCAL_BRANCH,
307 REMOTE_BRANCH,
308 TAG,
309 STASH,
310 BISECT_GOOD,
311 BISECT_BAD,
312 NOTES,
313 UNKNOWN,
315 }REF_TYPE;
317 int GetRemoteList(STRING_VECTOR &list);
318 int GetBranchList(STRING_VECTOR &list, int *Current,BRANCH_TYPE type=BRANCH_LOCAL);
319 int GetTagList(STRING_VECTOR &list);
320 int GetRemoteTags(const CString& remote, STRING_VECTOR& list);
321 int DeleteRemoteRefs(const CString& remote, const STRING_VECTOR& list);
322 int GetMapHashToFriendName(MAP_HASH_NAME &map);
323 static int GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map);
325 CString DerefFetchHead();
327 // FixBranchName():
328 // When branchName == FETCH_HEAD, derefrence it.
329 // A selected branch name got from GetBranchList(), with flag BRANCH_FETCH_HEAD enabled,
330 // should go through this function before it is used.
331 CString FixBranchName_Mod(CString& branchName);
332 CString FixBranchName(const CString& branchName);
334 CString GetLogCmd(const CString &range, const CTGitPath *path = NULL, int count=-1, int InfoMask = LOG_INFO_FULL_DIFF|LOG_INFO_STAT|LOG_INFO_FILESTATE|LOG_INFO_BOUNDARY|LOG_INFO_DETECT_COPYRENAME|LOG_INFO_SHOW_MERGEDFILE, bool paramonly=false, CFilterData * filter =NULL);
336 int GetHash(CGitHash &hash, const CString& friendname);
337 static int GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck = false);
339 int BuildOutputFormat(CString &format,bool IsFull=TRUE);
340 static void StringAppend(CString *str, const BYTE *p, int code = CP_UTF8, int length = -1);
342 BOOL CanParseRev(CString ref);
343 BOOL IsInitRepos();
344 int ListConflictFile(CTGitPathList &list, const CTGitPath *path = nullptr);
345 int GetRefList(STRING_VECTOR &list);
347 int RefreshGitIndex();
348 int GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile);
350 //Example: master -> refs/heads/master
351 CString GetFullRefName(const CString& shortRefName);
352 //Removes 'refs/heads/' or just 'refs'. Example: refs/heads/master -> master
353 static CString StripRefName(CString refName);
355 int GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outpathlist, bool ignoreSpaceAtEol = false, bool ignoreSpaceChange = false, bool ignoreAllSpace = false, bool ignoreBlankLines = false);
356 int GetInitAddList(CTGitPathList &outpathlist);
358 __int64 filetime_to_time_t(const FILETIME *ft)
360 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
361 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
362 winTime /= 10000000; /* Nano to seconds resolution */
363 return (time_t)winTime;
366 int GetFileModifyTime(LPCTSTR filename, __int64* time, bool* isDir = nullptr, __int64* size = nullptr)
368 WIN32_FILE_ATTRIBUTE_DATA fdata;
369 if (GetFileAttributesEx(filename, GetFileExInfoStandard, &fdata))
371 if(time)
372 *time = filetime_to_time_t(&fdata.ftLastWriteTime);
374 if (size)
375 *size = ((__int64)fdata.nFileSizeHigh << 32) + fdata.nFileSizeLow;
377 if(isDir)
378 *isDir = !!( fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
380 return 0;
382 return -1;
385 int GetShortHASHLength() const;
387 static BOOL GetShortName(const CString &ref, CString &shortname, CString prefix)
389 //TRACE(_T("%s %s\r\n"),ref,prefix);
390 if (ref.Left(prefix.GetLength()) == prefix)
392 shortname = ref.Right(ref.GetLength() - prefix.GetLength());
393 if (shortname.Right(3) == _T("^{}"))
394 shortname=shortname.Left(shortname.GetLength() - 3);
395 return TRUE;
397 return FALSE;
400 static CString GetShortName(const CString& ref, REF_TYPE *type);
402 static bool LoadTextFile(const CString &filename, CString &msg);
404 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext);
405 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext);
407 int GitRevert(int parent, const CGitHash &hash);
409 CString CombinePath(const CString &path) const
411 if (path.IsEmpty())
412 return m_CurrentDir;
413 if (m_CurrentDir.IsEmpty())
414 return path;
415 return m_CurrentDir + (m_CurrentDir.Right(1) == _T("\\") ? _T("") : _T("\\")) + path;
418 CString CombinePath(const CTGitPath &path) const
420 return CombinePath(path.GetWinPath());
423 CString CombinePath(const CTGitPath *path) const
425 ATLASSERT(path);
426 return CombinePath(path->GetWinPath());
429 extern void GetTempPath(CString &path);
430 extern CString GetTempFile();
431 extern DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer);
433 extern CGit g_Git;