Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f83134c3632a8ed19398bbf2c97383889d6ec2c7 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*******************************************************************************
 * Copyright (C) 2007, IBM Corporation and others
 * Copyright (C) 2007, Dave Watson <dwatson@mimvista.com>
 * Copyright (C) 2008, Robin Rosenberg <robin.rosenberg@dewire.com>
 * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
 * Copyright (C) 2008, Google Inc.
 * Copyright (C) 2008, Tor Arne Vestbø <torarnv@gmail.com>
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *******************************************************************************/

package org.eclipse.egit.ui.internal.decorators;

import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.egit.core.AdaptableFileTreeIterator;
import org.eclipse.egit.core.ContainerTreeIterator;
import org.eclipse.egit.core.ContainerTreeIterator.ResourceEntry;
import org.eclipse.egit.core.project.RepositoryMapping;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.team.core.Team;
import org.eclipse.jgit.dircache.DirCache;
import org.eclipse.jgit.dircache.DirCacheEntry;
import org.eclipse.jgit.dircache.DirCacheIterator;
import org.eclipse.jgit.errors.IncorrectObjectTypeException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.FileMode;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevWalk;
import org.eclipse.jgit.treewalk.EmptyTreeIterator;
import org.eclipse.jgit.treewalk.TreeWalk;
import org.eclipse.jgit.treewalk.WorkingTreeIterator;
import org.eclipse.jgit.treewalk.filter.AndTreeFilter;
import org.eclipse.jgit.treewalk.filter.PathFilterGroup;
import org.eclipse.jgit.treewalk.filter.TreeFilter;

class DecoratableResourceAdapter implements IDecoratableResource {

	private final IResource resource;

	private final RepositoryMapping mapping;

	private final Repository repository;

	private final ObjectId headId;

	private final IPreferenceStore store;

	private String branch = ""; //$NON-NLS-1$

	private boolean tracked = false;

	private boolean ignored = false;

	private boolean dirty = false;

	private boolean conflicts = false;

	private boolean assumeValid = false;

	private Staged staged = Staged.NOT_STAGED;

	static final int T_HEAD = 0;

	static final int T_INDEX = 1;

	static final int T_WORKSPACE = 2;

	@SuppressWarnings("fallthrough")
	public DecoratableResourceAdapter(IResource resourceToWrap)
			throws IOException {
		resource = resourceToWrap;
		mapping = RepositoryMapping.getMapping(resource);
		repository = mapping.getRepository();
		headId = repository.resolve(Constants.HEAD);

		store = Activator.getDefault().getPreferenceStore();

		// TODO: Add option to shorten branch name to 6 chars if it's a SHA
		branch = repository.getBranch();

		TreeWalk treeWalk = createThreeWayTreeWalk();
		if (treeWalk == null)
			return;

		switch (resource.getType()) {
		case IResource.FILE:
			if (!treeWalk.next())
				return;
			extractResourceProperties(treeWalk);
			break;
		case IResource.PROJECT:
			tracked = true;
		case IResource.FOLDER:
			extractContainerProperties(treeWalk);
			break;
		}
	}

