Allow to use the repository name in Git Label Decorations
[egit.git] / org.eclipse.egit.ui / src / org / eclipse / egit / ui / internal / decorators / DecoratableResourceAdapter.java
blob2cf5b8bd81cc9effbf24d92263e4b737e3f15915
1 /*******************************************************************************
2 * Copyright (C) 2007, IBM Corporation and others
3 * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
4 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
5 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
6 * Copyright (C) 2008, Google Inc.
7 * Copyright (C) 2008, Tor Arne Vestbø <torarnv@gmail.com>
9 * All rights reserved. This program and the accompanying materials
10 * are made available under the terms of the Eclipse Public License v1.0
11 * which accompanies this distribution, and is available at
12 * http://www.eclipse.org/legal/epl-v10.html
13 *******************************************************************************/
15 package org.eclipse.egit.ui.internal.decorators;
17 import java.io.File;
18 import java.io.IOException;
19 import java.util.Collections;
20 import java.util.Set;
22 import org.eclipse.core.resources.IProject;
23 import org.eclipse.core.resources.IResource;
24 import org.eclipse.core.resources.IWorkspaceRoot;
25 import org.eclipse.egit.core.AdaptableFileTreeIterator;
26 import org.eclipse.egit.core.ContainerTreeIterator;
27 import org.eclipse.egit.core.ContainerTreeIterator.ResourceEntry;
28 import org.eclipse.egit.core.project.RepositoryMapping;
29 import org.eclipse.egit.ui.Activator;
30 import org.eclipse.egit.ui.UIPreferences;
31 import org.eclipse.jface.preference.IPreferenceStore;
32 import org.eclipse.team.core.Team;
33 import org.eclipse.jgit.dircache.DirCache;
34 import org.eclipse.jgit.dircache.DirCacheEntry;
35 import org.eclipse.jgit.dircache.DirCacheIterator;
36 import org.eclipse.jgit.errors.IncorrectObjectTypeException;
37 import org.eclipse.jgit.errors.MissingObjectException;
38 import org.eclipse.jgit.lib.Constants;
39 import org.eclipse.jgit.lib.FileMode;
40 import org.eclipse.jgit.lib.ObjectId;
41 import org.eclipse.jgit.lib.Repository;
42 import org.eclipse.jgit.revwalk.RevWalk;
43 import org.eclipse.jgit.treewalk.EmptyTreeIterator;
44 import org.eclipse.jgit.treewalk.TreeWalk;
45 import org.eclipse.jgit.treewalk.WorkingTreeIterator;
46 import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
47 import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
48 import org.eclipse.jgit.treewalk.filter.TreeFilter;
50 class DecoratableResourceAdapter implements IDecoratableResource {
52 private final IResource resource;
54 private final RepositoryMapping mapping;
56 private final Repository repository;
58 private final ObjectId headId;
60 private final IPreferenceStore store;
62 private String branch = ""; //$NON-NLS-1$
64 private final String repositoryName;
66 private boolean tracked = false;
68 private boolean ignored = false;
70 private boolean dirty = false;
72 private boolean conflicts = false;
74 private boolean assumeValid = false;
76 private Staged staged = Staged.NOT_STAGED;
78 static final int T_HEAD = 0;
80 static final int T_INDEX = 1;
82 static final int T_WORKSPACE = 2;
84 @SuppressWarnings("fallthrough")
85 public DecoratableResourceAdapter(IResource resourceToWrap)
86 throws IOException {
87 resource = resourceToWrap;
88 mapping = RepositoryMapping.getMapping(resource);
89 repository = mapping.getRepository();
90 headId = repository.resolve(Constants.HEAD);
92 store = Activator.getDefault().getPreferenceStore();
94 File gitDir = repository.getDirectory();
95 if (gitDir != null)
96 repositoryName = repository.getDirectory().getParentFile()
97 .getName();
98 else
99 repositoryName = ""; //$NON-NLS-1$
100 // TODO: Add option to shorten branch name to 6 chars if it's a SHA
101 branch = repository.getBranch();
103 TreeWalk treeWalk = createThreeWayTreeWalk();
104 if (treeWalk == null)
105 return;
107 switch (resource.getType()) {
108 case IResource.FILE:
109 if (!treeWalk.next())
110 return;
111 extractResourceProperties(treeWalk);
112 break;
113 case IResource.PROJECT:
114 tracked = true;
115 case IResource.FOLDER:
116 extractContainerProperties(treeWalk);
117 break;
121 private void extractResourceProperties(TreeWalk treeWalk) {
122 final ContainerTreeIterator workspaceIterator = treeWalk.getTree(
123 T_WORKSPACE, ContainerTreeIterator.class);
124 final ResourceEntry resourceEntry = workspaceIterator != null ? workspaceIterator
125 .getResourceEntry() : null;
127 if (resourceEntry == null)
128 return;
130 if (isIgnored(resourceEntry.getResource())) {
131 ignored = true;
132 return;
135 final int mHead = treeWalk.getRawMode(T_HEAD);
136 final int mIndex = treeWalk.getRawMode(T_INDEX);
138 if (mHead == FileMode.MISSING.getBits()
139 && mIndex == FileMode.MISSING.getBits())
140 return;
142 tracked = true;
144 if (mHead == FileMode.MISSING.getBits()) {
145 staged = Staged.ADDED;
146 } else if (mIndex == FileMode.MISSING.getBits()) {
147 staged = Staged.REMOVED;
148 } else if (mHead != mIndex
149 || (mIndex != FileMode.TREE.getBits() && !treeWalk.idEqual(
150 T_HEAD, T_INDEX))) {
151 staged = Staged.MODIFIED;
152 } else {
153 staged = Staged.NOT_STAGED;
156 final DirCacheIterator indexIterator = treeWalk.getTree(T_INDEX,
157 DirCacheIterator.class);
158 final DirCacheEntry indexEntry = indexIterator != null ? indexIterator
159 .getDirCacheEntry() : null;
161 if (indexEntry == null)
162 return;
164 if (indexEntry.getStage() > 0)
165 conflicts = true;
167 if (indexEntry.isAssumeValid()) {
168 dirty = false;
169 assumeValid = true;
170 } else {
171 if (!timestampMatches(indexEntry, resourceEntry))
172 dirty = true;
174 // TODO: Consider doing a content check here, to rule out false
175 // positives, as we might get mismatch between timestamps, even
176 // if the content is the same.
180 private class RecursiveStateFilter extends TreeFilter {
182 private int filesChecked = 0;
184 private int targetDepth = -1;
186 private final int recurseLimit;
188 public RecursiveStateFilter() {
189 recurseLimit = store
190 .getInt(UIPreferences.DECORATOR_RECURSIVE_LIMIT);
193 @Override
194 public boolean include(TreeWalk treeWalk)
195 throws MissingObjectException, IncorrectObjectTypeException,
196 IOException {
198 if (treeWalk.getFileMode(T_HEAD) == FileMode.MISSING
199 && treeWalk.getFileMode(T_INDEX) == FileMode.MISSING)
200 return false;
202 if (FileMode.TREE.equals(treeWalk.getRawMode(T_WORKSPACE)))
203 return shouldRecurse(treeWalk);
205 // Backup current state so far
206 Staged wasStaged = staged;
207 boolean wasDirty = dirty;
208 boolean hadConflicts = conflicts;
210 extractResourceProperties(treeWalk);
211 filesChecked++;
213 // Merge results with old state
214 ignored = false;
215 assumeValid = false;
216 dirty = wasDirty || dirty;
217 conflicts = hadConflicts || conflicts;
218 if (staged != wasStaged && filesChecked > 1)
219 staged = Staged.MODIFIED;
221 return false;
224 private boolean shouldRecurse(TreeWalk treeWalk) {
225 final WorkingTreeIterator workspaceIterator = treeWalk.getTree(
226 T_WORKSPACE, WorkingTreeIterator.class);
228 if (workspaceIterator instanceof AdaptableFileTreeIterator)
229 return true;
231 ResourceEntry resourceEntry = null;
232 if (workspaceIterator != null)
233 resourceEntry = ((ContainerTreeIterator) workspaceIterator)
234 .getResourceEntry();
236 if (resourceEntry == null)
237 return true;
239 IResource visitingResource = resourceEntry.getResource();
240 if (targetDepth == -1) {
241 if (visitingResource.equals(resource)
242 || visitingResource.getParent().equals(resource))
243 targetDepth = treeWalk.getDepth();
244 else
245 return true;
248 if ((treeWalk.getDepth() - targetDepth) >= recurseLimit) {
249 if (visitingResource.equals(resource))
250 extractResourceProperties(treeWalk);
252 return false;
255 return true;
258 @Override
259 public TreeFilter clone() {
260 RecursiveStateFilter clone = new RecursiveStateFilter();
261 clone.filesChecked = this.filesChecked;
262 return clone;
265 @Override
266 public boolean shouldBeRecursive() {
267 return true;
271 private void extractContainerProperties(TreeWalk treeWalk) throws IOException {
273 if (isIgnored(resource)) {
274 ignored = true;
275 return;
278 treeWalk.setFilter(AndTreeFilter.create(treeWalk.getFilter(),
279 new RecursiveStateFilter()));
280 treeWalk.setRecursive(true);
282 treeWalk.next();
286 * Adds a filter to the specified tree walk limiting the results to only
287 * those matching the resource specified by <code>resourceToFilterBy</code>
288 * <p>
289 * If the resource does not exists in the current repository, no filter is
290 * added and the method returns <code>false</code>. If the resource is a
291 * project, no filter is added, but the operation is considered a success.
293 * @param treeWalk
294 * the tree walk to add the filter to
295 * @param resourceToFilterBy
296 * the resource to filter by
298 * @return <code>true</code> if the filter could be added,
299 * <code>false</code> otherwise
301 private boolean addResourceFilter(final TreeWalk treeWalk,
302 final IResource resourceToFilterBy) {
303 Set<String> repositoryPaths = Collections.singleton(mapping
304 .getRepoRelativePath(resourceToFilterBy));
305 if (repositoryPaths.isEmpty())
306 return false;
308 if (repositoryPaths.contains("")) //$NON-NLS-1$
309 return true; // Project filter
311 treeWalk.setFilter(PathFilterGroup.createFromStrings(repositoryPaths));
312 return true;
316 * Helper method to create a new tree walk between the repository, the
317 * index, and the working tree.
319 * @return the created tree walk, or null if it could not be created
320 * @throws IOException
321 * if there were errors when creating the tree walk
323 private TreeWalk createThreeWayTreeWalk() throws IOException {
324 final TreeWalk treeWalk = new TreeWalk(repository);
325 if (!addResourceFilter(treeWalk, resource))
326 return null;
328 treeWalk.setRecursive(treeWalk.getFilter().shouldBeRecursive());
329 treeWalk.reset();
331 // Repository
332 if (headId != null)
333 treeWalk.addTree(new RevWalk(repository).parseTree(headId));
334 else
335 treeWalk.addTree(new EmptyTreeIterator());
337 // Index
338 treeWalk.addTree(new DirCacheIterator(DirCache.read(repository)));
340 // Working directory
341 IProject project = resource.getProject();
342 IWorkspaceRoot workspaceRoot = resource.getWorkspace().getRoot();
343 File repoRoot = repository.getWorkDir();
345 if (repoRoot.equals(project.getLocation().toFile()))
346 treeWalk.addTree(new ContainerTreeIterator(project));
347 else if (repoRoot.equals(workspaceRoot.getLocation().toFile()))
348 treeWalk.addTree(new ContainerTreeIterator(workspaceRoot));
349 else
350 treeWalk.addTree(new AdaptableFileTreeIterator(repoRoot,
351 workspaceRoot));
353 return treeWalk;
356 private static boolean timestampMatches(DirCacheEntry indexEntry,
357 ResourceEntry resourceEntry) {
358 long tIndex = indexEntry.getLastModified();
359 long tWorkspaceResource = resourceEntry.getLastModified();
362 // C-Git under Windows stores timestamps with 1-seconds resolution,
363 // so we need to check to see if this is the case here, and possibly
364 // fix the timestamp of the resource to match the resolution of the
365 // index.
366 // It also appears the timestamp in Java on Linux may also be rounded
367 // in which case the index timestamp may have subseconds, but not
368 // the timestamp from the workspace resource.
369 // If either timestamp looks rounded we skip the subscond part.
370 if (tIndex % 1000 == 0 || tWorkspaceResource % 1000 == 0) {
371 return tIndex / 1000 == tWorkspaceResource / 1000;
372 } else {
373 return tIndex == tWorkspaceResource;
377 private static boolean isIgnored(IResource resource) {
378 // TODO: Also read ignores from .git/info/excludes et al.
379 return Team.isIgnoredHint(resource);
382 public String getName() {
383 return resource.getName();
386 public int getType() {
387 return resource.getType();
390 public String getRepositoryName() {
391 return repositoryName;
394 public String getBranch() {
395 return branch;
398 public boolean isTracked() {
399 return tracked;
402 public boolean isIgnored() {
403 return ignored;
406 public boolean isDirty() {
407 return dirty;
410 public Staged staged() {
411 return staged;
414 public boolean hasConflicts() {
415 return conflicts;
418 public boolean isAssumeValid() {
419 return assumeValid;