How to JGit blame a file before commit? - java

Context: My merge ran into conflicts and I have a file like this example:
Foo.txt (merged)
1
<<<<<< HEAD
2-master
======
2-side
>>>>>> df803849788fde47965b3dc8f07f07d48320ea9c
3
Question: In order to get the developers who actually changed the conflicting lines, how to blame result file (above) prior to the commit? It works for git blame Foo.txt
Problem: I tried to do the following, but the blame is null inside the loop.
MergeResult m = runMerge(aScenario);
BlameCommand blamer = new BlameCommand(git.getRepository());
BufferedReader br = new BufferedReader(new FileReader(new File(mergedfilepath)));
BlameResult blame = blamer.setFilePath(mergedfilepath).call();
for (int i = 0; (line= br.readLine())!=null ; i++) {
// the blame at this point is null.
PersonIdent person = blame.getSourceAuthor(i);
System.out.println(person.getName() + ": "+ line);
}

I think the source of the traversal should be the result contents.
Starting from there you can loop over the changed regions and ask for the author. For example:
BlameResult blameResult = git.blame().setFilePath( ... ).call();
int size = blameResult.getResultContents().size();
for( int i = 0; i < size; i++ ) {
System.out.println( blameResult.getSourceAuthor( i ) );
}
At least for lines added to the work directory version of the file, an author named Not Committed Yet is returned.
However, your code should be prepared cope with getSourceAuthor() returning null. The JavaDoc states that the return value may be null.

Related

How do I get jgit to find a different head if master isn't there?

I'm using this code to create a powerpoint with changed files:
try (Git git = new Git(repo)) {
DiffFormatter df = new DiffFormatter(NullOutputStream.INSTANCE);
df.setRepository( git.getRepository() );
Iterable<RevCommit> commits = git.log().all().call();
for (RevCommit commit : commits) {
if(commit.getParents().length != 0) {
System.out.println("LogCommit: " + commit);
List<DiffEntry> entries = df.scan(commit.getId(), commit.getParent(0).getId());
for( DiffEntry entry : entries ) {
String filename = entry.getPath(DiffEntry.Side.NEW);
if(!filename.equals("/dev/null")) {
Integer currentCount = 0;
if(fileChanges.containsKey(filename)) {
currentCount = fileChanges.get(filename);
}else {
System.out.println(" DiffEntry: " +entry.getPath(DiffEntry.Side.NEW));
}
fileChanges.put(filename, new Integer(currentCount + 1));
}
}
}
}
}
However when I run it on a repo:
org.eclipse.jgit.api.errors.NoHeadException: No HEAD exists and no explicit starting revision was specified
at org.eclipse.jgit.api.LogCommand.call(LogCommand.java:154)
at .GitAccessor.getFilesChanged(GitAccessor.java:47)
at Main.main(Main.java:45)
I've tried to replicate it (since it is on a client's machine) by making this repo without a master:
https://github.com/davidahines/no_master
I've tried deleting the HEAD, ORIG_HEAD, and FETCH_HEAD and still can't seem to get this error.
I think what I need to do is bypass this check somehow, or find another head within the refs folder but I can't find that within jgit.
I don't currently have access to the client's repo because it is closed source.
The problem was that jgit doesn't support the tilde shortcut for /home/username, once that was removed it worked.

Java - Won't read out File content

I have a .txt file with, for example, this content:
variable1="hello";
variable2="bye";
testing3="parameter";
whatisthis4="hello";
var5="exampletext";
example=3;
wellthen=8;
---
It read in the file, line by line, fine until I added a way of saving the data.
This whole code plus another reader (with other variable names of course) is wrapped in a try-catch statement.
String path_playlist = new File("").getAbsolutePath();
String fileName_playlist = path_playlist
+ "/src/dancefusion/game/playlist.txt";
FileReader fr_playlist = new FileReader(fileName_playlist);
BufferedReader br_playlist = new BufferedReader(fr_playlist);
int track_counter = track_sum*9;
String trackinfos[] = new String[track_counter];
while(track_counter < 0)
{
System.out.println("linecount="+track_counter);
trackinfos[track_counter] = br_playlist.readLine();
System.out.println(trackinfos[track_counter]);
track_counter--;
}
System.out.println(Arrays.toString(trackinfos));
In this example track_sum equals 1.
The while loop should read in the file one line at a time but only reads null's:
[null, null, null, null, null, null, null, null, null]
Update 1:
The while-condition was set up the wrong way... thanks!
The corrected version:
while(track_counter < 0)
However, now it gives me an exception with an "ArrayOutOfBounds: 9".
Any guesses?
Final Update:
As mentioned by #GiorgiMoniava, I just needed to reduce track_counter by one before starting to read in as in Java arrays begin with 0, thanks!
int track_counter = track_sum*8;
String trackinfos[] = new String[track_counter];
track_counter--;
while(track_counter >= 0)
{
System.out.println("linecount="+track_counter);
trackinfos[track_counter] = br_playlist.readLine();
System.out.println(trackinfos[track_counter]);
track_counter--;
}
Maybe one of you can figure out what I did wrong...
Of course I can deliver more information/code if needed!
Thanks in advance!
This looks weird
while(track_counter < 0)
Are you sure loop is ever entered in? It is my guess (from your output) that track_counter is 9.
About your array out of bounds exception: if you create array of size N you can only access it using indexes: [0, N-1]
try this
while(track_counter > 0)
{
System.out.println("linecount="+track_counter);
track_counter--;
trackinfos[track_counter] = br_playlist.readLine();
System.out.println(trackinfos[track_counter]);
}

