Skip to content

Commit

Permalink
Private repo support (#40)
Browse files Browse the repository at this point in the history
* 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]>
  • Loading branch information
3 people authored Apr 3, 2022
1 parent 0005589 commit f4c83ba
Show file tree
Hide file tree
Showing 7 changed files with 49 additions and 32 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ jobs:

- **Description**: Set this option to false to analyze any source files in the repo.
- Default: true
- 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)

#### `ignore`

Expand All @@ -115,6 +116,7 @@ jobs:
- To use thread comments, the `GITHUB_TOKEN` (provided by Github to each repository) must be declared as an environment
variable. See [Authenticating with the GITHUB_TOKEN](https://docs.github.com/en/actions/reference/authentication-in-a-workflow)
- Default: true
- 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.

#### `database`

Expand Down
29 changes: 19 additions & 10 deletions cpp_linter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import io
import os
import logging
from requests import Response

FOUND_RICH_LIB = False
try:
Expand All @@ -26,11 +27,9 @@
# global constant variables
GITHUB_SHA = os.getenv("GITHUB_SHA", "")
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", os.getenv("GIT_REST_API", ""))
API_HEADERS = {
"Authorization": f"token {GITHUB_TOKEN}",
"Accept": "application/vnd.github.v3.text+json",
}

API_HEADERS = {"Accept": "application/vnd.github.v3.text+json",}
if GITHUB_TOKEN:
API_HEADERS["Authorization"] = f"token {GITHUB_TOKEN}"

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


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


def log_response_msg():
"""Output the response buffer's message on a failed request."""
def log_response_msg() -> bool:
"""Output the response buffer's message on a failed request.
Returns:
A bool decribing if response's status code was less than 400.
"""
if Globals.response_buffer.status_code >= 400:
logger.error("response returned message: %s", Globals.response_buffer.text)
logger.error(
"response returned %d message: %s",
Globals.response_buffer.status_code,
Globals.response_buffer.text,
)
return False
return True
8 changes: 4 additions & 4 deletions cpp_linter/clang_tidy_yml.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
from . import GlobalParser, get_line_cnt_from_cols


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


class TidyDiagnostic:
Expand Down Expand Up @@ -121,10 +121,10 @@ def parse_tidy_suggestions_yml():
print(
"filtering header guard suggestion (making relative to repo root)"
)
fix.text = fix.text.replace(CWD_HEADER_GAURD, b"")
fix.text = fix.text.replace(CWD_HEADER_GUARD, b"")
diag.replacements.append(fix)
fixit.diagnostics.append(diag)
# filter out absolute header gaurds
# filter out absolute header guards
GlobalParser.tidy_advice.append(fixit)


Expand Down
18 changes: 12 additions & 6 deletions cpp_linter/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@


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


def filter_out_non_source_files(
Expand Down Expand Up @@ -761,15 +761,16 @@ def main():
# change working directory
os.chdir(args.repo_root)

exit_early = False
with open(GITHUB_EVEN_PATH, "r", encoding="utf-8") as payload:
# load event's json info about the workflow run
with open(GITHUB_EVENT_PATH, "r", encoding="utf-8") as payload:
Globals.EVENT_PAYLOAD = json.load(payload)
if logger.getEffectiveLevel() <= logging.DEBUG:
start_log_group("Event json from the runner")
logger.debug(json.dumps(Globals.EVENT_PAYLOAD))
end_log_group()

exit_early = False
if args.files_changed_only:
# load event's json info about the workflow run
get_list_of_changed_files()
exit_early = not filter_out_non_source_files(
args.extensions,
Expand All @@ -795,7 +796,12 @@ def main():
)

start_log_group("Posting comment(s)")
if args.thread_comments:
thread_comments_allowed = True
if "private" in Globals.EVENT_PAYLOAD["repository"]:
thread_comments_allowed = (
Globals.EVENT_PAYLOAD["repository"]["private"] is not True
)
if args.thread_comments and thread_comments_allowed:
post_results(False) # False is hard-coded to disable diff comments.
set_exit_code(int(make_annotations(args.style)))
end_log_group()
Expand Down
14 changes: 7 additions & 7 deletions cpp_linter/thread_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ def remove_bot_comments(comments_url: str, user_id: int):
user_id: The user's account id number.
"""
logger.info("comments_url: %s", comments_url)
Globals.response_buffer = requests.get(comments_url)
Globals.response_buffer = requests.get(comments_url, headers=API_HEADERS)
if not log_response_msg():
return # error getting comments for the thread; stop here
comments = Globals.response_buffer.json()
for i, comment in enumerate(comments):
# only serach for comments from the user's ID and
for comment in comments:
# only search for comments from the user's ID and
# whose comment body begins with a specific html comment
if (
int(comment["user"]["id"]) == user_id
Expand All @@ -36,7 +38,6 @@ def remove_bot_comments(comments_url: str, user_id: int):
comment["url"][comment["url"].find(".com") + 4 :],
)
log_response_msg()
del comments[i]
logger.debug(
"comment id %d from user %s (%d)",
comment["id"],
Expand Down Expand Up @@ -229,9 +230,8 @@ def get_review_id(reviews_url: str, user_id: int) -> int:
Globals.response_buffer.status_code,
)
Globals.response_buffer = requests.get(reviews_url)
if Globals.response_buffer.status_code != 200:
log_response_msg()
raise RuntimeError("could not create a review for commemts")
if Globals.response_buffer.status_code != 200 and log_response_msg():
raise RuntimeError("could not create a review for comments")
reviews = json.loads(Globals.response_buffer.text)
reviews.reverse() # traverse the list in reverse
review_id = find_review(reviews, user_id)
Expand Down
6 changes: 3 additions & 3 deletions demo/demo.cpp
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
/** This is a very ugly test code (doomed to fail linting) */
#include "demo.hpp"
#include <stdio.h> ///
#include <stdio.h>




int main(){

for (;;) break; ///
for (;;) break;


printf("Hello world!\n"); ///
printf("Hello world!\n");



Expand Down
4 changes: 2 additions & 2 deletions demo/demo.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class Dummy {
Dummy() :numb(0), useless("\0"){}

public:
void *not_usefull(char *str){useless = str;} ///
void *not_usefull(char *str){useless = str;}
};


Expand All @@ -31,6 +31,6 @@ class Dummy {
struct LongDiff
{

long diff; ///
long diff;

};

1 comment on commit f4c83ba

@github-actions
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📜 Run clang-format on the following files

  • demo/demo.cpp
  • demo/demo.hpp

💬 Output from clang-tidy

demo/demo.cpp
demo/demo.cpp:3:10: warning: [modernize-deprecated-headers]

inclusion of deprecated C++ header 'stdio.h'; consider using 'cstdio' instead

#include <stdio.h>
         ^~~~~~~~~
         <cstdio>

demo/demo.cpp:8:5: warning: [modernize-use-trailing-return-type]

use a trailing return type for this function

int main(){
~~~ ^
auto       -> int

demo/demo.cpp:10:13: warning: [readability-braces-around-statements]

statement should be inside braces

    for (;;) break;
            ^
             {

demo/demo.cpp:13:5: warning: [cppcoreguidelines-pro-type-vararg]

do not call c-style vararg functions

    printf("Hello world!\n");
    ^


demo/demo.hpp
demo/demo.hpp:6:11: warning: [modernize-use-default-member-init]

use default member initializer for 'useless'

    char* useless;
          ^
                 {"\0"}

demo/demo.hpp:7:9: warning: [modernize-use-default-member-init]

use default member initializer for 'numb'

    int numb;
        ^
            {0}

demo/demo.hpp:11:11: warning: [modernize-use-trailing-return-type]

use a trailing return type for this function

    void *not_usefull(char *str){useless = str;}
    ~~~~~~^
    auto                         -> void *

Please sign in to comment.