Skip to content

Commit

Permalink
Merge pull request apache#7093 from mbien/fix-jgit-deprecations
Browse files Browse the repository at this point in the history
Fixes all deprecated API usage in libs.jgit
  • Loading branch information
mbien authored Feb 28, 2024
2 parents acd617c + 2983c0f commit bcaa1ab
Show file tree
Hide file tree
Showing 25 changed files with 182 additions and 165 deletions.
3 changes: 2 additions & 1 deletion ide/libs.git/nbproject/project.properties
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

is.autoload=true

javac.source=1.8
javac.source=11
javac.target=11

javadoc.arch=${basedir}/arch.xml
javadoc.apichanges=${basedir}/apichanges.xml
Expand Down
12 changes: 12 additions & 0 deletions ide/libs.git/src/org/netbeans/libs/git/GitBranch.java
Original file line number Diff line number Diff line change
Expand Up @@ -91,4 +91,16 @@ public GitBranch getTrackedBranch () {
void setTrackedBranch (GitBranch trackedBranch) {
this.trackedBranch = trackedBranch;
}

@Override
public String toString() {
return "GitBranch{"
+ "name=" + name
+ ", id=" + getId()
+ ", remote=" + remote
+ ", active=" + active
+ ", trackedBranch=" + trackedBranch
+ '}';
}

}
8 changes: 4 additions & 4 deletions ide/libs.git/src/org/netbeans/libs/git/jgit/IgnoreRule.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ public class IgnoreRule extends org.eclipse.jgit.ignore.FastIgnoreRule {
private final String noNegationPattern;

public IgnoreRule (String pattern) {
super(pattern.trim());
super(pattern.strip());
this.pattern = pattern;
pattern = pattern.trim();
this.noNegationPattern = pattern.startsWith("!") ? pattern.substring(1) : null;
String neg = pattern.strip();
this.noNegationPattern = neg.startsWith("!") ? neg.substring(1) : null;
}

public String getPattern (boolean preprocess) {
Expand All @@ -50,7 +50,7 @@ public String getPattern (boolean preprocess) {

@Override
public boolean isMatch(String target, boolean isDirectory) {
String trimmed = pattern.trim();
String trimmed = pattern.strip();
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
// this is a comment or an empty line
return false;
Expand Down
2 changes: 1 addition & 1 deletion ide/libs.git/src/org/netbeans/libs/git/jgit/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -442,7 +442,7 @@ public static GitBranch getTrackedBranch (Config config, String branchName, Map<
}
}

public static Map getAllBranches (Repository repository, GitClassFactory fac, ProgressMonitor monitor) throws GitException {
public static Map<String, GitBranch> getAllBranches(Repository repository, GitClassFactory fac, ProgressMonitor monitor) throws GitException {
ListBranchCommand cmd = new ListBranchCommand(repository, fac, true, monitor);
cmd.execute();
return cmd.getBranches();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ protected void run() throws GitException {
if (f != null) { // the file exists
File file = new File(repository.getWorkTree().getAbsolutePath() + File.separator + path);
DirCacheEntry entry = new DirCacheEntry(path);
entry.setLastModified(f.getEntryLastModified());
entry.setLastModified(f.getEntryLastModifiedInstant());
int fm = f.getEntryFileMode().getBits();
long sz = f.getEntryLength();
Path p = null;
Expand All @@ -129,7 +129,7 @@ protected void run() throws GitException {
entry.setLength(0);
BasicFileAttributes attrs = Files.readAttributes(p, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
if (attrs != null) {
entry.setLastModified(attrs.lastModifiedTime().toMillis());
entry.setLastModified(attrs.lastModifiedTime().toInstant());
}
entry.setObjectId(inserter.insert(Constants.OBJ_BLOB, Constants.encode(link.toString())));
} else if ((f.getEntryFileMode().getBits() & FileMode.TYPE_TREE) == FileMode.TYPE_TREE) {
Expand All @@ -153,7 +153,7 @@ protected void run() throws GitException {
}
}
ObjectId oldId = treeWalk.getObjectId(0);
if (ObjectId.equals(oldId, ObjectId.zeroId()) || !ObjectId.equals(oldId, entry.getObjectId())) {
if (ObjectId.isEqual(oldId, ObjectId.zeroId()) || !ObjectId.isEqual(oldId, entry.getObjectId())) {
listener.notifyFile(file, path);
}
builder.add(entry);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
import org.netbeans.libs.git.progress.FileListener;
import org.netbeans.libs.git.progress.ProgressMonitor;

import static java.nio.charset.StandardCharsets.UTF_8;

/**
*
* @author ondra
Expand Down Expand Up @@ -325,7 +327,7 @@ private void resolveEntries (MergeAlgorithm merger, String path, DirCacheEntry[]
DirCacheEntry e = new DirCacheEntry(path);
e.setCreationTime(theirs.getCreationTime());
e.setFileMode(theirs.getFileMode());
e.setLastModified(theirs.getLastModified());
e.setLastModified(theirs.getLastModifiedInstant());
e.setLength(theirs.getLength());
e.setObjectId(theirs.getObjectId());
builder.add(e);
Expand Down Expand Up @@ -360,8 +362,7 @@ private void checkoutFile (MergeResult<RawText> merge, String path) throws IOExc
try (OutputStream fos = opt.getAutoCRLF() != CoreConfig.AutoCRLF.FALSE
? new AutoCRLFOutputStream(new FileOutputStream(file))
: new FileOutputStream(file)) {
format.formatMerge(fos, merge, Arrays.asList(new String[] { "BASE", "OURS", "THEIRS" }), //NOI18N
Constants.CHARACTER_ENCODING);
format.formatMerge(fos, merge, Arrays.asList(new String[] { "BASE", "OURS", "THEIRS" }), UTF_8); //NOI18N
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,11 @@
public class ConflictCommand extends StatusCommand {

private final ProgressMonitor monitor;
private final StatusListener listener;
private final File[] roots;

public ConflictCommand (Repository repository, GitClassFactory gitFactory, File[] roots, ProgressMonitor monitor, StatusListener listener) {
super(repository, Constants.HEAD, roots, gitFactory, monitor, listener);
this.monitor = monitor;
this.listener = listener;
this.roots = roots;
}

Expand Down Expand Up @@ -93,7 +91,7 @@ protected void run () throws GitException {
DirCacheIterator indexIterator = treeWalk.getTree(0, DirCacheIterator.class);
DirCacheEntry indexEntry = indexIterator != null ? indexIterator.getDirCacheEntry() : null;
int stage = indexEntry == null ? 0 : indexEntry.getStage();
long indexTS = indexEntry == null ? -1 : indexEntry.getLastModified();
long indexTS = indexEntry == null ? -1 : indexEntry.getLastModifiedInstant().toEpochMilli();

if (stage != 0) {
GitStatus status = getClassFactory().createStatus(true, path, workTreePath, file,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package org.netbeans.libs.git.jgit.commands;

import java.io.IOException;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.RefUpdate;
import org.eclipse.jgit.lib.RefUpdate.Result;
Expand All @@ -35,23 +36,21 @@
*/
public class DeleteTagCommand extends GitCommand {
private final String tagName;
private GitRefUpdateResult result;

public DeleteTagCommand (Repository repository, GitClassFactory gitFactory, String tagName, ProgressMonitor monitor) {
public DeleteTagCommand(Repository repository, GitClassFactory gitFactory, String tagName, ProgressMonitor monitor) {
super(repository, gitFactory, monitor);
this.tagName = tagName;
}

@Override
protected void run () throws GitException {
protected void run() throws GitException {
Repository repository = getRepository();
Ref currentRef = repository.getTags().get(tagName);
if (currentRef == null) {
throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
}
String fullName = currentRef.getName();
try {
RefUpdate update = repository.updateRef(fullName);
Ref currentRef = repository.exactRef(Constants.R_TAGS + tagName);
if (currentRef == null) {
throw new GitException.MissingObjectException(tagName, GitObjectType.TAG);
}
RefUpdate update = repository.updateRef(currentRef.getName());
update.setRefLogMessage("tag deleted", false);
update.setForceUpdate(true);
Result deleteResult = update.delete();
Expand All @@ -69,7 +68,7 @@ protected void run () throws GitException {
}

@Override
protected String getCommandDescription () {
protected String getCommandDescription() {
return "git tag -d " + tagName;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,19 @@
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jgit.ignore.IgnoreNode.MatchResult;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.CoreConfig;
Expand Down Expand Up @@ -64,7 +63,7 @@ public IgnoreUnignoreCommand (Repository repository, GitClassFactory gitFactory,
super(repository, gitFactory, monitor);
this.files = files;
this.monitor = monitor;
this.ignoreFiles = new LinkedHashSet<File>();
this.ignoreFiles = new LinkedHashSet<>();
this.listener = listener;
}

Expand Down Expand Up @@ -104,7 +103,7 @@ protected void run () {
private void changeIgnoreStatus (File f) throws IOException {
File parent = f;
boolean isDirectory = f.isDirectory() && (! Files.isSymbolicLink(f.toPath()));
StringBuilder sb = new StringBuilder('/');
StringBuilder sb = new StringBuilder();
if (isDirectory) {
sb.append('/');
}
Expand All @@ -129,68 +128,56 @@ private boolean addStatement (File gitIgnore, String path, boolean isDirectory,
return addStatement(ignoreRules, gitIgnore, path, isDirectory, forceWrite, true) == MatchResult.CHECK_PARENT;
}

protected final void save (File gitIgnore, List<IgnoreRule> ignoreRules) throws IOException {
BufferedWriter bw = null;
File tmpFile = Files.createTempFile(gitIgnore.getParentFile().toPath(), Constants.DOT_GIT_IGNORE, "tmp").toFile(); //NOI18N
protected final void save(File gitIgnore, List<IgnoreRule> ignoreRules) throws IOException {
try {
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tmpFile), Constants.CHARSET));
for (ListIterator<IgnoreRule> it = ignoreRules.listIterator(); it.hasNext(); ) {
String s = it.next().getPattern(false);
bw.write(s, 0, s.length());
bw.newLine();
}
} finally {
if (bw != null) {
try {
bw.close();
} catch (IOException ex) { }
}
if (!tmpFile.renameTo(gitIgnore)) {
// cannot rename directly, try backup and delete te original .gitignore
File tmpCopy = generateTempFile(Constants.DOT_GIT_IGNORE, gitIgnore.getParentFile()); //NOI18N
boolean success = false;
if (gitIgnore.renameTo(tmpCopy)) {
// and try to rename again
success = tmpFile.renameTo(gitIgnore);
if (!success) {
// restore te original .gitignore file
tmpCopy.renameTo(gitIgnore);
Path tmpFile = Files.createTempFile(gitIgnore.getParentFile().toPath(), Constants.DOT_GIT_IGNORE, "tmp"); //NOI18N
try {
String lineSeparator = probeLineSeparator(gitIgnore.toPath());
try (BufferedWriter writer = Files.newBufferedWriter(tmpFile)) {
for (IgnoreRule rule : ignoreRules) {
writer.write(rule.getPattern(false));
writer.write(lineSeparator);
}
tmpCopy.delete();
}
if (!success) {
tmpFile.delete();
throw new IOException("Cannot write to " + gitIgnore.getAbsolutePath());
}
Files.move(tmpFile, gitIgnore.toPath(), StandardCopyOption.REPLACE_EXISTING);
} finally {
Files.deleteIfExists(tmpFile);
}

} catch (IOException ex) {
throw new IOException("Cannot update .gitignore at " + gitIgnore.getAbsolutePath(), ex);
}
ignoreFiles.add(gitIgnore);
}

private List<IgnoreRule> parse (File gitIgnore) throws IOException {
List<IgnoreRule> rules = new LinkedList<IgnoreRule>();
private List<IgnoreRule> parse(File gitIgnore) throws IOException {
if (gitIgnore.exists()) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(gitIgnore), Constants.CHARSET));
String txt;
while ((txt = br.readLine()) != null) {
rules.add(new IgnoreRule(txt));
}
} finally {
if (br != null) {
try {
br.close();
} catch (IOException ex) { }
try (Stream<String> lines = Files.lines(gitIgnore.toPath())) {
return lines.map(IgnoreRule::new)
.collect(Collectors.toCollection(LinkedList::new));
}
}
return new LinkedList<>();
}

@SuppressWarnings("NestedAssignment")
private static String probeLineSeparator(Path file) throws IOException {
if (Files.exists(file)) {
try (BufferedReader br = Files.newBufferedReader(file)) {
int current;
int last = -1;
while ((current = br.read()) != -1) {
if (current == '\n') {
return last == '\r' ? "\r\n" : "\n";
}
last = current;
}
}
}
return rules;
return System.lineSeparator();
}

public File[] getModifiedIgnoreFiles () {
return ignoreFiles.toArray(new File[0]);
return ignoreFiles.toArray(File[]::new);
}

protected abstract MatchResult addStatement (List<IgnoreRule> ignoreRules, File gitIgnore, String path, boolean isDirectory, boolean forceWrite, boolean writable) throws IOException;
Expand All @@ -214,14 +201,6 @@ protected final MatchResult checkGlobalExcludeFile (String path, boolean directo
return MatchResult.NOT_IGNORED;
}

private File generateTempFile (String basename, File parent) {
File tempFile = new File(parent, basename);
while (tempFile.exists()) {
tempFile = new File(parent, basename + Long.toString(System.currentTimeMillis()));
}
return tempFile;
}

private File getGlobalExcludeFile () {
Repository repository = getRepository();
String path = repository.getConfig().get(CoreConfig.KEY).getExcludesFile();
Expand Down
Loading

0 comments on commit bcaa1ab

Please sign in to comment.