I am trying to write a small script that can comment on github PRs using eslint output.
The problem is eslint gives me the absolute line numbers for each error. But github API wants the line number relative to the diff.
From the github API docs: https://developer.github.com/v3/pulls/comments/#create-a-comment
To comment on a specific line in a file, you will need to first determine the position in the diff. GitHub offers a application/vnd.github.v3.diff media type which you can use in a preceding request to view the pull request's diff. The diff needs to be interpreted to translate from the line in the file to a position in the diff. The position value is the number of lines down from the first "@@" hunk header in the file you would like to comment on.
The line just below the "@@" line is position 1, the next line is position 2, and so on. The position in the file's diff continues to increase through lines of whitespace and additional hunks until a new file is reached.
So if I want to add a comment on new line number 5 in the above image, then I would need to pass 12 to the API
My question is how can I easily map between the new line numbers which the eslint will give in it's error messages to the relative line numbers required by the github API
What I have tried so far
I am using parse-diff to convert the diff provided by github API into json object
[{
"chunks": [{
"content": "@@ -,OLD_TOTAL_LINES +NEW_STARTING_LINE_NUMBER,NEW_TOTAL_LINES @@",
"changes": [
{
"type": STRING("normal"|"add"|"del"),
"normal": BOOLEAN,
"add": BOOLEAN,
"del": BOOLEAN,
"ln1": OLD_LINE_NUMBER,
"ln2": NEW_LINE_NUMBER,
"content": STRING,
"oldStart": NUMBER,
"oldLines": NUMBER,
"newStart": NUMBER,
"newLines": NUMBER
}
}]
}]
I am thinking of the following algorithm
- make an array of new line numbers starting from
NEW_STARTING_LINE_NUMBER
toNEW_STARTING_LINE_NUMBER+NEW_TOTAL_LINES
for each file - subtract
newStart
from each number and make it another arrayrelativeLineNumbers
- traverse through the array and for each deleted line (
type==='del'
) increment the corresponding remainingrelativeLineNumbers
- for another hunk (line having
@@
) decrement the corresponding remainingrelativeLineNumbers