View Javadoc
1   /*
2    * Copyright (C) 2019, Google LLC 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.internal.storage.reftable;
12  
13  import org.eclipse.jgit.lib.ReflogEntry;
14  import org.eclipse.jgit.lib.ReflogReader;
15  
16  import java.io.IOException;
17  import java.util.ArrayList;
18  import java.util.List;
19  import java.util.concurrent.locks.Lock;
20  
21  /**
22   * Implement the ReflogReader interface for a reflog stored in reftable.
23   */
24  public class ReftableReflogReader implements ReflogReader {
25  	private final Lock lock;
26  
27  	private final Reftable reftable;
28  
29  	private final String refname;
30  
31  	ReftableReflogReader(Lock lock, Reftable merged, String refname) {
32  		this.lock = lock;
33  		this.reftable = merged;
34  		this.refname = refname;
35  	}
36  
37  	/** {@inheritDoc} */
38  	@Override
39  	public ReflogEntry getLastEntry() throws IOException {
40  		lock.lock();
41  		try {
42  			LogCursor cursor = reftable.seekLog(refname);
43  			return cursor.next() ? cursor.getReflogEntry() : null;
44  		} finally {
45  			lock.unlock();
46  		}
47  	}
48  
49  	/** {@inheritDoc} */
50  	@Override
51  	public List<ReflogEntry> getReverseEntries() throws IOException {
52  		return getReverseEntries(Integer.MAX_VALUE);
53  	}
54  
55  	/** {@inheritDoc} */
56  	@Override
57  	public ReflogEntry getReverseEntry(int number) throws IOException {
58  		lock.lock();
59  		try {
60  			LogCursor cursor = reftable.seekLog(refname);
61  			while (true) {
62  				if (!cursor.next() || number < 0) {
63  					return null;
64  				}
65  				if (number == 0) {
66  					return cursor.getReflogEntry();
67  				}
68  				number--;
69  			}
70  		} finally {
71  			lock.unlock();
72  		}
73  	}
74  
75  	/** {@inheritDoc} */
76  	@Override
77  	public List<ReflogEntry> getReverseEntries(int max) throws IOException {
78  		lock.lock();
79  		try {
80  			LogCursor cursor = reftable.seekLog(refname);
81  
82  			List<ReflogEntry> result = new ArrayList<>();
83  			while (cursor.next() && result.size() < max) {
84  				result.add(cursor.getReflogEntry());
85  			}
86  
87  			return result;
88  		} finally {
89  			lock.unlock();
90  		}
91  	}
92  }