	private void extractResourceProperties(TreeWalk treeWalk) {
		final ContainerTreeIterator workspaceIterator = treeWalk.getTree(
				T_WORKSPACE, ContainerTreeIterator.class);
		final ResourceEntry resourceEntry = workspaceIterator != null ? workspaceIterator
				.getResourceEntry() : null;

		if (resourceEntry == null)
			return;

		if (isIgnored(resourceEntry.getResource())) {
			ignored = true;
			return;
		}

		final int mHead = treeWalk.getRawMode(T_HEAD);
		final int mIndex = treeWalk.getRawMode(T_INDEX);

		if (mHead == FileMode.MISSING.getBits()
				&& mIndex == FileMode.MISSING.getBits())
			return;

		tracked = true;

		if (mHead == FileMode.MISSING.getBits()) {
			staged = Staged.ADDED;
		} else if (mIndex == FileMode.MISSING.getBits()) {
			staged = Staged.REMOVED;
		} else if (mHead != mIndex
				|| (mIndex != FileMode.TREE.getBits() && !treeWalk.idEqual(
						T_HEAD, T_INDEX))) {
			staged = Staged.MODIFIED;
		} else {
			staged = Staged.NOT_STAGED;
		}

		final DirCacheIterator indexIterator = treeWalk.getTree(T_INDEX,
				DirCacheIterator.class);
		final DirCacheEntry indexEntry = indexIterator != null ? indexIterator
				.getDirCacheEntry() : null;

		if (indexEntry == null)
			return;

		if (indexEntry.getStage() > 0)
			conflicts = true;

		if (indexEntry.isAssumeValid()) {
			dirty = false;
			assumeValid = true;
		} else {
			if (!timestampMatches(indexEntry, resourceEntry))
				dirty = true;

			// TODO: Consider doing a content check here, to rule out false
			// positives, as we might get mismatch between timestamps, even
			// if the content is the same.
		}
	}

	private class RecursiveStateFilter extends TreeFilter {

		private int filesChecked = 0;

		private int targetDepth = -1;

		private final int recurseLimit;

		public RecursiveStateFilter() {
			recurseLimit = store
					.getInt(UIPreferences.DECORATOR_RECURSIVE_LIMIT);
		}

		@Override
		public boolean include(TreeWalk treeWalk)
				throws MissingObjectException, IncorrectObjectTypeException,
				IOException {

			if (treeWalk.getFileMode(T_HEAD) == FileMode.MISSING
					&& treeWalk.getFileMode(T_INDEX) == FileMode.MISSING)
				return false;

			if (FileMode.TREE.equals(treeWalk.getRawMode(T_WORKSPACE)))
				return shouldRecurse(treeWalk);

			// Backup current state so far
			Staged wasStaged = staged;
			boolean wasDirty = dirty;
			boolean hadConflicts = conflicts;

			extractResourceProperties(treeWalk);
			filesChecked++;

			// Merge results with old state
			ignored = false;
			assumeValid = false;
			dirty = wasDirty || dirty;
			conflicts = hadConflicts || conflicts;
			if (staged != wasStaged && filesChecked > 1)
				staged = Staged.MODIFIED;

			return false;
		}

		private boolean shouldRecurse(TreeWalk treeWalk) {
			final WorkingTreeIterator workspaceIterator = treeWalk.getTree(
					T_WORKSPACE, WorkingTreeIterator.class);

			if (workspaceIterator instanceof AdaptableFileTreeIterator)
				return true;

			ResourceEntry resourceEntry = null;
			if (workspaceIterator != null)
				resourceEntry = ((ContainerTreeIterator) workspaceIterator)
						.getResourceEntry();

			if (resourceEntry == null)
				return true;

			IResource visitingResource = resourceEntry.getResource();
			if (targetDepth == -1) {
				if (visitingResource.equals(resource)
						|| visitingResource.getParent().equals(resource))
					targetDepth = treeWalk.getDepth();
				else
					return true;
			}

			if ((treeWalk.getDepth() - targetDepth) >= recurseLimit) {
				if (visitingResource.equals(resource))
					extractResourceProperties(treeWalk);

				return false;
			}

			return true;
		}

		@Override
		public TreeFilter clone() {
			RecursiveStateFilter clone = new RecursiveStateFilter();
			clone.filesChecked = this.filesChecked;
			return clone;
		}

		@Override
		public boolean shouldBeRecursive() {
			return true;
		}
	}

	private void extractContainerProperties(TreeWalk treeWalk) throws IOException {

		if (isIgnored(resource)) {
			ignored = true;
			return;
		}

		treeWalk.setFilter(AndTreeFilter.create(treeWalk.getFilter(),
				new RecursiveStateFilter()));
		treeWalk.setRecursive(true);

		treeWalk.next();
	}

