DBS DBS - 2 months ago 13
Python Question

If statement with multiple conditions using regex

I would like to loop through pull requests in GitHub and if the pull request has the comments in the code below, do something (for now, print the pull request number). I have a pull request that has the comments I'm looking for (spread over multiple comments in the pull request), but it doesn't print the pull request number. I suspect it has something to do with the regex I'm using because if I break the if statement down to look for just the regex or the string values, it works fine, but when I try to combine them in one if statement, it doesn't work.

I don't think this is a duplicate question as I've looked at all the suggestions under questions that may already have your answer.

for pr in repo.pull_requests():
#check to ensure pull request meets criteria before processing
conflicts_base_branch = "This branch has no conflicts with the base branch"
checks = "All checks have passed"
sign_off_comment_present = re.compile(r"\B#sign-off\b", re.IGNORECASE)
for comment in list(repo.issue(pr.number).comments()):
if (conflicts_base_branch and checks in comment.body) and (sign_off_comment_present.search(comment.body)):
print(pr.number)

Answer

Your solution requires all of the conditions to be met on the same comment, it won't work if they are on different comments. For that you need to keep track which conditions are met while iterating through the comments, e.g:

for pr in repo.pull_requests():
    #check to ensure pull request meets criteria before processing
    conflicts_base_branch = "This branch has no conflicts with the base branch"
    checks = "All checks have passed"
    sign_off_comment_present = re.compile(r"\B#sign-off\b", re.IGNORECASE)
    passes_checks = False
    has_signoff = False
    has_no_conflicts = False
    for comment in list(repo.issue(pr.number).comments()):
        if checks in comment.body:
            passes_checks = True
        if conflicts_base_branch in comment.body:
            has_no_conflicts = True
        if sign_off_comment_present.search(comment.body):
            has_signoff = True
    if passes_checks and has_no_conflicts and has_signoff:
        print(pr.number)