Dropped unused includes
[TortoiseGit.git] / src / Git / GitIndex.cpp
blobfb184a978d237e36dcd306087759baa405a714c0
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 "registry.h"
23 #include "GitConfig.h"
24 #include <map>
25 #include "UnicodeUtils.h"
26 #include "TGitPath.h"
27 #include "gitindex.h"
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include "SmartHandle.h"
32 class CAutoReadLock
34 SharedMutex *m_Lock;
35 public:
36 CAutoReadLock(SharedMutex * lock)
38 m_Lock = lock;
39 lock->AcquireShared();
41 ~CAutoReadLock()
43 m_Lock->ReleaseShared();
47 class CAutoWriteLock
49 SharedMutex *m_Lock;
50 public:
51 CAutoWriteLock(SharedMutex * lock)
53 m_Lock = lock;
54 lock->AcquireExclusive();
56 ~CAutoWriteLock()
58 m_Lock->ReleaseExclusive();
62 CGitAdminDirMap g_AdminDirMap;
64 int CGitIndex::Print()
66 _tprintf(_T("0x%08X 0x%08X %s %s\n"),
67 (int)this->m_ModifyTime,
68 this->m_Flags,
69 this->m_IndexHash.ToString(),
70 this->m_FileName);
72 return 0;
75 CGitIndexList::CGitIndexList()
77 this->m_LastModifyTime = 0;
78 m_critRepoSec.Init();
79 repository = NULL;
80 m_bCheckContent = !!(CRegDWORD(_T("Software\\TortoiseGit\\TGitCacheCheckContent"), TRUE) == TRUE);
83 CGitIndexList::~CGitIndexList()
85 if (repository != NULL)
87 git_repository_free(repository);
88 m_critRepoSec.Term();
92 static bool SortIndex(CGitIndex &Item1, CGitIndex &Item2)
94 return Item1.m_FileName.Compare(Item2.m_FileName) < 0;
97 static bool SortTree(CGitTreeItem &Item1, CGitTreeItem &Item2)
99 return Item1.m_FileName.Compare(Item2.m_FileName) < 0;
102 int CGitIndexList::ReadIndex(CString dgitdir)
104 this->clear();
106 CStringA gitdir = CUnicodeUtils::GetMulti(dgitdir, CP_UTF8);
108 m_critRepoSec.Lock();
109 if (repository != NULL)
111 git_repository_free(repository);
112 repository = NULL;
114 git_index *index = NULL;
116 int ret = git_repository_open(&repository, gitdir.GetBuffer());
117 gitdir.ReleaseBuffer();
118 if (ret)
119 return -1;
121 // add config files
122 git_config * config;
123 git_config_new(&config);
125 CString projectConfig = dgitdir + _T("config");
126 CString globalConfig = g_Git.GetGitGlobalConfig();
127 CString globalXDGConfig = g_Git.GetGitGlobalXDGConfig();
128 CString msysGitBinPath(CRegString(REG_MSYSGIT_PATH, _T(""), FALSE));
130 CStringA projectConfigA = CUnicodeUtils::GetMulti(projectConfig, CP_UTF8);
131 git_config_add_file_ondisk(config, projectConfigA.GetBuffer(), 4, FALSE);
132 projectConfigA.ReleaseBuffer();
133 CStringA globalConfigA = CUnicodeUtils::GetMulti(globalConfig, CP_UTF8);
134 git_config_add_file_ondisk(config, globalConfigA.GetBuffer(), 3, FALSE);
135 globalConfigA.ReleaseBuffer();
136 CStringA globalXDGConfigA = CUnicodeUtils::GetMulti(globalXDGConfig, CP_UTF8);
137 git_config_add_file_ondisk(config, globalXDGConfigA.GetBuffer(), 2, FALSE);
138 globalXDGConfigA.ReleaseBuffer();
139 if (!msysGitBinPath.IsEmpty())
141 CString systemConfig = msysGitBinPath + _T("\\..\\etc\\gitconfig");
142 CStringA systemConfigA = CUnicodeUtils::GetMulti(systemConfig, CP_UTF8);
143 git_config_add_file_ondisk(config, systemConfigA.GetBuffer(), 1, FALSE);
144 systemConfigA.ReleaseBuffer();
147 git_repository_set_config(repository, config);
148 git_config_free(config);
149 config = nullptr;
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 if (filesize == 0)
525 ret = -1;
526 break;
528 DWORD size =0;
529 char *buff;
530 buff = new char[filesize];
532 ReadFile(hfile, buff, filesize, &size, NULL);
534 if (size != filesize)
536 delete[] buff;
537 ret = -1;
538 break;
541 CString hash;
542 CString ref;
544 for(DWORD i=0;i<filesize;)
546 hash.Empty();
547 ref.Empty();
548 if (buff[i] == '#' || buff[i] == '^')
550 while (buff[i] != '\n')
552 ++i;
553 if (i == filesize)
554 break;
556 ++i;
559 if (i >= filesize)
560 break;
562 while (buff[i] != ' ')
564 hash.AppendChar(buff[i]);
565 ++i;
566 if (i == filesize)
567 break;
570 ++i;
571 if (i >= filesize)
572 break;
574 while (buff[i] != '\n')
576 ref.AppendChar(buff[i]);
577 ++i;
578 if (i == filesize)
579 break;
582 if (!ref.IsEmpty() )
584 this->m_PackRefMap[ref] = hash;
587 while (buff[i] == '\n')
589 ++i;
590 if (i == filesize)
591 break;
595 delete[] buff;
597 } while(0);
599 return ret;
602 int CGitHeadFileList::ReadHeadHash(CString gitdir)
604 int ret = 0;
605 CAutoWriteLock lock(&this->m_SharedMutex);
606 m_Gitdir = g_AdminDirMap.GetAdminDir(gitdir);
608 m_HeadFile = m_Gitdir + _T("HEAD");
610 if( g_Git.GetFileModifyTime(m_HeadFile, &m_LastModifyTimeHead))
611 return -1;
617 CAutoFile hfile = CreateFile(m_HeadFile,
618 GENERIC_READ,
619 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
620 NULL,
621 OPEN_EXISTING,
622 FILE_ATTRIBUTE_NORMAL,
623 NULL);
625 if (!hfile)
627 ret = -1;
628 break;
631 DWORD size = 0,filesize = 0;
632 unsigned char buffer[40] ;
633 ReadFile(hfile, buffer, 4, &size, NULL);
634 if (size != 4)
636 ret = -1;
637 break;
639 buffer[4]=0;
640 if (strcmp((const char*)buffer,"ref:") == 0)
642 filesize = GetFileSize(hfile, NULL);
643 if (filesize < 5)
645 m_HeadRefFile.Empty();
646 ret = -1;
647 break;
650 unsigned char *p = (unsigned char*)malloc(filesize -4);
652 ReadFile(hfile, p, filesize - 4, &size, NULL);
654 m_HeadRefFile.Empty();
655 g_Git.StringAppend(&this->m_HeadRefFile, p, CP_UTF8, filesize - 4);
656 CString ref = this->m_HeadRefFile;
657 ref = ref.Trim();
658 int start = 0;
659 ref = ref.Tokenize(_T("\n"), start);
660 free(p);
661 m_HeadRefFile = m_Gitdir + m_HeadRefFile.Trim();
662 m_HeadRefFile.Replace(_T('/'),_T('\\'));
664 __int64 time;
665 if (g_Git.GetFileModifyTime(m_HeadRefFile, &time, NULL))
667 m_HeadRefFile.Empty();
668 if (GetPackRef(gitdir))
670 ret = -1;
671 break;
673 if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
675 ret = -1;
676 break;
678 this ->m_Head = m_PackRefMap[ref];
679 ret = 0;
680 break;
683 CAutoFile href = CreateFile(m_HeadRefFile,
684 GENERIC_READ,
685 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
686 NULL,
687 OPEN_EXISTING,
688 FILE_ATTRIBUTE_NORMAL,
689 NULL);
691 if (!href)
693 m_HeadRefFile.Empty();
695 if (GetPackRef(gitdir))
697 ret = -1;
698 break;
701 if (this->m_PackRefMap.find(ref) == m_PackRefMap.end())
703 ret = -1;
704 break;
706 this ->m_Head = m_PackRefMap[ref];
707 ret = 0;
708 break;
710 ReadFile(href, buffer, 40, &size, NULL);
711 if (size != 40)
713 ret = -1;
714 break;
716 this->m_Head.ConvertFromStrA((char*)buffer);
718 this->m_LastModifyTimeRef = time;
721 else
723 ReadFile(hfile, buffer + 4, 40 - 4, &size, NULL);
724 if(size != 36)
726 ret = -1;
727 break;
729 m_HeadRefFile.Empty();
731 this->m_Head.ConvertFromStrA((char*)buffer);
733 } while(0);
735 catch(...)
737 ret = -1;
740 return ret;
743 bool CGitHeadFileList::CheckHeadUpdate()
745 CAutoReadLock lock(&m_SharedMutex);
746 if (this->m_HeadFile.IsEmpty())
747 return true;
749 __int64 mtime=0;
751 if (g_Git.GetFileModifyTime(m_HeadFile, &mtime))
752 return true;
754 if (mtime != this->m_LastModifyTimeHead)
755 return true;
757 if (!this->m_HeadRefFile.IsEmpty())
759 if (g_Git.GetFileModifyTime(m_HeadRefFile, &mtime))
760 return true;
762 if (mtime != this->m_LastModifyTimeRef)
763 return true;
766 if(!this->m_PackRefFile.IsEmpty())
768 if (g_Git.GetFileModifyTime(m_PackRefFile, &mtime))
769 return true;
771 if (mtime != this->m_LastModifyTimePackRef)
772 return true;
775 // in an empty repo HEAD points to refs/heads/master, but this ref doesn't exist.
776 // So we need to retry again and again until the ref exists - otherwise we will never notice
777 if (this->m_Head.IsEmpty() && this->m_HeadRefFile.IsEmpty() && this->m_PackRefFile.IsEmpty())
778 return true;
780 return false;
783 bool CGitHeadFileList::HeadHashEqualsTreeHash()
785 CAutoReadLock lock(&this->m_SharedMutex);
786 return (m_Head == m_TreeHash);
789 bool CGitHeadFileList::HeadFileIsEmpty()
791 CAutoReadLock lock(&this->m_SharedMutex);
792 return m_HeadFile.IsEmpty();
795 bool CGitHeadFileList::HeadIsEmpty()
797 CAutoReadLock lock(&this->m_SharedMutex);
798 return m_Head.IsEmpty();
801 int CGitHeadFileList::CallBack(const unsigned char *sha1, const char *base, int baselen,
802 const char *pathname, unsigned mode, int /*stage*/, void *context)
804 #define S_IFGITLINK 0160000
806 CGitHeadFileList *p = (CGitHeadFileList*)context;
807 if( mode&S_IFDIR )
809 if( (mode&S_IFMT) != S_IFGITLINK)
810 return READ_TREE_RECURSIVE;
813 size_t cur = p->size();
814 p->resize(p->size() + 1);
815 p->at(cur).m_Hash = (char*)sha1;
816 p->at(cur).m_FileName.Empty();
818 if(base)
819 g_Git.StringAppend(&p->at(cur).m_FileName, (BYTE*)base, CP_UTF8, baselen);
821 g_Git.StringAppend(&p->at(cur).m_FileName,(BYTE*)pathname, CP_UTF8);
823 p->at(cur).m_FileName.MakeLower();
825 //p->at(cur).m_FileName.Replace(_T('/'), _T('\\'));
827 //p->m_Map[p->at(cur).m_FileName] = cur;
829 if( (mode&S_IFMT) == S_IFGITLINK)
830 return 0;
832 return READ_TREE_RECURSIVE;
835 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)
837 size_t count = git_tree_entrycount(tree);
838 for (size_t i = 0; i < count; ++i)
840 const git_tree_entry *entry = git_tree_entry_byindex(tree, i);
841 if (entry == NULL)
842 continue;
843 int mode = git_tree_entry_filemode(entry);
844 if( CallBack(git_tree_entry_id(entry)->id,
845 base,
846 base.GetLength(),
847 git_tree_entry_name(entry),
848 mode,
850 data) == READ_TREE_RECURSIVE
853 if(mode&S_IFDIR)
855 git_object *object = NULL;
856 git_tree_entry_to_object(&object, &repo, entry);
857 if (object == NULL)
858 continue;
859 CStringA parent = base;
860 parent += git_tree_entry_name(entry);
861 parent += "/";
862 ReadTreeRecursive(repo, (git_tree*)object, parent, CallBack, data);
863 git_object_free(object);
869 return 0;
872 // ReadTree is/must only be executed on an empty list
873 int CGitHeadFileList::ReadTree()
875 CAutoWriteLock lock(&m_SharedMutex);
876 CStringA gitdir = CUnicodeUtils::GetMulti(m_Gitdir, CP_UTF8);
877 git_repository *repository = NULL;
878 git_commit *commit = NULL;
879 git_tree * tree = NULL;
880 int ret = 0;
881 ATLASSERT(this->empty());
884 ret = git_repository_open(&repository, gitdir.GetBuffer());
885 gitdir.ReleaseBuffer();
886 if(ret)
887 break;
888 ret = git_commit_lookup(&commit, repository, (const git_oid*)m_Head.m_hash);
889 if(ret)
890 break;
892 ret = git_commit_tree(&tree, commit);
893 if(ret)
894 break;
896 ret = ReadTreeRecursive(*repository, tree,"", CGitHeadFileList::CallBack,this);
897 if(ret)
898 break;
900 std::sort(this->begin(), this->end(), SortTree);
901 this->m_TreeHash = (char*)(git_commit_id(commit)->id);
903 } while(0);
905 if (tree)
906 git_tree_free(tree);
908 if (commit)
909 git_commit_free(commit);
911 if (repository)
912 git_repository_free(repository);
914 if (ret)
916 clear();
917 m_LastModifyTimeHead = 0;
920 return ret;
923 int CGitIgnoreItem::FetchIgnoreList(const CString &projectroot, const CString &file, bool isGlobal)
925 CAutoWriteLock lock(&this->m_SharedMutex);
927 if (this->m_pExcludeList)
929 git_free_exclude_list(m_pExcludeList);
930 m_pExcludeList=NULL;
932 if (m_buffer)
934 free(m_buffer);
935 m_buffer = NULL;
938 this->m_BaseDir.Empty();
939 if (!isGlobal)
941 CString base = file.Mid(projectroot.GetLength() + 1);
942 base.Replace(_T('\\'), _T('/'));
944 int start = base.ReverseFind(_T('/'));
945 if(start > 0)
947 base = base.Left(start);
948 this->m_BaseDir = CUnicodeUtils::GetMulti(base, CP_UTF8) + "/";
953 if(g_Git.GetFileModifyTime(file, &m_LastModifyTime))
954 return -1;
956 if(git_create_exclude_list(&this->m_pExcludeList))
957 return -1;
960 CAutoFile hfile = CreateFile(file,
961 GENERIC_READ,
962 FILE_SHARE_READ|FILE_SHARE_DELETE|FILE_SHARE_WRITE,
963 NULL,
964 OPEN_EXISTING,
965 FILE_ATTRIBUTE_NORMAL,
966 NULL);
969 if (!hfile)
970 return -1 ;
972 DWORD size=0,filesize=0;
974 filesize=GetFileSize(hfile, NULL);
976 if(filesize == INVALID_FILE_SIZE)
977 return -1;
979 m_buffer = new BYTE[filesize + 1];
981 if (m_buffer == NULL)
982 return -1;
984 if (!ReadFile(hfile, m_buffer, filesize, &size, NULL))
985 return GetLastError();
987 BYTE *p = m_buffer;
988 for (DWORD i = 0; i < size; ++i)
990 if (m_buffer[i] == '\n' || m_buffer[i] == '\r' || i == (size - 1))
992 if (m_buffer[i] == '\n' || m_buffer[i] == '\r')
993 m_buffer[i] = 0;
994 if (i == size - 1)
995 m_buffer[size] = 0;
997 if(p[0] != '#' && p[0] != 0)
998 git_add_exclude((const char*)p,
999 this->m_BaseDir.GetBuffer(),
1000 m_BaseDir.GetLength(),
1001 this->m_pExcludeList);
1003 p = m_buffer + i + 1;
1007 return 0;
1010 bool CGitIgnoreList::CheckFileChanged(const CString &path)
1012 __int64 time = 0;
1014 int ret = g_Git.GetFileModifyTime(path, &time);
1016 this->m_SharedMutex.AcquireShared();
1017 bool cacheExist = (m_Map.find(path) != m_Map.end());
1018 this->m_SharedMutex.ReleaseShared();
1020 if (!cacheExist && ret == 0)
1022 CAutoWriteLock lock(&this->m_SharedMutex);
1023 m_Map[path].m_LastModifyTime = 0;
1024 m_Map[path].m_SharedMutex.Init();
1026 // both cache and file is not exist
1027 if ((ret != 0) && (!cacheExist))
1028 return false;
1030 // file exist but cache miss
1031 if ((ret == 0) && (!cacheExist))
1032 return true;
1034 // file not exist but cache exist
1035 if ((ret != 0) && (cacheExist))
1037 return true;
1039 // file exist and cache exist
1042 CAutoReadLock lock(&this->m_SharedMutex);
1043 if (m_Map[path].m_LastModifyTime == time)
1044 return false;
1046 return true;
1049 bool CGitIgnoreList::CheckIgnoreChanged(const CString &gitdir,const CString &path)
1051 CString temp;
1052 temp = gitdir;
1053 temp += _T("\\");
1054 temp += path;
1056 temp.Replace(_T('/'), _T('\\'));
1058 while(!temp.IsEmpty())
1060 CString tempOrig = temp;
1061 temp += _T("\\.git");
1063 if (CGit::GitPathFileExists(temp))
1065 CString gitignore=temp;
1066 gitignore += _T("ignore");
1067 if (CheckFileChanged(gitignore))
1068 return true;
1070 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1071 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1072 if (CheckFileChanged(wcglobalgitignore))
1073 return true;
1075 if (CheckAndUpdateCoreExcludefile(adminDir))
1076 return true;
1078 return false;
1080 else
1082 temp += _T("ignore");
1083 if (CheckFileChanged(temp))
1084 return true;
1087 int found=0;
1088 int i;
1089 for (i = temp.GetLength() - 1; i >= 0; i--)
1091 if(temp[i] == _T('\\'))
1092 ++found;
1094 if(found == 2)
1095 break;
1098 temp = temp.Left(i);
1100 return true;
1103 int CGitIgnoreList::FetchIgnoreFile(const CString &gitdir, const CString &gitignore, bool isGlobal)
1105 if (CGit::GitPathFileExists(gitignore)) //if .gitignore remove, we need remote cache
1107 CAutoWriteLock lock(&this->m_SharedMutex);
1108 if (m_Map.find(gitignore) == m_Map.end())
1109 m_Map[gitignore].m_SharedMutex.Init();
1111 m_Map[gitignore].FetchIgnoreList(gitdir, gitignore, isGlobal);
1113 else
1115 CAutoWriteLock lock(&this->m_SharedMutex);
1116 if (m_Map.find(gitignore) != m_Map.end())
1117 m_Map[gitignore].m_SharedMutex.Release();
1119 m_Map.erase(gitignore);
1121 return 0;
1124 int CGitIgnoreList::LoadAllIgnoreFile(const CString &gitdir,const CString &path)
1126 CString temp;
1128 temp = gitdir;
1129 temp += _T("\\");
1130 temp += path;
1132 temp.Replace(_T('/'), _T('\\'));
1134 while (!temp.IsEmpty())
1136 CString tempOrig = temp;
1137 temp += _T("\\.git");
1139 if (CGit::GitPathFileExists(temp))
1141 CString gitignore = temp;
1142 gitignore += _T("ignore");
1143 if (CheckFileChanged(gitignore))
1145 FetchIgnoreFile(gitdir, gitignore, false);
1148 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1149 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1150 if (CheckFileChanged(wcglobalgitignore))
1152 FetchIgnoreFile(gitdir, wcglobalgitignore, true);
1155 if (CheckAndUpdateCoreExcludefile(adminDir))
1157 m_SharedMutex.AcquireShared();
1158 CString excludesFile = m_CoreExcludesfiles[adminDir];
1159 m_SharedMutex.ReleaseShared();
1160 if (!excludesFile.IsEmpty())
1161 FetchIgnoreFile(gitdir, excludesFile, true);
1164 return 0;
1166 else
1168 temp += _T("ignore");
1169 if (CheckFileChanged(temp))
1171 FetchIgnoreFile(gitdir, temp, false);
1175 int found = 0;
1176 int i;
1177 for (i = temp.GetLength() - 1; i >= 0; i--)
1179 if(temp[i] == _T('\\'))
1180 ++found;
1182 if(found == 2)
1183 break;
1186 temp = temp.Left(i);
1188 return 0;
1190 bool CGitIgnoreList::CheckAndUpdateMsysGitBinpath(bool force)
1192 // recheck every 30 seconds
1193 if (GetTickCount() - m_dMsysGitBinPathLastChecked > 30000 || force)
1195 m_dMsysGitBinPathLastChecked = GetTickCount();
1196 CString msysGitBinPath(CRegString(REG_MSYSGIT_PATH, _T(""), FALSE));
1197 if (msysGitBinPath != m_sMsysGitBinPath)
1199 m_sMsysGitBinPath = msysGitBinPath;
1200 return true;
1203 return false;
1205 bool CGitIgnoreList::CheckAndUpdateCoreExcludefile(const CString &adminDir)
1207 bool hasChanged = false;
1209 CString projectConfig = adminDir + _T("config");
1210 CString globalConfig = g_Git.GetGitGlobalConfig();
1211 CString globalXDGConfig = g_Git.GetGitGlobalXDGConfig();
1213 CAutoWriteLock lock(&m_coreExcludefilesSharedMutex);
1214 hasChanged = CheckAndUpdateMsysGitBinpath();
1215 CString systemConfig = m_sMsysGitBinPath + _T("\\..\\etc\\gitconfig");
1217 hasChanged = hasChanged || CheckFileChanged(projectConfig);
1218 hasChanged = hasChanged || CheckFileChanged(globalConfig);
1219 hasChanged = hasChanged || CheckFileChanged(globalXDGConfig);
1220 if (!m_sMsysGitBinPath.IsEmpty())
1221 hasChanged = hasChanged || CheckFileChanged(systemConfig);
1223 m_SharedMutex.AcquireShared();
1224 CString excludesFile = m_CoreExcludesfiles[adminDir];
1225 m_SharedMutex.ReleaseShared();
1226 if (!excludesFile.IsEmpty())
1227 hasChanged = hasChanged || CheckFileChanged(excludesFile);
1229 if (!hasChanged)
1230 return false;
1232 git_config * config;
1233 git_config_new(&config);
1234 CStringA projectConfigA = CUnicodeUtils::GetMulti(projectConfig, CP_UTF8);
1235 git_config_add_file_ondisk(config, projectConfigA.GetBuffer(), 4, FALSE);
1236 projectConfigA.ReleaseBuffer();
1237 CStringA globalConfigA = CUnicodeUtils::GetMulti(globalConfig, CP_UTF8);
1238 git_config_add_file_ondisk(config, globalConfigA.GetBuffer(), 3, FALSE);
1239 globalConfigA.ReleaseBuffer();
1240 CStringA globalXDGConfigA = CUnicodeUtils::GetMulti(globalXDGConfig, CP_UTF8);
1241 git_config_add_file_ondisk(config, globalXDGConfigA.GetBuffer(), 2, FALSE);
1242 globalXDGConfigA.ReleaseBuffer();
1243 if (!m_sMsysGitBinPath.IsEmpty())
1245 CStringA systemConfigA = CUnicodeUtils::GetMulti(systemConfig, CP_UTF8);
1246 git_config_add_file_ondisk(config, systemConfigA.GetBuffer(), 1, FALSE);
1247 systemConfigA.ReleaseBuffer();
1249 const char * out = NULL;
1250 CStringA name(_T("core.excludesfile"));
1251 git_config_get_string(&out, config, name.GetBuffer());
1252 name.ReleaseBuffer();
1253 CStringA excludesFileA(out);
1254 excludesFile = CUnicodeUtils::GetUnicode(excludesFileA);
1255 if (excludesFile.IsEmpty())
1256 excludesFile = GetWindowsHome() + _T("\\.config\\git\\ignore");
1257 else if (excludesFile.Find(_T("~/")) == 0)
1258 excludesFile = GetWindowsHome() + excludesFile.Mid(1);
1259 git_config_free(config);
1261 CAutoWriteLock lockMap(&m_SharedMutex);
1262 g_Git.GetFileModifyTime(projectConfig, &m_Map[projectConfig].m_LastModifyTime);
1263 g_Git.GetFileModifyTime(globalXDGConfig, &m_Map[globalXDGConfig].m_LastModifyTime);
1264 if (m_Map[globalXDGConfig].m_LastModifyTime == 0)
1266 m_Map[globalXDGConfig].m_SharedMutex.Release();
1267 m_Map.erase(globalXDGConfig);
1269 g_Git.GetFileModifyTime(globalConfig, &m_Map[globalConfig].m_LastModifyTime);
1270 if (m_Map[globalConfig].m_LastModifyTime == 0)
1272 m_Map[globalConfig].m_SharedMutex.Release();
1273 m_Map.erase(globalConfig);
1275 if (!m_sMsysGitBinPath.IsEmpty())
1276 g_Git.GetFileModifyTime(systemConfig, &m_Map[systemConfig].m_LastModifyTime);
1277 if (m_Map[systemConfig].m_LastModifyTime == 0 || m_sMsysGitBinPath.IsEmpty())
1279 m_Map[systemConfig].m_SharedMutex.Release();
1280 m_Map.erase(systemConfig);
1282 m_CoreExcludesfiles[adminDir] = excludesFile;
1284 return true;
1286 const CString CGitIgnoreList::GetWindowsHome()
1288 static CString sWindowsHome(g_Git.GetHomeDirectory());
1289 return sWindowsHome;
1291 bool CGitIgnoreList::IsIgnore(const CString &path,const CString &projectroot)
1293 CString str=path;
1295 str.Replace(_T('\\'),_T('/'));
1297 if (str.GetLength()>0)
1298 if (str[str.GetLength()-1] == _T('/'))
1299 str = str.Left(str.GetLength() - 1);
1301 int ret;
1302 ret = CheckIgnore(str, projectroot);
1303 while (ret < 0)
1305 int start = str.ReverseFind(_T('/'));
1306 if(start < 0)
1307 return (ret == 1);
1309 str = str.Left(start);
1310 ret = CheckIgnore(str, projectroot);
1313 return (ret == 1);
1315 int CGitIgnoreList::CheckFileAgainstIgnoreList(const CString &ignorefile, const CStringA &patha, const char * base, int &type)
1317 if (m_Map.find(ignorefile) != m_Map.end())
1319 int ret = -1;
1320 if(m_Map[ignorefile].m_pExcludeList)
1321 ret = git_check_excluded_1(patha, patha.GetLength(), base, &type, m_Map[ignorefile].m_pExcludeList);
1322 if (ret == 0 || ret == 1)
1323 return ret;
1325 return -1;
1327 int CGitIgnoreList::CheckIgnore(const CString &path,const CString &projectroot)
1329 __int64 time = 0;
1330 bool dir = 0;
1331 CString temp = projectroot + _T("\\") + path;
1332 temp.Replace(_T('/'), _T('\\'));
1334 CStringA patha = CUnicodeUtils::GetMulti(path, CP_UTF8);
1335 patha.Replace('\\', '/');
1337 if(g_Git.GetFileModifyTime(temp, &time, &dir))
1338 return -1;
1340 int type = 0;
1341 if (dir)
1343 type = DT_DIR;
1345 // strip directory name
1346 // we do not need to check for a .ignore file inside a directory we might ignore
1347 int i = temp.ReverseFind(_T('\\'));
1348 if (i >= 0)
1349 temp = temp.Left(i);
1351 else
1352 type = DT_REG;
1354 char * base = NULL;
1355 int pos = patha.ReverseFind('/');
1356 base = pos >= 0 ? patha.GetBuffer() + pos + 1 : patha.GetBuffer();
1358 int ret = -1;
1360 CAutoReadLock lock(&this->m_SharedMutex);
1361 while (!temp.IsEmpty())
1363 CString tempOrig = temp;
1364 temp += _T("\\.git");
1366 if (CGit::GitPathFileExists(temp))
1368 CString gitignore = temp;
1369 gitignore += _T("ignore");
1370 if ((ret = CheckFileAgainstIgnoreList(gitignore, patha, base, type)) != -1)
1371 break;
1373 CString adminDir = g_AdminDirMap.GetAdminDir(tempOrig);
1374 CString wcglobalgitignore = adminDir + _T("info\\exclude");
1375 if ((ret = CheckFileAgainstIgnoreList(wcglobalgitignore, patha, base, type)) != -1)
1376 break;
1378 m_SharedMutex.AcquireShared();
1379 CString excludesFile = m_CoreExcludesfiles[adminDir];
1380 m_SharedMutex.ReleaseShared();
1381 if (!excludesFile.IsEmpty())
1382 ret = CheckFileAgainstIgnoreList(excludesFile, patha, base, type);
1384 break;
1386 else
1388 temp += _T("ignore");
1389 if ((ret = CheckFileAgainstIgnoreList(temp, patha, base, type)) != -1)
1390 break;
1393 int found = 0;
1394 int i;
1395 for (i = temp.GetLength() - 1; i >= 0; i--)
1397 if (temp[i] == _T('\\'))
1398 ++found;
1400 if (found == 2)
1401 break;
1404 temp = temp.Left(i);
1407 patha.ReleaseBuffer();
1409 return ret;
1412 bool CGitHeadFileMap::CheckHeadAndUpdate(const CString &gitdir, bool readTree /* = true */)
1414 SHARED_TREE_PTR ptr;
1415 ptr = this->SafeGet(gitdir);
1417 if (ptr.get() && !ptr->CheckHeadUpdate() && (!readTree || ptr->HeadHashEqualsTreeHash()))
1418 return false;
1420 ptr = SHARED_TREE_PTR(new CGitHeadFileList);
1421 ptr->ReadHeadHash(gitdir);
1422 if (readTree)
1423 ptr->ReadTree();
1425 this->SafeSet(gitdir, ptr);
1427 return true;
1430 int CGitHeadFileMap::IsUnderVersionControl(const CString &gitdir, const CString &path, bool isDir, bool *isVersion)
1434 if (path.IsEmpty())
1436 *isVersion = true;
1437 return 0;
1440 CString subpath = path;
1441 subpath.Replace(_T('\\'), _T('/'));
1442 if(isDir)
1443 subpath += _T('/');
1445 subpath.MakeLower();
1447 CheckHeadAndUpdate(gitdir);
1449 SHARED_TREE_PTR treeptr = SafeGet(gitdir);
1451 // Init Repository
1452 if (treeptr->HeadFileIsEmpty())
1454 *isVersion = false;
1455 return 0;
1457 else if (treeptr->empty())
1459 *isVersion = false;
1460 return 1;
1463 if(isDir)
1464 *isVersion = (SearchInSortVector(*treeptr, subpath.GetBuffer(), subpath.GetLength()) >= 0);
1465 else
1466 *isVersion = (SearchInSortVector(*treeptr, subpath.GetBuffer(), -1) >= 0);
1467 subpath.ReleaseBuffer();
1469 catch(...)
1471 return -1;
1474 return 0;