Skip to content

Commit f4c83ba

Browse files
2bndy5shenxianpengDingXuefeng
authored
Private repo support (#40)
* use header's accept for REST API calls * also fix some spelling errors * reduce 3 lines to 1; invoke test in demo * get event payload for any supported event * don't delete comments from the response buffer * skip removing thread comments if none found * try requesting with the accepted format in the header * try using token in the header * Update `version` in README.md (#43) * [feat] Add the ability to specify the compilation database (#42) * add database option * fix existing typos * use header's accept for REST API calls * also fix some spelling errors * reduce 3 lines to 1; invoke test in demo * get event payload for any supported event * don't delete comments from the response buffer * skip removing thread comments if none found * try requesting with the accepted format in the header * try using token in the header * force thread comments disabled on private repos * private flag in the header is a bool, not str * Pleasing pylint * remove duplicated fix * update README about private repos needing a token Co-authored-by: 2bndy5 <[email protected]> Co-authored-by: Peter Shen <[email protected]> Co-authored-by: Xuefeng Ding <[email protected]>
1 parent 0005589 commit f4c83ba

File tree

7 files changed

+49
-32
lines changed

7 files changed

+49
-32
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,7 @@ jobs:
9292

9393
- **Description**: Set this option to false to analyze any source files in the repo.
9494
- Default: true
95+
- NOTE: The `GITHUB_TOKEN` should be supplied when running on a private repository with this option enabled, otherwise the runner does not not have the privilege to list changed files for an event. See [Authenticating with the GITHUB_TOKEN](https://docs.github.com/en/actions/reference/authentication-in-a-workflow)
9596

9697
#### `ignore`
9798

@@ -115,6 +116,7 @@ jobs:
115116
- To use thread comments, the `GITHUB_TOKEN` (provided by Github to each repository) must be declared as an environment
116117
variable. See [Authenticating with the GITHUB_TOKEN](https://docs.github.com/en/actions/reference/authentication-in-a-workflow)
117118
- Default: true
119+
- NOTE: If run on a private repository, then this feature is disabled because the GitHub REST API behaves differently for thread comments on a private repository.
118120

119121
#### `database`
120122

cpp_linter/__init__.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io
44
import os
55
import logging
6+
from requests import Response
67

78
FOUND_RICH_LIB = False
89
try:
@@ -26,11 +27,9 @@
2627
# global constant variables
2728
GITHUB_SHA = os.getenv("GITHUB_SHA", "")
2829
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", os.getenv("GIT_REST_API", ""))
29-
API_HEADERS = {
30-
"Authorization": f"token {GITHUB_TOKEN}",
31-
"Accept": "application/vnd.github.v3.text+json",
32-
}
33-
30+
API_HEADERS = {"Accept": "application/vnd.github.v3.text+json",}
31+
if GITHUB_TOKEN:
32+
API_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}"
3433

3534
class Globals:
3635
"""Global variables for re-use (non-constant)."""
@@ -40,10 +39,10 @@ class Globals:
4039
OUTPUT = ""
4140
"""The accumulated body of the resulting comment that gets posted."""
4241
FILES = []
43-
"""The reponding payload containing info about changed files."""
42+
"""The responding payload containing info about changed files."""
4443
EVENT_PAYLOAD = {}
4544
"""The parsed JSON of the event payload."""
46-
response_buffer = None
45+
response_buffer = Response()
4746
"""A shared response object for `requests` module."""
4847

4948

@@ -93,7 +92,17 @@ def get_line_cnt_from_cols(file_path: str, offset: int) -> tuple:
9392
return (line_cnt, cols)
9493

9594

96-
def log_response_msg():
97-
"""Output the response buffer's message on a failed request."""
95+
def log_response_msg() -> bool:
96+
"""Output the response buffer's message on a failed request.
97+
98+
Returns:
99+
A bool decribing if response's status code was less than 400.
100+
"""
98101
if Globals.response_buffer.status_code >= 400:
99-
logger.error("response returned message: %s", Globals.response_buffer.text)
102+
logger.error(
103+
"response returned %d message: %s",
104+
Globals.response_buffer.status_code,
105+
Globals.response_buffer.text,
106+
)
107+
return False
108+
return True

cpp_linter/clang_tidy_yml.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
from . import GlobalParser, get_line_cnt_from_cols
55

66

7-
CWD_HEADER_GAURD = bytes(
7+
CWD_HEADER_GUARD = bytes(
88
os.getcwd().upper().replace(os.sep, "_").replace("-", "_"), encoding="utf-8"
9-
) #: The constant used to trim absolute paths from header gaurd suggestions.
9+
) #: The constant used to trim absolute paths from header guard suggestions.
1010

1111

1212
class TidyDiagnostic:
@@ -121,10 +121,10 @@ def parse_tidy_suggestions_yml():
121121
print(
122122
"filtering header guard suggestion (making relative to repo root)"
123123
)
124-
fix.text = fix.text.replace(CWD_HEADER_GAURD, b"")
124+
fix.text = fix.text.replace(CWD_HEADER_GUARD, b"")
125125
diag.replacements.append(fix)
126126
fixit.diagnostics.append(diag)
127-
# filter out absolute header gaurds
127+
# filter out absolute header guards
128128
GlobalParser.tidy_advice.append(fixit)
129129

130130

cpp_linter/run.py

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535

3636

3737
# global constant variables
38-
GITHUB_EVEN_PATH = os.getenv("GITHUB_EVENT_PATH", "")
38+
GITHUB_EVENT_PATH = os.getenv("GITHUB_EVENT_PATH", "")
3939
GITHUB_API_URL = os.getenv("GITHUB_API_URL", "https://api.github.com")
4040
GITHUB_REPOSITORY = os.getenv("GITHUB_REPOSITORY", "")
4141
GITHUB_EVENT_NAME = os.getenv("GITHUB_EVENT_NAME", "unknown")
@@ -211,7 +211,7 @@ def get_list_of_changed_files() -> None:
211211
logger.warning("triggered on unsupported event.")
212212
sys.exit(set_exit_code(0))
213213
logger.info("Fetching files list from url: %s", files_link)
214-
Globals.FILES = requests.get(files_link).json()
214+
Globals.FILES = requests.get(files_link, headers=API_HEADERS).json()
215215

216216

217217
def filter_out_non_source_files(
@@ -761,15 +761,16 @@ def main():
761761
# change working directory
762762
os.chdir(args.repo_root)
763763

764-
exit_early = False
765-
with open(GITHUB_EVEN_PATH, "r", encoding="utf-8") as payload:
764+
# load event's json info about the workflow run
765+
with open(GITHUB_EVENT_PATH, "r", encoding="utf-8") as payload:
766766
Globals.EVENT_PAYLOAD = json.load(payload)
767767
if logger.getEffectiveLevel() <= logging.DEBUG:
768768
start_log_group("Event json from the runner")
769769
logger.debug(json.dumps(Globals.EVENT_PAYLOAD))
770770
end_log_group()
771+
772+
exit_early = False
771773
if args.files_changed_only:
772-
# load event's json info about the workflow run
773774
get_list_of_changed_files()
774775
exit_early = not filter_out_non_source_files(
775776
args.extensions,
@@ -795,7 +796,12 @@ def main():
795796
)
796797

797798
start_log_group("Posting comment(s)")
798-
if args.thread_comments:
799+
thread_comments_allowed = True
800+
if "private" in Globals.EVENT_PAYLOAD["repository"]:
801+
thread_comments_allowed = (
802+
Globals.EVENT_PAYLOAD["repository"]["private"] is not True
803+
)
804+
if args.thread_comments and thread_comments_allowed:
799805
post_results(False) # False is hard-coded to disable diff comments.
800806
set_exit_code(int(make_annotations(args.style)))
801807
end_log_group()

cpp_linter/thread_comments.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ def remove_bot_comments(comments_url: str, user_id: int):
1515
user_id: The user's account id number.
1616
"""
1717
logger.info("comments_url: %s", comments_url)
18-
Globals.response_buffer = requests.get(comments_url)
18+
Globals.response_buffer = requests.get(comments_url, headers=API_HEADERS)
19+
if not log_response_msg():
20+
return # error getting comments for the thread; stop here
1921
comments = Globals.response_buffer.json()
20-
for i, comment in enumerate(comments):
21-
# only serach for comments from the user's ID and
22+
for comment in comments:
23+
# only search for comments from the user's ID and
2224
# whose comment body begins with a specific html comment
2325
if (
2426
int(comment["user"]["id"]) == user_id
@@ -36,7 +38,6 @@ def remove_bot_comments(comments_url: str, user_id: int):
3638
comment["url"][comment["url"].find(".com") + 4 :],
3739
)
3840
log_response_msg()
39-
del comments[i]
4041
logger.debug(
4142
"comment id %d from user %s (%d)",
4243
comment["id"],
@@ -229,9 +230,8 @@ def get_review_id(reviews_url: str, user_id: int) -> int:
229230
Globals.response_buffer.status_code,
230231
)
231232
Globals.response_buffer = requests.get(reviews_url)
232-
if Globals.response_buffer.status_code != 200:
233-
log_response_msg()
234-
raise RuntimeError("could not create a review for commemts")
233+
if Globals.response_buffer.status_code != 200 and log_response_msg():
234+
raise RuntimeError("could not create a review for comments")
235235
reviews = json.loads(Globals.response_buffer.text)
236236
reviews.reverse() # traverse the list in reverse
237237
review_id = find_review(reviews, user_id)

demo/demo.cpp

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
/** This is a very ugly test code (doomed to fail linting) */
22
#include "demo.hpp"
3-
#include <stdio.h> ///
3+
#include <stdio.h>
44

55

66

77

88
int main(){
99

10-
for (;;) break; ///
10+
for (;;) break;
1111

1212

13-
printf("Hello world!\n"); ///
13+
printf("Hello world!\n");
1414

1515

1616

demo/demo.hpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ class Dummy {
88
Dummy() :numb(0), useless("\0"){}
99

1010
public:
11-
void *not_usefull(char *str){useless = str;} ///
11+
void *not_usefull(char *str){useless = str;}
1212
};
1313

1414

@@ -31,6 +31,6 @@ class Dummy {
3131
struct LongDiff
3232
{
3333

34-
long diff; ///
34+
long diff;
3535

3636
};

0 commit comments

Comments
 (0)