Correctly free memory
[TortoiseGit.git] / src / Git / GitIndex.cpp
blobfc8bf498f9ef680ce2bd25c577d27d1ed1d121c2
1 // TortoiseGit - a Windows shell extension for easy version control
3 // Copyright (C) 2008-2013 - 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 #include "stdafx.h"
21 #include "Git.h"
22 #include "atlconv.h"
23 #include "GitRev.h"
24 #include "registry.h"
25 #include "GitConfig.h"
26 #include <map>
27 #include "UnicodeUtils.h"
28 #include "TGitPath.h"
29 #include "gitindex.h"
30 #include <sys/types.h>
31 #include <sys/stat.h>
32 #include "SmartHandle.h"
34 class CAutoReadLock
36 SharedMutex *m_Lock;
37 public:
38 CAutoReadLock(SharedMutex * lock)
40 m_Lock = lock;
41 lock->AcquireShared();
43 ~CAutoReadLock()
45 m_Lock->ReleaseShared();
49 class CAutoWriteLock
51 SharedMutex *m_Lock;
52 public:
53 CAutoWriteLock(SharedMutex * lock)
55 m_Lock = lock;
56 lock->AcquireExclusive();
58 ~CAutoWriteLock()
60 m_Lock->ReleaseExclusive();
64 CGitAdminDirMap g_AdminDirMap;
66 int CGitIndex::Print()
68 _tprintf(_T("0x%08X 0x%08X %s %s\n"),
69 (int)this->m_ModifyTime,
70 this->m_Flags,
71 this->m_IndexHash.ToString(),
72 this->m_FileName);
74 return 0;
77 CGitIndexList::CGitIndexList()
79 this->m_LastModifyTime = 0;
80 m_critRepoSec.Init();
81 repository = NULL;
82 m_bCheckContent = !!(CRegDWORD(_T("Software\\TortoiseGit\\TGitCacheCheckContent"), TRUE) == TRUE);
85 CGitIndexList::~CGitIndexList()
87 if (repository != NULL)
89 git_repository_free(repository);
90 m_critRepoSec.Term();
94 static bool SortIndex(CGitIndex &Item1, CGitIndex &Item2)
96 return Item1.m_FileName.Compare(Item2.m_FileName) < 0;
99 static bool SortTree(CGitTreeItem &Item1, CGitTreeItem &Item2)
101 return Item1.m_FileName.Compare(Item2.m_FileName) < 0;
104 int CGitIndexList::ReadIndex(CString dgitdir)
106 this->clear();
108 CStringA gitdir = CUnicodeUtils::GetMulti(dgitdir, CP_UTF8);
110 m_critRepoSec.Lock();
111 if (repository != NULL)
113 git_repository_free(repository);
114 repository = NULL;
116 git_index *index = NULL;
118 int ret = git_repository_open(&repository, gitdir.GetBuffer());
119 gitdir.ReleaseBuffer();
120 if (ret)
121 return -1;
123 // add config files
124 git_config * config;
125 git_config_new(&config);
127 CString projectConfig = dgitdir + _T("config");
128 CString globalConfig = g_Git.GetGitGlobalConfig();
129 CString globalXDGConfig = g_Git.GetGitGlobalXDGConfig();
130 CString msysGitBinPath(CRegString(REG_MSYSGIT_PATH, _T(""), FALSE));
132 CStringA projectConfigA = CUnicodeUtils::GetMulti(projectConfig, CP_UTF8);
133 git_config_add_file_ondisk(config, projectConfigA.GetBuffer(), 4, FALSE);
134 projectConfigA.ReleaseBuffer();
135 CStringA globalConfigA = CUnicodeUtils::GetMulti(globalConfig, CP_UTF8);
136 git_config_add_file_ondisk(config, globalConfigA.GetBuffer(), 3, FALSE);
137 globalConfigA.ReleaseBuffer();
138 CStringA globalXDGConfigA = CUnicodeUtils::GetMulti(globalXDGConfig, CP_UTF8);
139 git_config_add_file_ondisk(config, globalXDGConfigA.GetBuffer(), 2, FALSE);
140 globalXDGConfigA.ReleaseBuffer();
141 if (!msysGitBinPath.IsEmpty())
143 CString systemConfig = msysGitBinPath + _T("\\..\\etc\\gitconfig");
144 CStringA systemConfigA = CUnicodeUtils::GetMulti(systemConfig, CP_UTF8);
145 git_config_add_file_ondisk(config, systemConfigA.GetBuffer(), 1, FALSE);
146 systemConfigA.ReleaseBuffer();
149 git_repository_set_config(repository, config);
151 // load index in order to enumerate files
152 if (git_repository_index(&index, repository))
154 repository = NULL;
155 m_critRepoSec.Unlock();
156 return -1;
159 size_t ecount = git_index_entrycount(index);
160 resize(ecount);
161 for (size_t i = 0; i < ecount; ++i)
163 const git_index_entry *e = git_index_get_byindex(index, i);
165 this->at(i).m_FileName.Empty();
166 g_Git.StringAppend(&this->at(i).m_FileName, (BYTE*)e->path, CP_UTF8);
167 this->at(i).m_FileName.MakeLower();
168 this->at(i).m_ModifyTime = e->mtime.seconds;
169 this->at(i).m_Flags = e->flags | e->flags_extended;
170 this->at(i).m_IndexHash = (char *) e->oid.id;
173 git_index_free(index);
175 g_Git.GetFileModifyTime(dgitdir + _T("index"), &this->m_LastModifyTime);
176 std::sort(this->begin(), this->end(), SortIndex);
178 m_critRepoSec.Unlock();
180 return 0;
183 int CGitIndexList::GetFileStatus(const CString &gitdir,const CString &pathorg,git_wc_status_kind *status,__int64 time,FIll_STATUS_CALLBACK callback,void *pData, CGitHash *pHash, bool * assumeValid, bool * skipWorktree)
185 if(status)
187 CString path = pathorg;
188 path.MakeLower();
190 int start = SearchInSortVector(*this, ((CString&)path).GetBuffer(), -1);
191 ((CString&)path).ReleaseBuffer();
193 if (start < 0)
195 *status = git_wc_status_unversioned;
196 if (pHash)
197 pHash->Empty();
200 else
202 int index = start;
203 if (index <0)
204 return -1;
205 if (index >= (int)size())
206 return -1;
208 // skip-worktree has higher priority than assume-valid
209 if (at(index).m_Flags & GIT_IDXENTRY_SKIP_WORKTREE)
211 *status = git_wc_status_normal;
212 if (skipWorktree)
213 *skipWorktree = true;
215 else if (at(index).m_Flags & GIT_IDXENTRY_VALID)
217 *status = git_wc_status_normal;
218 if (assumeValid)
219 *assumeValid = true;
221 else if (time == at(index).m_ModifyTime)
223 *status = git_wc_status_normal;
225 else if (m_bCheckContent && repository)
227 git_oid actual;
228 CStringA fileA = CUnicodeUtils::GetMulti(pathorg, CP_UTF8);
229 m_critRepoSec.Lock(); // prevent concurrent access to repository instance and especially filter-lists
230 if (!git_repository_hashfile(&actual, repository, fileA.GetBuffer(), GIT_OBJ_BLOB, NULL) && !git_oid_cmp(&actual, (const git_oid*)at(index).m_IndexHash.m_hash))
232 at(index).m_ModifyTime = time;
233 *status = git_wc_status_normal;
235 else
236 *status = git_wc_status_modified;
237 fileA.ReleaseBuffer();
238 m_critRepoSec.Unlock();
240 else
241 *status = git_wc_status_modified;
243 if (at(index).m_Flags & GIT_IDXENTRY_STAGEMASK)
244 *status = git_wc_status_conflicted;
245 else if (at(index).m_Flags & GIT_IDXENTRY_INTENT_TO_ADD)
246 *status = git_wc_status_added;
248 if(pHash)
249 *pHash = at(index).m_IndexHash;
254 if(callback && status)
255 callback(gitdir + _T("\\") + pathorg, *status, false, pData, *assumeValid, *skipWorktree);
256 return 0;
259 int CGitIndexList::GetStatus(const CString &gitdir,const CString &pathParam, git_wc_status_kind *status,
260 BOOL IsFull, BOOL /*IsRecursive*/,
261 FIll_STATUS_CALLBACK callback,void *pData,
262 CGitHash *pHash, bool * assumeValid, bool * skipWorktree)
264 int result;
265 git_wc_status_kind dirstatus = git_wc_status_none;
266 __int64 time;
267 bool isDir = false;
268 CString path = pathParam;
270 if (status)
272 if (path.IsEmpty())
273 result = g_Git.GetFileModifyTime(gitdir, &time, &isDir);
274 else
275 result = g_Git.GetFileModifyTime(gitdir + _T("\\") + path, &time, &isDir);
277 if (result)
279 *status = git_wc_status_deleted;
280 if (callback)
281 callback(gitdir + _T("\\") + path, git_wc_status_deleted, false, pData, *assumeValid, *skipWorktree);
283 return 0;
285 if (isDir)
287 if (!path.IsEmpty())
289 if (path.Right(1) != _T("\\"))
290 path += _T("\\");
292 int len = path.GetLength();
294 for (size_t i = 0; i < size(); ++i)
296 if (at(i).m_FileName.GetLength() > len)
298 if (at(i).m_FileName.Left(len) == path)
300 if (!IsFull)
302 *status = git_wc_status_normal;
303 if (callback)
304 callback(gitdir + _T("\\") + path, *status, false, pData, (at(i).m_Flags & GIT_IDXENTRY_VALID) && !(at(i).m_Flags & GIT_IDXENTRY_SKIP_WORKTREE), (at(i).m_Flags & GIT_IDXENTRY_SKIP_WORKTREE) != 0);
305 return 0;
308 else
310 result = g_Git.GetFileModifyTime(gitdir+_T("\\") + at(i).m_FileName, &time);
311 if (result)
312 continue;
314 *status = git_wc_status_none;
315 if (assumeValid)
316 *assumeValid = false;
317 if (skipWorktree)
318 *skipWorktree = false;
319 GetFileStatus(gitdir, at(i).m_FileName, status, time, callback, pData, NULL, assumeValid, skipWorktree);
320 // if a file is assumed valid, we need to inform the caller, otherwise the assumevalid flag might not get to the explorer on first open of a repository
321 if (callback && (assumeValid || skipWorktree))
322 callback(gitdir + _T("\\") + path, *status, false, pData, *assumeValid, *skipWorktree);
323 if (*status != git_wc_status_none)
325 if (dirstatus == git_wc_status_none)
327 dirstatus = git_wc_status_normal;
329 if (*status != git_wc_status_normal)
331 dirstatus = git_wc_status_modified;
338 } /* End For */
340 if (dirstatus != git_wc_status_none)
342 *status = dirstatus;
344 else
346 *status = git_wc_status_unversioned;
348 if(callback)
349 callback(gitdir + _T("\\") + path, *status, false, pData, false, false);
351 return 0;
354 else
356 GetFileStatus(gitdir, path, status, time, callback, pData, pHash, assumeValid, skipWorktree);
359 return 0;
362 int CGitIndexFileMap::Check(const CString &gitdir, bool *isChanged)
364 __int64 time;
365 int result;
367 CString IndexFile = g_AdminDirMap.GetAdminDir(gitdir) + _T("index");
369 /* Get data associated with "crt_stat.c": */
370 result = g_Git.GetFileModifyTime(IndexFile, &time);
372 if (result)
373 return result;
375 SHARED_INDEX_PTR pIndex;
376 pIndex = this->SafeGet(gitdir);
378 if (pIndex.get() == NULL)
380 if(isChanged)
381 *isChanged = true;
382 return 0;
385 if (pIndex->m_LastModifyTime == time)
387 if (isChanged)
388 *isChanged = false;
390 else
392 if (isChanged)
393 *isChanged = true;
395 return 0;
398 int CGitIndexFileMap::LoadIndex(const CString &gitdir)
402 SHARED_INDEX_PTR pIndex(new CGitIndexList);
404 if(pIndex->ReadIndex(g_AdminDirMap.GetAdminDir(gitdir)))
405 return -1;
407 this->SafeSet(gitdir, pIndex);
409 }catch(...)
411 return -1;
413 return 0;
416 int CGitIndexFileMap::GetFileStatus(const CString &gitdir, const CString &path, git_wc_status_kind *status,BOOL IsFull, BOOL IsRecursive,
417 FIll_STATUS_CALLBACK callback,void *pData,
418 CGitHash *pHash,
419 bool isLoadUpdatedIndex, bool * assumeValid, bool * skipWorktree)
423 CheckAndUpdate(gitdir, isLoadUpdatedIndex);
425 SHARED_INDEX_PTR pIndex = this->SafeGet(gitdir);
426 if (pIndex.get() != NULL)
428 pIndex->GetStatus(gitdir, path, status, IsFull, IsRecursive, callback, pData, pHash, assumeValid, skipWorktree);
430 else
432 // git working tree has not index
433 *status = git_wc_status_unversioned;
436 catch(...)
438 return -1;
440 return 0;
443 int CGitIndexFileMap::IsUnderVersionControl(const CString &gitdir, const CString &path, bool isDir,bool *isVersion, bool isLoadUpdateIndex)
447 if (path.IsEmpty())
449 *isVersion = true;
450 return 0;
453 CString subpath = path;
454 subpath.Replace(_T('\\'), _T('/'));
455 if(isDir)
456 subpath += _T('/');
458 subpath.MakeLower();
460 CheckAndUpdate(gitdir, isLoadUpdateIndex);
462 SHARED_INDEX_PTR pIndex = this->SafeGet(gitdir);
464 if(pIndex.get())
466 if(isDir)
467 *isVersion = (SearchInSortVector(*pIndex, subpath.GetBuffer(), subpath.GetLength()) >= 0);
468 else
469 *isVersion = (SearchInSortVector(*pIndex, subpath.GetBuffer(), -1) >= 0);
470 subpath.ReleaseBuffer();
473 }catch(...)
475 return -1;
477 return 0;
480 // This method is assumed to be called with m_SharedMutex locked.
481 int CGitHeadFileList::GetPackRef(const CString &gitdir)
483 CString PackRef = g_AdminDirMap.GetAdminDir(gitdir) + _T("packed-refs");
485 __int64 mtime;
486 if (g_Git.GetFileModifyTime(PackRef, &mtime))
488 //packed refs is not existed
489 this->m_PackRefFile.Empty();
490 this->m_PackRefMap.clear();
491 return 0;
493 else if(mtime == m_LastModifyTimePackRef)
495 return 0;
497 else
499 this->m_PackRefFile = PackRef;
500 this->m_LastModifyTimePackRef = mtime;
503 int ret = 0;
505 this->m_PackRefMap.clear();
507 CAutoFile hfile = CreateFile(PackRef,
508 GENERIC_READ,
509 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
510 NULL,
511 OPEN_EXISTING,
512 FILE_ATTRIBUTE_NORMAL,
513 NULL);
516 if (!hfile)
518 ret = -1;
519 break;
522 DWORD filesize = GetFileSize(hfile, NULL);
523 DWORD size =0;
524 char *buff;
525 buff = new char[filesize];
527 ReadFile(hfile, buff, filesize, &size, NULL);
529 if (size != filesize)
531 delete[] buff;
532 ret = -1;
533 break;
536 CString hash;
537 CString ref;
539 for(DWORD i=0;i<filesize;)
541 hash.Empty();
542 ref.Empty();
543 if (buff[i] == '#' || buff[i] == '^')
545 while (buff[i] != '\n')
547 ++i;
548 if (i == filesize)
549 break;
551 ++i;
554 if (i >= filesize)
555 break;
557 while (buff[i] != ' ')
559 hash.AppendChar(buff[i]);
560 ++i;
561 if (i == filesize)
562 break;
565 ++i;
566 if (i >= filesize)
567 break;
569 while (buff[i] != '\n')
571 ref.AppendChar(buff[i]);
572 ++i;
573 if (i == filesize)
574 break;
577 if (!ref.IsEmpty() )
579 this->m_PackRefMap[ref] = hash;
582 while (buff[i] == '\n')
584 ++i;
585 if (i == filesize)
586 break;
590 delete[] buff;
592 } while(0);
594 return ret;
597 int CGitHeadFileList::ReadHeadHash(CString gitdir)
599 int ret = 0;
600 CAutoWriteLock lock(&this->m_SharedMutex);
601 m_Gitdir = g_AdminDirMap.GetAdminDir(gitdir);
603 m_HeadFile = m_Gitdir + _T("HEAD");
605 if( g_Git.GetFileModifyTime(m_HeadFile, &m_LastModifyTimeHead))
606 return -1;
612 CAutoFile hfile = CreateFile(m_HeadFile,
613 GENERIC_READ,
614 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
615 NULL,
616 OPEN_EXISTING,
617 FILE_ATTRIBUTE_NORMAL,
618 NULL);
620 if (!hfile)
622 ret = -1;
623 break;
626 DWORD size = 0,filesize = 0;
627 unsigned char buffer[40] ;
628 ReadFile(hfile, buffer, 4, &size, NULL);
629 if (size != 4)
631 ret = -1;
632 break;
634 buffer[4]=0;
635 if (strcmp((const char*)buffer,"ref:") == 0)
637 filesize = GetFileSize(hfile, NULL);
639 unsigned char *p = (unsigned char*)malloc(filesize -4);
641 ReadFile(hfile, p, filesize - 4, &size, NULL);
643 m_HeadRefFile.Empty();
644 g_Git.StringAppend(&this->m_HeadRefFile, p, CP_UTF8, filesize - 4);
645 CString ref = this->m_HeadRefFile;
646 ref = ref.Trim();
647 int start = 0;
648 ref = ref.Tokenize(_T("\n"), start);
649 free(p);
650 m_HeadRefFile = m_Gitdir + m_HeadRefFile.Trim();
651 m_HeadRefFile.Replace(_T('/'),_T('\\'));
653 __int64 time;
654 if (g_Git.GetFileModifyTime(m_HeadRefFile, &time, NULL))
656 m_HeadRefFile.Empty();
657 if (GetPackRef(gitdir))
659 ret = -1;
660 break;
662 if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
664 ret = -1;
665 break;
667 this ->m_Head = m_PackRefMap[ref];
668 ret = 0;
669 break;
672 CAutoFile href = CreateFile(m_HeadRefFile,
673 GENERIC_READ,
674 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
675 NULL,
676 OPEN_EXISTING,
677 FILE_ATTRIBUTE_NORMAL,
678 NULL);
680 if (!href)
682 m_HeadRefFile.Empty();
684 if (GetPackRef(gitdir))
686 ret = -1;
687 break;
690 if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
692 ret = -1;
693 break;
695 this ->m_Head = m_PackRefMap[ref];
696 ret = 0;
697 break;
699 ReadFile(href, buffer, 40, &size, NULL);
700 if (size != 40)
702 ret = -1;
703 break;
705 this->m_Head.ConvertFromStrA((char*)buffer);
707 this->m_LastModifyTimeRef = time;
710 else
712 ReadFile(hfile, buffer + 4, 40 - 4, &size, NULL);
713 if(size != 36)
715 ret = -1;
716 break;
718 m_HeadRefFile.Empty();
720 this->m_Head.ConvertFromStrA((char*)buffer);
722 } while(0);
724 catch(...)
726 ret = -1;
729 return ret;
732 bool CGitHeadFileList::CheckHeadUpdate()
734 CAutoReadLock lock(&m_SharedMutex);
735 if (this->m_HeadFile.IsEmpty())
736 return true;
738 __int64 mtime=0;
740 if (g_Git.GetFileModifyTime(m_HeadFile, &mtime))
741 return true;
743 if (mtime != this->m_LastModifyTimeHead)
744 return true;
746 if (!this->m_HeadRefFile.IsEmpty())
748 if (g_Git.GetFileModifyTime(m_HeadRefFile, &mtime))
749 return true;
751 if (mtime != this->m_LastModifyTimeRef)
752 return true;
755 if(!this->m_PackRefFile.IsEmpty())
757 if (g_Git.GetFileModifyTime(m_PackRefFile, &mtime))
758 return true;
760 if (mtime != this->m_LastModifyTimePackRef)
761 return true;
764 // in an empty repo HEAD points to refs/heads/master, but this ref doesn't exist.
765 // So we need to retry again and again until the ref exists - otherwise we will never notice
766 if (this->m_Head.IsEmpty() && this->m_HeadRefFile.IsEmpty() && this->m_PackRefFile.IsEmpty())
767 return true;
769 return false;
772 bool CGitHeadFileList::HeadHashEqualsTreeHash()
774 CAutoReadLock lock(&this->m_SharedMutex);
775 return (m_Head == m_TreeHash);
778 bool CGitHeadFileList::HeadFileIsEmpty()
780 CAutoReadLock lock(&this->m_SharedMutex);
781 return m_HeadFile.IsEmpty();
784 bool CGitHeadFileList::HeadIsEmpty()
786 CAutoReadLock lock(&this->m_SharedMutex);
787 return m_Head.IsEmpty();
790 int CGitHeadFileList::CallBack(const unsigned char *sha1, const char *base, int baselen,
791 const char *pathname, unsigned mode, int /*stage*/, void *context)
793 #define S_IFGITLINK 0160000
795 CGitHeadFileList *p = (CGitHeadFileList*)context;
796 if( mode&S_IFDIR )
798 if( (mode&S_IFMT) != S_IFGITLINK)
799 return READ_TREE_RECURSIVE;
802 size_t cur = p->size();
803 p->resize(p->size() + 1);
804 p->at(cur).m_Hash = (char*)sha1;
805 p->at(cur).m_FileName.Empty();
807 if(base)
808 g_Git.StringAppend(&p->at(cur).m_FileName, (BYTE*)base, CP_UTF8, baselen);
810 g_Git.StringAppend(&p->at(cur).m_FileName,(BYTE*)pathname, CP_UTF8);
812 p->at(cur).m_FileName.MakeLower();
814 //p->at(cur).m_FileName.Replace(_T('/'), _T('\\'));
816 //p->m_Map[p->at(cur).m_FileName] = cur;
818 if( (mode&S_IFMT) == S_IFGITLINK)
819 return 0;
821 return READ_TREE_RECURSIVE;
824 int ReadTreeRecursive(git_repository &repo, git_tree * tree, CStringA base, int (*CallBack) (const unsigned char *, const char *, int, const char *, unsigned int, int, void *),void *data)
826 size_t count = git_tree_entrycount(tree);
827 for (size_t i = 0; i < count; ++i)
829 const git_tree_entry *entry = git_tree_entry_byindex(tree, i);
830 if (entry == NULL)
831 continue;
832 int mode = git_tree_entry_filemode(entry);
833 if( CallBack(git_tree_entry_id(entry)->id,
834 base,
835 base.GetLength(),
836 git_tree_entry_name(entry),
837 mode,
839 data) == READ_TREE_RECURSIVE
842 if(mode&S_IFDIR)
844 git_object *object = NULL;
845 git_tree_entry_to_object(&object, &repo, entry);
846 if (object == NULL)
847 continue;
848 CStringA parent = base;
849 parent += git_tree_entry_name(entry);
850 parent += "/";
851 ReadTreeRecursive(repo, (git_tree*)object, parent, CallBack, data);
852 git_object_free(object);
858 return 0;
861 // ReadTree is/must only be executed on an empty list
862 int CGitHeadFileList::ReadTree()
864 CAutoWriteLock lock(&m_SharedMutex);
865 CStringA gitdir = CUnicodeUtils::GetMulti(m_Gitdir, CP_UTF8);
866 git_repository *repository = NULL;
867 git_commit *commit = NULL;
868 git_tree * tree = NULL;
869 int ret = 0;
870 ATLASSERT(this->empty());
873 ret = git_repository_open(&repository, gitdir.GetBuffer());
874 gitdir.ReleaseBuffer();
875 if(ret)
876 break;
877 ret = git_commit_lookup(&commit, repository, (const git_oid*)m_Head.m_hash);
878 if(ret)
879 break;
881 ret = git_commit_tree(&tree, commit);
882 if(ret)
883 break;
885 ret = ReadTreeRecursive(*repository, tree,"", CGitHeadFileList::CallBack,this);
886 if(ret)
887 break;
889 std::sort(this->begin(), this->end(), SortTree);
890 this->m_TreeHash = (char*)(git_commit_id(commit)->id);
892 } while(0);
894 if (tree)
895 git_tree_free(tree);
897 if (commit)
898 git_commit_free(commit);
900 if (repository)
901 git_repository_free(repository);
903 if (ret)
905 clear();
906 m_LastModifyTimeHead = 0;
909 return ret;
912 int CGitIgnoreItem::FetchIgnoreList(const CString &projectroot, const CString &file, bool isGlobal)
914 CAutoWriteLock lock(&this->m_SharedMutex);
916 if (this->m_pExcludeList)
918 git_free_exclude_list(m_pExcludeList);
919 m_pExcludeList=NULL;
921 if (m_buffer)
923 free(m_buffer);
924 m_buffer = NULL;
927 this->m_BaseDir.Empty();
928 if (!isGlobal)
930 CString base = file.Mid(projectroot.GetLength() + 1);
931 base.Replace(_T('\\'), _T('/'));
933 int start = base.ReverseFind(_T('/'));
934 if(start > 0)
936 base = base.Left(start);
937 this->m_BaseDir = CUnicodeUtils::GetMulti(base, CP_UTF8) + "/";
942 if(g_Git.GetFileModifyTime(file, &m_LastModifyTime))
943 return -1;
945 if(git_create_exclude_list(&this->m_pExcludeList))
946 return -1;
949 CAutoFile hfile = CreateFile(file,
950 GENERIC_READ,
951 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
952 NULL,
953 OPEN_EXISTING,
954 FILE_ATTRIBUTE_NORMAL,
955 NULL);
958 if (!hfile)
959 return -1 ;
961 DWORD size=0,filesize=0;
963 filesize=GetFileSize(hfile, NULL);
965 if(filesize == INVALID_FILE_SIZE)
966 return -1;
968 m_buffer = new BYTE[filesize + 1];
970 if (m_buffer == NULL)
971 return -1;
973 if (!ReadFile(hfile, m_buffer, filesize, &size, NULL))
974 return GetLastError();
976 BYTE *p = m_buffer;
977 for (DWORD i = 0; i < size; ++i)
979 if (m_buffer[i] == '\n' || m_buffer[i] == '\r' || i == (size - 1))
981 if (m_buffer[i] == '\n' || m_buffer[i] == '\r')
982 m_buffer[i] = 0;
983 if (i == size - 1)
984 m_buffer[size] = 0;
986 if(p[0] != '#' && p[0] != 0)
987 git_add_exclude((const char*)p,
988 this->m_BaseDir.GetBuffer(),
989 m_BaseDir.GetLength(),
990 this->m_pExcludeList);
992 p = m_buffer + i + 1;
996 return 0;
999 bool CGitIgnoreList::CheckFileChanged(const CString &path)
1001 __int64 time = 0;
1003 int ret = g_Git.GetFileModifyTime(path, &time);
1005 this->m_SharedMutex.AcquireShared();
1006 bool cacheExist = (m_Map.find(path) != m_Map.end());
1007 this->m_SharedMutex.ReleaseShared();
1009 if (!cacheExist && ret == 0)
1011 CAutoWriteLock lock(&this->m_SharedMutex);
1012 m_Map[path].m_LastModifyTime = 0;
1013 m_Map[path].m_SharedMutex.Init();
1015 // both cache and file is not exist
1016 if ((ret != 0) && (!cacheExist))
1017 return false;
1019 // file exist but cache miss
1020 if ((ret == 0) && (!cacheExist))
1021 return true;
1023 // file not exist but cache exist
1024 if ((ret != 0) && (cacheExist))
1026 return true;
1028 // file exist and cache exist
1031 CAutoReadLock lock(&this->m_SharedMutex);
1032 if (m_Map[path].m_LastModifyTime == time)
1033 return false;
1035 return true;
1038 bool CGitIgnoreList::CheckIgnoreChanged(const CString &gitdir,const CString &path)
1040 CString temp;
1041 temp = gitdir;
1042 temp += _T("\\");
1043 temp += path;
1045 temp.Replace(_T('/'), _T('\\'));
1047 while(!temp.IsEmpty())
1049 CString tempOrig = temp;
1050 temp += _T("\\.git");
1052 if (CGit::GitPathFileExists(temp))
1054 CString gitignore=temp;
1055 gitignore += _T("ignore");
1056 if (CheckFileChanged(gitignore))
1057 return true;
1059 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1060 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1061 if (CheckFileChanged(wcglobalgitignore))
1062 return true;
1064 if (CheckAndUpdateCoreExcludefile(adminDir))
1065 return true;
1067 return false;
1069 else
1071 temp += _T("ignore");
1072 if (CheckFileChanged(temp))
1073 return true;
1076 int found=0;
1077 int i;
1078 for (i = temp.GetLength() - 1; i >= 0; i--)
1080 if(temp[i] == _T('\\'))
1081 ++found;
1083 if(found == 2)
1084 break;
1087 temp = temp.Left(i);
1089 return true;
1092 int CGitIgnoreList::FetchIgnoreFile(const CString &gitdir, const CString &gitignore, bool isGlobal)
1094 if (CGit::GitPathFileExists(gitignore)) //if .gitignore remove, we need remote cache
1096 CAutoWriteLock lock(&this->m_SharedMutex);
1097 if (m_Map.find(gitignore) == m_Map.end())
1098 m_Map[gitignore].m_SharedMutex.Init();
1100 m_Map[gitignore].FetchIgnoreList(gitdir, gitignore, isGlobal);
1102 else
1104 CAutoWriteLock lock(&this->m_SharedMutex);
1105 if (m_Map.find(gitignore) != m_Map.end())
1106 m_Map[gitignore].m_SharedMutex.Release();
1108 m_Map.erase(gitignore);
1110 return 0;
1113 int CGitIgnoreList::LoadAllIgnoreFile(const CString &gitdir,const CString &path)
1115 CString temp;
1117 temp = gitdir;
1118 temp += _T("\\");
1119 temp += path;
1121 temp.Replace(_T('/'), _T('\\'));
1123 while (!temp.IsEmpty())
1125 CString tempOrig = temp;
1126 temp += _T("\\.git");
1128 if (CGit::GitPathFileExists(temp))
1130 CString gitignore = temp;
1131 gitignore += _T("ignore");
1132 if (CheckFileChanged(gitignore))
1134 FetchIgnoreFile(gitdir, gitignore, false);
1137 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1138 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1139 if (CheckFileChanged(wcglobalgitignore))
1141 FetchIgnoreFile(gitdir, wcglobalgitignore, true);
1144 if (CheckAndUpdateCoreExcludefile(adminDir))
1146 m_SharedMutex.AcquireShared();
1147 CString excludesFile = m_CoreExcludesfiles[adminDir];
1148 m_SharedMutex.ReleaseShared();
1149 if (!excludesFile.IsEmpty())
1150 FetchIgnoreFile(gitdir, excludesFile, true);
1153 return 0;
1155 else
1157 temp += _T("ignore");
1158 if (CheckFileChanged(temp))
1160 FetchIgnoreFile(gitdir, temp, false);
1164 int found = 0;
1165 int i;
1166 for (i = temp.GetLength() - 1; i >= 0; i--)
1168 if(temp[i] == _T('\\'))
1169 ++found;
1171 if(found == 2)
1172 break;
1175 temp = temp.Left(i);
1177 return 0;
1179 bool CGitIgnoreList::CheckAndUpdateMsysGitBinpath(bool force)
1181 // recheck every 30 seconds
1182 if (GetTickCount() - m_dMsysGitBinPathLastChecked > 30000 || force)
1184 m_dMsysGitBinPathLastChecked = GetTickCount();
1185 CString msysGitBinPath(CRegString(REG_MSYSGIT_PATH, _T(""), FALSE));
1186 if (msysGitBinPath != m_sMsysGitBinPath)
1188 m_sMsysGitBinPath = msysGitBinPath;
1189 return true;
1192 return false;
1194 bool CGitIgnoreList::CheckAndUpdateCoreExcludefile(const CString &adminDir)
1196 bool hasChanged = false;
1198 CString projectConfig = adminDir + _T("config");
1199 CString globalConfig = g_Git.GetGitGlobalConfig();
1200 CString globalXDGConfig = g_Git.GetGitGlobalXDGConfig();
1202 CAutoWriteLock lock(&m_coreExcludefilesSharedMutex);
1203 hasChanged = CheckAndUpdateMsysGitBinpath();
1204 CString systemConfig = m_sMsysGitBinPath + _T("\\..\\etc\\gitconfig");
1206 hasChanged = hasChanged || CheckFileChanged(projectConfig);
1207 hasChanged = hasChanged || CheckFileChanged(globalConfig);
1208 hasChanged = hasChanged || CheckFileChanged(globalXDGConfig);
1209 if (!m_sMsysGitBinPath.IsEmpty())
1210 hasChanged = hasChanged || CheckFileChanged(systemConfig);
1212 m_SharedMutex.AcquireShared();
1213 CString excludesFile = m_CoreExcludesfiles[adminDir];
1214 m_SharedMutex.ReleaseShared();
1215 if (!excludesFile.IsEmpty())
1216 hasChanged = hasChanged || CheckFileChanged(excludesFile);
1218 if (!hasChanged)
1219 return false;
1221 git_config * config;
1222 git_config_new(&config);
1223 CStringA projectConfigA = CUnicodeUtils::GetMulti(projectConfig, CP_UTF8);
1224 git_config_add_file_ondisk(config, projectConfigA.GetBuffer(), 4, FALSE);
1225 projectConfigA.ReleaseBuffer();
1226 CStringA globalConfigA = CUnicodeUtils::GetMulti(globalConfig, CP_UTF8);
1227 git_config_add_file_ondisk(config, globalConfigA.GetBuffer(), 3, FALSE);
1228 globalConfigA.ReleaseBuffer();
1229 CStringA globalXDGConfigA = CUnicodeUtils::GetMulti(globalXDGConfig, CP_UTF8);
1230 git_config_add_file_ondisk(config, globalXDGConfigA.GetBuffer(), 2, FALSE);
1231 globalXDGConfigA.ReleaseBuffer();
1232 if (!m_sMsysGitBinPath.IsEmpty())
1234 CStringA systemConfigA = CUnicodeUtils::GetMulti(systemConfig, CP_UTF8);
1235 git_config_add_file_ondisk(config, systemConfigA.GetBuffer(), 1, FALSE);
1236 systemConfigA.ReleaseBuffer();
1238 const char * out = NULL;
1239 CStringA name(_T("core.excludesfile"));
1240 git_config_get_string(&out, config, name.GetBuffer());
1241 name.ReleaseBuffer();
1242 CStringA excludesFileA(out);
1243 excludesFile = CUnicodeUtils::GetUnicode(excludesFileA);
1244 if (excludesFile.IsEmpty())
1245 excludesFile = GetWindowsHome() + _T("\\.config\\git\\ignore");
1246 else if (excludesFile.Find(_T("~/")) == 0)
1247 excludesFile = GetWindowsHome() + excludesFile.Mid(1);
1248 git_config_free(config);
1250 CAutoWriteLock lockMap(&m_SharedMutex);
1251 g_Git.GetFileModifyTime(projectConfig, &m_Map[projectConfig].m_LastModifyTime);
1252 g_Git.GetFileModifyTime(globalXDGConfig, &m_Map[globalXDGConfig].m_LastModifyTime);
1253 if (m_Map[globalXDGConfig].m_LastModifyTime == 0)
1255 m_Map[globalXDGConfig].m_SharedMutex.Release();
1256 m_Map.erase(globalXDGConfig);
1258 g_Git.GetFileModifyTime(globalConfig, &m_Map[globalConfig].m_LastModifyTime);
1259 if (m_Map[globalConfig].m_LastModifyTime == 0)
1261 m_Map[globalConfig].m_SharedMutex.Release();
1262 m_Map.erase(globalConfig);
1264 if (!m_sMsysGitBinPath.IsEmpty())
1265 g_Git.GetFileModifyTime(systemConfig, &m_Map[systemConfig].m_LastModifyTime);
1266 if (m_Map[systemConfig].m_LastModifyTime == 0 || m_sMsysGitBinPath.IsEmpty())
1268 m_Map[systemConfig].m_SharedMutex.Release();
1269 m_Map.erase(systemConfig);
1271 m_CoreExcludesfiles[adminDir] = excludesFile;
1273 return true;
1275 const CString CGitIgnoreList::GetWindowsHome()
1277 static CString sWindowsHome(g_Git.GetHomeDirectory());
1278 return sWindowsHome;
1280 bool CGitIgnoreList::IsIgnore(const CString &path,const CString &projectroot)
1282 CString str=path;
1284 str.Replace(_T('\\'),_T('/'));
1286 if (str.GetLength()>0)
1287 if (str[str.GetLength()-1] == _T('/'))
1288 str = str.Left(str.GetLength() - 1);
1290 int ret;
1291 ret = CheckIgnore(str, projectroot);
1292 while (ret < 0)
1294 int start = str.ReverseFind(_T('/'));
1295 if(start < 0)
1296 return (ret == 1);
1298 str = str.Left(start);
1299 ret = CheckIgnore(str, projectroot);
1302 return (ret == 1);
1304 int CGitIgnoreList::CheckFileAgainstIgnoreList(const CString &ignorefile, const CStringA &patha, const char * base, int &type)
1306 if (m_Map.find(ignorefile) != m_Map.end())
1308 int ret = -1;
1309 if(m_Map[ignorefile].m_pExcludeList)
1310 ret = git_check_excluded_1(patha, patha.GetLength(), base, &type, m_Map[ignorefile].m_pExcludeList);
1311 if (ret == 0 || ret == 1)
1312 return ret;
1314 return -1;
1316 int CGitIgnoreList::CheckIgnore(const CString &path,const CString &projectroot)
1318 __int64 time = 0;
1319 bool dir = 0;
1320 CString temp = projectroot + _T("\\") + path;
1321 temp.Replace(_T('/'), _T('\\'));
1323 CStringA patha = CUnicodeUtils::GetMulti(path, CP_UTF8);
1324 patha.Replace('\\', '/');
1326 if(g_Git.GetFileModifyTime(temp, &time, &dir))
1327 return -1;
1329 int type = 0;
1330 if (dir)
1332 type = DT_DIR;
1334 // strip directory name
1335 // we do not need to check for a .ignore file inside a directory we might ignore
1336 int i = temp.ReverseFind(_T('\\'));
1337 if (i >= 0)
1338 temp = temp.Left(i);
1340 else
1341 type = DT_REG;
1343 char * base = NULL;
1344 int pos = patha.ReverseFind('/');
1345 base = pos >= 0 ? patha.GetBuffer() + pos + 1 : patha.GetBuffer();
1347 int ret = -1;
1349 CAutoReadLock lock(&this->m_SharedMutex);
1350 while (!temp.IsEmpty())
1352 CString tempOrig = temp;
1353 temp += _T("\\.git");
1355 if (CGit::GitPathFileExists(temp))
1357 CString gitignore = temp;
1358 gitignore += _T("ignore");
1359 if ((ret = CheckFileAgainstIgnoreList(gitignore, patha, base, type)) != -1)
1360 break;
1362 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1363 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1364 if ((ret = CheckFileAgainstIgnoreList(wcglobalgitignore, patha, base, type)) != -1)
1365 break;
1367 m_SharedMutex.AcquireShared();
1368 CString excludesFile = m_CoreExcludesfiles[adminDir];
1369 m_SharedMutex.ReleaseShared();
1370 if (!excludesFile.IsEmpty())
1371 ret = CheckFileAgainstIgnoreList(excludesFile, patha, base, type);
1373 break;
1375 else
1377 temp += _T("ignore");
1378 if ((ret = CheckFileAgainstIgnoreList(temp, patha, base, type)) != -1)
1379 break;
1382 int found = 0;
1383 int i;
1384 for (i = temp.GetLength() - 1; i >= 0; i--)
1386 if (temp[i] == _T('\\'))
1387 ++found;
1389 if (found == 2)
1390 break;
1393 temp = temp.Left(i);
1396 patha.ReleaseBuffer();
1398 return ret;
1401 bool CGitHeadFileMap::CheckHeadAndUpdate(const CString &gitdir, bool readTree /* = true */)
1403 SHARED_TREE_PTR ptr;
1404 ptr = this->SafeGet(gitdir);
1406 if (ptr.get() && !ptr->CheckHeadUpdate() && (!readTree || ptr->HeadHashEqualsTreeHash()))
1407 return false;
1409 ptr = SHARED_TREE_PTR(new CGitHeadFileList);
1410 ptr->ReadHeadHash(gitdir);
1411 if (readTree)
1412 ptr->ReadTree();
1414 this->SafeSet(gitdir, ptr);
1416 return true;
1419 int CGitHeadFileMap::IsUnderVersionControl(const CString &gitdir, const CString &path, bool isDir, bool *isVersion)
1423 if (path.IsEmpty())
1425 *isVersion = true;
1426 return 0;
1429 CString subpath = path;
1430 subpath.Replace(_T('\\'), _T('/'));
1431 if(isDir)
1432 subpath += _T('/');
1434 subpath.MakeLower();
1436 CheckHeadAndUpdate(gitdir);
1438 SHARED_TREE_PTR treeptr = SafeGet(gitdir);
1440 // Init Repository
1441 if (treeptr->HeadFileIsEmpty())
1443 *isVersion = false;
1444 return 0;
1446 else if (treeptr->empty())
1448 *isVersion = false;
1449 return 1;
1452 if(isDir)
1453 *isVersion = (SearchInSortVector(*treeptr, subpath.GetBuffer(), subpath.GetLength()) >= 0);
1454 else
1455 *isVersion = (SearchInSortVector(*treeptr, subpath.GetBuffer(), -1) >= 0);
1456 subpath.ReleaseBuffer();
1458 catch(...)
1460 return -1;
1463 return 0;