File size: 1,701 Bytes
282ada1
 
 
1f8e463
 
 
 
 
 
 
 
 
282ada1
1f8e463
 
 
 
 
 
 
 
 
 
282ada1
 
 
 
 
 
 
 
 
 
 
1f8e463
282ada1
 
 
1f8e463
282ada1
1f8e463
 
282ada1
 
 
 
 
1f8e463
 
 
282ada1
 
 
 
 
1f8e463
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import time
import traceback
from functools import lru_cache
from os import environ as env
from os import listdir
from typing import List

import requests

from codedog_demo.github_utils import parse_github_pr_url

codedog_api = env.get("CODEDOG_API_URL", "")
github_token = env.get("GITHUB_TOKEN", "")

sample_names = []
sample_contents = []
for file in listdir("samples"):
    sample_names.append(file.replace("@", "/"))
    with open("samples/" + file, "r") as f:
        sample_contents.append(f.read())


def request_pr_review(url: str):
    try:
        repo, pr_number = parse_github_pr_url(url)
        if not repo or not pr_number:
            return "Invalid URL. Accept format is: https://www.github.com/{owner}/{repository}/pull/{pr_number}", ""

        result = _request_pr_review(repo, pr_number, ttl_hash=get_ttl_hash())

    except Exception:
        traceback.print_exc()
        return "Something went wrong. Please try again later.", ""
    return result, result


@lru_cache(maxsize=100)
def _request_pr_review(repo: str, pr_number: int, ttl_hash=None):
    response = requests.post(
        codedog_api, json={"repository": repo, "pull_request_number": pr_number, "token": github_token}
    )
    result = response.text
    if len(result) < 100:
        if result == "stream timeout":
            raise ValueError("Timeout")
        print(f"Error result: {result}")
        raise ValueError()
    return result


def get_ttl_hash(seconds=120):
    """Return the same value withing `seconds` time period"""
    return round(time.time() / seconds)


def get_sample_choices() -> List[str]:
    return sample_names


def show_sample(idx: int) -> str:
    return sample_contents[idx]