Use libgit2 to check clean working tree
[TortoiseGit.git] / src / Git / Git.h
blob266a8e5bb1e89d2452900bae712b86235eb9ae6e
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 #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)
33 struct git_repository;
35 class CFilterData
37 public:
38 CFilterData()
40 m_From=m_To=-1;
41 m_IsRegex=1;
43 __time64_t m_From;
44 __time64_t m_To;
45 CString m_Author;
46 CString m_Committer;
47 CString m_MessageFilter;
48 BOOL m_IsRegex;
51 class CGitCall
53 public:
54 CGitCall(){}
55 CGitCall(CString cmd):m_Cmd(cmd){}
57 CString GetCmd()const{return m_Cmd;}
58 void SetCmd(CString cmd){m_Cmd=cmd;}
60 //This function is called when command output data is available.
61 //When this function returns 'true' the git command should be aborted.
62 //This behavior is not implemented yet.
63 virtual bool OnOutputData(const BYTE* data, size_t size)=0;
64 virtual bool OnOutputErrData(const BYTE* data, size_t size)=0;
65 virtual void OnEnd(){}
67 private:
68 CString m_Cmd;
71 typedef std::function<void (const CStringA&)> GitReceiverFunc;
73 class CTGitPath;
74 class CEnvironment:public std::vector<TCHAR>
76 public:
77 void CopyProcessEnvironment();
78 CString GetEnv(const TCHAR *name);
79 void SetEnv(const TCHAR* name, const TCHAR* value);
81 class CGit
83 private:
84 CString gitLastErr;
85 protected:
86 bool m_IsGitDllInited;
87 GIT_DIFF m_GitDiff;
88 GIT_DIFF m_GitSimpleListDiff;
89 public:
90 CComCriticalSection m_critGitDllSec;
91 bool m_IsUseGitDLL;
92 bool m_IsUseLibGit2;
93 DWORD m_IsUseLibGit2_mask;
95 CEnvironment m_Environment;
97 static BOOL GitPathFileExists(const CString &path)
99 if(path[0] == _T('\\') && path[1] == _T('\\'))
100 //it is netshare \\server\sharefoldername
101 // \\server\.git will create smb error log.
103 int length = path.GetLength();
105 if(length<2)
106 return false;
108 int start = path.Find(_T('\\'),2);
109 if(start<0)
110 return false;
112 start = path.Find(_T('\\'),start+1);
113 if(start<0)
114 return false;
116 return PathFileExists(path);
119 else
120 return PathFileExists(path);
122 void CheckAndInitDll()
124 if(!m_IsGitDllInited)
126 git_init();
127 m_IsGitDllInited=true;
131 GIT_DIFF GetGitDiff()
133 if(m_GitDiff)
134 return m_GitDiff;
135 else
137 git_open_diff(&m_GitDiff,"-C -M -r");
138 return m_GitDiff;
142 GIT_DIFF GetGitSimpleListDiff()
144 if(m_GitSimpleListDiff)
145 return m_GitSimpleListDiff;
146 else
148 git_open_diff(&m_GitSimpleListDiff,"-r -r");
149 return m_GitSimpleListDiff;
153 BOOL CheckMsysGitDir(BOOL bFallback = TRUE);
154 BOOL m_bInitialized;
156 typedef enum
158 GIT_CMD_CLONE,
159 GIT_CMD_FETCH,
160 GIT_CMD_COMMIT_UPDATE_INDEX,
161 GIT_CMD_DIFF,
162 GIT_CMD_RESET,
163 GIT_CMD_REVERT,
164 GIT_CMD_MERGE_BASE,
165 GIT_CMD_DELETETAGBRANCH,
166 GIT_CMD_GETONEFILE,
167 GIT_CMD_ADD,
168 GIT_CMD_PUSH,
169 GIT_CMD_CHECK_CLEAN_WT,
170 } LIBGIT2_CMD;
171 bool UsingLibGit2(LIBGIT2_CMD cmd) const;
173 * callback type should be git_cred_acquire_cb
175 static void SetGit2CredentialCallback(void* callback);
176 static void SetGit2CertificateCheckCertificate(void* callback);
178 CString GetHomeDirectory() const;
179 CString GetGitLocalConfig() const;
180 CString GetGitGlobalConfig() const;
181 CString GetGitGlobalXDGConfigPath() const;
182 CString GetGitGlobalXDGConfig() const;
183 CString GetGitSystemConfig() const;
184 git_repository * GetGitRepository() const;
185 static CStringA GetGitPathStringA(const CString &path);
186 static CString ms_LastMsysGitDir; // the last msysgitdir added to the path, blank if none
187 static int ms_LastMsysGitVersion;
188 static bool ms_bCygwinGit;
189 static int m_LogEncode;
190 static bool IsBranchNameValid(const CString& branchname);
191 bool IsBranchTagNameUnique(const CString& name);
193 * Checks if a branch or tag with the given name exists
194 *isBranch is true -> branch, tag otherwise
196 bool BranchTagExists(const CString& name, bool isBranch = true);
197 unsigned int Hash2int(const CGitHash &hash);
199 PROCESS_INFORMATION m_CurrentGitPi;
201 CGit(void);
202 ~CGit(void);
204 int Run(CString cmd, CString* output, int code);
205 int Run(CString cmd, CString* output, CString* outputErr, int code);
206 int Run(CString cmd, BYTE_VECTOR *byte_array, BYTE_VECTOR *byte_arrayErr = NULL);
207 int Run(CGitCall* pcall);
208 int Run(CString cmd, const GitReceiverFunc& recv);
210 private:
211 static DWORD WINAPI AsyncReadStdErrThread(LPVOID lpParam);
212 typedef struct AsyncReadStdErrThreadArguments
214 HANDLE fileHandle;
215 CGitCall* pcall;
216 } ASYNCREADSTDERRTHREADARGS, *PASYNCREADSTDERRTHREADARGS;
217 CString GetUnifiedDiffCmd(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, bool bMerge, bool bCombine, int diffContext);
219 public:
220 int RunAsync(CString cmd, PROCESS_INFORMATION *pi, HANDLE* hRead, HANDLE *hErrReadOut, CString *StdioFile = NULL);
221 int RunLogFile(CString cmd, const CString &filename, CString *stdErr);
223 int GetDiffPath(CTGitPathList *PathList, CGitHash *hash1, CGitHash *hash2, char *arg=NULL);
225 int GetGitEncode(TCHAR* configkey);
227 bool IsFastForward(const CString &from, const CString &to, CGitHash * commonAncestor = NULL);
228 CString GetConfigValue(const CString& name);
229 bool GetConfigValueBool(const CString& name);
230 int GetConfigValueInt32(const CString& name, int def = 0);
232 int SetConfigValue(const CString& key, const CString& value, CONFIG_TYPE type = CONFIG_LOCAL);
233 int UnsetConfigValue(const CString& key, CONFIG_TYPE type = CONFIG_LOCAL);
235 CString GetUserName(void);
236 CString GetUserEmail(void);
237 CString GetCurrentBranch(bool fallback = false);
238 void GetRemoteTrackedBranch(const CString& localBranch, CString& remote, CString& branch);
239 void GetRemoteTrackedBranchForHEAD(CString& remote, CString& branch);
240 // read current branch name from HEAD file, returns 0 on success, -1 on failure, 1 detached (branch name "HEAD" returned)
241 static int GetCurrentBranchFromFile(const CString &sProjectRoot, CString &sBranchOut, bool fallback = false);
243 Use this method only when the HEAD is exist.
245 BOOL CheckCleanWorkTree(bool stagedOk = false);
246 int Revert(const CString& commit, const CTGitPathList &list, CString& err);
247 int Revert(const CString& commit, const CTGitPath &path, CString& err);
248 int DeleteRef(const CString& reference);
250 Use this method only if m_IsUseLibGit2 is used for fallbacks.
251 If you directly use libgit2 methods, use GetLibGit2LastErr instead.
253 CString GetGitLastErr(const CString& msg);
254 CString GetGitLastErr(const CString& msg, LIBGIT2_CMD cmd);
255 static CString GetLibGit2LastErr();
256 static CString GetLibGit2LastErr(const CString& msg);
257 bool SetCurrentDir(CString path, bool submodule = false)
259 bool b = GitAdminDir::HasAdminDir(path, submodule ? false : !!PathIsDirectory(path), &m_CurrentDir);
260 if (!b && GitAdminDir::IsBareRepo(path))
262 m_CurrentDir = path;
263 b = true;
265 if(m_CurrentDir.GetLength() == 2 && m_CurrentDir[1] == _T(':')) //C: D:
267 m_CurrentDir += _T('\\');
269 return b;
271 CString m_CurrentDir;
273 enum
275 LOG_ORDER_CHRONOLOGIALREVERSED,
276 LOG_ORDER_TOPOORDER,
277 LOG_ORDER_DATEORDER,
280 typedef enum
282 BRANCH_LOCAL = 0x1,
283 BRANCH_REMOTE = 0x2,
284 BRANCH_FETCH_HEAD = 0x4,
285 BRANCH_LOCAL_F = BRANCH_LOCAL | BRANCH_FETCH_HEAD,
286 BRANCH_ALL = BRANCH_LOCAL | BRANCH_REMOTE,
287 BRANCH_ALL_F = BRANCH_ALL | BRANCH_FETCH_HEAD,
288 }BRANCH_TYPE;
290 typedef enum
292 LOG_INFO_STAT=0x1,
293 LOG_INFO_FILESTATE=0x2,
294 LOG_INFO_PATCH=0x4,
295 LOG_INFO_FULLHISTORY=0x8,
296 LOG_INFO_BOUNDARY=0x10,
297 LOG_INFO_ALL_BRANCH=0x20,
298 LOG_INFO_ONLY_HASH=0x40,
299 LOG_INFO_DETECT_RENAME=0x80,
300 LOG_INFO_DETECT_COPYRENAME=0x100,
301 LOG_INFO_FIRST_PARENT = 0x200,
302 LOG_INFO_NO_MERGE = 0x400,
303 LOG_INFO_FOLLOW = 0x800,
304 LOG_INFO_SHOW_MERGEDFILE=0x1000,
305 LOG_INFO_FULL_DIFF = 0x2000,
306 LOG_INFO_SIMPILFY_BY_DECORATION = 0x4000,
307 LOG_INFO_LOCAL_BRANCHES = 0x8000,
308 }LOG_INFO_MASK;
310 typedef enum
312 LOCAL_BRANCH,
313 REMOTE_BRANCH,
314 TAG,
315 STASH,
316 BISECT_GOOD,
317 BISECT_BAD,
318 NOTES,
319 UNKNOWN,
321 }REF_TYPE;
323 int GetRemoteList(STRING_VECTOR &list);
324 int GetBranchList(STRING_VECTOR &list, int *Current,BRANCH_TYPE type=BRANCH_LOCAL);
325 int GetTagList(STRING_VECTOR &list);
326 int GetRemoteTags(const CString& remote, STRING_VECTOR& list);
327 int DeleteRemoteRefs(const CString& remote, const STRING_VECTOR& list);
328 int GetMapHashToFriendName(MAP_HASH_NAME &map);
329 static int GetMapHashToFriendName(git_repository* repo, MAP_HASH_NAME &map);
331 CString DerefFetchHead();
333 // FixBranchName():
334 // When branchName == FETCH_HEAD, derefrence it.
335 // A selected branch name got from GetBranchList(), with flag BRANCH_FETCH_HEAD enabled,
336 // should go through this function before it is used.
337 CString FixBranchName_Mod(CString& branchName);
338 CString FixBranchName(const CString& branchName);
340 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);
342 int GetHash(CGitHash &hash, const CString& friendname);
343 static int GetHash(git_repository * repo, CGitHash &hash, const CString& friendname, bool skipFastCheck = false);
345 int BuildOutputFormat(CString &format,bool IsFull=TRUE);
346 static void StringAppend(CString *str, const BYTE *p, int code = CP_UTF8, int length = -1);
348 BOOL CanParseRev(CString ref);
349 BOOL IsInitRepos();
350 int ListConflictFile(CTGitPathList &list, const CTGitPath *path = nullptr);
351 int GetRefList(STRING_VECTOR &list);
353 int RefreshGitIndex();
354 int GetOneFile(const CString &Refname, const CTGitPath &path, const CString &outputfile);
356 //Example: master -> refs/heads/master
357 CString GetFullRefName(const CString& shortRefName);
358 //Removes 'refs/heads/' or just 'refs'. Example: refs/heads/master -> master
359 static CString StripRefName(CString refName);
361 int GetCommitDiffList(const CString &rev1, const CString &rev2, CTGitPathList &outpathlist, bool ignoreSpaceAtEol = false, bool ignoreSpaceChange = false, bool ignoreAllSpace = false, bool ignoreBlankLines = false);
362 int GetInitAddList(CTGitPathList &outpathlist);
364 __int64 filetime_to_time_t(const FILETIME *ft)
366 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
367 winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */
368 winTime /= 10000000; /* Nano to seconds resolution */
369 return (time_t)winTime;
372 int GetFileModifyTime(LPCTSTR filename, __int64* time, bool* isDir = nullptr, __int64* size = nullptr)
374 WIN32_FILE_ATTRIBUTE_DATA fdata;
375 if (GetFileAttributesEx(filename, GetFileExInfoStandard, &fdata))
377 if(time)
378 *time = filetime_to_time_t(&fdata.ftLastWriteTime);
380 if (size)
381 *size = ((__int64)fdata.nFileSizeHigh << 32) + fdata.nFileSizeLow;
383 if(isDir)
384 *isDir = !!( fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
386 return 0;
388 return -1;
391 int GetShortHASHLength() const;
393 static BOOL GetShortName(const CString &ref, CString &shortname, CString prefix)
395 //TRACE(_T("%s %s\r\n"),ref,prefix);
396 if (ref.Left(prefix.GetLength()) == prefix)
398 shortname = ref.Right(ref.GetLength() - prefix.GetLength());
399 if (shortname.Right(3) == _T("^{}"))
400 shortname=shortname.Left(shortname.GetLength() - 3);
401 return TRUE;
403 return FALSE;
406 static CString GetShortName(const CString& ref, REF_TYPE *type);
408 static bool LoadTextFile(const CString &filename, CString &msg);
410 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CString patchfile, bool bMerge, bool bCombine, int diffContext);
411 int GetUnifiedDiff(const CTGitPath& path, const git_revnum_t& rev1, const git_revnum_t& rev2, CStringA * buffer, bool bMerge, bool bCombine, int diffContext);
413 int GitRevert(int parent, const CGitHash &hash);
415 CString CombinePath(const CString &path) const
417 if (path.IsEmpty())
418 return m_CurrentDir;
419 if (m_CurrentDir.IsEmpty())
420 return path;
421 return m_CurrentDir + (m_CurrentDir.Right(1) == _T("\\") ? _T("") : _T("\\")) + path;
424 CString CombinePath(const CTGitPath &path) const
426 return CombinePath(path.GetWinPath());
429 CString CombinePath(const CTGitPath *path) const
431 ATLASSERT(path);
432 return CombinePath(path->GetWinPath());
435 extern void GetTempPath(CString &path);
436 extern CString GetTempFile();
437 extern DWORD GetTortoiseGitTempPath(DWORD nBufferLength, LPTSTR lpBuffer);
439 extern CGit g_Git;