	/**
	 * Adds a filter to the specified tree walk limiting the results to only
	 * those matching the resource specified by <code>resourceToFilterBy</code>
	 * <p>
	 * If the resource does not exists in the current repository, no filter is
	 * added and the method returns <code>false</code>. If the resource is a
	 * project, no filter is added, but the operation is considered a success.
	 *
	 * @param treeWalk
	 *            the tree walk to add the filter to
	 * @param resourceToFilterBy
	 *            the resource to filter by
	 *
	 * @return <code>true</code> if the filter could be added,
	 *         <code>false</code> otherwise
	 */
	private boolean addResourceFilter(final TreeWalk treeWalk,
			final IResource resourceToFilterBy) {
		Set<String> repositoryPaths = Collections.singleton(mapping
				.getRepoRelativePath(resourceToFilterBy));
		if (repositoryPaths.isEmpty())
			return false;

		if (repositoryPaths.contains("")) //$NON-NLS-1$
			return true; // Project filter

		treeWalk.setFilter(PathFilterGroup.createFromStrings(repositoryPaths));
		return true;
	}

	/**
	 * Helper method to create a new tree walk between the repository, the
	 * index, and the working tree.
	 *
	 * @return the created tree walk, or null if it could not be created
	 * @throws IOException
	 *             if there were errors when creating the tree walk
	 */
	private TreeWalk createThreeWayTreeWalk() throws IOException {
		final TreeWalk treeWalk = new TreeWalk(repository);
		if (!addResourceFilter(treeWalk, resource))
			return null;

		treeWalk.setRecursive(treeWalk.getFilter().shouldBeRecursive());
		treeWalk.reset();

		// Repository
		if (headId != null)
			treeWalk.addTree(new RevWalk(repository).parseTree(headId));
		else
			treeWalk.addTree(new EmptyTreeIterator());

		// Index
		treeWalk.addTree(new DirCacheIterator(DirCache.read(repository)));

		// Working directory
		IProject project = resource.getProject();
		IWorkspaceRoot workspaceRoot = resource.getWorkspace().getRoot();
		File repoRoot = repository.getWorkDir();

		if (repoRoot.equals(project.getLocation().toFile()))
			treeWalk.addTree(new ContainerTreeIterator(project));
		else if (repoRoot.equals(workspaceRoot.getLocation().toFile()))
			treeWalk.addTree(new ContainerTreeIterator(workspaceRoot));
		else
			treeWalk.addTree(new AdaptableFileTreeIterator(repoRoot,
					workspaceRoot));

		return treeWalk;
	}

	private static boolean timestampMatches(DirCacheEntry indexEntry,
			ResourceEntry resourceEntry) {
		long tIndex = indexEntry.getLastModified();
		long tWorkspaceResource = resourceEntry.getLastModified();


		// C-Git under Windows stores timestamps with 1-seconds resolution,
		// so we need to check to see if this is the case here, and possibly
		// fix the timestamp of the resource to match the resolution of the
		// index.
		// It also appears the timestamp in Java on Linux may also be rounded
		// in which case the index timestamp may have subseconds, but not
		// the timestamp from the workspace resource.
		// If either timestamp looks rounded we skip the subscond part.
		if (tIndex % 1000 == 0 || tWorkspaceResource % 1000 == 0) {
			return tIndex / 1000 == tWorkspaceResource / 1000;
		} else {
			return tIndex == tWorkspaceResource;
		}
	}

	private static boolean isIgnored(IResource resource) {
		// TODO: Also read ignores from .git/info/excludes et al.
		return Team.isIgnoredHint(resource);
	}

	public String getName() {
		return resource.getName();
	}

	public int getType() {
		return resource.getType();
	}

	public String getBranch() {
		return branch;
	}

	public boolean isTracked() {
		return tracked;
	}

	public boolean isIgnored() {
		return ignored;
	}

	public boolean isDirty() {
		return dirty;
	}

	public Staged staged() {
		return staged;
	}

	public boolean hasConflicts() {
		return conflicts;
	}

	public boolean isAssumeValid() {
		return assumeValid;
	}
}

Back to the top