View Javadoc
1   /*
2    * Copyright (C) 2015, 2021 Dariusz Luksza <dariusz@luksza.org> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  
11  package org.eclipse.jgit.lfs.lib;
12  
13  import java.io.IOException;
14  
15  import org.eclipse.jgit.errors.IncorrectObjectTypeException;
16  import org.eclipse.jgit.errors.MissingObjectException;
17  import org.eclipse.jgit.lfs.LfsPointer;
18  import org.eclipse.jgit.lib.ObjectId;
19  import org.eclipse.jgit.lib.ObjectLoader;
20  import org.eclipse.jgit.lib.ObjectStream;
21  import org.eclipse.jgit.treewalk.TreeWalk;
22  import org.eclipse.jgit.treewalk.filter.TreeFilter;
23  
24  /**
25   * Detects Large File pointers, as described in [1] in Git repository.
26   *
27   * [1] https://github.com/github/git-lfs/blob/master/docs/spec.md
28   *
29   * @since 4.7
30   */
31  public class LfsPointerFilter extends TreeFilter {
32  
33  	private LfsPointer pointer;
34  
35  	/**
36  	 * Get the field <code>pointer</code>.
37  	 *
38  	 * @return {@link org.eclipse.jgit.lfs.LfsPointer} or {@code null}
39  	 */
40  	public LfsPointer getPointer() {
41  		return pointer;
42  	}
43  
44  	/** {@inheritDoc} */
45  	@Override
46  	public boolean include(TreeWalk walk) throws MissingObjectException,
47  			IncorrectObjectTypeException, IOException {
48  		pointer = null;
49  		if (walk.isSubtree()) {
50  			return walk.isRecursive();
51  		}
52  		ObjectId objectId = walk.getObjectId(0);
53  		ObjectLoader object = walk.getObjectReader().open(objectId);
54  		if (object.getSize() > 1024) {
55  			return false;
56  		}
57  
58  		try (ObjectStream stream = object.openStream()) {
59  			pointer = LfsPointer.parseLfsPointer(stream);
60  			return pointer != null;
61  		} catch (RuntimeException e) {
62  			return false;
63  		}
64  	}
65  
66  	/** {@inheritDoc} */
67  	@Override
68  	public boolean shouldBeRecursive() {
69  		return false;
70  	}
71  
72  	/** {@inheritDoc} */
73  	@Override
74  	public TreeFilter clone() {
75  		return new LfsPointerFilter();
76  	}
77  }