Eclipse can't find/open text files from path

I'm currently making an app which reads from text files and then does cool stuff with the words inside it. Now I unfortunately have the problem that Eclipse can't seem to find/open the text files. Since this is my first app I am not 100% sure if I did the whole "putting-files-in-eclipse"-thing correctly.
Here are two screenshots that pretty much sum up the whole problem:
Error message when the method is executed
My directories look like this.
I already wrote another program where I used similar pathing and everything worked fine.
Here's the code: (elemArray contains "wi", "wa", "f", "l", "d")
String[] elemArray = elems.toArray(new String[0]);
for(int i = 0; i < 5; ++i){
for(int l = 3; l < 6; ++l){
checkFile = new Scanner(new File("texts/" + elemArray[i] + "monster" + l + ".txt")).useDelimiter(",\\s*");
.
.
. does some other irrelevant stuff here
What am I doing wrong?
From the available information I suspect a working directory mismatch.
Working Directory
Your working directory when launching your Java program is not what you expect. The new File("texts/" [...] will create a relative path.
You can specify the working directory in the Launch Configuration in the Arguments tab near the bottom in the Working directory: section:
Test/Debug
Extract the new File("texts/" [...] to a variable (it is quite a long line as it is). You can add an expression of f.getAbsoluteFile() to ensure it resolves as expected.
i.e. rewrite like this (I would probably extract the string passed to new File() too BTW):
String[] elemArray = elems.toArray(new String[0]);
for(int i = 0; i < 5; ++i){
for(int l = 3; l < 6; ++l){
File f = new File("texts/" + elemArray[i] + "monster" + l + ".txt");
checkFile = new Scanner(f).useDelimiter(",\\s*");

How to get previous revision CL in perforce

I am writing a program, where i have the CL ,from which I need to access the previoius revision CL of each file.
How can I get it ?
Code I have written till now is:
IChangelist cl = server.getChangelist(clId);
List<IFileSpec> files = cl.getFiles(true);
for(int i = 0; i < files.size() ; i++) {
IFileSpec fileSpec=files.get(i);
}
Revision specifiers can help you here (see 'p4 help revisions').
In particular, the previous revision of each of those files is the file as of the previous changelist.
So, since clId is the changelist you care about, compute change clPrev = (clId - 1), and then look for 'file#clPrev'.

Weird BufferedReader behavior for a huge file

I am getting a very weird error. So, my program read a csv file.
Whenever it comes to this line:
"275081";"cernusco astreet, milan, italy";NULL
I get an error:
In the debug screen, I see that the BufferedReader read only
"275081";"cernusco as
That is a part of the line. But, it should read all of the line.
What bugs me the most is when I simply remove that line out of the csv file, the bug disappear! The program runs without any problem. I can remove the line, maybe it is a bad input or whatever; but, I want to understand why I am having this problem.
For better understanding, I will include a part of my code here:
reader = new BufferedReader(new FileReader(userFile));
reader.readLine(); // skip first line
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\";\"");
int id = Integer.parseInt(stripPunctionMark(fields[0]));
String location = fields[1];
if (location.contains("\";")) { // When there is no age. The data is represented as "location";NULL. We cannot split for ";" here. So check for "; and split.
location = location.split("\";")[0];
System.out.printf("Added %d at %s\n", id, location);
people.put(id, new Person(id, location));
numberOfPeople++;
}
else {
int age = Integer.parseInt(stripPunctionMark(fields[2]));
people.put(id, new Person(id, location, age));
System.out.printf("Added %d at: %s age: %d \n", id, location, age);
numberOfPeople++;
}
Also, you can find the csv file here or here is a short version of the part that I encountered the error:
"275078";"el paso, texas, usa";"62"
"275079";"istanbul, eurasia, turkey";"26"
"275080";"madrid, n/a, spain";"29"
"275081";"cernusco astreet, milan, italy";NULL
"275082";"hacienda heights, california, usa";"16"
"275083";"cedar rapids, iowa, usa";"22"
This has nothing whatsoever to do with BufferedReader. It doesn't even appear in the stack trace.
It has to do with your failure to check the result and length of the array returned by String.split(). Instead you are just assuming the input is well-formed, with at least three columns in each row, and you have no defences if it isn't.

Categories