path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_following
Modified
avgupta456~github-trends
571e73f1afc11fc36f8ae008bbddaedb3dac0a46
add more test cases
<1>:<del>
# module: tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): <0> response = get_user_following(user_id="avgupta456") <1> <2> self.assertIsInstance(response, UserFollowAPIResponse) <3>
===========changed ref 0=========== # module: tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_followers(self): response = get_user_followers(user_id="avgupta456") - self.assertIsInstance(response, UserFollowAPIResponse) ===========changed ref 1=========== # module: tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_stats(self): response = get_user_contribution_stats(user_id="avgupta456") - self.assertIsInstance(response, UserContributionStatsAPIResponse) ===========changed ref 2=========== # module: tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_commits(self): response = get_user_contribution_commits(user_id="avgupta456") - self.assertIsInstance(response, UserContributionCommitsAPIResponse)
external.github_api.graphql.user/get_user_contribution_stats
Modified
avgupta456~github-trends
1ada6ac1410964b355ec188ca18f9855a7ebc38c
update query logic
# module: external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: <0> """Fetches user contribution calendar and contribution years""" <1> query = { <2> "variables": { <3> "login": user_id, <4> "maxRepos": max_repos, <5> "first": first, <6> "after": after, <7> }, <8> "query": """ <9> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { <10> user(login: $login){ <11> contributionsCollection{ <12> issueContributionsByRepository(maxRepositories: $maxRepos){ <13> repository{ <14> name <15> }, <16> contributions(first: $first, after: $after){ <17> totalCount, <18> nodes{ <19> occurredAt, <20> issue{ <21> state <22> } <23> } <24> pageInfo{ <25> hasNextPage, <26> endCursor <27> } <28> } <29> } <30> pullRequestContributionsByRepository(maxRepositories: $maxRepos){ <31> repository{ <32> name <33> }, <34> contributions(first: $first, after: $after){ <35> totalCount, <36> nodes{ <37> occurredAt, <38> pullRequest{ <39> state, <40> } <41> } <42> pageInfo{ <43> hasNextPage, <44> endCursor <45> } <46> } <47> } <48> pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ <49> repository{ <50> name <51> }, <52> contributions(first: $first, after: $after){ <53> totalCount, <54> nodes{ <55> occurredAt, <56> pullRequestReview{ <57> state, <58> } <59> } <60> pageInfo{ <61> hasNextPage, <62> endCursor <63> }</s>
===========below chunk 0=========== # module: external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: # offset: 1 }, repositoryContributions(first: $first, after: $after){ totalCount, nodes{ repository{ name, } occurredAt, } pageInfo{ hasNextPage, endCursor } }, restrictedContributionsCount, totalIssueContributions, totalPullRequestContributions, totalPullRequestReviewContributions, totalRepositoryContributions, totalRepositoriesWithContributedIssues, totalRepositoriesWithContributedPullRequests, totalRepositoriesWithContributedPullRequestReviews }, } } """, } try: output_dict = get_template(query)["data"]["user"]["contributionsCollection"] return UserContributionStatsAPIResponse.parse_obj(output_dict) except Exception as e: logging.exception(e) raise e ===========unchanged ref 0=========== at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] at: logging exception(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: models.user.contribution_stats class APIResponse_RepoContribs(BaseModel): """ BaseModel which accepts: - totalCount: int - nodes: List[APIResponse_RepoContribs_Contrib] - - pageInfo: APIResponse_PageInfo """ total_count: int = Field(alias="totalCount") nodes: List[APIResponse_RepoContribs_Contrib] - page_info: APIResponse_PageInfo = Field(alias="pageInfo")
processing.user.contribution_stats/get_user_contribution_stats
Modified
avgupta456~github-trends
1ada6ac1410964b355ec188ca18f9855a7ebc38c
update query logic
# module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> ContribStats: <0> """Gets the daily contribution history for a users top x repositories""" <1> repo_names = set() <2> repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <3> lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} <4> ) <5> total_contribs: Dict[str, List[Contribution]] = { <6> "issues": [], <7> "prs": [], <8> "reviews": [], <9> "repo": [], <10> } <11> <12> # only need them from the first data pull <13> restricted_contrib_count = 0 <14> issue_contribs_count = 0 <15> pr_contribs_count = 0 <16> pr_review_contribs_count = 0 <17> repo_contribs_count = 0 <18> repos_with_issue_contrib = 0 <19> repos_with_pr_contrib = 0 <20> repos_with_pr_review_contrib = 0 <21> <22> after: Optional[str] = "" <23> index, cont = 0, True # initialize variables <24> while cont and index < 10: <25> try: <26> after_str: str = after if isinstance(after, str) else "" <27> data = run_query(user_id, max_repos, after=after_str) <28> except Exception as e: <29> raise e <30> <31> restricted_contrib_count = data.restricted_contrib_count <32> issue_contribs_count = data.issue_contribs_count <33> pr_contribs_count = data.pr_contribs_count <34> pr_review_contribs_count = data.pr_review_contribs_count <35> repo_contribs_count = data.repo_contribs_count <36> repos</s>
===========below chunk 0=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> ContribStats: # offset: 1 repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) repo_contribs[repo_name][category].append(contrib) total_contribs[category].append(contrib) if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date(repo.occurred_at)) repo_contribs[repo.repository.name]["repo"].append</s> ===========below chunk 1=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> ContribStats: # offset: 2 <s>_at=Date(repo.occurred_at)) repo_contribs[repo.repository.name]["repo"].append(contrib) total_contribs["repo"].append(contrib) if data.repo_contribs.page_info.has_next_page: after = data.repo_contribs.page_info.end_cursor cont = True index += 1 date_filter: Callable[[Contribution], bool] = ( lambda x: start_date <= x.occurred_at <= end_date ) repo_contrib_objs: List[RepoContribStats] = [ RepoContribStats( name=k, issues=list(filter(date_filter, v["issues"])), prs=list(filter(date_filter, v["prs"])), reviews=list(filter(date_filter, v["reviews"])), repo=list(filter(date_filter, v["repo"])), ) for k, v in repo_contribs.items() ] total_contrib_obj: RepoContribStats = RepoContribStats( name="total", issues=list(filter(date_filter, total_contribs["issues"])), prs=list(filter(date_filter, total_contribs["prs"])), reviews=list(filter(date_filter, total_contribs["reviews"])), repo=list(filter(date_filter, total_contribs["repo"])), ) output: ContribStats = ContribStats( total=total_contrib_obj, repos</s> ===========below chunk 2=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> ContribStats: # offset: 3 <s>_contrib_objs, restricted_contrib_count=restricted_contrib_count, issue_contribs_count=issue_contribs_count, pr_contribs_count=pr_contribs_count, pr_review_contribs_count=pr_review_contribs_count, repo_contribs_count=repo_contribs_count, repos_with_issue_contrib=repos_with_issue_contrib, repos_with_pr_contrib=repos_with_pr_contrib, repos_with_pr_review_contrib=repos_with_pr_review_contrib, ) return output ===========unchanged ref 0=========== at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: external.github_api.graphql.user get_user_contribution_stats(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionStatsAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_stats.APIResponse issue_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="issueContributionsByRepository" ) pr_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestContributionsByRepository" ) pr_review_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestReviewContributionsByRepository" ) repo_contribs: APIResponse_RepoContribs = Field(alias="repositoryContributions") restricted_contrib_count: int = Field(alias="restrictedContributionsCount") issue_contribs_count: int = Field(alias="totalIssueContributions") pr_contribs_count: int = Field(alias="totalPullRequestContributions")
models.user.contribution_calendar/create_contribution_period
Modified
avgupta456~github-trends
94def8c01e4a9d9548cd2620e6ef8b7bb7e3bfc6
bug fixes
<2>:<add> avg_contributions = total_contributions / max(num_days, 1) <del> avg_contributions = total_contributions / num_days
# module: models.user.contribution_calendar def create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod: <0> num_days = len(days) <1> total_contributions = sum([day.contribution_count for day in days]) <2> avg_contributions = total_contributions / num_days <3> return ContributionPeriod( <4> total_contributions=total_contributions, <5> avg_contributions=avg_contributions, <6> days=days, <7> num_days=num_days, <8> ) <9>
===========unchanged ref 0=========== at: models.user.contribution_calendar.ContributionDay date: Date weekday: int contribution_count: int contribution_level: Quartile at: typing List = _alias(list, 1, inst=False, name='List')
processing.user.contribution_commits/get_user_contribution_commits
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
# module: processing.user.contribution_commits def get_user_contribution_commits( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCommits: - ) -> CommitContributions: <0> """Gets the daily commit history for a users top x repositories""" <1> time_range = today - start_date # gets number of days to end date <2> segments = min(math.ceil(time_range / 100), 10) # no more than three years <3> raw_repos: List[CommitContributionsByRepository] = [] <4> commit_contribs_count, repos_with_commit_contrib = 0, 0 <5> after: Optional[str] = "" <6> index, cont = 0, True # initialize variables <7> while cont and index < segments: <8> try: <9> after_str = after if isinstance(after, str) else "" <10> data = run_query(user_id, max_repos, after=after_str) <11> except Exception as e: <12> raise e <13> <14> commit_contribs_count = data.commit_contribs_count <15> repos_with_commit_contrib = data.repos_with_commit_contrib <16> <17> cont = False <18> for i, repo in enumerate(data.commits_by_repo): <19> if index == 0: <20> raw_repos.append( <21> CommitContributionsByRepository( <22> name=repo.repository.name, <23> contributions=repo.total_count.total_count, <24> contributions_in_range=0, <25> timeline=[], <26> ) <27> ) <28> <29> raw_contribs = repo.contributions.nodes <30> contribs = map( <31> lambda x: create_commit_contribution(x), <32> raw_contribs, <33> ) <34> contribs = filter( <35> lambda x: start_date <= x.occurred_at <= end_date, contribs <36> ) <37> raw_repos</s>
===========below chunk 0=========== # module: processing.user.contribution_commits def get_user_contribution_commits( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCommits: - ) -> CommitContributions: # offset: 1 if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True index += 1 # adds contributionsInRange for repo in raw_repos: repo.contributions_in_range = sum([x.commit_count for x in repo.timeline]) # converts to objects repo_objects = map( lambda x: CommitContributionsByRepository.parse_obj(x), raw_repos ) # filters out empty results repo_objects = list(filter(lambda x: x.contributions_in_range > 0, repo_objects)) timeline: List[int] = [0 for _ in range(end_date - start_date + 1)] for repo in repo_objects: for day in repo.timeline: timeline[day.occurred_at - start_date] += day.commit_count timeline_object = [ CommitContribution(occurred_at=start_date + i, commit_count=x) for i, x in enumerate(timeline) ] total_object = CommitContributionsByRepository( name="total", contributions=commit_contribs_count, contributions_in_range=sum(timeline), timeline=timeline_object, ) output = CommitContributions( commit_contribs_by_repo=list(repo_objects), commit_contribs=total_object, repos_with_commit_contrib=repos_with_commit_contrib, ) return output ===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_contribution_commits(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionCommitsAPIResponse at: math ceil(x: SupportsFloat, /) -> int at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_commits create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution at: models.user.contribution_commits.APIResponse commits_by_repo: List[APIResponse_Repo] = Field( alias="commitContributionsByRepository" ) commit_contribs_count: int = Field(alias="totalCommitContributions") repos_with_commit_contrib: int = Field( alias="totalRepositoriesWithContributedCommits" ) at: models.user.contribution_commits.APIResponse_Repo repository: APIResponse_Repo_Repo total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount") contributions: APIResponse_Repo_Contribs at: models.user.contribution_commits.APIResponse_Repo_Contribs nodes: List[APIResponse_Repo_Contribs_Node] page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo") at: models.user.contribution_commits.APIResponse_Repo_Contribs_PageInfo has_next_page: bool = Field(alias="hasNextPage") end_cursor: Optional[str] = Field(alias="endCursor") at: models.user.contribution_commits.APIResponse_Repo_Repo name: str at: models.user.contribution_commits.APIResponse_Repo_TotalCount total_count: int = Field(alias="totalCount") at: models.user.contribution_commits.CommitContribution commit_count: int ===========unchanged ref 1=========== occurred_at: Date at: models.user.contribution_commits.CommitContributionsByRepository name: str contributions: int contributions_in_range: int timeline: List[CommitContribution] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 1=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 2=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 3=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 4=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int -
processing.user.contribution_calendar/get_user_contribution_calendar
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
# module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: <0> """get user contributions for the past year""" <1> if today - start_date > 365: <2> raise AssertionError("start_date can only be within past 1 year") <3> <4> try: <5> data = run_query(user_id) <6> except Exception as e: <7> raise e <8> <9> contribution_years = data.contribution_years <10> colors = data.contribution_calendar.colors <11> days = map( <12> lambda x: ContributionDay.parse_obj( <13> { <14> "date": Date(x.date), <15> "weekday": x.weekday, <16> "contribution_count": x.contribution_count, <17> "contribution_level": x.contribution_level, <18> } <19> ), <20> [ <21> day <22> for week in data.contribution_calendar.weeks <23> for day in week.contribution_days <24> ], <25> ) <26> <27> days = list(filter(lambda x: start_date <= x.date <= end_date, days)) <28> <29> # creates total period (up to 1 year long) <30> total = create_contribution_period(days) <31> <32> # creates months (0 is January, 11 is December) <33> months = [[] for _ in range(12)] <34> for day in days: <35> months[day.date.month() - 1].append(day) <36> <37> months = list(map(lambda x: create_contribution_period(x), months)) <38> <39> # create weekdays (0 is Sunday, 6 is Saturday) <40> weekdays = [[] for _ in range(7)] <41> for day in days: <42> weekdays[day.weekday].append(day) <43> </s>
===========below chunk 0=========== # module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: # offset: 1 # create final output calendar = ContributionCalendar( contribution_years=contribution_years, colors=colors, total=total, months=months, weekdays=weekdays, ) return calendar ===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_calendar create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod at: models.user.contribution_calendar.APIResponse contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar") contribution_years: List[int] = Field(alias="contributionYears") at: models.user.contribution_calendar.APIResponse_Calendar total_contributions: int = Field(alias="totalContributions") weeks: List[APIResponse_Calendar_Week] colors: List[str] ===========changed ref 0=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 1=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 2=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 3=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 4=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 5=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 6=========== # module: processing.user.contribution_commits def get_user_contribution_commits( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCommits: - ) -> CommitContributions: """Gets the daily commit history for a users top x repositories""" time_range = today - start_date # gets number of days to end date segments = min(math.ceil(time_range / 100), 10) # no more than three years raw_repos: List[CommitContributionsByRepository] = [] commit_contribs_count, repos_with_commit_contrib = 0, 0 after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < segments: try: after_str = after if isinstance(after, str) else "" data = run_query(user_id, max_repos, after=after_str) except Exception as e: raise e commit_contribs_count = data.commit_contribs_count repos_with_commit_contrib = data.repos_with_commit_contrib cont = False for i, repo in enumerate(data.commits_by_repo): if index == 0: raw_repos.append( CommitContributionsByRepository( name=repo.repository.name, contributions=repo.total_count.total_count, contributions_in_range=0, timeline=[], ) ) raw_contribs = repo.contributions.nodes contribs = map( lambda x: create_commit_contribution(x), raw_contribs, ) contribs = filter( lambda x: start_date <= x.occurred_at <= end_date, contribs ) raw_repos[i].timeline.extend(contribs) if repo.contributions.page_info.has_next_page: after = repo.contributions.</s>
tests.processing.user.test_contribution_calendar/TestTemplate.test_get_user_contribution_calendar
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
<1>:<add> self.assertIsInstance(response, UserContribCalendar) <del> self.assertIsInstance(response, ContributionCalendar)
# module: tests.processing.user.test_contribution_calendar class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): <0> response = get_user_contribution_calendar(user_id="avgupta456") <1> self.assertIsInstance(response, ContributionCalendar) <2> <3> start = today - 100 <4> response = get_user_contribution_calendar( <5> user_id="avgupta456", start_date=start <6> ) <7> date = response.total.days[0].date <8> self.assertGreaterEqual(date - start, 0) <9> self.assertGreaterEqual(today - date, 0) <10>
===========changed ref 0=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 1=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 2=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 3=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 4=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 5=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 6=========== # module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: """get user contributions for the past year""" if today - start_date > 365: raise AssertionError("start_date can only be within past 1 year") try: data = run_query(user_id) except Exception as e: raise e contribution_years = data.contribution_years colors = data.contribution_calendar.colors days = map( lambda x: ContributionDay.parse_obj( { "date": Date(x.date), "weekday": x.weekday, "contribution_count": x.contribution_count, "contribution_level": x.contribution_level, } ), [ day for week in data.contribution_calendar.weeks for day in week.contribution_days ], ) days = list(filter(lambda x: start_date <= x.date <= end_date, days)) # creates total period (up to 1 year long) total = create_contribution_period(days) # creates months (0 is January, 11 is December) months = [[] for _ in range(12)] for day in days: months[day.date.month() - 1].append(day) months = list(map(lambda x: create_contribution_period(x), months)) # create weekdays (0 is Sunday, 6 is Saturday) weekdays = [[] for _ in range(7)] for day in days: weekdays[day.weekday].append(day) weekdays = list(map(lambda x: create_contribution_period(x), weekdays)) # create final output + calendar = UserContribCalendar( - </s> ===========changed ref 7=========== # module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: # offset: 1 <s>contribution_period(x), weekdays)) # create final output + calendar = UserContribCalendar( - calendar = ContributionCalendar( contribution_years=contribution_years, colors=colors, total=total, months=months, weekdays=weekdays, ) return calendar
tests.processing.user.test_contribution_commits/TestTemplate.test_get_user_contribution_commits
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
<1>:<add> self.assertIsInstance(response, UserContribCommits) <del> self.assertIsInstance(response, CommitContributions)
# module: tests.processing.user.test_contribution_commits class TestTemplate(unittest.TestCase): def test_get_user_contribution_commits(self): <0> response = get_user_contribution_commits(user_id="avgupta456") <1> self.assertIsInstance(response, CommitContributions) <2> <3> response = get_user_contribution_commits(user_id="avgupta456", max_repos=1) <4> self.assertLessEqual(len(response.commit_contribs_by_repo), 1) <5> <6> start = today - 100 <7> response = get_user_contribution_commits(user_id="avgupta456", start_date=start) <8> date = response.commit_contribs_by_repo[0].timeline[0].occurred_at <9> self.assertGreaterEqual(date - start, 0) <10> self.assertGreaterEqual(today - date, 0) <11>
===========changed ref 0=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 1=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 2=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 3=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 4=========== # module: tests.processing.user.test_contribution_calendar class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): response = get_user_contribution_calendar(user_id="avgupta456") + self.assertIsInstance(response, UserContribCalendar) - self.assertIsInstance(response, ContributionCalendar) start = today - 100 response = get_user_contribution_calendar( user_id="avgupta456", start_date=start ) date = response.total.days[0].date self.assertGreaterEqual(date - start, 0) self.assertGreaterEqual(today - date, 0) ===========changed ref 5=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 6=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 7=========== # module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: """get user contributions for the past year""" if today - start_date > 365: raise AssertionError("start_date can only be within past 1 year") try: data = run_query(user_id) except Exception as e: raise e contribution_years = data.contribution_years colors = data.contribution_calendar.colors days = map( lambda x: ContributionDay.parse_obj( { "date": Date(x.date), "weekday": x.weekday, "contribution_count": x.contribution_count, "contribution_level": x.contribution_level, } ), [ day for week in data.contribution_calendar.weeks for day in week.contribution_days ], ) days = list(filter(lambda x: start_date <= x.date <= end_date, days)) # creates total period (up to 1 year long) total = create_contribution_period(days) # creates months (0 is January, 11 is December) months = [[] for _ in range(12)] for day in days: months[day.date.month() - 1].append(day) months = list(map(lambda x: create_contribution_period(x), months)) # create weekdays (0 is Sunday, 6 is Saturday) weekdays = [[] for _ in range(7)] for day in days: weekdays[day.weekday].append(day) weekdays = list(map(lambda x: create_contribution_period(x), weekdays)) # create final output + calendar = UserContribCalendar( - </s> ===========changed ref 8=========== # module: processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribCalendar: - ) -> ContributionCalendar: # offset: 1 <s>contribution_period(x), weekdays)) # create final output + calendar = UserContribCalendar( - calendar = ContributionCalendar( contribution_years=contribution_years, colors=colors, total=total, months=months, weekdays=weekdays, ) return calendar
processing.user.contribution_stats/get_user_contribution_stats
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
# module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribStats: - ) -> ContribStats: <0> """Gets the daily contribution history for a users top x repositories""" <1> repo_names = set() <2> repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <3> lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} <4> ) <5> total_contribs: Dict[str, List[Contribution]] = { <6> "issues": [], <7> "prs": [], <8> "reviews": [], <9> "repo": [], <10> } <11> <12> # only need them from the first data pull <13> restricted_contrib_count = 0 <14> issue_contribs_count = 0 <15> pr_contribs_count = 0 <16> pr_review_contribs_count = 0 <17> repo_contribs_count = 0 <18> repos_with_issue_contrib = 0 <19> repos_with_pr_contrib = 0 <20> repos_with_pr_review_contrib = 0 <21> <22> after: Optional[str] = "" <23> index, cont = 0, True # initialize variables <24> while cont and index < 10: <25> try: <26> after_str: str = after if isinstance(after, str) else "" <27> data = run_query(user_id, max_repos, after=after_str) <28> except Exception as e: <29> raise e <30> <31> restricted_contrib_count = data.restricted_contrib_count <32> issue_contribs_count = data.issue_contribs_count <33> pr_contribs_count = data.pr_contribs_count <34> pr_review_contribs_count = data.pr_review_contribs_count <35> repo_contribs_count = data.</s>
===========below chunk 0=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribStats: - ) -> ContribStats: # offset: 1 repos_with_issue_contrib = data.repos_with_issue_contrib repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) repo_contribs[repo_name][category].append(contrib) total_contribs[category].append(contrib) if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_</s> ===========below chunk 1=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribStats: - ) -> ContribStats: # offset: 2 <s> cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date(repo.occurred_at)) repo_contribs[repo.repository.name]["repo"].append(contrib) total_contribs["repo"].append(contrib) index += 1 date_filter: Callable[[Contribution], bool] = ( lambda x: start_date <= x.occurred_at <= end_date ) repo_contrib_objs: List[RepoContribStats] = [ RepoContribStats( name=k, issues=list(filter(date_filter, v["issues"])), prs=list(filter(date_filter, v["prs"])), reviews=list(filter(date_filter, v["reviews"])), repo=list(filter(date_filter, v["repo"])), ) for k, v in repo_contribs.items() ] # can get more than max_repos outputs if issues/prs/reviews come from different repos repo_contrib_objs = sorted( repo_contrib_objs, key=lambda x: len(x.issues) + len(x.prs) + len(x.reviews) + len(x.repo), reverse=True, )[:max_repos] total_contrib_obj: RepoContribStats = RepoContribStats( name="total", issues=list(filter(date_filter, total_contribs["issues"])), prs=list(filter</s> ===========below chunk 2=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, + ) -> UserContribStats: - ) -> ContribStats: # offset: 3 <s>_filter, total_contribs["prs"])), reviews=list(filter(date_filter, total_contribs["reviews"])), repo=list(filter(date_filter, total_contribs["repo"])), ) output: ContribStats = ContribStats( total=total_contrib_obj, repos=repo_contrib_objs, restricted_contrib_count=restricted_contrib_count, issue_contribs_count=issue_contribs_count, pr_contribs_count=pr_contribs_count, pr_review_contribs_count=pr_review_contribs_count, repo_contribs_count=repo_contribs_count, repos_with_issue_contrib=repos_with_issue_contrib, repos_with_pr_contrib=repos_with_pr_contrib, repos_with_pr_review_contrib=repos_with_pr_review_contrib, ) return output ===========unchanged ref 0=========== at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: external.github_api.graphql.user get_user_contribution_stats(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionStatsAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_stats.APIResponse issue_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="issueContributionsByRepository" ) pr_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestContributionsByRepository" ) pr_review_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestReviewContributionsByRepository" ) repo_contribs: APIResponse_RepoContribs = Field(alias="repositoryContributions") restricted_contrib_count: int = Field(alias="restrictedContributionsCount") issue_contribs_count: int = Field(alias="totalIssueContributions") pr_contribs_count: int = Field(alias="totalPullRequestContributions")
tests.processing.user.test_contribution_stats/TestTemplate.test_get_user_contribution_stats
Modified
avgupta456~github-trends
e0ef05e79d6f0f903fad815ae3a08a5053c87ba2
rename models
<1>:<add> self.assertIsInstance(response, UserContribStats) <del> self.assertIsInstance(response, ContribStats) <4>:<del> print(response.repos)
# module: tests.processing.user.test_contribution_stats class TestTemplate(unittest.TestCase): def test_get_user_contribution_stats(self): <0> response = get_user_contribution_stats(user_id="avgupta456") <1> self.assertIsInstance(response, ContribStats) <2> <3> response = get_user_contribution_stats(user_id="avgupta456", max_repos=1) <4> print(response.repos) <5> self.assertLessEqual(len(response.repos), 1) <6> <7> start = today - 100 <8> response = get_user_contribution_stats(user_id="avgupta456", start_date=start) <9> date = response.total.issues[0].occurred_at <10> self.assertGreaterEqual(date - start, 0) <11> self.assertGreaterEqual(today - date, 0) <12>
===========changed ref 0=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 1=========== # module: models.user.contribution_commits - class CommitContributions(BaseModel): - """ - BaseModel which accepts: - - commit_contribs_by_repo: List[CommitContributionsByRepository] - - commit_contribs: CommitContributionsByRepository - - repos_with_commit_contrib: int - """ - - commit_contribs_by_repo: List[CommitContributionsByRepository] - commit_contribs: CommitContributionsByRepository - repos_with_commit_contrib: int - ===========changed ref 2=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 3=========== # module: models.user.contribution_calendar - class ContributionCalendar(BaseModel): - """ - BaseModel which accepts: - - total_contributions: int - - colors: List[str] - - total: ContributionPeriod - - months: List[ContributionPeriod] - - weekdays: List[ContributionPeriod] - """ - - contribution_years: List[int] - colors: List[str] - total: ContributionPeriod - months: List[ContributionPeriod] - weekdays: List[ContributionPeriod] - ===========changed ref 4=========== # module: tests.processing.user.test_contribution_calendar class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): response = get_user_contribution_calendar(user_id="avgupta456") + self.assertIsInstance(response, UserContribCalendar) - self.assertIsInstance(response, ContributionCalendar) start = today - 100 response = get_user_contribution_calendar( user_id="avgupta456", start_date=start ) date = response.total.days[0].date self.assertGreaterEqual(date - start, 0) self.assertGreaterEqual(today - date, 0) ===========changed ref 5=========== # module: tests.processing.user.test_contribution_commits class TestTemplate(unittest.TestCase): def test_get_user_contribution_commits(self): response = get_user_contribution_commits(user_id="avgupta456") + self.assertIsInstance(response, UserContribCommits) - self.assertIsInstance(response, CommitContributions) response = get_user_contribution_commits(user_id="avgupta456", max_repos=1) self.assertLessEqual(len(response.commit_contribs_by_repo), 1) start = today - 100 response = get_user_contribution_commits(user_id="avgupta456", start_date=start) date = response.commit_contribs_by_repo[0].timeline[0].occurred_at self.assertGreaterEqual(date - start, 0) self.assertGreaterEqual(today - date, 0) ===========changed ref 6=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int - ===========changed ref 7=========== # module: models.user.contribution_stats - class ContribStats(BaseModel): - """ - BaseModel which accepts: - - repos: List[RepoContribStats] - - total: RepoContribStats - - restricted_contrib_count: int - - issue_contribs_count: int - - pr_contribs_count: int - - pr_review_contribs_count: int - - repo_contribs_count: int - - repos_with_issue_contrib: int - - repos_with_pr_contrib: int - - repos_with_pr_review_contrib: int - """ - - repos: List[RepoContribStats] - total: RepoContribStats - - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int -
packaging.user/_main
Modified
avgupta456~github-trends
6cbdf3eb731982168ec7faab4cc2031098a71b9f
accept all parameters
<2>:<add> async_function(get_user_contribution_calendar)(user_id=user_id, start_date=start_date, end_date=end_date), # type: ignore <del> async_function(get_user_contribution_calendar)(user_id=user_id), # type: ignore <3>:<add> async_function(get_user_contribution_commits)(user_id=user_id, max_repos=max_repos, start_date=start_date, end_date=end_date), # type: ignore <add> async_function(get_user_contribution_stats)(user_id=user_id, max_repos=max_repos, start_date=start_date, end_date=end_date), # type: ignore <del> async_function(get_user_contribution_commits)(user_id=user_id), # type: ignore <4>:<del> async_function(get_user_contribution_stats)(user_id=user_id), # type: ignore
# module: packaging.user + def _main( + user_id: str, + max_repos: int = 100, + start_date: Date = today - 365, + end_date: Date = today, + ) -> UserPackage: - def _main(user_id: str) -> UserPackage: <0> output: List[Union[ContribCalendar, ContribCommits, ContribStats, Follows]] = list( <1> await asyncio.gather( <2> async_function(get_user_contribution_calendar)(user_id=user_id), # type: ignore <3> async_function(get_user_contribution_commits)(user_id=user_id), # type: ignore <4> async_function(get_user_contribution_stats)(user_id=user_id), # type: ignore <5> async_function(get_user_followers)(user_id=user_id), # type: ignore <6> ) <7> ) <8> <9> types = Union[ContribCalendar, ContribCommits, ContribStats, Follows, None] <10> array: List[types] = [None for _ in range(4)] <11> types = [ContribCalendar, ContribCommits, ContribStats, Follows] <12> for i, type in enumerate(types): <13> array[i] = list(filter(lambda x: isinstance(x, type), output))[0] <14> <15> user_package = UserPackage( <16> contribution_calendar=array[0], <17> contribution_commits=array[1], <18> contribution_stats=array[2], <19> follows=array[3], <20> ) <21> <22> return user_package <23>
packaging.user/main
Modified
avgupta456~github-trends
6cbdf3eb731982168ec7faab4cc2031098a71b9f
accept all parameters
<0>:<add> return asyncio.run( <add> _main( <add> user_id=user_id, <add> max_repos=max_repos, <add> start_date=start_date, <add> end_date=end_date, <add> ) <add> ) <del> return asyncio.run(_main(user_id=user_id))
# module: packaging.user + def main( + user_id: str, + max_repos: int = 100, + start_date: Date = today - 365, + end_date: Date = today, + ) -> UserPackage: - def main(user_id: str) -> UserPackage: <0> return asyncio.run(_main(user_id=user_id)) <1>
===========changed ref 0=========== # module: packaging.user + def _main( + user_id: str, + max_repos: int = 100, + start_date: Date = today - 365, + end_date: Date = today, + ) -> UserPackage: - def _main(user_id: str) -> UserPackage: output: List[Union[ContribCalendar, ContribCommits, ContribStats, Follows]] = list( await asyncio.gather( + async_function(get_user_contribution_calendar)(user_id=user_id, start_date=start_date, end_date=end_date), # type: ignore - async_function(get_user_contribution_calendar)(user_id=user_id), # type: ignore + async_function(get_user_contribution_commits)(user_id=user_id, max_repos=max_repos, start_date=start_date, end_date=end_date), # type: ignore + async_function(get_user_contribution_stats)(user_id=user_id, max_repos=max_repos, start_date=start_date, end_date=end_date), # type: ignore - async_function(get_user_contribution_commits)(user_id=user_id), # type: ignore - async_function(get_user_contribution_stats)(user_id=user_id), # type: ignore async_function(get_user_followers)(user_id=user_id), # type: ignore ) ) types = Union[ContribCalendar, ContribCommits, ContribStats, Follows, None] array: List[types] = [None for _ in range(4)] types = [ContribCalendar, ContribCommits, ContribStats, Follows] for i, type in enumerate(types): array[i] = list(filter(lambda x: isinstance(x, type), output))[0] user_package = UserPackage( contribution_calendar=array[0], contribution_commits=array[1</s> ===========changed ref 1=========== # module: packaging.user + def _main( + user_id: str, + max_repos: int = 100, + start_date: Date = today - 365, + end_date: Date = today, + ) -> UserPackage: - def _main(user_id: str) -> UserPackage: # offset: 1 <s>] user_package = UserPackage( contribution_calendar=array[0], contribution_commits=array[1], contribution_stats=array[2], follows=array[3], ) return user_package
processing.user.contribution_stats/get_user_contribution_stats
Modified
avgupta456~github-trends
65c94816d17ea8e768997c8d11913f39df8a25e4
updated contribution_stats processing
<2>:<add> raw_repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <del> repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <5>:<add> raw_total_contribs: Dict[str, List[Contribution]] = { <del> total_contribs: Dict[str, List[Contribution]] = {
# module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: <0> """Gets the daily contribution history for a users top x repositories""" <1> repo_names = set() <2> repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <3> lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} <4> ) <5> total_contribs: Dict[str, List[Contribution]] = { <6> "issues": [], <7> "prs": [], <8> "reviews": [], <9> "repo": [], <10> } <11> <12> # only need them from the first data pull <13> restricted_contrib_count = 0 <14> issue_contribs_count = 0 <15> pr_contribs_count = 0 <16> pr_review_contribs_count = 0 <17> repo_contribs_count = 0 <18> repos_with_issue_contrib = 0 <19> repos_with_pr_contrib = 0 <20> repos_with_pr_review_contrib = 0 <21> <22> after: Optional[str] = "" <23> index, cont = 0, True # initialize variables <24> while cont and index < 10: <25> try: <26> after_str: str = after if isinstance(after, str) else "" <27> data = run_query(user_id, max_repos, after=after_str) <28> except Exception as e: <29> raise e <30> <31> restricted_contrib_count = data.restricted_contrib_count <32> issue_contribs_count = data.issue_contribs_count <33> pr_contribs_count = data.pr_contribs_count <34> pr_review_contribs_count = data.pr_review_contribs_count <35> repo_contribs_count = data.repo_contribs_count <36> </s>
===========below chunk 0=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 1 repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) repo_contribs[repo_name][category].append(contrib) total_contribs[category].append(contrib) if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date(repo.occurred_at)) repo_contribs[repo.repository.name]["repo"].</s> ===========below chunk 1=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 2 <s>red_at=Date(repo.occurred_at)) repo_contribs[repo.repository.name]["repo"].append(contrib) total_contribs["repo"].append(contrib) index += 1 date_filter: Callable[[Contribution], bool] = ( lambda x: start_date <= x.occurred_at <= end_date ) repo_contrib_objs: List[RepoContribStats] = [ RepoContribStats( name=k, issues=list(filter(date_filter, v["issues"])), prs=list(filter(date_filter, v["prs"])), reviews=list(filter(date_filter, v["reviews"])), repo=list(filter(date_filter, v["repo"])), ) for k, v in repo_contribs.items() ] # can get more than max_repos outputs if issues/prs/reviews come from different repos repo_contrib_objs = sorted( repo_contrib_objs, key=lambda x: len(x.issues) + len(x.prs) + len(x.reviews) + len(x.repo), reverse=True, )[:max_repos] total_contrib_obj: RepoContribStats = RepoContribStats( name="total", issues=list(filter(date_filter, total_contribs["issues"])), prs=list(filter(date_filter, total_contribs["prs"])), reviews=list(filter(date_filter, total_contribs["reviews"])</s> ===========below chunk 2=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 3 <s> repo=list(filter(date_filter, total_contribs["repo"])), ) output: UserContribStats = UserContribStats( total=total_contrib_obj, repos=repo_contrib_objs, restricted_contrib_count=restricted_contrib_count, issue_contribs_count=issue_contribs_count, pr_contribs_count=pr_contribs_count, pr_review_contribs_count=pr_review_contribs_count, repo_contribs_count=repo_contribs_count, repos_with_issue_contrib=repos_with_issue_contrib, repos_with_pr_contrib=repos_with_pr_contrib, repos_with_pr_review_contrib=repos_with_pr_review_contrib, ) return output ===========unchanged ref 0=========== at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: external.github_api.graphql.user get_user_contribution_stats(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionStatsAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_stats.APIResponse issue_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="issueContributionsByRepository" ) pr_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestContributionsByRepository" ) pr_review_contribs_by_repo: List[APIResponse_ContribsByRepo] = Field( alias="pullRequestReviewContributionsByRepository" ) repo_contribs: APIResponse_RepoContribs = Field(alias="repositoryContributions") restricted_contrib_count: int = Field(alias="restrictedContributionsCount") issue_contribs_count: int = Field(alias="totalIssueContributions") pr_contribs_count: int = Field(alias="totalPullRequestContributions")
tests.processing.user.test_contribution_stats/TestTemplate.test_get_user_contribution_stats
Modified
avgupta456~github-trends
65c94816d17ea8e768997c8d11913f39df8a25e4
updated contribution_stats processing
<4>:<add> self.assertLessEqual(len(response.contribs_by_repo), 1) <del> self.assertLessEqual(len(response.repos), 1) <8>:<add> date = response.contribs.issues[0].occurred_at <del> date = response.total.issues[0].occurred_at
# module: tests.processing.user.test_contribution_stats class TestTemplate(unittest.TestCase): def test_get_user_contribution_stats(self): <0> response = get_user_contribution_stats(user_id="avgupta456") <1> self.assertIsInstance(response, UserContribStats) <2> <3> response = get_user_contribution_stats(user_id="avgupta456", max_repos=1) <4> self.assertLessEqual(len(response.repos), 1) <5> <6> start = today - 100 <7> response = get_user_contribution_stats(user_id="avgupta456", start_date=start) <8> date = response.total.issues[0].occurred_at <9> self.assertGreaterEqual(date - start, 0) <10> self.assertGreaterEqual(today - date, 0) <11>
===========changed ref 0=========== # module: models.user.contribution_stats + class ContributionTimeline(BaseModel): + class Config: + arbitrary_types_allowed = True + ===========changed ref 1=========== # module: models.user.contribution_stats + class ContributionTimeline(BaseModel): + """ + BaseModel which accepts: + - occurred_at: Date + - count: int + """ + + occurred_at: Date + count: int + ===========changed ref 2=========== # module: models.user.contribution_stats class RepoContribStats(BaseModel): """ BaseModel which includes: - name: str - issues: List[Contribution] - prs: List[Contribution] - reviews: List[Contribution] - repo: List[Contribution] """ name: str + issues: List[ContributionTimeline] - issues: List[Contribution] + prs: List[ContributionTimeline] - prs: List[Contribution] + reviews: List[ContributionTimeline] - reviews: List[Contribution] + repo: List[ContributionTimeline] - repo: List[Contribution] ===========changed ref 3=========== # module: models.user.contribution_stats class UserContribStats(BaseModel): """ BaseModel which accepts: + - contribs_by_repo: List[RepoContribStats] - - repos: List[RepoContribStats] + - contribs: RepoContribStats - - total: RepoContribStats - restricted_contrib_count: int - issue_contribs_count: int - pr_contribs_count: int - pr_review_contribs_count: int - repo_contribs_count: int - repos_with_issue_contrib: int - repos_with_pr_contrib: int - repos_with_pr_review_contrib: int """ + contribs_by_repo: List[RepoContribStats] - repos: List[RepoContribStats] + contribs: RepoContribStats - total: RepoContribStats restricted_contrib_count: int issue_contribs_count: int pr_contribs_count: int pr_review_contribs_count: int repo_contribs_count: int repos_with_issue_contrib: int repos_with_pr_contrib: int repos_with_pr_review_contrib: int ===========changed ref 4=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: """Gets the daily contribution history for a users top x repositories""" repo_names = set() + raw_repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( - repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} ) + raw_total_contribs: Dict[str, List[Contribution]] = { - total_contribs: Dict[str, List[Contribution]] = { "issues": [], "prs": [], "reviews": [], "repo": [], } # only need them from the first data pull restricted_contrib_count = 0 issue_contribs_count = 0 pr_contribs_count = 0 pr_review_contribs_count = 0 repo_contribs_count = 0 repos_with_issue_contrib = 0 repos_with_pr_contrib = 0 repos_with_pr_review_contrib = 0 after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: try: after_str: str = after if isinstance(after, str) else "" data = run_query(user_id, max_repos, after=after_str) except Exception as e: raise e restricted_contrib_count = data.restricted_contrib_count issue_contribs_count = data.issue_contribs_count pr_contribs_count = data.pr_contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo_contrib</s> ===========changed ref 5=========== # module: processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 1 <s>contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo_contribs_count = data.repo_contribs_count repos_with_issue_contrib = data.repos_with_issue_contrib repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) + raw_repo_contribs[repo_name][category].append(contrib) - repo_contribs</s>
backend.processing.user.contribution_calendar/get_user_contribution_calendar
Modified
avgupta456~github-trends
38144b54a09ff97a4782cd8425c7ed0d39c348c0
updated month handling
<32>:<add> # creates months (0 is first month, up to present) <add> start_year, start_month = start_date.year(), start_date.month() <add> year_diff = end_date.year() - start_year <add> month_diff = end_date.month() - start_month <add> num_months = year_diff * 12 + month_diff + 1 <del> # creates months (0 is January, 11 is December) <33>:<add> months = [[] for _ in range(num_months)] <del> months = [[] for _ in range(12)] <35>:<add> date = day.date <add> year_diff = date.year() - start_year <add> month_diff = date.month() - start_month <add> index = year_diff * 12 + month_diff <add> months[index].append(day) <del> months[day.date.month() - 1].append(day)
# module: backend.processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCalendar: <0> """get user contributions for the past year""" <1> if today - start_date > 365: <2> raise AssertionError("start_date can only be within past 1 year") <3> <4> try: <5> data = run_query(user_id) <6> except Exception as e: <7> raise e <8> <9> contribution_years = data.contribution_years <10> colors = data.contribution_calendar.colors <11> days = map( <12> lambda x: ContributionDay.parse_obj( <13> { <14> "date": Date(x.date), <15> "weekday": x.weekday, <16> "contribution_count": x.contribution_count, <17> "contribution_level": x.contribution_level, <18> } <19> ), <20> [ <21> day <22> for week in data.contribution_calendar.weeks <23> for day in week.contribution_days <24> ], <25> ) <26> <27> days = list(filter(lambda x: start_date <= x.date <= end_date, days)) <28> <29> # creates total period (up to 1 year long) <30> total = create_contribution_period(days) <31> <32> # creates months (0 is January, 11 is December) <33> months = [[] for _ in range(12)] <34> for day in days: <35> months[day.date.month() - 1].append(day) <36> <37> months = list(map(lambda x: create_contribution_period(x), months)) <38> <39> # create weekdays (0 is Sunday, 6 is Saturday) <40> weekdays = [[] for _ in range(7)] <41> for day in days: <42> weekdays[day.weekday].append(day) <43> <44> weekdays = list</s>
===========below chunk 0=========== # module: backend.processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCalendar: # offset: 1 # create final output calendar = UserContribCalendar( contribution_years=contribution_years, colors=colors, total=total, months=months, weekdays=weekdays, ) return calendar ===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.misc.date.Date year() -> int month() -> int at: models.user.contribution_calendar create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod at: models.user.contribution_calendar.APIResponse contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar") contribution_years: List[int] = Field(alias="contributionYears") at: models.user.contribution_calendar.APIResponse_Calendar total_contributions: int = Field(alias="totalContributions") weeks: List[APIResponse_Calendar_Week] colors: List[str] ===========changed ref 0=========== # module: backend.models.misc.date today = Date(datetime.now()) + date_2019 = Date("2019-01-01") + date_2020 = Date("2020-01-01") + date_2021 = Date("2021-01-01")
backend.processing.user.follows/get_user_followers
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<11>:<del> try: <12>:<add> after_str: str = after if isinstance(after, str) else "" <del> after_str: str = after if isinstance(after, str) else "" <13>:<add> data = get_func(user_id, after=after_str) <del> data = get_func(user_id, after=after_str) <14>:<del> except Exception as e: <15>:<del> raise e
# module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: <0> """get user followers and users following for given user""" <1> <2> followers: List[User] = [] <3> following: List[User] = [] <4> <5> for user_list, get_func in zip( <6> [followers, following], [_get_user_followers, _get_user_following] <7> ): <8> after: Optional[str] = "" <9> index, cont = 0, True # initialize variables <10> while cont and index < 10: <11> try: <12> after_str: str = after if isinstance(after, str) else "" <13> data = get_func(user_id, after=after_str) <14> except Exception as e: <15> raise e <16> <17> cont = False <18> <19> user_list.extend( <20> map( <21> lambda x: User(name=x.name, login=x.login, url=x.url), <22> data.nodes, <23> ) <24> ) <25> if data.page_info.has_next_page: <26> after = data.page_info.end_cursor <27> cont = True <28> <29> index += 1 <30> <31> output = UserFollows(followers=followers, following=following) <32> return output <33>
===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_followers(user_id: str, first: int=100, after: str="") -> UserFollowAPIResponse get_user_following(user_id: str, first: int=10, after: str="") -> UserFollowAPIResponse at: models.user.follows.APIResponse nodes: List[APIResponse_User] page_info: APIResponse_PageInfo = Field(alias="pageInfo") at: models.user.follows.APIResponse_PageInfo has_next_page: bool = Field(alias="hasNextPage") end_cursor: Optional[str] = Field(alias="endCursor") at: typing List = _alias(list, 1, inst=False, name='List')
backend.processing.user.contribution_stats/get_user_contribution_stats
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<25>:<del> try: <26>:<add> after_str: str = after if isinstance(after, str) else "" <del> after_str: str = after if isinstance(after, str) else "" <27>:<add> data = run_query(user_id, max_repos, after=after_str) <del> data = run_query(user_id, max_repos, after=after_str) <28>:<del> except Exception as e: <29>:<del> raise e
# module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: <0> """Gets the daily contribution history for a users top x repositories""" <1> repo_names = set() <2> raw_repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( <3> lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} <4> ) <5> raw_total_contribs: Dict[str, List[Contribution]] = { <6> "issues": [], <7> "prs": [], <8> "reviews": [], <9> "repo": [], <10> } <11> <12> # only need them from the first data pull <13> restricted_contrib_count = 0 <14> issue_contribs_count = 0 <15> pr_contribs_count = 0 <16> pr_review_contribs_count = 0 <17> repo_contribs_count = 0 <18> repos_with_issue_contrib = 0 <19> repos_with_pr_contrib = 0 <20> repos_with_pr_review_contrib = 0 <21> <22> after: Optional[str] = "" <23> index, cont = 0, True # initialize variables <24> while cont and index < 10: <25> try: <26> after_str: str = after if isinstance(after, str) else "" <27> data = run_query(user_id, max_repos, after=after_str) <28> except Exception as e: <29> raise e <30> <31> restricted_contrib_count = data.restricted_contrib_count <32> issue_contribs_count = data.issue_contribs_count <33> pr_contribs_count = data.pr_contribs_count <34> pr_review_contribs_count = data.pr_review_contribs_count <35> repo_contribs_count = data.repo_contrib</s>
===========below chunk 0=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 1 repos_with_issue_contrib = data.repos_with_issue_contrib repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) raw_repo_contribs[repo_name][category].append(contrib) raw_total_contribs[category].append(contrib) if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date</s> ===========below chunk 1=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 2 <s> = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date(repo.occurred_at)) raw_repo_contribs[repo.repository.name]["repo"].append(contrib) raw_total_contribs["repo"].append(contrib) index += 1 repo_contribs: DefaultDict[ str, Dict[str, Dict[int, ContributionTimeline]] ] = defaultdict(lambda: {"issues": {}, "prs": {}, "reviews": {}, "repo": {}}) for name, repo in raw_repo_contribs.items(): for type, event_list in repo.items(): for event in event_list: key = today - event.occurred_at if key not in repo_contribs[name][type]: repo_contribs[name][type][key] = ContributionTimeline( occurred_at=event.occurred_at, count=0 ) repo_contribs[name][type][key].count += 1 total_contribs: Dict[str, Dict[int, ContributionTimeline]] = { "issues": {}, "prs": {}, "reviews": {}, "repo": {}, } for type, event_list in raw_total_contribs.items(): for event in event_list: key = today - event.occurred_at if key not in total_contribs[type]: total_contribs[type][key] = ContributionTimeline( occurred_at=event.occurred_at, count=0 ) total_contribs[</s> ===========below chunk 2=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 3 <s>key].count += 1 date_filter: Callable[[ContributionTimeline], bool] = ( lambda x: start_date <= x.occurred_at <= end_date ) repo_contrib_objs: List[RepoContribStats] = [ RepoContribStats( name=k, issues=list(filter(date_filter, v["issues"].values())), prs=list(filter(date_filter, v["prs"].values())), reviews=list(filter(date_filter, v["reviews"].values())), repo=list(filter(date_filter, v["repo"].values())), ) for k, v in repo_contribs.items() ] # can get more than max_repos outputs if issues/prs/reviews come from different repos repo_contrib_objs = sorted( repo_contrib_objs, key=lambda x: len(x.issues) + len(x.prs) + len(x.reviews) + len(x.repo), reverse=True, )[:max_repos] total_contrib_obj: RepoContribStats = RepoContribStats( name="total", issues=list(filter(date_filter, total_contribs["issues"].values())), prs=list(filter(date_filter, total_contribs["prs"].values())), reviews=list(filter(date_filter, total_contribs["reviews"].values())), repo=list(filter(date_filter, total_contribs["repo"].values())), ) output:</s> ===========below chunk 3=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 4 <s>tribStats = UserContribStats( contribs=total_contrib_obj, contribs_by_repo=repo_contrib_objs, restricted_contrib_count=restricted_contrib_count, issue_contribs_count=issue_contribs_count, pr_contribs_count=pr_contribs_count, pr_review_contribs_count=pr_review_contribs_count, repo_contribs_count=repo_contribs_count, repos_with_issue_contrib=repos_with_issue_contrib, repos_with_pr_contrib=repos_with_pr_contrib, repos_with_pr_review_contrib=repos_with_pr_review_contrib, ) return output
backend.external.github_api.graphql.user/get_user_contribution_commits
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<38>:<del> try: <39>:<add> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <del> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <40>:<add> return UserContributionCommitsAPIResponse.parse_obj(output_dict) <del> return UserContributionCommitsAPIResponse.parse_obj(output_dict) <41>:<del> except Exception as e: <42>:<del> logging.exception(e) <43>:<del> raise e
# module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: <0> """Runs an individual query, fetching at most 100 days of history""" <1> query = { <2> "variables": { <3> "login": user_id, <4> "maxRepos": max_repos, <5> "first": first, <6> "after": after, <7> }, <8> "query": """ <9> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { <10> user(login: $login){ <11> contributionsCollection{ <12> commitContributionsByRepository(maxRepositories: $maxRepos){ <13> repository{ <14> name, <15> }, <16> totalCount:contributions(first: 1){ <17> totalCount <18> } <19> contributions(first: $first, after: $after){ <20> nodes{ <21> commitCount, <22> occurredAt, <23> } <24> pageInfo{ <25> hasNextPage, <26> endCursor <27> } <28> } <29> } <30> totalCommitContributions, <31> totalRepositoriesWithContributedCommits, <32> }, <33> }, <34> } <35> """, <36> } <37> <38> try: <39> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <40> return UserContributionCommitsAPIResponse.parse_obj(output_dict) <41> except Exception as e: <42> logging.exception(e) <43> raise e <44>
===========unchanged ref 0=========== at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, after=after_str) - data = get_func(user_id, after=after_str) - except Exception as e: - raise e cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output ===========changed ref 1=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: """Gets the daily contribution history for a users top x repositories""" repo_names = set() raw_repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} ) raw_total_contribs: Dict[str, List[Contribution]] = { "issues": [], "prs": [], "reviews": [], "repo": [], } # only need them from the first data pull restricted_contrib_count = 0 issue_contribs_count = 0 pr_contribs_count = 0 pr_review_contribs_count = 0 repo_contribs_count = 0 repos_with_issue_contrib = 0 repos_with_pr_contrib = 0 repos_with_pr_review_contrib = 0 after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = run_query(user_id, max_repos, after=after_str) - data = run_query(user_id, max_repos, after=after_str) - except Exception as e: - raise e restricted_contrib_count = data.restricted_contrib_count issue_contribs_count = data.issue_contribs_count pr_contribs_count = data.pr_contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo</s> ===========changed ref 2=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 1 <s>pr_contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo_contribs_count = data.repo_contribs_count repos_with_issue_contrib = data.repos_with_issue_contrib repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) raw_repo_contribs[repo_name][category].append(contrib) raw_</s> ===========changed ref 3=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 2 <s>contribs[category].append(contrib) if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True for repo in data.repo_contribs.nodes: contrib = Contribution(occurred_at=Date(repo.occurred_at)) raw_repo_contribs[repo.repository.name]["repo"].append(contrib) raw_total_contribs["repo"].append(contrib) index += 1 repo_contribs: DefaultDict[ str, Dict[str, Dict[int, ContributionTimeline]] ] = defaultdict(lambda: {"issues": {}, "prs": {}, "reviews": {}, "repo": {}}) for name, repo in raw_repo_contribs.items(): for type, event_list in repo.items(): for event in event_list: key = today - event.occurred_at if key not in repo_contribs[name][type]: repo_contribs[name][type][key] = ContributionTimeline( occurred_at=event.occurred_at, count=0 ) repo_contribs[name][type][key].count += 1 total_contribs: Dict[str, Dict[int, ContributionTimeline]] = { "issues": {}, "prs": {}, "reviews": {}, "repo": {}, } for type, event_list in raw_total_contribs.items(): for event in event_list: key = today - event.occurred_at if key not in total_contrib</s>
backend.external.github_api.graphql.user/get_user_contribution_calendar
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<26>:<del> try: <27>:<add> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <del> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <28>:<add> return UserContributionCalendarAPIResponse.parse_obj(output_dict) <del> return UserContributionCalendarAPIResponse.parse_obj(output_dict) <29>:<del> except Exception as e: <30>:<del> logging.exception(e) <31>:<del> raise e
# module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: <0> """Fetches user contribution calendar and contribution years""" <1> query = { <2> "variables": {"login": user_id}, <3> "query": """ <4> query getUser($login: String!) { <5> user(login: $login){ <6> contributionsCollection{ <7> contributionCalendar{ <8> totalContributions, <9> weeks{ <10> contributionDays{ <11> date, <12> weekday, <13> contributionCount, <14> contributionLevel, <15> } <16> } <17> colors, <18> } <19> contributionYears, <20> } <21> }, <22> } <23> """, <24> } <25> <26> try: <27> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <28> return UserContributionCalendarAPIResponse.parse_obj(output_dict) <29> except Exception as e: <30> logging.exception(e) <31> raise e <32>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_contribution_calendar query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: """Runs an individual query, fetching at most 100 days of history""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } totalCommitContributions, totalRepositoriesWithContributedCommits, }, }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCommitsAPIResponse.parse_obj(output_dict) - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, after=after_str) - data = get_func(user_id, after=after_str) - except Exception as e: - raise e cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output ===========changed ref 2=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: """Gets the daily contribution history for a users top x repositories""" repo_names = set() raw_repo_contribs: DefaultDict[str, Dict[str, List[Contribution]]] = defaultdict( lambda: {"issues": [], "prs": [], "reviews": [], "repo": []} ) raw_total_contribs: Dict[str, List[Contribution]] = { "issues": [], "prs": [], "reviews": [], "repo": [], } # only need them from the first data pull restricted_contrib_count = 0 issue_contribs_count = 0 pr_contribs_count = 0 pr_review_contribs_count = 0 repo_contribs_count = 0 repos_with_issue_contrib = 0 repos_with_pr_contrib = 0 repos_with_pr_review_contrib = 0 after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = run_query(user_id, max_repos, after=after_str) - data = run_query(user_id, max_repos, after=after_str) - except Exception as e: - raise e restricted_contrib_count = data.restricted_contrib_count issue_contribs_count = data.issue_contribs_count pr_contribs_count = data.pr_contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo</s> ===========changed ref 3=========== # module: backend.processing.user.contribution_stats def get_user_contribution_stats( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribStats: # offset: 1 <s>pr_contribs_count pr_review_contribs_count = data.pr_review_contribs_count repo_contribs_count = data.repo_contribs_count repos_with_issue_contrib = data.repos_with_issue_contrib repos_with_pr_contrib = data.repos_with_pr_contrib repos_with_pr_review_contrib = data.repos_with_pr_review_contrib for repo in data.issue_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.pr_review_contribs_by_repo: repo_names.add(repo.repository.name) for repo in data.repo_contribs.nodes: repo_names.add(repo.repository.name) cont = False repo_lists: List[List[APIResponse_ContribsByRepo]] = [ data.issue_contribs_by_repo, data.pr_contribs_by_repo, data.pr_review_contribs_by_repo, ] for category, repo_list in zip(["issues", "prs", "reviews"], repo_lists): for repo in repo_list: repo_name = repo.repository.name for event in repo.contributions.nodes: contrib = Contribution(occurred_at=Date(event.occurred_at)) raw_repo_contribs[repo_name][category].append(contrib) raw_</s>
backend.external.github_api.graphql.user/get_user_contribution_stats
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
# module: backend.external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: <0> """Fetches user contribution calendar and contribution years""" <1> query = { <2> "variables": { <3> "login": user_id, <4> "maxRepos": max_repos, <5> "first": first, <6> "after": after, <7> }, <8> "query": """ <9> query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { <10> user(login: $login){ <11> contributionsCollection{ <12> issueContributionsByRepository(maxRepositories: $maxRepos){ <13> repository{ <14> name <15> }, <16> contributions(first: $first, after: $after){ <17> totalCount, <18> nodes{ <19> occurredAt, <20> issue{ <21> state <22> } <23> } <24> pageInfo{ <25> hasNextPage, <26> endCursor <27> } <28> } <29> } <30> pullRequestContributionsByRepository(maxRepositories: $maxRepos){ <31> repository{ <32> name <33> }, <34> contributions(first: $first, after: $after){ <35> totalCount, <36> nodes{ <37> occurredAt, <38> pullRequest{ <39> state, <40> } <41> } <42> pageInfo{ <43> hasNextPage, <44> endCursor <45> } <46> } <47> } <48> pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ <49> repository{ <50> name <51> }, <52> contributions(first: $first, after: $after){ <53> totalCount, <54> nodes{ <55> occurredAt, <56> pullRequestReview{ <57> state, <58> } <59> } <60> pageInfo{ <61> hasNextPage, <62> endCursor <63> </s>
===========below chunk 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: # offset: 1 } }, repositoryContributions(first: $maxRepos){ totalCount, nodes{ repository{ name, } occurredAt, } }, restrictedContributionsCount, totalIssueContributions, totalPullRequestContributions, totalPullRequestReviewContributions, totalRepositoryContributions, totalRepositoriesWithContributedIssues, totalRepositoriesWithContributedPullRequests, totalRepositoriesWithContributedPullRequestReviews }, } } """, } try: output_dict = get_template(query)["data"]["user"]["contributionsCollection"] return UserContributionStatsAPIResponse.parse_obj(output_dict) except Exception as e: logging.exception(e) raise e ===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_contribution_stats query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ issueContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, issue{ state } } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, pullRequest{ state, } } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, pullRequestReview{ state, } } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount, nodes{ repository{ name, } occurredAt, } }, restrictedContributionsCount, totalIssueContributions, totalPullRequestContributions, totalPullRequestReviewContributions, totalRepositoryContributions, totalRepositoriesWithContributedIssues, totalRepositoriesWithContributedPullRequests,</s> ===========unchanged ref 1=========== at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCalendarAPIResponse.parse_obj(output_dict) - return UserContributionCalendarAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: """Runs an individual query, fetching at most 100 days of history""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } totalCommitContributions, totalRepositoriesWithContributedCommits, }, }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCommitsAPIResponse.parse_obj(output_dict) - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 2=========== # module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, after=after_str) - data = get_func(user_id, after=after_str) - except Exception as e: - raise e cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output
backend.external.github_api.graphql.user/get_user_followers
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<51>:<del> try: <52>:<add> output_dict = get_template(query)["data"]["user"]["followers"] <del> output_dict = get_template(query)["data"]["user"]["followers"] <53>:<add> return UserFollowAPIResponse.parse_obj(output_dict) <del> return UserFollowAPIResponse.parse_obj(output_dict) <54>:<del> except Exception as e: <55>:<del> logging.exception(e) <56>:<del> raise e
# module: backend.external.github_api.graphql.user def get_user_followers( user_id: str, first: int = 100, after: str = "" ) -> UserFollowAPIResponse: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> followers(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> followers(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> try: <52> output_dict = get_template(query)["data"]["user"]["followers"] <53> return UserFollowAPIResponse.parse_obj(output_dict) <54> except Exception as e: <55> logging.exception(e) <56> raise e <57>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_followers variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ followers(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ followers(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCalendarAPIResponse.parse_obj(output_dict) - return UserContributionCalendarAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: """Runs an individual query, fetching at most 100 days of history""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } totalCommitContributions, totalRepositoriesWithContributedCommits, }, }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCommitsAPIResponse.parse_obj(output_dict) - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ issueContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, issue{ state } } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, pullRequest{ state, } } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, contributions(first: $first, after: $after){ totalCount, nodes{ occurredAt, pullRequestReview{ state, } } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount, nodes{ repository{ name, } occurredAt, } }, restrictedContributionsCount, totalIssueContributions,</s> ===========changed ref 3=========== # module: backend.external.github_api.graphql.user def get_user_contribution_stats( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionStatsAPIResponse: # offset: 1 <s> name, } occurredAt, } }, restrictedContributionsCount, totalIssueContributions, totalPullRequestContributions, totalPullRequestReviewContributions, totalRepositoryContributions, totalRepositoriesWithContributedIssues, totalRepositoriesWithContributedPullRequests, totalRepositoriesWithContributedPullRequestReviews }, } } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionStatsAPIResponse.parse_obj(output_dict) - return UserContributionStatsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e
backend.external.github_api.graphql.user/get_user_following
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<51>:<del> try: <52>:<add> output_dict = get_template(query)["data"]["user"]["following"] <del> output_dict = get_template(query)["data"]["user"]["following"] <53>:<add> return UserFollowAPIResponse.parse_obj(output_dict) <del> return UserFollowAPIResponse.parse_obj(output_dict) <54>:<del> except Exception as e: <55>:<del> logging.exception(e) <56>:<del> raise e
# module: backend.external.github_api.graphql.user def get_user_following( user_id: str, first: int = 10, after: str = "" ) -> UserFollowAPIResponse: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> following(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> following(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> try: <52> output_dict = get_template(query)["data"]["user"]["following"] <53> return UserFollowAPIResponse.parse_obj(output_dict) <54> except Exception as e: <55> logging.exception(e) <56> raise e <57>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_following variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ following(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ following(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_followers( user_id: str, first: int = 100, after: str = "" ) -> UserFollowAPIResponse: """gets user's followers and users following'""" variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ followers(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ followers(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) query = { "variables": variables, "query": query_str, } - try: + output_dict = get_template(query)["data"]["user"]["followers"] - output_dict = get_template(query)["data"]["user"]["followers"] + return UserFollowAPIResponse.parse_obj(output_dict) - return UserFollowAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCalendarAPIResponse.parse_obj(output_dict) - return UserContributionCalendarAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: """Runs an individual query, fetching at most 100 days of history""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } totalCommitContributions, totalRepositoriesWithContributedCommits, }, }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCommitsAPIResponse.parse_obj(output_dict) - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e
backend.processing.user.contribution_commits/get_user_contribution_commits
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<8>:<del> try: <9>:<add> after_str = after if isinstance(after, str) else "" <del> after_str = after if isinstance(after, str) else "" <10>:<add> data = run_query(user_id, max_repos, after=after_str) <del> data = run_query(user_id, max_repos, after=after_str) <11>:<del> except Exception as e: <12>:<del> raise e
# module: backend.processing.user.contribution_commits def get_user_contribution_commits( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCommits: <0> """Gets the daily commit history for a users top x repositories""" <1> time_range = today - start_date # gets number of days to end date <2> segments = min(math.ceil(time_range / 100), 10) # no more than three years <3> raw_repos: List[CommitContributionsByRepository] = [] <4> commit_contribs_count, repos_with_commit_contrib = 0, 0 <5> after: Optional[str] = "" <6> index, cont = 0, True # initialize variables <7> while cont and index < segments: <8> try: <9> after_str = after if isinstance(after, str) else "" <10> data = run_query(user_id, max_repos, after=after_str) <11> except Exception as e: <12> raise e <13> <14> commit_contribs_count = data.commit_contribs_count <15> repos_with_commit_contrib = data.repos_with_commit_contrib <16> <17> cont = False <18> for i, repo in enumerate(data.commits_by_repo): <19> if index == 0: <20> raw_repos.append( <21> CommitContributionsByRepository( <22> name=repo.repository.name, <23> contributions=repo.total_count.total_count, <24> contributions_in_range=0, <25> timeline=[], <26> ) <27> ) <28> <29> raw_contribs = repo.contributions.nodes <30> contribs = map( <31> lambda x: create_commit_contribution(x), <32> raw_contribs, <33> ) <34> contribs = filter( <35> lambda x: start_date <= x.occurred_at <= end_date, contribs <36> ) <37> raw_repos[i].timeline.extend(</s>
===========below chunk 0=========== # module: backend.processing.user.contribution_commits def get_user_contribution_commits( user_id: str, max_repos: int = 100, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCommits: # offset: 1 if repo.contributions.page_info.has_next_page: after = repo.contributions.page_info.end_cursor cont = True index += 1 # adds contributionsInRange for repo in raw_repos: repo.contributions_in_range = sum([x.commit_count for x in repo.timeline]) # converts to objects repo_objects = map( lambda x: CommitContributionsByRepository.parse_obj(x), raw_repos ) # filters out empty results repo_objects = list(filter(lambda x: x.contributions_in_range > 0, repo_objects)) timeline: List[int] = [0 for _ in range(end_date - start_date + 1)] for repo in repo_objects: for day in repo.timeline: timeline[day.occurred_at - start_date] += day.commit_count timeline_object = [ CommitContribution(occurred_at=start_date + i, commit_count=x) for i, x in enumerate(timeline) ] total_object = CommitContributionsByRepository( name="total", contributions=commit_contribs_count, contributions_in_range=sum(timeline), timeline=timeline_object, ) output = UserContribCommits( commit_contribs_by_repo=list(repo_objects), commit_contribs=total_object, repos_with_commit_contrib=repos_with_commit_contrib, ) return output ===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_contribution_commits(user_id: str, max_repos: int=100, first: int=100, after: str="") -> UserContributionCommitsAPIResponse at: math ceil(x: SupportsFloat, /) -> int at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.user.contribution_commits create_commit_contribution(x: APIResponse_Repo_Contribs_Node) -> CommitContribution at: models.user.contribution_commits.APIResponse commits_by_repo: List[APIResponse_Repo] = Field( alias="commitContributionsByRepository" ) commit_contribs_count: int = Field(alias="totalCommitContributions") repos_with_commit_contrib: int = Field( alias="totalRepositoriesWithContributedCommits" ) at: models.user.contribution_commits.APIResponse_Repo repository: APIResponse_Repo_Repo total_count: APIResponse_Repo_TotalCount = Field(alias="totalCount") contributions: APIResponse_Repo_Contribs at: models.user.contribution_commits.APIResponse_Repo_Contribs nodes: List[APIResponse_Repo_Contribs_Node] page_info: APIResponse_Repo_Contribs_PageInfo = Field(alias="pageInfo") at: models.user.contribution_commits.APIResponse_Repo_Contribs_PageInfo has_next_page: bool = Field(alias="hasNextPage") end_cursor: Optional[str] = Field(alias="endCursor") at: models.user.contribution_commits.APIResponse_Repo_Repo name: str at: models.user.contribution_commits.APIResponse_Repo_TotalCount total_count: int = Field(alias="totalCount") at: models.user.contribution_commits.CommitContribution commit_count: int ===========unchanged ref 1=========== occurred_at: Date at: models.user.contribution_commits.CommitContributionsByRepository name: str contributions: int contributions_in_range: int timeline: List[CommitContribution] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCalendarAPIResponse.parse_obj(output_dict) - return UserContributionCalendarAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, after=after_str) - data = get_func(user_id, after=after_str) - except Exception as e: - raise e cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output
backend.processing.user.contribution_calendar/get_user_contribution_calendar
Modified
avgupta456~github-trends
bec1c8e1a8664d7e11449b444a9a08ec6598542c
remove try except without substance
<4>:<del> try: <5>:<add> data = run_query(user_id) <del> data = run_query(user_id) <6>:<del> except Exception as e: <7>:<del> raise e
# module: backend.processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCalendar: <0> """get user contributions for the past year""" <1> if today - start_date > 365: <2> raise AssertionError("start_date can only be within past 1 year") <3> <4> try: <5> data = run_query(user_id) <6> except Exception as e: <7> raise e <8> <9> contribution_years = data.contribution_years <10> colors = data.contribution_calendar.colors <11> days = map( <12> lambda x: ContributionDay.parse_obj( <13> { <14> "date": Date(x.date), <15> "weekday": x.weekday, <16> "contribution_count": x.contribution_count, <17> "contribution_level": x.contribution_level, <18> } <19> ), <20> [ <21> day <22> for week in data.contribution_calendar.weeks <23> for day in week.contribution_days <24> ], <25> ) <26> <27> days = list(filter(lambda x: start_date <= x.date <= end_date, days)) <28> <29> # creates total period (up to 1 year long) <30> total = create_contribution_period(days) <31> <32> # creates months (0 is first month, up to present) <33> start_year, start_month = start_date.year(), start_date.month() <34> year_diff = end_date.year() - start_year <35> month_diff = end_date.month() - start_month <36> num_months = year_diff * 12 + month_diff + 1 <37> months = [[] for _ in range(num_months)] <38> for day in days: <39> date = day.date <40> year_diff = date.year() - start_year <41> month_diff = date.month() - start_</s>
===========below chunk 0=========== # module: backend.processing.user.contribution_calendar def get_user_contribution_calendar( user_id: str, start_date: Date = today - 365, end_date: Date = today, ) -> UserContribCalendar: # offset: 1 index = year_diff * 12 + month_diff months[index].append(day) months = list(map(lambda x: create_contribution_period(x), months)) # create weekdays (0 is Sunday, 6 is Saturday) weekdays = [[] for _ in range(7)] for day in days: weekdays[day.weekday].append(day) weekdays = list(map(lambda x: create_contribution_period(x), weekdays)) # create final output calendar = UserContribCalendar( contribution_years=contribution_years, colors=colors, total=total, months=months, weekdays=weekdays, ) return calendar ===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse at: models.misc.date Date(date: Union[str, datetime]) today = Date(datetime.now()) at: models.misc.date.Date year() -> int month() -> int at: models.user.contribution_calendar create_contribution_period(days: List[ContributionDay]) -> ContributionPeriod at: models.user.contribution_calendar.APIResponse contribution_calendar: APIResponse_Calendar = Field(alias="contributionCalendar") contribution_years: List[int] = Field(alias="contributionYears") at: models.user.contribution_calendar.APIResponse_Calendar total_contributions: int = Field(alias="totalContributions") weeks: List[APIResponse_Calendar_Week] colors: List[str] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: """Fetches user contribution calendar and contribution years""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions, weeks{ contributionDays{ date, weekday, contributionCount, contributionLevel, } } colors, } contributionYears, } }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCalendarAPIResponse.parse_obj(output_dict) - return UserContributionCalendarAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e ===========changed ref 1=========== # module: backend.processing.user.follows def get_user_followers(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: - try: + after_str: str = after if isinstance(after, str) else "" - after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, after=after_str) - data = get_func(user_id, after=after_str) - except Exception as e: - raise e cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_commits( user_id: str, max_repos: int = 100, first: int = 100, after: str = "", ) -> UserContributionCommitsAPIResponse: """Runs an individual query, fetching at most 100 days of history""" query = { "variables": { "login": user_id, "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection{ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } totalCommitContributions, totalRepositoriesWithContributedCommits, }, }, } """, } - try: + output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + return UserContributionCommitsAPIResponse.parse_obj(output_dict) - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - except Exception as e: - logging.exception(e) - raise e
backend.external.github_api.graphql.user/get_user_contribution_calendar
Modified
avgupta456~github-trends
d23bbb62210057c35f853e8788de6caa32fb514d
update graphql queries
<0>:<add> """Gets contribution calendar for a given time period (max one year)""" <add> if (end_date - start_date).days > 365: <add> raise ValueError("date range can be at most 1 year") <del> """Fetches user contribution calendar and contribution years""" <2>:<add> "variables": { <add> "login": user_id, <del> "variables": {"login": user_id}, <3>:<add> "startDate": str(start_date) + "T00:00:00.000Z", <add> "endDate": str(end_date) + "T00:00:00.000Z", <add> }, <4>:<add> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ <del> query getUser($login: String!) { <6>:<add> contributionsCollection(from: $startDate, to: $endDate){ <del> contributionsCollection{ <8>:<del> totalContributions, <11>:<add> date <del> date, <12>:<add> weekday <del> weekday, <13>:<add> contributionCount <del> contributionCount, <14>:<del> contributionLevel, <17>:<add> totalContributions <del> colors, <19>:<del> contributionYears, <21>:<add> } <del> }, <26>:<add> output = get_template(query)["data"]["user"]["contributionsCollection"][ <del> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <27>:<add> "
# module: backend.external.github_api.graphql.user + def get_user_contribution_calendar( + user_id: str, + start_date: date = date.today() - timedelta(days=365), + end_date: date = date.today(), + ) -> RawCalendar: - def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: <0> """Fetches user contribution calendar and contribution years""" <1> query = { <2> "variables": {"login": user_id}, <3> "query": """ <4> query getUser($login: String!) { <5> user(login: $login){ <6> contributionsCollection{ <7> contributionCalendar{ <8> totalContributions, <9> weeks{ <10> contributionDays{ <11> date, <12> weekday, <13> contributionCount, <14> contributionLevel, <15> } <16> } <17> colors, <18> } <19> contributionYears, <20> } <21> }, <22> } <23> """, <24> } <25> <26> output_dict = get_template(query)["data"]["user"]["contributionsCollection"] <27> return UserContributionCalendarAPIResponse.parse_obj(output_dict) <28>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_contribution_calendar query = { "variables": { "login": user_id, "startDate": str(start_date) + "T00:00:00.000Z", "endDate": str(end_date) + "T00:00:00.000Z", }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ contributionCalendar{ weeks{ contributionDays{ date weekday contributionCount } } totalContributions } } } } """, } at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str) -> List[int]: + """Gets years where the user had activity""" + query = { + "variables": {"login": user_id}, + "query": """ + query getUser($login: String!) { + user(login: $login){ + contributionsCollection{ + contributionYears + } + } + } + """, + } + + years = get_template(query)["data"]["user"]["contributionsCollection"][ + "contributionYears" + ] + + return years + ===========changed ref 1=========== # module: backend.external.github_api.graphql.user - def get_user_contribution_commits( - user_id: str, - max_repos: int = 100, - first: int = 100, - after: str = "", - ) -> UserContributionCommitsAPIResponse: - """Runs an individual query, fetching at most 100 days of history""" - query = { - "variables": { - "login": user_id, - "maxRepos": max_repos, - "first": first, - "after": after, - }, - "query": """ - query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { - user(login: $login){ - contributionsCollection{ - commitContributionsByRepository(maxRepositories: $maxRepos){ - repository{ - name, - }, - totalCount:contributions(first: 1){ - totalCount - } - contributions(first: $first, after: $after){ - nodes{ - commitCount, - occurredAt, - } - pageInfo{ - hasNextPage, - endCursor - } - } - } - totalCommitContributions, - totalRepositoriesWithContributedCommits, - }, - }, - } - """, - } - - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - return UserContributionCommitsAPIResponse.parse_obj(output_dict) -
backend.external.github_api.graphql.user/get_user_followers
Modified
avgupta456~github-trends
d23bbb62210057c35f853e8788de6caa32fb514d
update graphql queries
<52>:<add> return RawFollows.parse_obj(output_dict) <del> return UserFollowAPIResponse.parse_obj(output_dict)
# module: backend.external.github_api.graphql.user - def get_user_followers( - user_id: str, first: int = 100, after: str = "" - ) -> UserFollowAPIResponse: + def get_user_followers(user_id: str, first: int = 100, after: str = "") -> RawFollows: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> followers(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> followers(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> output_dict = get_template(query)["data"]["user"]["followers"] <52> return UserFollowAPIResponse.parse_obj(output_dict) <53>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_followers variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ followers(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ followers(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str) -> List[int]: + """Gets years where the user had activity""" + query = { + "variables": {"login": user_id}, + "query": """ + query getUser($login: String!) { + user(login: $login){ + contributionsCollection{ + contributionYears + } + } + } + """, + } + + years = get_template(query)["data"]["user"]["contributionsCollection"][ + "contributionYears" + ] + + return years + ===========changed ref 1=========== # module: backend.external.github_api.graphql.user - def get_user_contribution_commits( - user_id: str, - max_repos: int = 100, - first: int = 100, - after: str = "", - ) -> UserContributionCommitsAPIResponse: - """Runs an individual query, fetching at most 100 days of history""" - query = { - "variables": { - "login": user_id, - "maxRepos": max_repos, - "first": first, - "after": after, - }, - "query": """ - query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { - user(login: $login){ - contributionsCollection{ - commitContributionsByRepository(maxRepositories: $maxRepos){ - repository{ - name, - }, - totalCount:contributions(first: 1){ - totalCount - } - contributions(first: $first, after: $after){ - nodes{ - commitCount, - occurredAt, - } - pageInfo{ - hasNextPage, - endCursor - } - } - } - totalCommitContributions, - totalRepositoriesWithContributedCommits, - }, - }, - } - """, - } - - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - ===========changed ref 2=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_calendar( + user_id: str, + start_date: date = date.today() - timedelta(days=365), + end_date: date = date.today(), + ) -> RawCalendar: - def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: + """Gets contribution calendar for a given time period (max one year)""" + if (end_date - start_date).days > 365: + raise ValueError("date range can be at most 1 year") - """Fetches user contribution calendar and contribution years""" query = { + "variables": { + "login": user_id, - "variables": {"login": user_id}, + "startDate": str(start_date) + "T00:00:00.000Z", + "endDate": str(end_date) + "T00:00:00.000Z", + }, "query": """ + query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ - query getUser($login: String!) { user(login: $login){ + contributionsCollection(from: $startDate, to: $endDate){ - contributionsCollection{ contributionCalendar{ - totalContributions, weeks{ contributionDays{ + date - date, + weekday - weekday, + contributionCount - contributionCount, - contributionLevel, } } + totalContributions - colors, } - contributionYears, } + } - }, } """, } + output = get_template(query)["data"]["user"]["contributionsCollection"][ - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + "contributionCalendar" + ] + return RawCalendar.parse_obj(output) </s> ===========changed ref 3=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_calendar( + user_id: str, + start_date: date = date.today() - timedelta(days=365), + end_date: date = date.today(), + ) -> RawCalendar: - def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: # offset: 1 <s>contributionsCollection"] + "contributionCalendar" + ] + return RawCalendar.parse_obj(output) - return UserContributionCalendarAPIResponse.parse_obj(output_dict)
backend.external.github_api.graphql.user/get_user_following
Modified
avgupta456~github-trends
d23bbb62210057c35f853e8788de6caa32fb514d
update graphql queries
<52>:<add> return RawFollows.parse_obj(output_dict) <del> return UserFollowAPIResponse.parse_obj(output_dict)
# module: backend.external.github_api.graphql.user - def get_user_following( - user_id: str, first: int = 10, after: str = "" - ) -> UserFollowAPIResponse: + def get_user_following(user_id: str, first: int = 10, after: str = "") -> RawFollows: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> following(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> following(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> output_dict = get_template(query)["data"]["user"]["following"] <52> return UserFollowAPIResponse.parse_obj(output_dict) <53>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.user.get_user_following variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ following(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ following(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str) -> List[int]: + """Gets years where the user had activity""" + query = { + "variables": {"login": user_id}, + "query": """ + query getUser($login: String!) { + user(login: $login){ + contributionsCollection{ + contributionYears + } + } + } + """, + } + + years = get_template(query)["data"]["user"]["contributionsCollection"][ + "contributionYears" + ] + + return years + ===========changed ref 1=========== # module: backend.external.github_api.graphql.user - def get_user_followers( - user_id: str, first: int = 100, after: str = "" - ) -> UserFollowAPIResponse: + def get_user_followers(user_id: str, first: int = 100, after: str = "") -> RawFollows: """gets user's followers and users following'""" variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ followers(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ followers(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) query = { "variables": variables, "query": query_str, } output_dict = get_template(query)["data"]["user"]["followers"] + return RawFollows.parse_obj(output_dict) - return UserFollowAPIResponse.parse_obj(output_dict) ===========changed ref 2=========== # module: backend.external.github_api.graphql.user - def get_user_contribution_commits( - user_id: str, - max_repos: int = 100, - first: int = 100, - after: str = "", - ) -> UserContributionCommitsAPIResponse: - """Runs an individual query, fetching at most 100 days of history""" - query = { - "variables": { - "login": user_id, - "maxRepos": max_repos, - "first": first, - "after": after, - }, - "query": """ - query getUser($login: String!, $maxRepos: Int!, $first: Int!, $after: String!) { - user(login: $login){ - contributionsCollection{ - commitContributionsByRepository(maxRepositories: $maxRepos){ - repository{ - name, - }, - totalCount:contributions(first: 1){ - totalCount - } - contributions(first: $first, after: $after){ - nodes{ - commitCount, - occurredAt, - } - pageInfo{ - hasNextPage, - endCursor - } - } - } - totalCommitContributions, - totalRepositoriesWithContributedCommits, - }, - }, - } - """, - } - - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] - return UserContributionCommitsAPIResponse.parse_obj(output_dict) - ===========changed ref 3=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_calendar( + user_id: str, + start_date: date = date.today() - timedelta(days=365), + end_date: date = date.today(), + ) -> RawCalendar: - def get_user_contribution_calendar(user_id: str) -> UserContributionCalendarAPIResponse: + """Gets contribution calendar for a given time period (max one year)""" + if (end_date - start_date).days > 365: + raise ValueError("date range can be at most 1 year") - """Fetches user contribution calendar and contribution years""" query = { + "variables": { + "login": user_id, - "variables": {"login": user_id}, + "startDate": str(start_date) + "T00:00:00.000Z", + "endDate": str(end_date) + "T00:00:00.000Z", + }, "query": """ + query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ - query getUser($login: String!) { user(login: $login){ + contributionsCollection(from: $startDate, to: $endDate){ - contributionsCollection{ contributionCalendar{ - totalContributions, weeks{ contributionDays{ + date - date, + weekday - weekday, + contributionCount - contributionCount, - contributionLevel, } } + totalContributions - colors, } - contributionYears, } + } - }, } """, } + output = get_template(query)["data"]["user"]["contributionsCollection"][ - output_dict = get_template(query)["data"]["user"]["contributionsCollection"] + "contributionCalendar" + ] + return RawCalendar.parse_obj(output) </s>
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_calendar
Modified
avgupta456~github-trends
964c1d5f67fd077750554d58bfa13c8d6e9173cb
use updated code
<1>:<add> self.assertIsInstance(response, RawCalendar) <2>:<del> # aside from validating APIResponse class, pydantic will validate tree <3>:<del> self.assertIsInstance(response, UserContributionCalendarAPIResponse) <4>:<del>
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): <0> response = get_user_contribution_calendar(user_id="avgupta456") <1> <2> # aside from validating APIResponse class, pydantic will validate tree <3> self.assertIsInstance(response, UserContributionCalendarAPIResponse) <4>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456") + + # aside from validating APIResponse class, pydantic will validate tree + self.assertIsInstance(response, List[int]) +
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_followers
Modified
avgupta456~github-trends
964c1d5f67fd077750554d58bfa13c8d6e9173cb
use updated code
<1>:<add> self.assertIsInstance(response, RawFollows) <del> self.assertIsInstance(response, UserFollowAPIResponse)
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + # TODO: Add more validation here + def test_get_user_followers(self): <0> response = get_user_followers(user_id="avgupta456") <1> self.assertIsInstance(response, UserFollowAPIResponse) <2> <3> response = get_user_followers(user_id="avgupta456", first=1) <4> self.assertLessEqual(len(response.nodes), 1) <5>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + def test_get_user_contribution_events(self): + response = get_user_contribution_events(user_id="avgupta456") + self.assertIsInstance(response, RawEvents) + ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456") + + # aside from validating APIResponse class, pydantic will validate tree + self.assertIsInstance(response, List[int]) + ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): response = get_user_contribution_calendar(user_id="avgupta456") + self.assertIsInstance(response, RawCalendar) - # aside from validating APIResponse class, pydantic will validate tree - self.assertIsInstance(response, UserContributionCalendarAPIResponse) - ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): - def test_get_user_contribution_stats(self): - response = get_user_contribution_stats(user_id="avgupta456") - self.assertIsInstance(response, UserContributionStatsAPIResponse) - - response = get_user_contribution_stats(user_id="avgupta456", max_repos=1) - self.assertLessEqual(len(response.issue_contribs_by_repo), 1) - - response = get_user_contribution_stats(user_id="avgupta456", first=1) - self.assertLessEqual( - len(response.issue_contribs_by_repo[0].contributions.nodes), 1 - ) - ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): - def test_get_user_contribution_commits(self): - response = get_user_contribution_commits(user_id="avgupta456") - self.assertIsInstance(response, UserContributionCommitsAPIResponse) - - response = get_user_contribution_commits(user_id="avgupta456", max_repos=1) - self.assertLessEqual(len(response.commits_by_repo), 1) - - response = get_user_contribution_commits(user_id="avgupta456", first=1) - self.assertLessEqual(len(response.commits_by_repo[0].contributions.nodes), 1) -
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_following
Modified
avgupta456~github-trends
964c1d5f67fd077750554d58bfa13c8d6e9173cb
use updated code
<1>:<add> self.assertIsInstance(response, RawFollows) <del> self.assertIsInstance(response, UserFollowAPIResponse)
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): <0> response = get_user_following(user_id="avgupta456") <1> self.assertIsInstance(response, UserFollowAPIResponse) <2> <3> response = get_user_following(user_id="avgupta456", first=1) <4> self.assertLessEqual(len(response.nodes), 1) <5>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + def test_get_user_contribution_events(self): + response = get_user_contribution_events(user_id="avgupta456") + self.assertIsInstance(response, RawEvents) + ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456") + + # aside from validating APIResponse class, pydantic will validate tree + self.assertIsInstance(response, List[int]) + ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): + # TODO: Add more validation here + def test_get_user_followers(self): response = get_user_followers(user_id="avgupta456") + self.assertIsInstance(response, RawFollows) - self.assertIsInstance(response, UserFollowAPIResponse) response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): response = get_user_contribution_calendar(user_id="avgupta456") + self.assertIsInstance(response, RawCalendar) - # aside from validating APIResponse class, pydantic will validate tree - self.assertIsInstance(response, UserContributionCalendarAPIResponse) - ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): - def test_get_user_contribution_stats(self): - response = get_user_contribution_stats(user_id="avgupta456") - self.assertIsInstance(response, UserContributionStatsAPIResponse) - - response = get_user_contribution_stats(user_id="avgupta456", max_repos=1) - self.assertLessEqual(len(response.issue_contribs_by_repo), 1) - - response = get_user_contribution_stats(user_id="avgupta456", first=1) - self.assertLessEqual( - len(response.issue_contribs_by_repo[0].contributions.nodes), 1 - ) - ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): - def test_get_user_contribution_commits(self): - response = get_user_contribution_commits(user_id="avgupta456") - self.assertIsInstance(response, UserContributionCommitsAPIResponse) - - response = get_user_contribution_commits(user_id="avgupta456", max_repos=1) - self.assertLessEqual(len(response.commits_by_repo), 1) - - response = get_user_contribution_commits(user_id="avgupta456", first=1) - self.assertLessEqual(len(response.commits_by_repo[0].contributions.nodes), 1) -
backend.processing.user.contributions/get_contributions
Modified
avgupta456~github-trends
91408745eebe14d6043109fc22b6a40b03935279
updated logic, typing
<41>:<del> total_stats: Dict[str, int] = { <42>:<del> "contribs_count": 0, <43>:<del> "commits_count": 0, <44>:<del> "issues_count": 0, <45>:<del> "prs_count": 0, <46>:<del> "reviews
# module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), + ) -> UserContributions: - ) -> Any: <0> # get years for contribution calendar <1> years = list( <2> filter( <3> lambda x: start_date.year <= x <= end_date.year, <4> get_user_contribution_years(user_id), <5> ) <6> ) <7> <8> # async get contribution calendars <9> calendars: List[RawCalendar] = gather( <10> funcs=[get_user_contribution_calendar for _ in years], <11> args_dicts=[ <12> { <13> "user_id": user_id, <14> "start_date": max(date(year, 1, 1), start_date), <15> "end_date": min(date(year, 12, 31), end_date), <16> } <17> for year in years <18> ], <19> ) <20> <21> events: List[t] = gather( <22> funcs=[get_user_all_contribution_events for _ in years], <23> args_dicts=[ <24> { <25> "user_id": user_id, <26> "start_date": max(date(year, 1, 1), start_date), <27> "end_date": min(date(year, 12, 31), end_date), <28> } <29> for year in years <30> ], <31> ) <32> <33> # TODO: Supplement with commit times <34> <35> repos = set() <36> for events_year in events: <37> for repo in events_year: <38> repos.add(repo) <39> repos = list(repos) <40> <41> total_stats: Dict[str, int] = { <42> "contribs_count": 0, <43> "commits_count": 0, <44> "issues_count": 0, <45> "prs_count": 0, <46> "reviews</s>
===========below chunk 0=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), + ) -> UserContributions: - ) -> Any: # offset: 1 "repos_count": 0, "other_count": 0, } total: DefaultDict[str, Dict[str, Any]] = defaultdict( lambda: { "weekday": 0, "contribs_count": 0, "commits_count": 0, "issues_count": 0, "prs_count": 0, "reviews_count": 0, "repos_count": 0, "other_count": 0, "commits": [], "issues": [], "prs": [], "reviews": [], "repos": [], "repos_contributed": set(), } ) repo_stats: DefaultDict[str, Dict[str, int]] = defaultdict( lambda: { "contribs_count": 0, "commits_count": 0, "issues_count": 0, "prs_count": 0, "reviews_count": 0, "repos_count": 0, "other_count": 0, } ) repositories: DefaultDict[str, DefaultDict[str, Dict[str, Any]]] = defaultdict( lambda: defaultdict( lambda: { "weekday": 0, "contribs_count": 0, "commits_count": 0, "issues_count": 0, "prs_count": 0, "reviews_count": 0, "repos_count": 0, "other_count": 0, "commits": [], "issues": [], "prs": [], "reviews": [], "repos": [], } ) ) for calendar_year in calendars</s> ===========below chunk 1=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), + ) -> UserContributions: - ) -> Any: # offset: 2 <s>views": [], "repos": [], } ) ) for calendar_year in calendars: for week in calendar_year.weeks: for day in week.contribution_days: total[str(day.date)]["weekday"] = day.weekday total[str(day.date)]["contribs_count"] = day.count total[str(day.date)]["other_count"] = day.count total_stats["contribs_count"] += day.count total_stats["other_count"] += day.count for events_year in events: for repo, repo_events in events_year.items(): for event_type in ["commits", "issues", "prs", "reviews", "repos"]: for event in repo_events[event_type]: datetime_obj = event.occurred_at.astimezone(eastern) date_str = str(datetime_obj.date()) if isinstance(event, RawEventsCommit): total[date_str]["commits_count"] += event.count total_stats["commits_count"] += event.count repositories[repo][date_str]["commits_count"] += event.count repo_stats[repo]["commits_count"] += event.count total[date_str]["other_count"] -= event.count total_stats["other_count"] -= event.count repositories[repo][date_str]["contribs_count"] += event.count repo_stats[repo]["contribs_count"] += event.count else: total[date_str][</s> ===========below chunk 2=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), + ) -> UserContributions: - ) -> Any: # offset: 3 <s>type + "_count"] += 1 total_stats[event_type + "_count"] += 1 repositories[repo][date_str][event_type + "_count"] += 1 repo_stats[repo][event_type + "_count"] += 1 total[date_str][event_type].append(datetime_obj) repositories[repo][date_str][event_type].append(datetime_obj) total[date_str]["other_count"] -= 1 total_stats["other_count"] -= 1 repositories[repo][date_str]["contribs_count"] += 1 repo_stats[repo]["contribs_count"] += 1 total[date_str]["repos_contributed"].add(repo) return { "stats": total_stats, "total": total, "repo_stats": repo_stats, "repos": repositories, } ===========unchanged ref 0=========== at: backend.processing.user.contributions t = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] eastern = timezone("US/Eastern") get_user_all_contribution_events(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today()) -> t at: backend.processing.user.contributions.get_user_all_contribution_events repo_contribs: t = defaultdict( lambda: {"commits": [], "issues": [], "prs": [], "reviews": [], "repos": []} ) at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_years
Modified
avgupta456~github-trends
852755c40b0bba819fc0a7ff654c1b83384f72bd
updated tests
<3>:<add> self.assertIsInstance(response, list) <del> self.assertIsInstance(response, List[int])
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): <0> response = get_user_contribution_years(user_id="avgupta456") <1> <2> # aside from validating APIResponse class, pydantic will validate tree <3> self.assertIsInstance(response, List[int]) <4>
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
77af327230c3874de45695e164c097c98ee02582
fix antipatterns
<13>:<del> else: <14>:<del> raise GraphQlError( <15>:<del> "Invalid status code " <16>:<del> + str(r.status_code) <17>:<del> + ": " <18>:<del> + str(r.json()["message"]) # type: ignore <19>:<del> + " Documentation at " <20>:<del> + str(r.json()["documentation_url"]) # type: ignore <21>:<del> )
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> token = os.getenv("AUTH_TOKEN", "") <2> headers: Dict[str, str] = {"Authorization": "bearer " + token} <3> start = datetime.now() <4> r = s.post( # type: ignore <5> "https://api.github.com/graphql", json=query, headers=headers <6> ) <7> print("GraphQL", datetime.now() - start) <8> if r.status_code == 200: <9> data = r.json() # type: ignore <10> if "errors" in data: <11> raise GraphQlError("GraphQL errors: " + str(data["errors"])) <12> return data <13> else: <14> raise GraphQlError( <15> "Invalid status code " <16> + str(r.status_code) <17> + ": " <18> + str(r.json()["message"]) # type: ignore <19> + " Documentation at " <20> + str(r.json()["documentation_url"]) # type: ignore <21> ) <22>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() GraphQlError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.processing.user.contributions/get_contributions
Modified
avgupta456~github-trends
77af327230c3874de45695e164c097c98ee02582
fix antipatterns
# module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: <0> # get years for contribution calendar <1> years = list( <2> filter( <3> lambda x: start_date.year <= x <= end_date.year, <4> get_user_contribution_years(user_id), <5> ) <6> ) <7> <8> # async get contribution calendars <9> calendars: List[RawCalendar] = gather( <10> funcs=[get_user_contribution_calendar for _ in years], <11> args_dicts=[ <12> { <13> "user_id": user_id, <14> "start_date": max(date(year, 1, 1), start_date), <15> "end_date": min(date(year, 12, 31), end_date), <16> } <17> for year in years <18> ], <19> ) <20> <21> events: List[t] = gather( <22> funcs=[get_user_all_contribution_events for _ in years], <23> args_dicts=[ <24> { <25> "user_id": user_id, <26> "start_date": max(date(year, 1, 1), start_date), <27> "end_date": min(date(year, 12, 31), end_date), <28> } <29> for year in years <30> ], <31> ) <32> <33> # TODO: Supplement with commit times <34> <35> repos = set() <36> for events_year in events: <37> for repo in events_year: <38> repos.add(repo) <39> repos = list(repos) <40> <41> def get_stats(): <42> return { <43> "contribs_count": 0, <44> "commits_count": 0, <45> "issues_count": 0, <46> "prs_count": 0, <47> "reviews_count": 0, <48> "</s>
===========below chunk 0=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: # offset: 1 "other_count": 0, } def get_lists(): return { "commits": [], "issues": [], "prs": [], "reviews": [], "repos": [], } total_stats: Dict[str, int] = get_stats() total: DefaultDict[str, Dict[str, Any]] = defaultdict( lambda: {"date": "", "weekday": 0, "stats": get_stats(), "lists": get_lists()} ) repo_stats: DefaultDict[str, Dict[str, int]] = defaultdict(lambda: get_stats()) repositories: DefaultDict[str, DefaultDict[str, Dict[str, Any]]] = defaultdict( lambda: defaultdict( lambda: { "date": "", "weekday": 0, "stats": get_stats(), "lists": get_lists(), } ) ) for calendar_year in calendars: for week in calendar_year.weeks: for day in week.contribution_days: total[str(day.date)]["date"] = day.date total[str(day.date)]["weekday"] = day.weekday total[str(day.date)]["stats"]["contribs_count"] = day.count total[str(day.date)]["stats"]["other_count"] = day.count total_stats["contribs_count"] += day.count total_stats["other_count"] += day.count for events_year in events: for repo, repo_events in events_year.items(): for event_type in ["commits", "issues", "prs", "reviews", "repos"]: for event in repo_events[</s> ===========below chunk 1=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: # offset: 2 <s>_type in ["commits", "issues", "prs", "reviews", "repos"]: for event in repo_events[event_type]: datetime_obj = event.occurred_at.astimezone(eastern) date_str = str(datetime_obj.date()) if isinstance(event, RawEventsCommit): total[date_str]["stats"]["commits_count"] += event.count total_stats["commits_count"] += event.count repositories[repo][date_str]["stats"][ "commits_count" ] += event.count repo_stats[repo]["commits_count"] += event.count total[date_str]["stats"]["other_count"] -= event.count total_stats["other_count"] -= event.count repositories[repo][date_str]["stats"][ "contribs_count" ] += event.count repo_stats[repo]["contribs_count"] += event.count else: total[date_str]["stats"][event_type + "_count"] += 1 total_stats[event_type + "_count"] += 1 repositories[repo][date_str]["stats"][ event_type + "_count" ] += 1 repo_stats[repo][event_type + "_count"] += 1 total[date_str]["lists"][event_type].append(datetime_obj) repositories[repo][date_str]["lists"][event_type].append( datetime_obj ) total[date_str]["stats"]["other_count"] -= 1 total_stats["other_count"] -= 1 </s> ===========below chunk 2=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: # offset: 3 <s>[repo][date_str]["stats"]["contribs_count"] += 1 repo_stats[repo]["contribs_count"] += 1 repositories[repo][date_str]["date"] = datetime_obj.date() total_list = list(total.values()) repositories_list = { name: list(repo.values()) for name, repo in repositories.items() } output = UserContributions.parse_obj( { "total_stats": total_stats, "total": total_list, "repo_stats": repo_stats, "repos": repositories_list, } ) return output ===========unchanged ref 0=========== at: backend.processing.user.contributions t = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] eastern = timezone("US/Eastern") get_user_all_contribution_events(user_id: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today()) -> t at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ date() -> _date astimezone(tz: Optional[_tzinfo]=...) -> datetime __radd__ = __add__ at: external.github_api.graphql.user get_user_contribution_years(user_id: str) -> List[int]
backend.external.github_api.rest.template/get_template
Modified
avgupta456~github-trends
77af327230c3874de45695e164c097c98ee02582
fix antipatterns
<8>:<del> else: <9>:<del> raise RESTError( <10>:<del> "Invalid status code " <11>:<del> + str(r.status_code) <12>:<del> + ": " <13>:<del> + str(r.json()["message"]) # type: ignore <14>:<del> + " Documentation at " <15>:<del> + str(r.json()["documentation_url"]) # type: ignore <16>:<del> )
# module: backend.external.github_api.rest.template def get_template( query: str, plural: bool = False, per_page: int = 100, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: <0> """Template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> headers: Dict[str, str] = {"Accept": str(accept_header)} <3> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {} <4> r = s.get(query, params=params, headers=headers) # type: ignore <5> if r.status_code == 200: <6> print("REST API", datetime.now() - start) <7> return r.json() # type: ignore <8> else: <9> raise RESTError( <10> "Invalid status code " <11> + str(r.status_code) <12> + ": " <13> + str(r.json()["message"]) # type: ignore <14> + " Documentation at " <15> + str(r.json()["documentation_url"]) # type: ignore <16> ) <17>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() RESTError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} start = datetime.now() r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: raise GraphQlError("GraphQL errors: " + str(data["errors"])) return data - else: - raise GraphQlError( - "Invalid status code " - + str(r.status_code) - + ": " - + str(r.json()["message"]) # type: ignore - + " Documentation at " - + str(r.json()["documentation_url"]) # type: ignore - ) ===========changed ref 1=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: # get years for contribution calendar years = list( filter( lambda x: start_date.year <= x <= end_date.year, get_user_contribution_years(user_id), ) ) # async get contribution calendars calendars: List[RawCalendar] = gather( funcs=[get_user_contribution_calendar for _ in years], args_dicts=[ { "user_id": user_id, "start_date": max(date(year, 1, 1), start_date), "end_date": min(date(year, 12, 31), end_date), } for year in years ], ) events: List[t] = gather( funcs=[get_user_all_contribution_events for _ in years], args_dicts=[ { "user_id": user_id, "start_date": max(date(year, 1, 1), start_date), "end_date": min(date(year, 12, 31), end_date), } for year in years ], ) # TODO: Supplement with commit times repos = set() for events_year in events: for repo in events_year: repos.add(repo) repos = list(repos) def get_stats(): return { "contribs_count": 0, "commits_count": 0, "issues_count": 0, "prs_count": 0, "reviews_count": 0, "repos_count": 0, "other_count": 0, } def get_lists(): return { "commits": [], "issues": [], "prs</s> ===========changed ref 2=========== # module: backend.processing.user.contributions def get_contributions( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), ) -> UserContributions: # offset: 1 <s> def get_lists(): return { "commits": [], "issues": [], "prs": [], "reviews": [], "repos": [], } total_stats: Dict[str, int] = get_stats() total: DefaultDict[str, Dict[str, Any]] = defaultdict( lambda: {"date": "", "weekday": 0, "stats": get_stats(), "lists": get_lists()} ) + repo_stats: DefaultDict[str, Dict[str, int]] = defaultdict(get_stats) - repo_stats: DefaultDict[str, Dict[str, int]] = defaultdict(lambda: get_stats()) repositories: DefaultDict[str, DefaultDict[str, Dict[str, Any]]] = defaultdict( lambda: defaultdict( lambda: { "date": "", "weekday": 0, "stats": get_stats(), "lists": get_lists(), } ) ) for calendar_year in calendars: for week in calendar_year.weeks: for day in week.contribution_days: total[str(day.date)]["date"] = day.date total[str(day.date)]["weekday"] = day.weekday total[str(day.date)]["stats"]["contribs_count"] = day.count total[str(day.date)]["stats"]["other_count"] = day.count total_stats["contribs_count"] += day.count total_stats["other_count"] += day.count for events_year in events: </s>
backend.external.github_api.graphql.user/get_user_contribution_events
Modified
avgupta456~github-trends
756f1faf5f7ec08a6b0d8c3b7e87b65f25822c88
get owner name
<18>:<add> nameWithOwner, <del> name, <36>:<add> nameWithOwner <del> name
# module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: <0> """Fetches user contributions (commits, issues, prs, reviews)""" <1> if (end_date - start_date).days > 365: <2> raise ValueError("date range can be at most 1 year") <3> query = { <4> "variables": { <5> "login": user_id, <6> "startDate": str(start_date) + "T00:00:00.000Z", <7> "endDate": str(end_date) + "T00:00:00.000Z", <8> "maxRepos": max_repos, <9> "first": first, <10> "after": after, <11> }, <12> "query": """ <13> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { <14> user(login: $login){ <15> contributionsCollection(from: $startDate, to: $endDate){ <16> commitContributionsByRepository(maxRepositories: $maxRepos){ <17> repository{ <18> name, <19> }, <20> totalCount:contributions(first: 1){ <21> totalCount <22> } <23> contributions(first: $first, after: $after){ <24> nodes{ <25> commitCount, <26> occurredAt, <27> } <28> pageInfo{ <29> hasNextPage, <30> endCursor <31> } <32> } <33> } <34> issueContributionsByRepository(maxRepositories: $maxRepos){ <35> repository{ <36> name <37> }, <38> totalCount:contributions(first: 1){ <39> totalCount <40> } <41> contributions(first: $first, after: $after){</s>
===========below chunk 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: # offset: 1 occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ name }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount nodes{ repository{ name, } occurredAt, } }, }, } } """, } output = get_template(query)["data"]["user"]["contributionsCollection"] # print(json.dumps(output, indent=2)) return RawEvents.parse_obj(output) ===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any]
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
756f1faf5f7ec08a6b0d8c3b7e87b65f25822c88
get owner name
<1>:<add> start = datetime.now() <3>:<del> start = datetime.now()
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> token = os.getenv("AUTH_TOKEN", "") <2> headers: Dict[str, str] = {"Authorization": "bearer " + token} <3> start = datetime.now() <4> r = s.post( # type: ignore <5> "https://api.github.com/graphql", json=query, headers=headers <6> ) <7> print("GraphQL", datetime.now() - start) <8> if r.status_code == 200: <9> data = r.json() # type: ignore <10> if "errors" in data: <11> raise GraphQlError("GraphQL errors: " + str(data["errors"])) <12> return data <13> <14> raise GraphQlError( <15> "Invalid status code " <16> + str(r.status_code) <17> + ": " <18> + str(r.json()["message"]) # type: ignore <19> + " Documentation at " <20> + str(r.json()["documentation_url"]) # type: ignore <21> ) <22>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() GraphQlError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.models.user.contribs class RawEventsRepoName(BaseModel): + name: str = Field(alias="nameWithOwner") - name: str ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: """Fetches user contributions (commits, issues, prs, reviews)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": str(start_date) + "T00:00:00.000Z", "endDate": str(end_date) + "T00:00:00.000Z", "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ + nameWithOwner, - name, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } issueContributionsByRepository(maxRepositories: $maxRepos){ repository{ + nameWithOwner - name }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor </s> ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: # offset: 1 <s> $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ + nameWithOwner - name }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ + nameWithOwner - name }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount nodes{ repository{ + nameWithOwner, - name, } occurredAt, } }, }, } } """, } output = get_template(query)["data"]["user"]["contributionsCollection"] - # print(json.dumps(output, indent=2)) return RawEvents.parse_obj(output)
backend.external.github_api.rest.template/get_template
Modified
avgupta456~github-trends
2d2470814a3a1795e59db51f5e80b6ce21247782
rest api authentication
<2>:<add> token = os.getenv("AUTH_TOKEN", "") <add> headers: Dict[str, str] = { <add> "Accept": str(accept_header), <add> "Authorization": "bearer " + token, <add> } <add> params: Dict[str, str] = ( <add> {"per_page": str(per_page), "page": str(page)} if plural else {} <add> ) <del> headers: Dict[str, str] = {"Accept": str(accept_header)} <3>:<del> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {}
# module: backend.external.github_api.rest.template def get_template( query: str, plural: bool = False, per_page: int = 100, + page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: <0> """Template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> headers: Dict[str, str] = {"Accept": str(accept_header)} <3> params: Dict[str, str] = {"per_page": str(per_page)} if plural else {} <4> r = s.get(query, params=params, headers=headers) # type: ignore <5> if r.status_code == 200: <6> print("REST API", datetime.now() - start) <7> return r.json() # type: ignore <8> <9> raise RESTError( <10> "Invalid status code " <11> + str(r.status_code) <12> + ": " <13> + str(r.json()["message"]) # type: ignore <14> + " Documentation at " <15> + str(r.json()["documentation_url"]) # type: ignore <16> ) <17>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.helper.gather/_gather
Modified
avgupta456~github-trends
ba9b44683f17e2d019038ecbc86b36184bc8640b
gather with semaphore
<5>:<add> await gather_with_concurrency( <add> max_threads, <del> await asyncio.gather(
# module: backend.helper.gather def _gather( + funcs: List[Callable[..., Any]], + args_dicts: List[Dict[str, Any]], + max_threads: int = 5, - funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]] ) -> List[Any]: <0> """runs the given functions asynchronously""" <1> <2> async_funcs = [async_function(func) for func in funcs] <3> <4> output: List[Any] = list( <5> await asyncio.gather( <6> *( <7> async_func(**kwargs) <8> for async_func, kwargs in zip(async_funcs, args_dicts) <9> ) <10> ) <11> ) <12> <13> return output <14>
===========changed ref 0=========== # module: backend.helper.gather + def gather_with_concurrency( + n: int, *tasks: List[Callable[..., Any]] + ) -> List[Any]: + semaphore = asyncio.Semaphore(n) + + async def sem_task(task: Callable[..., Any]) -> Any: + async with semaphore: + return await task # type: ignore + + return await asyncio.gather(*(sem_task(task) for task in tasks)) # type: ignore +
backend.helper.gather/gather
Modified
avgupta456~github-trends
ba9b44683f17e2d019038ecbc86b36184bc8640b
gather with semaphore
<2>:<add> return asyncio.run( <add> _gather(funcs=funcs, args_dicts=args_dicts, max_threads=max_threads) <add> ) <del> return asyncio.run(_gather(funcs=funcs, args_dicts=args_dicts))
# module: backend.helper.gather def gather( + funcs: List[Callable[..., Any]], + args_dicts: List[Dict[str, Any]], + max_threads: int = 5, - funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]] ) -> List[Any]: <0> """runs the given functions asynchronously""" <1> <2> return asyncio.run(_gather(funcs=funcs, args_dicts=args_dicts)) <3>
===========changed ref 0=========== # module: backend.helper.gather + def gather_with_concurrency( + n: int, *tasks: List[Callable[..., Any]] + ) -> List[Any]: + semaphore = asyncio.Semaphore(n) + + async def sem_task(task: Callable[..., Any]) -> Any: + async with semaphore: + return await task # type: ignore + + return await asyncio.gather(*(sem_task(task) for task in tasks)) # type: ignore + ===========changed ref 1=========== # module: backend.helper.gather def _gather( + funcs: List[Callable[..., Any]], + args_dicts: List[Dict[str, Any]], + max_threads: int = 5, - funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]] ) -> List[Any]: """runs the given functions asynchronously""" async_funcs = [async_function(func) for func in funcs] output: List[Any] = list( + await gather_with_concurrency( + max_threads, - await asyncio.gather( *( async_func(**kwargs) for async_func, kwargs in zip(async_funcs, args_dicts) ) ) ) return output
backend.external.github_api.graphql.user/get_user_contribution_calendar
Modified
avgupta456~github-trends
036866c9a7424753bde5ec53a6303bc396b653f4
use datetime instead of date
<6>:<add> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <add> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <del> "startDate": str(start_date) + "T00:00:00.000Z", <7>:<del> "endDate": str(end_date) + "T00:00:00.000Z",
# module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + start_date: datetime = datetime.now() - timedelta(days=365), - start_date: date = date.today() - timedelta(days=365), + end_date: datetime = datetime.now(), - end_date: date = date.today(), ) -> RawCalendar: <0> """Gets contribution calendar for a given time period (max one year)""" <1> if (end_date - start_date).days > 365: <2> raise ValueError("date range can be at most 1 year") <3> query = { <4> "variables": { <5> "login": user_id, <6> "startDate": str(start_date) + "T00:00:00.000Z", <7> "endDate": str(end_date) + "T00:00:00.000Z", <8> }, <9> "query": """ <10> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ <11> user(login: $login){ <12> contributionsCollection(from: $startDate, to: $endDate){ <13> contributionCalendar{ <14> weeks{ <15> contributionDays{ <16> date <17> weekday <18> contributionCount <19> } <20> } <21> totalContributions <22> } <23> } <24> } <25> } <26> """, <27> } <28> <29> output = get_template(query)["data"]["user"]["contributionsCollection"][ <30> "contributionCalendar" <31> ] <32> return RawCalendar.parse_obj(output) <33>
===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) datetime() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' strftime(fmt: _Text) -> str __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any]
backend.external.github_api.graphql.user/get_user_contribution_events
Modified
avgupta456~github-trends
036866c9a7424753bde5ec53a6303bc396b653f4
use datetime instead of date
<6>:<add> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <add> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <del> "startDate": str(start_date) + "T00:00:00.000Z", <7>:<del> "endDate": str(end_date) + "T00:00:00.000Z",
<s> backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + start_date: datetime = datetime.now() - timedelta(365), - start_date: date = date.today() - timedelta(365), + end_date: datetime = datetime.now(), - end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: <0> """Fetches user contributions (commits, issues, prs, reviews)""" <1> if (end_date - start_date).days > 365: <2> raise ValueError("date range can be at most 1 year") <3> query = { <4> "variables": { <5> "login": user_id, <6> "startDate": str(start_date) + "T00:00:00.000Z", <7> "endDate": str(end_date) + "T00:00:00.000Z", <8> "maxRepos": max_repos, <9> "first": first, <10> "after": after, <11> }, <12> "query": """ <13> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { <14> user(login: $login){ <15> contributionsCollection(from: $startDate, to: $endDate){ <16> commitContributionsByRepository(maxRepositories: $maxRepos){ <17> repository{ <18> nameWithOwner, <19> }, <20> totalCount:contributions(first: 1){ <21> totalCount <22> } <23> contributions(first: $first, after: $after){ <24> nodes{ <25> commitCount, <26> occurredAt, <27> } <28> pageInfo{ <29> hasNextPage, <30> endCursor <31> } <32> } <33> } <34> issueContributionsByRepository(maxRepositories: $maxRepos){ <35> repository{ <36> nameWithOwner <37> },</s>
===========below chunk 0=========== <s>_api.graphql.user def get_user_contribution_events( user_id: str, + start_date: datetime = datetime.now() - timedelta(365), - start_date: date = date.today() - timedelta(365), + end_date: datetime = datetime.now(), - end_date: date = date.today(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: # offset: 1 totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount nodes{ repository{ nameWithOwner, } occurredAt, } }, }, } } """, } output = get_template(query)["data"]["user"]["contributionsCollection"] return RawEvents.parse_obj(output) ===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) datetime() at: datetime.date strftime(fmt: _Text) -> str at: datetime.datetime now(tz: Optional[_tzinfo]=...) -> _S at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + start_date: datetime = datetime.now() - timedelta(days=365), - start_date: date = date.today() - timedelta(days=365), + end_date: datetime = datetime.now(), - end_date: date = date.today(), ) -> RawCalendar: """Gets contribution calendar for a given time period (max one year)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, + "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), + "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), - "startDate": str(start_date) + "T00:00:00.000Z", - "endDate": str(end_date) + "T00:00:00.000Z", }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ contributionCalendar{ weeks{ contributionDays{ date weekday contributionCount } } totalContributions } } } } """, } output = get_template(query)["data"]["user"]["contributionsCollection"][ "contributionCalendar" ] return RawCalendar.parse_obj(output)
backend.endpoints.user/main
Modified
avgupta456~github-trends
3e117ff86636903fa240a9e306f3e377152e81d9
add contribs_per_repo_per_day
<2>:<add> [contribs_per_day, contribs_per_repo_per_day] = gather( <add> funcs=[get_contribs_per_day, get_contribs_per_repo_per_day], <add> args_dicts=[{"data": data} for _ in range(2)], <add> ) <del> contribs_per_day = get_contribs_per_day(data) <4>:<add> return { <add> "contribs_per_day": contribs_per_day, <del> return {"contribs_per_day": contribs_per_day} <5>:<add> "contribs_per_repo_per_day": contribs_per_repo_per_day, <add> }
# module: backend.endpoints.user def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Any: <0> data = get_data(user_id, start_date, end_date, timezone_str) <1> <2> contribs_per_day = get_contribs_per_day(data) <3> <4> return {"contribs_per_day": contribs_per_day} <5>
===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any]
backend.processing.user.contributions/get_all_commit_times
Modified
avgupta456~github-trends
4b50f6fa693d35ddf606aefebcda14fc1012d00e
fix some typing
<2>:<add> data: List[Any] = [] <add> index = 0 <del> data, index = [], 0
# module: backend.processing.user.contributions def get_all_commit_times( user_id: str, name_with_owner: str, start_date: datetime = datetime.now(), end_date: datetime = datetime.now(), ) -> List[datetime]: <0> """Gets all user's commit times for a given repository""" <1> owner, repo = name_with_owner.split("/") <2> data, index = [], 0 <3> while (index == 0 or (index > 0 and len(data) % 100 == 0)) and index < 10: <4> data.extend( <5> get_repo_commits( <6> owner=owner, <7> repo=repo, <8> user=user_id, <9> since=start_date, <10> until=end_date, <11> page=index + 1, <12> ) <13> ) <14> index += 1 <15> <16> data = list( <17> map( <18> lambda x: datetime.strptime( <19> x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" <20> ), <21> data, <22> ) <23> ) <24> <25> # sort ascending <26> data = sorted(data) <27> return data <28>
===========unchanged ref 0=========== at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S strptime(date_string: _Text, format: _Text) -> datetime __radd__ = __add__ at: external.github_api.rest.repo get_repo_commits(owner: str, repo: str, user: Optional[str], since: Optional[datetime], until: Optional[datetime], page: int=1) -> Dict[str, Any] at: typing List = _alias(list, 1, inst=False, name='List')
backend.analytics.user.contribs_per_day/get_contribs_per_day
Modified
avgupta456~github-trends
ff20b462a51f6219ae6d1249f1bf84a26222eafc
misc fixes
<1>:<del> <2>:<del> print(contribs_per_day) <3>:<del>
# module: backend.analytics.user.contribs_per_day def get_contribs_per_day(data: UserPackage) -> Dict[date, int]: <0> contribs_per_day = {x.date: x.stats.contribs_count for x in data.contribs.total} <1> <2> print(contribs_per_day) <3> <4> return contribs_per_day <5>
===========unchanged ref 0=========== at: datetime date() at: models.user.contribs.ContributionDay date: date weekday: int stats: ContributionStats lists: ContributionLists at: models.user.contribs.ContributionStats contribs_count: int commits_count: int issues_count: int prs_count: int reviews_count: int repos_count: int other_count: int at: models.user.contribs.UserContributions total_stats: ContributionStats total: List[ContributionDay] repo_stats: Dict[str, ContributionStats] repos: Dict[str, List[ContributionDay]] at: models.user.package.UserPackage contribs: UserContributions follows: UserFollows at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
77aa959055dfb1cb402dc93a89d96e3a71df455e
improve github api query
<4>:<add> # print(query, headers) <7>:<add> # print(r.status_code) <14>:<add> try: <add> raise GraphQlError( <del> raise GraphQlError( <15>:<add> "Invalid status code " <del> "Invalid status code " <16>:<add> + str(r.status_code) <del> + str(r.status_code) <17>:<add> + ": " <del> + ": " <18>:<add> + str(r.json()["message"]) # type: ignore <del> + str(r.json()["message"]) # type: ignore <19>:<add> + " Documentation at " <del> + " Documentation at " <20>:<add> + str(r.json()["documentation_url"]) # type: ignore <del> + str(r.json()["documentation_url"]) # type: ignore <21>:<add> ) <add> except Exception: <add> raise GraphQlError("Unknown Error") <del> )
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = {"Authorization": "bearer " + token} <4> r = s.post( # type: ignore <5> "https://api.github.com/graphql", json=query, headers=headers <6> ) <7> print("GraphQL", datetime.now() - start) <8> if r.status_code == 200: <9> data = r.json() # type: ignore <10> if "errors" in data: <11> raise GraphQlError("GraphQL errors: " + str(data["errors"])) <12> return data <13> <14> raise GraphQlError( <15> "Invalid status code " <16> + str(r.status_code) <17> + ": " <18> + str(r.json()["message"]) # type: ignore <19> + " Documentation at " <20> + str(r.json()["documentation_url"]) # type: ignore <21> ) <22>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() GraphQlError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.external.github_api.graphql.commit/get_commits
Modified
avgupta456~github-trends
77aa959055dfb1cb402dc93a89d96e3a71df455e
improve github api query
<11>:<add> languages(first: 5, orderBy: {field:SIZE, direction:DESC}){ <del> languages(first: 10, orderBy: {field:SIZE, direction:DESC}){ <12>:<del> totalSize
# module: backend.external.github_api.graphql.commit def get_commits(node_ids: List[str]) -> Union[Dict[str, Any], List[Any]]: <0> """gets all repository data from graphql""" <1> query = { <2> "variables": {"ids": node_ids}, <3> "query": """ <4> query getCommits($ids: [ID!]!) { <5> nodes(ids: $ids) { <6> ... on Commit { <7> additions <8> deletions <9> changedFiles <10> repository{ <11> languages(first: 10, orderBy: {field:SIZE, direction:DESC}){ <12> totalSize <13> edges{ <14> size <15> node{ <16> name <17> } <18> } <19> } <20> } <21> } <22> } <23> } <24> """, <25> } <26> <27> return get_template(query) <28>
===========unchanged ref 0=========== at: external.github_api.graphql.template get_template(query: Dict[str, Any]) -> Dict[str, Any] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} + # print(query, headers) r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) + # print(r.status_code) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: raise GraphQlError("GraphQL errors: " + str(data["errors"])) return data + try: + raise GraphQlError( - raise GraphQlError( + "Invalid status code " - "Invalid status code " + + str(r.status_code) - + str(r.status_code) + + ": " - + ": " + + str(r.json()["message"]) # type: ignore - + str(r.json()["message"]) # type: ignore + + " Documentation at " - + " Documentation at " + + str(r.json()["documentation_url"]) # type: ignore - + str(r.json()["documentation_url"]) # type: ignore + ) + except Exception: + raise GraphQlError("Unknown Error") - )
backend.external.github_api.rest.template/get_template
Modified
avgupta456~github-trends
77aa959055dfb1cb402dc93a89d96e3a71df455e
improve github api query
<10>:<add> # print(query, params, headers) <14>:<add> # print(r.status_code) <15>:<add> try: <add> raise RESTError( <del> raise RESTError( <16>:<add> "Invalid status code " <del> "Invalid status code " <17>:<add> + str(r.status_code) <del> + str(r.status_code) <18>:<add> + ": " <del> + ": " <19>:<add> + str(r.json()["message"]) # type: ignore <del> + str(r.json()["message"]) # type: ignore <20>:<add> + " Documentation at " <del> + " Documentation at " <21>:<add> + str(r.json()["documentation_url"]) # type: ignore <del> + str(r.json()["documentation_url"]) # type: ignore <22>:<add> ) <add> except Exception: <add> raise RESTError("Unknown Error") <del> )
# module: backend.external.github_api.rest.template def get_template( query: str, plural: bool = False, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: <0> """Template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = { <4> "Accept": str(accept_header), <5> "Authorization": "bearer " + token, <6> } <7> params: Dict[str, str] = ( <8> {"per_page": str(per_page), "page": str(page)} if plural else {} <9> ) <10> r = s.get(query, params=params, headers=headers) # type: ignore <11> if r.status_code == 200: <12> print("REST API", datetime.now() - start) <13> return r.json() # type: ignore <14> <15> raise RESTError( <16> "Invalid status code " <17> + str(r.status_code) <18> + ": " <19> + str(r.json()["message"]) # type: ignore <20> + " Documentation at " <21> + str(r.json()["documentation_url"]) # type: ignore <22> ) <23>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() RESTError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.commit def get_commits(node_ids: List[str]) -> Union[Dict[str, Any], List[Any]]: """gets all repository data from graphql""" query = { "variables": {"ids": node_ids}, "query": """ query getCommits($ids: [ID!]!) { nodes(ids: $ids) { ... on Commit { additions deletions changedFiles repository{ + languages(first: 5, orderBy: {field:SIZE, direction:DESC}){ - languages(first: 10, orderBy: {field:SIZE, direction:DESC}){ - totalSize edges{ size node{ name } } } } } } } """, } return get_template(query) ===========changed ref 1=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} + # print(query, headers) r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) + # print(r.status_code) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: raise GraphQlError("GraphQL errors: " + str(data["errors"])) return data + try: + raise GraphQlError( - raise GraphQlError( + "Invalid status code " - "Invalid status code " + + str(r.status_code) - + str(r.status_code) + + ": " - + ": " + + str(r.json()["message"]) # type: ignore - + str(r.json()["message"]) # type: ignore + + " Documentation at " - + " Documentation at " + + str(r.json()["documentation_url"]) # type: ignore - + str(r.json()["documentation_url"]) # type: ignore + ) + except Exception: + raise GraphQlError("Unknown Error") - )
backend.processing.commit/get_commits_languages
Modified
avgupta456~github-trends
ee5b1cf0605d191816ef07e5c59b0956e1f52b4f
add language stats to user package
<3>:<add> # TODO: handle exception to get_commits <add> # ideally would alert users somehow that data is incomplete <add> try: <del> # suppress pylance error <4>:<del> data: List[Dict[str, Any]] = get_commits( <5>:<add> raw_data = get_commits(node_ids[i : min(len(node_ids), i + 100)]) <del> node_ids[i : min(len(node_ids), i + 100)] <6>:<del> )[ <7>:<del> "data" <8>:<del> ][ # type: ignore <9>:<del> "nodes" <10>:<del> ] # type: ignore <11>:<add> data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore <add> all_data.extend(data) <del> all_data.extend(data) <12>:<add> except Exception: <add> print("Commit Exception") <16>:<add> languages = [ <add> x <add> for x in commit["repository"]["languages"]["edges"] <del> languages = commit["repository"]["languages"]["edges"] <17>:<add> if x["node"]["name"] not in blacklist <add> ] <23>:<del> out[-1][lang_name] = {} # type: ignore <24>:<add> additions = round( <del> out[-1][lang_name]["additions"] = round( <27>:<add> deletions = round( <del> out[-1][lang_name]["deletions"] = round( <30>:<add> if additions > 0 or deletions > 0: <add> out[-1][lang_name] = { <add> "additions": additions, <add>
# module: backend.processing.commit def get_commits_languages( node_ids: List[str], cutoff: int = 1000 ) -> List[Dict[str, Dict[str, int]]]: <0> out: List[Dict[str, Dict[str, int]]] = [] <1> all_data: List[Dict[str, Any]] = [] <2> for i in range(0, len(node_ids), 100): <3> # suppress pylance error <4> data: List[Dict[str, Any]] = get_commits( <5> node_ids[i : min(len(node_ids), i + 100)] <6> )[ <7> "data" <8> ][ # type: ignore <9> "nodes" <10> ] # type: ignore <11> all_data.extend(data) <12> <13> for commit in all_data: <14> out.append({}) <15> if commit["additions"] + commit["deletions"] < cutoff: <16> languages = commit["repository"]["languages"]["edges"] <17> num_langs = min(len(languages), commit["changedFiles"]) <18> total_repo_size = sum( <19> [language["size"] for language in languages[:num_langs]] <20> ) <21> for language in languages[:num_langs]: <22> lang_name = language["node"]["name"] <23> out[-1][lang_name] = {} # type: ignore <24> out[-1][lang_name]["additions"] = round( <25> commit["additions"] * language["size"] / total_repo_size <26> ) <27> out[-1][lang_name]["deletions"] = round( <28> commit["deletions"] * language["size"] / total_repo_size <29> ) <30> <31> return out <32>
===========unchanged ref 0=========== at: external.github_api.graphql.commit get_commits(node_ids: List[str]) -> Union[Dict[str, Any], List[Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.models.user.contribs + class CommitContribution(BaseModel): + timestamp: datetime + languages: Dict[str, Dict[str, int]] + ===========changed ref 1=========== # module: backend.models.user.contribs class ContributionLists(BaseModel): + commits: List[CommitContribution] - commits: List[datetime] issues: List[datetime] prs: List[datetime] reviews: List[datetime] repos: List[datetime] ===========changed ref 2=========== # module: backend.models.user.contribs class ContributionStats(BaseModel): contribs_count: int commits_count: int issues_count: int prs_count: int reviews_count: int repos_count: int other_count: int + languages: Dict[str, Dict[str, int]]
backend.endpoints.user/main
Modified
avgupta456~github-trends
8088b0226307701858674c83107b7b524d350fd2
for debugging
<8>:<add> "raw": data,
# module: backend.endpoints.user def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Dict[str, Any]: <0> data = get_data(user_id, start_date, end_date, timezone_str) <1> <2> [contribs_per_day, contribs_per_repo_per_day] = gather( <3> funcs=[get_contribs_per_day, get_contribs_per_repo_per_day], <4> args_dicts=[{"data": data} for _ in range(2)], <5> ) <6> <7> return { <8> "contribs_per_day": contribs_per_day, <9> "contribs_per_repo_per_day": contribs_per_repo_per_day, <10> } <11>
===========unchanged ref 0=========== at: analytics.user.contribs_per_day get_contribs_per_day(data: UserPackage) -> Dict[date, int] get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[date, int]] at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.external.github_api.rest.repo/get_repo_languages
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<1>:<add> return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") <del> return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True)
# module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns repository language breakdown""" <1> return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True) <2>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: external.github_api.rest.template get_template(query: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any]
backend.external.github_api.rest.repo/get_repo_stargazers
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<1>:<add> return get_template_plural( <del> return get_template( <3>:<del> plural=True,
# module: backend.external.github_api.rest.repo + def get_repo_stargazers( + owner: str, repo: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_repo_stargazers(owner: str, repo: str, per_page: int = 100) -> Dict[str, Any]: <0> """Returns stargazers with timestamp for repository""" <1> return get_template( <2> BASE_URL + owner + "/" + repo + "/stargazers", <3> plural=True, <4> per_page=per_page, <5> accept_header="applicaiton/vnd.github.v3.star+json", <6> ) <7>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: external.github_api.rest.template get_template_plural(query: str, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: """Returns repository language breakdown""" + return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") - return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True)
backend.external.github_api.rest.repo/get_repo_commits
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<7>:<add> try: <add> return get_template_plural(query, page=page) <del> return get_template(query, page=page, plural=True) <8>:<add> except RESTError409: <add> return []
# module: backend.external.github_api.rest.repo def get_repo_commits( owner: str, repo: str, user: Optional[str] = None, since: Optional[datetime] = None, until: Optional[datetime] = None, page: int = 1, + ) -> List[Dict[str, Any]]: - ) -> Dict[str, Any]: <0> """Returns most recent commits including commit message""" <1> user = user if user is not None else owner <2> query = BASE_URL + owner + "/" + repo + "/commits?author=" + user <3> if since is not None: <4> query += "&since=" + str(since) <5> if until is not None: <6> query += "&until=" + str(until) <7> return get_template(query, page=page, plural=True) <8>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: datetime datetime() at: external.github_api.rest.template get_template(query: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: """Returns repository language breakdown""" + return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") - return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_stargazers( + owner: str, repo: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_repo_stargazers(owner: str, repo: str, per_page: int = 100) -> Dict[str, Any]: """Returns stargazers with timestamp for repository""" + return get_template_plural( - return get_template( BASE_URL + owner + "/" + repo + "/stargazers", - plural=True, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", )
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<4>:<del> # print(query, headers) <8>:<del> # print(r.status_code) <13>:<add> raise GraphQlError("GraphQL Error: " + str(data["errors"])) <del> raise GraphQlError("GraphQL errors: " + str(data["errors"])) <16>:<del> try: <17>:<del> raise GraphQlError( <18>:<del> "Invalid status code " <19>:<del> + str(r.status_code) <20>:<del> + ": " <21>:<del> + str(r.json()["message"]) # type: ignore <22>:<del> + " Documentation at " <23>:<del> + str(r.json()["documentation_url"]) # type: ignore <24>:<del> ) <25>:<del> except Exception: <26>:<del> raise GraphQlError("Unknown Error") <27>:<add> raise GraphQlError("GraphQL Error" + str(r.status_code))
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = {"Authorization": "bearer " + token} <4> # print(query, headers) <5> r = s.post( # type: ignore <6> "https://api.github.com/graphql", json=query, headers=headers <7> ) <8> # print(r.status_code) <9> print("GraphQL", datetime.now() - start) <10> if r.status_code == 200: <11> data = r.json() # type: ignore <12> if "errors" in data: <13> raise GraphQlError("GraphQL errors: " + str(data["errors"])) <14> return data <15> <16> try: <17> raise GraphQlError( <18> "Invalid status code " <19> + str(r.status_code) <20> + ": " <21> + str(r.json()["message"]) # type: ignore <22> + " Documentation at " <23> + str(r.json()["documentation_url"]) # type: ignore <24> ) <25> except Exception: <26> raise GraphQlError("Unknown Error") <27>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() GraphQlError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: """Returns repository language breakdown""" + return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") - return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_stargazers( + owner: str, repo: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_repo_stargazers(owner: str, repo: str, per_page: int = 100) -> Dict[str, Any]: """Returns stargazers with timestamp for repository""" + return get_template_plural( - return get_template( BASE_URL + owner + "/" + repo + "/stargazers", - plural=True, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo def get_repo_commits( owner: str, repo: str, user: Optional[str] = None, since: Optional[datetime] = None, until: Optional[datetime] = None, page: int = 1, + ) -> List[Dict[str, Any]]: - ) -> Dict[str, Any]: """Returns most recent commits including commit message""" user = user if user is not None else owner query = BASE_URL + owner + "/" + repo + "/commits?author=" + user if since is not None: query += "&since=" + str(since) if until is not None: query += "&until=" + str(until) + try: + return get_template_plural(query, page=page) - return get_template(query, page=page, plural=True) + except RESTError409: + return []
backend.external.github_api.rest.user/get_user_starred_repos
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<1>:<add> return get_template_plural( <del> return get_template( <3>:<del> plural=True,
# module: backend.external.github_api.rest.user + def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> Dict[str, Any]: <0> """Returns list of starred repos""" <1> return get_template( <2> BASE_URL + user_id + "/starred", <3> plural=True, <4> per_page=per_page, <5> accept_header="application/vnd.github.v3.star+json", <6> ) <7>
===========unchanged ref 0=========== at: backend.external.github_api.rest.user BASE_URL = "https://api.github.com/users/" at: external.github_api.rest.template get_template_plural(query: str, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: """Returns repository language breakdown""" + return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") - return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_stargazers( + owner: str, repo: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_repo_stargazers(owner: str, repo: str, per_page: int = 100) -> Dict[str, Any]: """Returns stargazers with timestamp for repository""" + return get_template_plural( - return get_template( BASE_URL + owner + "/" + repo + "/stargazers", - plural=True, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo def get_repo_commits( owner: str, repo: str, user: Optional[str] = None, since: Optional[datetime] = None, until: Optional[datetime] = None, page: int = 1, + ) -> List[Dict[str, Any]]: - ) -> Dict[str, Any]: """Returns most recent commits including commit message""" user = user if user is not None else owner query = BASE_URL + owner + "/" + repo + "/commits?author=" + user if since is not None: query += "&since=" + str(since) if until is not None: query += "&until=" + str(until) + try: + return get_template_plural(query, page=page) - return get_template(query, page=page, plural=True) + except RESTError409: + return [] ===========changed ref 3=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} - # print(query, headers) r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) - # print(r.status_code) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: + raise GraphQlError("GraphQL Error: " + str(data["errors"])) - raise GraphQlError("GraphQL errors: " + str(data["errors"])) return data - try: - raise GraphQlError( - "Invalid status code " - + str(r.status_code) - + ": " - + str(r.json()["message"]) # type: ignore - + " Documentation at " - + str(r.json()["documentation_url"]) # type: ignore - ) - except Exception: - raise GraphQlError("Unknown Error") + raise GraphQlError("GraphQL Error" + str(r.status_code))
backend.external.github_api.rest.template/get_template
Modified
avgupta456~github-trends
ad6c5abe2f30aaabc23ec7a6646daf3436522c45
improved error handling github api
<0>:<add> """Template for interacting with the GitHub REST API (singular)""" <del> """Template for interacting with the GitHub REST API""" <1>:<del> start = datetime.now() <2>:<del> token = os.getenv("AUTH_TOKEN", "") <3>:<del> headers: Dict[str, str] = { <4>:<del> "Accept": str(accept_header), <5>:<del> "Authorization": "bearer " + token, <6>:<del> } <7>:<del> params: Dict[str, str] = ( <8>:<del> {"per_page": str(per_page), "page": str(page)} if plural else {} <9>:<del> ) <10>:<del> # print(query, params, headers) <11>:<del> r = s.get(query, params=params, headers=headers) # type: ignore <12>:<del> if r.status_code == 200: <13>:<del> print("REST API", datetime.now() - start) <14>:<del> return r.json() # type: ignore <15>:<del> # print(r.status_code) <18>:<del> raise RESTError( <19>:<del> "Invalid status code " <20>:<del> + str(r.status_code) <21>:<del> + ": " <22>:<del> + str(r.json()["message"]) # type: ignore <23>:<del> + " Documentation at " <24>:<del> + str(r.json()["documentation_url"]) # type: ignore <25>:<del> ) <26>:<add> return _get_template(query, {}, accept_header) <add> except Exception as e: <del> except Exception: <27>:<add> raise e <del> raise RESTError("Unknown Error")
# module: backend.external.github_api.rest.template def get_template( query: str, - plural: bool = False, - per_page: int = 100, - page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: <0> """Template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = { <4> "Accept": str(accept_header), <5> "Authorization": "bearer " + token, <6> } <7> params: Dict[str, str] = ( <8> {"per_page": str(per_page), "page": str(page)} if plural else {} <9> ) <10> # print(query, params, headers) <11> r = s.get(query, params=params, headers=headers) # type: ignore <12> if r.status_code == 200: <13> print("REST API", datetime.now() - start) <14> return r.json() # type: ignore <15> # print(r.status_code) <16> <17> try: <18> raise RESTError( <19> "Invalid status code " <20> + str(r.status_code) <21> + ": " <22> + str(r.json()["message"]) # type: ignore <23> + " Documentation at " <24> + str(r.json()["documentation_url"]) # type: ignore <25> ) <26> except Exception: <27> raise RESTError("Unknown Error") <28>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() RESTError409(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.template + class RESTError409(Exception): + pass + ===========changed ref 1=========== # module: backend.external.github_api.rest.template + def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: + """Internal template for interacting with the GitHub REST API""" + start = datetime.now() + + headers: Dict[str, str] = { + "Accept": str(accept_header), + "Authorization": "bearer " + os.getenv("AUTH_TOKEN", ""), + } + + r = s.get(query, params={}, headers=headers) + + if r.status_code == 200: + print("REST API", datetime.now() - start) + return r.json() # type: ignore + + if r.status_code == 409: + print("REST ERROR 409") + raise RESTError409() + + raise RESTError("Unknown Error" + str(r.status_code)) + ===========changed ref 2=========== # module: backend.external.github_api.rest.repo + def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> Dict[str, Any]: """Returns repository language breakdown""" + return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") - return get_template(BASE_URL + owner + "/" + repo + "/languages", plural=True) ===========changed ref 3=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> Dict[str, Any]: """Returns list of starred repos""" + return get_template_plural( - return get_template( BASE_URL + user_id + "/starred", - plural=True, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 4=========== # module: backend.external.github_api.rest.repo + def get_repo_stargazers( + owner: str, repo: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_repo_stargazers(owner: str, repo: str, per_page: int = 100) -> Dict[str, Any]: """Returns stargazers with timestamp for repository""" + return get_template_plural( - return get_template( BASE_URL + owner + "/" + repo + "/stargazers", - plural=True, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 5=========== # module: backend.external.github_api.rest.repo def get_repo_commits( owner: str, repo: str, user: Optional[str] = None, since: Optional[datetime] = None, until: Optional[datetime] = None, page: int = 1, + ) -> List[Dict[str, Any]]: - ) -> Dict[str, Any]: """Returns most recent commits including commit message""" user = user if user is not None else owner query = BASE_URL + owner + "/" + repo + "/commits?author=" + user if since is not None: query += "&since=" + str(since) if until is not None: query += "&until=" + str(until) + try: + return get_template_plural(query, page=page) - return get_template(query, page=page, plural=True) + except RESTError409: + return [] ===========changed ref 6=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} - # print(query, headers) r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) - # print(r.status_code) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: + raise GraphQlError("GraphQL Error: " + str(data["errors"])) - raise GraphQlError("GraphQL errors: " + str(data["errors"])) return data - try: - raise GraphQlError( - "Invalid status code " - + str(r.status_code) - + ": " - + str(r.json()["message"]) # type: ignore - + " Documentation at " - + str(r.json()["documentation_url"]) # type: ignore - ) - except Exception: - raise GraphQlError("Unknown Error") + raise GraphQlError("GraphQL Error" + str(r.status_code))
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
0cdbb75d35f1553eed3dbce7ba6f4bea6b6a8a29
bug fixes, performance improvement
<11>:<add> raise GraphQLError("GraphQL Error: " + str(data["errors"])) <del> raise GraphQlError("GraphQL Error: " + str(data["errors"])) <14>:<add> if r.status_code == 403: <add> raise GraphQLError403("GraphQL Error 403: Unauthorized") <del> raise GraphQlError("GraphQL Error" + str(r.status_code))
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = {"Authorization": "bearer " + token} <4> r = s.post( # type: ignore <5> "https://api.github.com/graphql", json=query, headers=headers <6> ) <7> print("GraphQL", datetime.now() - start) <8> if r.status_code == 200: <9> data = r.json() # type: ignore <10> if "errors" in data: <11> raise GraphQlError("GraphQL Error: " + str(data["errors"])) <12> return data <13> <14> raise GraphQlError("GraphQL Error" + str(r.status_code)) <15>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.template + class GraphQLError403(Exception): + pass + ===========changed ref 1=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 2=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 3=========== # module: backend.processing.user.contributions - # gets commit time and sha (for language breakdown) - def get_all_commit_info( - user_id: str, - name_with_owner: str, - start_date: datetime = datetime.now(), - end_date: datetime = datetime.now(), - ) -> List[datetime]: - """Gets all user's commit times for a given repository""" - owner, repo = name_with_owner.split("/") - data: List[Any] = [] - index = 0 - while (index == 0 or (index > 0 and len(data) % 100 == 0)) and index < 10: - data.extend( - get_repo_commits( - owner=owner, - repo=repo, - user=user_id, - since=start_date, - until=end_date, - page=index + 1, - ) - ) - index += 1 - - data = list( - map( - lambda x: [ - datetime.strptime( - x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" - ), - x["node_id"], - ], - data, - ) - ) - - # sort ascending - data = sorted(data, key=lambda x: x[0]) - return data -
backend.processing.commit/get_commits_languages
Modified
avgupta456~github-trends
0cdbb75d35f1553eed3dbce7ba6f4bea6b6a8a29
bug fixes, performance improvement
<18>:<add> if x["node"]["name"] not in BLACKLIST <del> if x["node"]["name"] not in blacklist
# module: backend.processing.commit def get_commits_languages( + node_ids: List[str], cutoff: int = CUTOFF - node_ids: List[str], cutoff: int = 1000 ) -> List[Dict[str, Dict[str, int]]]: <0> out: List[Dict[str, Dict[str, int]]] = [] <1> all_data: List[Dict[str, Any]] = [] <2> for i in range(0, len(node_ids), 100): <3> # TODO: handle exception to get_commits <4> # ideally would alert users somehow that data is incomplete <5> try: <6> raw_data = get_commits(node_ids[i : min(len(node_ids), i + 100)]) <7> data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore <8> all_data.extend(data) <9> except Exception: <10> print("Commit Exception") <11> <12> for commit in all_data: <13> out.append({}) <14> if commit["additions"] + commit["deletions"] < cutoff: <15> languages = [ <16> x <17> for x in commit["repository"]["languages"]["edges"] <18> if x["node"]["name"] not in blacklist <19> ] <20> num_langs = min(len(languages), commit["changedFiles"]) <21> total_repo_size = sum( <22> [language["size"] for language in languages[:num_langs]] <23> ) <24> for language in languages[:num_langs]: <25> lang_name = language["node"]["name"] <26> additions = round( <27> commit["additions"] * language["size"] / total_repo_size <28> ) <29> deletions = round( <30> commit["deletions"] * language["size"] / total_repo_size <31> ) <32> if additions > 0 or deletions > 0: <33> out[-1][lang_name] = { <34> "additions": additions, <35> "deletions": deletions, <36> } <37> </s>
===========below chunk 0=========== # module: backend.processing.commit def get_commits_languages( + node_ids: List[str], cutoff: int = CUTOFF - node_ids: List[str], cutoff: int = 1000 ) -> List[Dict[str, Dict[str, int]]]: # offset: 1 ===========unchanged ref 0=========== at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S strptime(date_string: _Text, format: _Text) -> datetime __radd__ = __add__ at: external.github_api.rest.repo get_repo_commits(owner: str, repo: str, user: Optional[str]=None, since: Optional[datetime]=None, until: Optional[datetime]=None, page: int=1) -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: backend.processing.commit + BLACKLIST = ["Jupyter Notebook"] + CUTOFF = 1000 - blacklist = ["Jupyter Notebook"] ===========changed ref 1=========== # module: backend.external.github_api.graphql.template + class GraphQLError403(Exception): + pass + ===========changed ref 2=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 3=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 4=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: + raise GraphQLError("GraphQL Error: " + str(data["errors"])) - raise GraphQlError("GraphQL Error: " + str(data["errors"])) return data + if r.status_code == 403: + raise GraphQLError403("GraphQL Error 403: Unauthorized") - raise GraphQlError("GraphQL Error" + str(r.status_code)) ===========changed ref 5=========== # module: backend.processing.user.contributions - # gets commit time and sha (for language breakdown) - def get_all_commit_info( - user_id: str, - name_with_owner: str, - start_date: datetime = datetime.now(), - end_date: datetime = datetime.now(), - ) -> List[datetime]: - """Gets all user's commit times for a given repository""" - owner, repo = name_with_owner.split("/") - data: List[Any] = [] - index = 0 - while (index == 0 or (index > 0 and len(data) % 100 == 0)) and index < 10: - data.extend( - get_repo_commits( - owner=owner, - repo=repo, - user=user_id, - since=start_date, - until=end_date, - page=index + 1, - ) - ) - index += 1 - - data = list( - map( - lambda x: [ - datetime.strptime( - x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" - ), - x["node_id"], - ], - data, - ) - ) - - # sort ascending - data = sorted(data, key=lambda x: x[0]) - return data -
backend.external.github_api.rest.template/_get_template
Modified
avgupta456~github-trends
0cdbb75d35f1553eed3dbce7ba6f4bea6b6a8a29
bug fixes, performance improvement
<8>:<add> r = s.get(query, params=params, headers=headers) <del> r = s.get(query, params={}, headers=headers) <18>:<add> raise RESTError("REST Error " + str(r.status_code)) <del> raise RESTError("Unknown Error" + str(r.status_code))
# module: backend.external.github_api.rest.template def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: <0> """Internal template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> <3> headers: Dict[str, str] = { <4> "Accept": str(accept_header), <5> "Authorization": "bearer " + os.getenv("AUTH_TOKEN", ""), <6> } <7> <8> r = s.get(query, params={}, headers=headers) <9> <10> if r.status_code == 200: <11> print("REST API", datetime.now() - start) <12> return r.json() # type: ignore <13> <14> if r.status_code == 409: <15> print("REST ERROR 409") <16> raise RESTError409() <17> <18> raise RESTError("Unknown Error" + str(r.status_code)) <19>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() RESTError409(*args: object) RESTError(*args: object) at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: os getenv(key: str, default: _T) -> Union[str, _T] getenv(key: str) -> Optional[str] at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.template + class GraphQLError403(Exception): + pass + ===========changed ref 1=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 2=========== # module: backend.external.github_api.graphql.template - class GraphQlError(Exception): - pass - ===========changed ref 3=========== # module: backend.processing.commit + BLACKLIST = ["Jupyter Notebook"] + CUTOFF = 1000 - blacklist = ["Jupyter Notebook"] ===========changed ref 4=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() token = os.getenv("AUTH_TOKEN", "") headers: Dict[str, str] = {"Authorization": "bearer " + token} r = s.post( # type: ignore "https://api.github.com/graphql", json=query, headers=headers ) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: + raise GraphQLError("GraphQL Error: " + str(data["errors"])) - raise GraphQlError("GraphQL Error: " + str(data["errors"])) return data + if r.status_code == 403: + raise GraphQLError403("GraphQL Error 403: Unauthorized") - raise GraphQlError("GraphQL Error" + str(r.status_code)) ===========changed ref 5=========== # module: backend.processing.commit + def get_all_commit_info( + user_id: str, + name_with_owner: str, + start_date: datetime = datetime.now(), + end_date: datetime = datetime.now(), + ) -> List[datetime]: + """Gets all user's commit times for a given repository""" + owner, repo = name_with_owner.split("/") + data: List[Any] = [] + index = 0 + while index in range(10) and len(data) == 100 * index: + data.extend( + get_repo_commits( + owner=owner, + repo=repo, + user=user_id, + since=start_date, + until=end_date, + page=index + 1, + ) + ) + index += 1 + + data = list( + map( + lambda x: [ + datetime.strptime( + x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" + ), + x["node_id"], + ], + data, + ) + ) + + # sort ascending + data = sorted(data, key=lambda x: x[0]) + return data + ===========changed ref 6=========== # module: backend.processing.user.contributions - # gets commit time and sha (for language breakdown) - def get_all_commit_info( - user_id: str, - name_with_owner: str, - start_date: datetime = datetime.now(), - end_date: datetime = datetime.now(), - ) -> List[datetime]: - """Gets all user's commit times for a given repository""" - owner, repo = name_with_owner.split("/") - data: List[Any] = [] - index = 0 - while (index == 0 or (index > 0 and len(data) % 100 == 0)) and index < 10: - data.extend( - get_repo_commits( - owner=owner, - repo=repo, - user=user_id, - since=start_date, - until=end_date, - page=index + 1, - ) - ) - index += 1 - - data = list( - map( - lambda x: [ - datetime.strptime( - x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" - ), - x["node_id"], - ], - data, - ) - ) - - # sort ascending - data = sorted(data, key=lambda x: x[0]) - return data - ===========changed ref 7=========== # module: backend.processing.commit def get_commits_languages( + node_ids: List[str], cutoff: int = CUTOFF - node_ids: List[str], cutoff: int = 1000 ) -> List[Dict[str, Dict[str, int]]]: out: List[Dict[str, Dict[str, int]]] = [] all_data: List[Dict[str, Any]] = [] for i in range(0, len(node_ids), 100): # TODO: handle exception to get_commits # ideally would alert users somehow that data is incomplete try: raw_data = get_commits(node_ids[i : min(len(node_ids), i + 100)]) data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore all_data.extend(data) except Exception: print("Commit Exception") for commit in all_data: out.append({}) if commit["additions"] + commit["deletions"] < cutoff: languages = [ x for x in commit["repository"]["languages"]["edges"] + if x["node"]["name"] not in BLACKLIST - if x["node"]["name"] not in blacklist ] num_langs = min(len(languages), commit["changedFiles"]) total_repo_size = sum( [language["size"] for language in languages[:num_langs]] ) for language in languages[:num_langs]: lang_name = language["node"]["name"] additions = round( commit["additions"] * language["size"] / total_repo_size ) deletions = round( commit["deletions"] * language["size"] / total_repo_size ) if additions > 0 or deletions > 0: out[-1][lang_name] = { "additions": additions, "deletions": deletions, } return out
backend.external.github_api.graphql.template/get_template
Modified
avgupta456~github-trends
6cc2473a9c7138d06d244b7b139edd24c129880f
another template revision
<2>:<del> token = os.getenv("AUTH_TOKEN", "") <3>:<add> headers: Dict[str, str] = {"Authorization": "bearer " + TOKEN} <del> headers: Dict[str, str] = {"Authorization": "bearer " + token} <4>:<add> <add> try: <add> r = s.post( # type: ignore <del> r = s.post( # type: ignore <5>:<add> "https://api.github.com/graphql", <add> json=query, <add> headers=headers, <add> timeout=TIMEOUT, <add> ) <add> except ReadTimeout: <add> raise GraphQLErrorTimeout("GraphQL Error: Request Timeout") <add> <del> "https://api.github.com/graphql", json=query, headers=headers <6>:<del> ) <11>:<add> if ( <add> "type" in data["errors"][0] <add> and data["errors"][0]["type"] == "SERVICE_UNAVAILABLE" <add> and "path" in data["errors"][0] <add> and isinstance(data["errors"][0]["path"], list) <add> and len(data["errors"][0]["path"]) == 3 # type: ignore <add> and data["errors"][0]["path"][0] == "nodes" <add> ): <add> raise GraphQLErrorMissingNode(
# module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: <0> """Template for interacting with the GitHub GraphQL API""" <1> start = datetime.now() <2> token = os.getenv("AUTH_TOKEN", "") <3> headers: Dict[str, str] = {"Authorization": "bearer " + token} <4> r = s.post( # type: ignore <5> "https://api.github.com/graphql", json=query, headers=headers <6> ) <7> print("GraphQL", datetime.now() - start) <8> if r.status_code == 200: <9> data = r.json() # type: ignore <10> if "errors" in data: <11> raise GraphQLError("GraphQL Error: " + str(data["errors"])) <12> return data <13> <14> if r.status_code == 403: <15> raise GraphQLError403("GraphQL Error 403: Unauthorized") <16> <17> raise GraphQLError("GraphQL Error " + str(r.status_code)) <18>
===========unchanged ref 0=========== at: backend.external.github_api.graphql.template s = requests.session() at: constants TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.template - class GraphQLError403(Exception): - pass - ===========changed ref 1=========== # module: backend.external.github_api.graphql.template + class GraphQLErrorMissingNode(Exception): + def __init__(self, node: int, *args: Tuple[Any], **kwargs: Dict[str, Any]): + super(Exception, self).__init__(*args, **kwargs) + self.node = node +
backend.external.github_api.rest.template/_get_template
Modified
avgupta456~github-trends
6cc2473a9c7138d06d244b7b139edd24c129880f
another template revision
<5>:<add> "Authorization": "bearer " + TOKEN, <del> "Authorization": "bearer " + os.getenv("AUTH_TOKEN", ""), <8>:<add> try: <add> r = s.get(query, params=params, headers=headers, timeout=TIMEOUT) <del> r = s.get(query, params=params, headers=headers) <9>:<add> except ReadTimeout: <add> raise RESTErrorTimeout("REST Error: Request Timeout") <15>:<del> print("REST ERROR 409") <16>:<del> raise RESTError409() <17>:<add> raise RESTErrorEmptyRepo("REST Error: Empty Repository") <18>:<add> raise RESTError("REST Error: " + str(r.status_code)) <del> raise RESTError("REST Error " + str(r.status_code))
# module: backend.external.github_api.rest.template def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: <0> """Internal template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> <3> headers: Dict[str, str] = { <4> "Accept": str(accept_header), <5> "Authorization": "bearer " + os.getenv("AUTH_TOKEN", ""), <6> } <7> <8> r = s.get(query, params=params, headers=headers) <9> <10> if r.status_code == 200: <11> print("REST API", datetime.now() - start) <12> return r.json() # type: ignore <13> <14> if r.status_code == 409: <15> print("REST ERROR 409") <16> raise RESTError409() <17> <18> raise RESTError("REST Error " + str(r.status_code)) <19>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() at: constants TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication TIMEOUT = 3 # max seconds to wait for api response at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: requests.exceptions ReadTimeout(*args, **kwargs) at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.template + class RESTErrorEmptyRepo(Exception): + pass + ===========changed ref 1=========== # module: backend.external.github_api.rest.template - class RESTError409(Exception): - pass - ===========changed ref 2=========== # module: backend.external.github_api.graphql.template + class GraphQLErrorTimeout(Exception): + pass + ===========changed ref 3=========== # module: backend.external.github_api.graphql.template + class GraphQLErrorAuth(Exception): + pass + ===========changed ref 4=========== # module: backend.external.github_api.graphql.template - class GraphQLError403(Exception): - pass - ===========changed ref 5=========== # module: backend.external.github_api.graphql.template + class GraphQLErrorMissingNode(Exception): + def __init__(self, node: int, *args: Tuple[Any], **kwargs: Dict[str, Any]): + super(Exception, self).__init__(*args, **kwargs) + self.node = node + ===========changed ref 6=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: """Template for interacting with the GitHub GraphQL API""" start = datetime.now() - token = os.getenv("AUTH_TOKEN", "") + headers: Dict[str, str] = {"Authorization": "bearer " + TOKEN} - headers: Dict[str, str] = {"Authorization": "bearer " + token} + + try: + r = s.post( # type: ignore - r = s.post( # type: ignore + "https://api.github.com/graphql", + json=query, + headers=headers, + timeout=TIMEOUT, + ) + except ReadTimeout: + raise GraphQLErrorTimeout("GraphQL Error: Request Timeout") + - "https://api.github.com/graphql", json=query, headers=headers - ) print("GraphQL", datetime.now() - start) if r.status_code == 200: data = r.json() # type: ignore if "errors" in data: + if ( + "type" in data["errors"][0] + and data["errors"][0]["type"] == "SERVICE_UNAVAILABLE" + and "path" in data["errors"][0] + and isinstance(data["errors"][0]["path"], list) + and len(data["errors"][0]["path"]) == 3 # type: ignore + and data["errors"][0]["path"][0] == "nodes" + ): + raise GraphQLErrorMissingNode(node=int(data["errors"][0]["path"][1])) # type: ignore raise GraphQLError("GraphQL Error: " + str(data["errors"])) return data if r.status_code == 403: + raise GraphQLErrorAuth("GraphQL Error: Unauthorized") - raise GraphQLError403("GraphQL Error 403: Unauthorized") </s> ===========changed ref 7=========== # module: backend.external.github_api.graphql.template def get_template(query: Dict[str, Any]) -> Dict[str, Any]: # offset: 1 <s> raise GraphQLErrorAuth("GraphQL Error: Unauthorized") - raise GraphQLError403("GraphQL Error 403: Unauthorized") + if r.status_code == 502: + raise GraphQLErrorTimeout("GraphQL Error: Request Timeout") - raise GraphQLError("GraphQL Error " + str(r.status_code))
backend.external.github_api.rest.repo/get_repo_commits
Modified
avgupta456~github-trends
dea216a9c553235c265d8d9cae9e779e8b037c97
Update repo.py
<9>:<add> except RESTErrorEmptyRepo: <del> except RESTError409:
# module: backend.external.github_api.rest.repo def get_repo_commits( owner: str, repo: str, user: Optional[str] = None, since: Optional[datetime] = None, until: Optional[datetime] = None, page: int = 1, ) -> List[Dict[str, Any]]: <0> """Returns most recent commits including commit message""" <1> user = user if user is not None else owner <2> query = BASE_URL + owner + "/" + repo + "/commits?author=" + user <3> if since is not None: <4> query += "&since=" + str(since) <5> if until is not None: <6> query += "&until=" + str(until) <7> try: <8> return get_template_plural(query, page=page) <9> except RESTError409: <10> return [] <11>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: datetime datetime() at: external.github_api.rest.template RESTErrorEmptyRepo(*args: object) get_template_plural(query: str, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict')
backend.processing.commit/get_commits_languages
Modified
avgupta456~github-trends
fe379d1d61836e83d52b8a142467e13f61cf036a
various bug fixes
<0>:<add> all_data = _get_commits_languages(node_ids, per_page=NODE_CHUNK_SIZE) <add> <1>:<del> all_data: List[Dict[str, Any]] = [] <2>:<del> for i in range(0, len(node_ids), 100): <3>:<del> # TODO: handle exception to get_commits <4>:<del> # ideally would alert users somehow that data is incomplete <5>:<del> try: <6>:<del> raw_data = get_commits(node_ids[i : min(len(node_ids), i + 100)]) <7>:<del> data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore <8>:<del> all_data.extend(data) <9>:<del> except Exception: <10>:<del> print("Commit Exception") <11>:<del> <14>:<add> if ( <add> "additions" in commit <add> and "deletions" in commit <add> and "changedFiles" in commit <add> and commit["additions"] + commit["deletions"] < cutoff <del> if commit["additions"] + commit["deletions"] < cutoff: <15>:<add> ):
# module: backend.processing.commit - def get_commits_languages( - node_ids: List[str], cutoff: int = CUTOFF - ) -> List[Dict[str, Dict[str, int]]]: + def get_commits_languages(node_ids: List[str], cutoff: int = CUTOFF): <0> out: List[Dict[str, Dict[str, int]]] = [] <1> all_data: List[Dict[str, Any]] = [] <2> for i in range(0, len(node_ids), 100): <3> # TODO: handle exception to get_commits <4> # ideally would alert users somehow that data is incomplete <5> try: <6> raw_data = get_commits(node_ids[i : min(len(node_ids), i + 100)]) <7> data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore <8> all_data.extend(data) <9> except Exception: <10> print("Commit Exception") <11> <12> for commit in all_data: <13> out.append({}) <14> if commit["additions"] + commit["deletions"] < cutoff: <15> languages = [ <16> x <17> for x in commit["repository"]["languages"]["edges"] <18> if x["node"]["name"] not in BLACKLIST <19> ] <20> num_langs = min(len(languages), commit["changedFiles"]) <21> total_repo_size = sum( <22> [language["size"] for language in languages[:num_langs]] <23> ) <24> for language in languages[:num_langs]: <25> lang_name = language["node"]["name"] <26> additions = round( <27> commit["additions"] * language["size"] / total_repo_size <28> ) <29> deletions = round( <30> commit["deletions"] * language["size"] / total_repo_size <31> ) <32> if additions > 0 or deletions > 0: <33> out[-1][lang_name] = { <34> "additions": additions, <35> </s>
===========below chunk 0=========== # module: backend.processing.commit - def get_commits_languages( - node_ids: List[str], cutoff: int = CUTOFF - ) -> List[Dict[str, Dict[str, int]]]: + def get_commits_languages(node_ids: List[str], cutoff: int = CUTOFF): # offset: 1 } return out ===========unchanged ref 0=========== at: backend.processing.commit.get_all_commit_info data = sorted(data, key=lambda x: x[0]) at: constants NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100) CUTOFF = 1000 # if > cutoff lines, assume imported, don't count at: external.github_api.graphql.commit get_commits(node_ids: List[str]) -> Union[Dict[str, Any], List[Any]] at: external.github_api.graphql.template GraphQLErrorMissingNode(node: int) GraphQLErrorAuth(*args: object) GraphQLErrorTimeout(*args: object) at: external.github_api.graphql.template.GraphQLErrorMissingNode.__init__ self.node = node at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.processing.commit - BLACKLIST = ["Jupyter Notebook"] - CUTOFF = 1000 -
backend.processing.user.contributions/get_user_all_contribution_events
Modified
avgupta456~github-trends
fe379d1d61836e83d52b8a142467e13f61cf036a
various bug fixes
<0>:<add> repo_contribs: t_stats = defaultdict( <del> repo_contribs: t = defaultdict(
# module: backend.processing.user.contributions def get_user_all_contribution_events( user_id: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), + ) -> t_stats: - ) -> t: <0> repo_contribs: t = defaultdict( <1> lambda: {"commits": [], "issues": [], "prs": [], "reviews": [], "repos": []} <2> ) <3> after: Optional[str] = "" <4> index, cont = 0, True <5> while index < 10 and cont: <6> after_str = after if isinstance(after, str) else "" <7> response = get_user_contribution_events( <8> user_id=user_id, start_date=start_date, end_date=end_date, after=after_str <9> ) <10> <11> cont = False <12> for event_type, event_list in zip( <13> ["commits", "issues", "prs", "reviews"], <14> [ <15> response.commit_contribs_by_repo, <16> response.issue_contribs_by_repo, <17> response.pr_contribs_by_repo, <18> response.review_contribs_by_repo, <19> ], <20> ): <21> for repo in event_list: <22> name = repo.repo.name <23> for event in repo.contribs.nodes: <24> repo_contribs[name][event_type].append(event) <25> if repo.contribs.page_info.has_next_page: <26> after = repo.contribs.page_info.end_cursor <27> cont = True <28> <29> for repo in response.repo_contribs.nodes: <30> name = repo.repo.name <31> repo_contribs[name]["repos"].append( <32> RawEventsEvent(occurredAt=str(repo.occurred_at)) <33> ) <34> <35> index += 1 <36> <37> return repo_contribs </s>
===========unchanged ref 0=========== at: backend.processing.user.contributions t_stats = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] at: collections defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]]) defaultdict(default_factory: Optional[Callable[[], _VT]]) defaultdict(**kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], iterable: Iterable[Tuple[_KT, _VT]], **kwargs: _VT) defaultdict(default_factory: Optional[Callable[[], _VT]], map: Mapping[_KT, _VT]) at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: external.github_api.graphql.user get_user_contribution_events(user_id: str, start_date: datetime=datetime.now() - timedelta(365), end_date: datetime=datetime.now(), max_repos: int=100, first: int=100, after: str="") -> RawEvents at: models.user.contribs.RawEvents commit_contribs_by_repo: List[RawEventsRepoCommits] = Field( alias="commitContributionsByRepository" ) ===========unchanged ref 1=========== issue_contribs_by_repo: List[RawEventsRepo] = Field( alias="issueContributionsByRepository" ) pr_contribs_by_repo: List[RawEventsRepo] = Field( alias="pullRequestContributionsByRepository" ) review_contribs_by_repo: List[RawEventsRepo] = Field( alias="pullRequestReviewContributionsByRepository" ) repo_contribs: RawEventsRepoContribs = Field(alias="repositoryContributions") at: models.user.contribs.RawEventsCommits nodes: List[RawEventsCommit] page_info: RawEventsPageInfo = Field(alias="pageInfo") at: models.user.contribs.RawEventsContribs nodes: List[RawEventsEvent] page_info: RawEventsPageInfo = Field(alias="pageInfo") at: models.user.contribs.RawEventsPageInfo has_next_page: bool = Field(alias="hasNextPage") end_cursor: Optional[str] = Field(alias="endCursor") at: models.user.contribs.RawEventsRepo repo: RawEventsRepoName = Field(alias="repository") count: RawEventsCount = Field(alias="totalCount") contribs: RawEventsContribs = Field(alias="contributions") at: models.user.contribs.RawEventsRepoCommits repo: RawEventsRepoName = Field(alias="repository") count: RawEventsCount = Field(alias="totalCount") contribs: RawEventsCommits = Field(alias="contributions") at: models.user.contribs.RawEventsRepoContribs count: int = Field(alias="totalCount") nodes: List[RawEventsRepoEvent] at: models.user.contribs.RawEventsRepoEvent repo: RawEventsRepoName = Field(alias="repository") occurred_at: datetime = Field(alias="occurredAt") at: models.user.contribs.RawEventsRepoName name: str = Field(alias="nameWithOwner") ===========changed ref 0=========== # module: backend.processing.user.contributions + t_stats = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] - t = DefaultDict[str, Dict[str, List[Union[RawEventsEvent, RawEventsCommit]]]] + t_commits = List[Dict[str, Union[Dict[str, Dict[str, int]], datetime]]] ===========changed ref 1=========== # module: backend.processing.commit - - ===========changed ref 2=========== # module: backend.processing.commit - BLACKLIST = ["Jupyter Notebook"] - CUTOFF = 1000 - ===========changed ref 3=========== # module: backend.processing.commit + def _get_commits_languages( + node_ids: List[str], per_page: int = NODE_CHUNK_SIZE + ) -> List[Dict[str, Any]]: + all_data: List[Dict[str, Any]] = [] + for i in range(0, len(node_ids), per_page): + # TODO: alert user/display if some nodes omitted + # TODO: figure out why Auth error code appears + cutoff = min(len(node_ids), i + per_page) + try: + raw_data = get_commits(node_ids[i:cutoff]) + data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore + all_data.extend(data) + except GraphQLErrorMissingNode as e: + curr = node_ids[i:cutoff] + curr.pop(e.node) + all_data.extend(_get_commits_languages(curr)) + except GraphQLErrorTimeout: + length = cutoff - i + if length == per_page: + midpoint = i + int(per_page / 2) + all_data.extend(_get_commits_languages(node_ids[i:midpoint])) + all_data.extend(_get_commits_languages(node_ids[midpoint:cutoff])) + else: + print("Commit Timeout Exception:", length, " nodes lost") + all_data.extend([{} for _ in range(length)]) + except GraphQLErrorAuth: + length = cutoff - i + print("Commit Auth Exception:", length, " nodes lost") + all_data.extend([{} for _ in range(length)]) + + return all_data +
backend.endpoints.user/main
Modified
avgupta456~github-trends
aa383a135b289a7359b937deb210c42914c17651
cleanup user output
<2>:<add> funcs = [get_top_languages, get_contribs_per_day, get_contribs_per_repo_per_day] <add> [top_languages, contribs_per_day, contribs_per_repo_per_day] = gather( <del> [contribs_per_day, contribs_per_repo_per_day] = gather( <3>:<del> funcs=[get_contribs_per_day, get_contribs_per_repo_per_day], <4>:<add> funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))] <del> args_dicts=[{"data": data} for _ in range(2)], <8>:<add> "top_languages": top_languages, <del> "raw": data,
# module: backend.endpoints.user def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Dict[str, Any]: <0> data = get_data(user_id, start_date, end_date, timezone_str) <1> <2> [contribs_per_day, contribs_per_repo_per_day] = gather( <3> funcs=[get_contribs_per_day, get_contribs_per_repo_per_day], <4> args_dicts=[{"data": data} for _ in range(2)], <5> ) <6> <7> return { <8> "raw": data, <9> "contribs_per_day": contribs_per_day, <10> "contribs_per_repo_per_day": contribs_per_repo_per_day, <11> } <12>
===========unchanged ref 0=========== at: analytics.user.contribs_per_day get_contribs_per_day(data: UserPackage) -> Dict[date, int] get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[date, int]] at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.models.user.contribs + class Language(BaseModel): + additions: int + deletions: int + ===========changed ref 1=========== # module: backend.models.user.contribs class ContributionStats(BaseModel): contribs_count: int commits_count: int issues_count: int prs_count: int reviews_count: int repos_count: int other_count: int + languages: Dict[str, Language] - languages: Dict[str, Dict[str, int]]
backend.endpoints.user/main
Modified
avgupta456~github-trends
d0316a8866a967e8c81b0a8b0c767c79b7c5c291
add top repos
<2>:<add> funcs = [ <add> get_top_languages, <add> get_top_repos, <add> get_contribs_per_day, <add> get_contribs_per_repo_per_day, <add> ] <del> funcs = [get_top_languages, get_contribs_per_day, get_contribs_per_repo_per_day] <3>:<add> [top_languages, top_repos, contribs_per_day, contribs_per_repo_per_day] = gather( <del> [top_languages, contribs_per_day, contribs_per_repo_per_day] = gather( <9>:<add> "top_repos": top_repos,
# module: backend.endpoints.user def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Dict[str, Any]: <0> data = get_data(user_id, start_date, end_date, timezone_str) <1> <2> funcs = [get_top_languages, get_contribs_per_day, get_contribs_per_repo_per_day] <3> [top_languages, contribs_per_day, contribs_per_repo_per_day] = gather( <4> funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))] <5> ) <6> <7> return { <8> "top_languages": top_languages, <9> "contribs_per_day": contribs_per_day, <10> "contribs_per_repo_per_day": contribs_per_repo_per_day, <11> } <12>
===========unchanged ref 0=========== at: analytics.user.commits get_top_languages(data: UserPackage) -> List[dict_type] get_top_repos(data: UserPackage) -> List[Any] at: analytics.user.contribs_per_day get_contribs_per_day(data: UserPackage) -> Dict[date, int] get_contribs_per_repo_per_day(data: UserPackage) -> Dict[str, Dict[date, int]] at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.constants TOKEN = os.getenv("AUTH_TOKEN", "") # for authentication TIMEOUT = 3 # max seconds to wait for api response NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100) NODE_THREADS = 30 # number of node queries simultaneously (avoid blacklisting) + BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore - BLACKLIST = ["Jupyter Notebook"] # languages to ignore CUTOFF = 1000 # if > cutoff lines, assume imported, don't count ===========changed ref 1=========== # module: backend.analytics.user.commits + def get_top_repos(data: UserPackage) -> List[Any]: + repos: List[Any] = [ + { + repo: repo, + "languages": [lang for lang in repo_stats.languages], + "additions": sum([x.additions for x in repo_stats.languages.values()]), + "deletions": sum([x.deletions for x in repo_stats.languages.values()]), + } + for repo, repo_stats in data.contribs.repo_stats.items() + ] + + for repo in repos: + repo["added"] = int(repo["additions"]) - int(repo["deletions"]) + repo["changed"] = int(repo["additions"]) + int(repo["deletions"]) + + repos = sorted(repos, key=lambda x: x["changed"], reverse=True) + + return repos[:5] +
backend.endpoints.user/main
Modified
avgupta456~github-trends
0540b93a58e590d60be9fb7c85de9459cba0ba05
use datastore
<0>:<add> access_token = get_access_token(user_id) <add> if access_token == "": <add> raise LookupError("Invalid UserId") <add> <add> output = get_user_endpoint(user_id) <add> if output is not None: <add> return output <add> <add> data = get_data(user_id, access_token, start_date, end_date, timezone_str) <del> data = get_data(user_id, start_date, end_date, timezone_str) <12>:<add> output = { <del> return {
# module: backend.endpoints.user @lru_cache(maxsize=1024) def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Dict[str, Any]: <0> data = get_data(user_id, start_date, end_date, timezone_str) <1> <2> funcs = [ <3> get_top_languages, <4> get_top_repos, <5> get_contribs_per_day, <6> get_contribs_per_repo_per_day, <7> ] <8> [top_languages, top_repos, contribs_per_day, contribs_per_repo_per_day] = gather( <9> funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))] <10> ) <11> <12> return { <13> "top_languages": top_languages, <14> "top_repos": top_repos, <15> "contribs_per_day": contribs_per_day, <16> "contribs_per_repo_per_day": contribs_per_repo_per_day, <17> } <18>
===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: external.google_datastore.datastore get_access_token(user_id: str) -> str get_user_endpoint(user_id: str) -> Any at: functools lru_cache(maxsize: Optional[int]=..., typed: bool=...) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]] lru_cache(maxsize: Callable[..., _T], typed: bool=...) -> _lru_cache_wrapper[_T] at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict')
backend.endpoints.github_auth/get_access_token
Modified
avgupta456~github-trends
0540b93a58e590d60be9fb7c85de9459cba0ba05
use datastore
<11>:<del> print(params) <12>:<del> <18>:<add> set_access_token(user_id, access_token) <del> print(user_id, access_token)
# module: backend.endpoints.github_auth def get_access_token(code: str) -> Any: <0> """Request a user's access token using code""" <1> <2> start = datetime.now() <3> <4> params = { <5> "client_id": OAUTH_CLIENT_ID, <6> "client_secret": OAUTH_CLIENT_SECRET, <7> "code": code, <8> "redirect_uri": OAUTH_REDIRECT_URI, <9> } <10> <11> print(params) <12> <13> r = s.post("https://github.com/login/oauth/access_token", params=params) # type: ignore <14> <15> if r.status_code == 200: <16> access_token = r.text.split("&")[0].split("=")[1] <17> user_id = get_unknown_user(access_token) <18> print(user_id, access_token) <19> print("OAuth API", datetime.now() - start) <20> return user_id <21> <22> raise OAuthError("OAuth Error: " + str(r.status_code)) <23>
===========unchanged ref 0=========== at: backend.endpoints.github_auth s = requests.session() OAuthError(*args: object) at: constants OAUTH_CLIENT_ID = os.getenv("OAUTH_CLIENT_ID", "") # client ID for GitHub OAuth App OAUTH_CLIENT_SECRET = os.getenv("OAUTH_CLIENT_SECRET", "") # client secret for App OAUTH_REDIRECT_URI = os.getenv("OAUTH_REDIRECT_URI", "") # redirect uri for App at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: external.github_auth.auth get_unknown_user(access_token: str) -> str at: external.google_datastore.datastore set_access_token(user_id: str, access_token: str) -> None at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] post(url: Union[Text, bytes], data: _Data=..., json: Optional[Any]=..., **kwargs) -> Response ===========changed ref 0=========== # module: backend.endpoints.user @lru_cache(maxsize=1024) def main( user_id: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> Dict[str, Any]: + access_token = get_access_token(user_id) + if access_token == "": + raise LookupError("Invalid UserId") + + output = get_user_endpoint(user_id) + if output is not None: + return output + + data = get_data(user_id, access_token, start_date, end_date, timezone_str) - data = get_data(user_id, start_date, end_date, timezone_str) funcs = [ get_top_languages, get_top_repos, get_contribs_per_day, get_contribs_per_repo_per_day, ] [top_languages, top_repos, contribs_per_day, contribs_per_repo_per_day] = gather( funcs=funcs, args_dicts=[{"data": data} for _ in range(len(funcs))] ) + output = { - return { "top_languages": top_languages, "top_repos": top_repos, "contribs_per_day": contribs_per_day, "contribs_per_repo_per_day": contribs_per_repo_per_day, }
backend.tests.processing.user.test_contributions/TestTemplate.test_get_contributions
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_contributions("avgupta456", TOKEN) <del> response = get_contributions("avgupta456")
# module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): <0> response = get_contributions("avgupta456") <1> self.assertIsInstance(response, UserContributions) <2>
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_years
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) <del> response = get_user_contribution_years(user_id="avgupta456")
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): <0> response = get_user_contribution_years(user_id="avgupta456") <1> <2> # aside from validating APIResponse class, pydantic will validate tree <3> self.assertIsInstance(response, list) <4>
===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions)
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_calendar
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_contribution_calendar( <del> response = get_user_contribution_calendar(user_id="avgupta456") <1>:<add> user_id="avgupta456", access_token=TOKEN <add> )
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): <0> response = get_user_contribution_calendar(user_id="avgupta456") <1> self.assertIsInstance(response, RawCalendar) <2>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions)
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_contribution_events
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_contribution_events( <del> response = get_user_contribution_events(user_id="avgupta456") <1>:<add> user_id="avgupta456", access_token=TOKEN <add> )
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): <0> response = get_user_contribution_events(user_id="avgupta456") <1> self.assertIsInstance(response, RawEvents) <2>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 2=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions)
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_followers
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_followers(user_id="avgupta456", access_token=TOKEN) <del> response = get_user_followers(user_id="avgupta456") <3>:<add> response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) <del> response = get_user_followers(user_id="avgupta456", first=1)
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): <0> response = get_user_followers(user_id="avgupta456") <1> self.assertIsInstance(response, RawFollows) <2> <3> response = get_user_followers(user_id="avgupta456", first=1) <4> self.assertLessEqual(len(response.nodes), 1) <5>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 3=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions)
backend.tests.external.github_api.graphql.test_user/TestTemplate.test_get_user_following
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_following(user_id="avgupta456", access_token=TOKEN) <del> response = get_user_following(user_id="avgupta456") <3>:<add> response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) <del> response = get_user_following(user_id="avgupta456", first=1)
# module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): <0> response = get_user_following(user_id="avgupta456") <1> self.assertIsInstance(response, RawFollows) <2> <3> response = get_user_following(user_id="avgupta456", first=1) <4> self.assertLessEqual(len(response.nodes), 1) <5>
===========changed ref 0=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 4=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions)
backend.packaging.user/main
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<6>:<add> "access_token": access_token, <10>:<add> {"user_id": user_id, "access_token": access_token}, <del> {"user_id": user_id},
# module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: <0> """packages all processing steps for the user query""" <1> data = gather( <2> funcs=[get_contributions, get_user_follows], <3> args_dicts=[ <4> { <5> "user_id": user_id, <6> "start_date": start_date, <7> "end_date": end_date, <8> "timezone_str": timezone_str, <9> }, <10> {"user_id": user_id}, <11> ], <12> ) <13> <14> return UserPackage(contribs=data[0], follows=data[1]) <15>
===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) date() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' today() -> _S __str__ = isoformat __radd__ = __add__ at: helper.gather gather(funcs: List[Callable[..., Any]], args_dicts: List[Dict[str, Any]], max_threads: int=5) -> List[Any] at: processing.user.contributions get_contributions(user_id: str, access_token: str, start_date: date=date.today() - timedelta(365), end_date: date=date.today(), timezone_str: str="US/Eastern") -> UserContributions at: processing.user.follows get_user_follows(user_id: str, access_token: str) -> UserFollows ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.processing.user.follows/get_user_follows
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<12>:<add> data = get_func(user_id, access_token, after=after_str) <del> data = get_func(user_id, after=after_str)
# module: backend.processing.user.follows + def get_user_follows(user_id: str, access_token: str) -> UserFollows: - def get_user_follows(user_id: str) -> UserFollows: <0> """get user followers and users following for given user""" <1> <2> followers: List[User] = [] <3> following: List[User] = [] <4> <5> for user_list, get_func in zip( <6> [followers, following], [_get_user_followers, _get_user_following] <7> ): <8> after: Optional[str] = "" <9> index, cont = 0, True # initialize variables <10> while cont and index < 10: <11> after_str: str = after if isinstance(after, str) else "" <12> data = get_func(user_id, after=after_str) <13> <14> cont = False <15> <16> user_list.extend( <17> map( <18> lambda x: User(name=x.name, login=x.login, url=x.url), <19> data.nodes, <20> ) <21> ) <22> if data.page_info.has_next_page: <23> after = data.page_info.end_cursor <24> cont = True <25> <26> index += 1 <27> <28> output = UserFollows(followers=followers, following=following) <29> return output <30>
===========unchanged ref 0=========== at: external.github_api.graphql.user get_user_followers(user_id: str, access_token: str, first: int=100, after: str="") -> RawFollows get_user_following(user_id: str, access_token: str, first: int=10, after: str="") -> RawFollows at: models.user.follows.PageInfo has_next_page: bool = Field(alias="hasNextPage") end_cursor: Optional[str] = Field(alias="endCursor") at: models.user.follows.RawFollows nodes: List[User] page_info: PageInfo = Field(alias="pageInfo") at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1])
backend.external.github_api.graphql.user/get_user_contribution_years
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<14>:<del> years = get_template(query)["data"]["user"]["contributionsCollection"][ <15>:<del> "contributionYears" <16>:<del> ] <17>:<del> <18>:<add> raw_data = get_template(query, access_token) <add> years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"]
# module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: <0> """Gets years where the user had activity""" <1> query = { <2> "variables": {"login": user_id}, <3> "query": """ <4> query getUser($login: String!) { <5> user(login: $login){ <6> contributionsCollection{ <7> contributionYears <8> } <9> } <10> } <11> """, <12> } <13> <14> years = get_template(query)["data"]["user"]["contributionsCollection"][ <15> "contributionYears" <16> ] <17> <18> return years <19>
===========unchanged ref 0=========== at: external.github_api.graphql.template get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 7=========== # module: backend.processing.user.follows + def get_user_follows(user_id: str, access_token: str) -> UserFollows: - def get_user_follows(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, access_token, after=after_str) - data = get_func(user_id, after=after_str) cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output
backend.external.github_api.graphql.user/get_user_contribution_calendar
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<29>:<del> output = get_template(query)["data"]["user"]["contributionsCollection"][ <30>:<del> "contributionCalendar" <31>:<del> ] <32>:<add> raw_data = get_template(query, access_token) <add> output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"]
# module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(days=365), end_date: datetime = datetime.now(), ) -> RawCalendar: <0> """Gets contribution calendar for a given time period (max one year)""" <1> if (end_date - start_date).days > 365: <2> raise ValueError("date range can be at most 1 year") <3> query = { <4> "variables": { <5> "login": user_id, <6> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <7> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <8> }, <9> "query": """ <10> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ <11> user(login: $login){ <12> contributionsCollection(from: $startDate, to: $endDate){ <13> contributionCalendar{ <14> weeks{ <15> contributionDays{ <16> date <17> weekday <18> contributionCount <19> } <20> } <21> totalContributions <22> } <23> } <24> } <25> } <26> """, <27> } <28> <29> output = get_template(query)["data"]["user"]["contributionsCollection"][ <30> "contributionCalendar" <31> ] <32> return RawCalendar.parse_obj(output) <33>
===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) datetime() at: datetime.date __slots__ = '_year', '_month', '_day', '_hashcode' strftime(fmt: _Text) -> str __str__ = isoformat __radd__ = __add__ at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: datetime.timedelta __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' __radd__ = __add__ __rmul__ = __mul__ at: external.github_api.graphql.template get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 8=========== # module: backend.processing.user.follows + def get_user_follows(user_id: str, access_token: str) -> UserFollows: - def get_user_follows(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, access_token, after=after_str) - data = get_func(user_id, after=after_str) cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output
backend.external.github_api.graphql.user/get_user_contribution_events
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
# module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: <0> """Fetches user contributions (commits, issues, prs, reviews)""" <1> if (end_date - start_date).days > 365: <2> raise ValueError("date range can be at most 1 year") <3> query = { <4> "variables": { <5> "login": user_id, <6> "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <7> "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), <8> "maxRepos": max_repos, <9> "first": first, <10> "after": after, <11> }, <12> "query": """ <13> query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { <14> user(login: $login){ <15> contributionsCollection(from: $startDate, to: $endDate){ <16> commitContributionsByRepository(maxRepositories: $maxRepos){ <17> repository{ <18> nameWithOwner, <19> }, <20> totalCount:contributions(first: 1){ <21> totalCount <22> } <23> contributions(first: $first, after: $after){ <24> nodes{ <25> commitCount, <26> occurredAt, <27> } <28> pageInfo{ <29> hasNextPage, <30> endCursor <31> } <32> } <33> } <34> issueContributionsByRepository(maxRepositories: $maxRepos){ <35> repository{ <36> nameWithOwner <37> }, <38> totalCount:contributions(first: 1){ <39> totalCount <40> </s>
===========below chunk 0=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: # offset: 1 contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount nodes{ repository{ nameWithOwner, } occurredAt, } }, }, } } """, } output = get_template(query)["data"]["user"]["contributionsCollection"] return RawEvents.parse_obj(output) ===========unchanged ref 0=========== at: datetime timedelta(days: float=..., seconds: float=..., microseconds: float=..., milliseconds: float=..., minutes: float=..., hours: float=..., weeks: float=..., *, fold: int=...) datetime() at: datetime.date strftime(fmt: _Text) -> str at: datetime.datetime now(tz: Optional[_tzinfo]=...) -> _S at: external.github_api.graphql.template get_template(query: Dict[str, Any], access_token: str) -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(days=365), end_date: datetime = datetime.now(), ) -> RawCalendar: """Gets contribution calendar for a given time period (max one year)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ contributionCalendar{ weeks{ contributionDays{ date weekday contributionCount } } totalContributions } } } } """, } - output = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionCalendar" - ] + raw_data = get_template(query, access_token) + output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"] return RawCalendar.parse_obj(output) ===========changed ref 2=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.external.github_api.graphql.user/get_user_followers
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<51>:<add> output_dict = get_template(query, access_token)["data"]["user"]["followers"] <del> output_dict = get_template(query)["data"]["user"]["followers"]
# module: backend.external.github_api.graphql.user + def get_user_followers( + user_id: str, access_token: str, first: int = 100, after: str = "" + ) -> RawFollows: - def get_user_followers(user_id: str, first: int = 100, after: str = "") -> RawFollows: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> followers(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> followers(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> output_dict = get_template(query)["data"]["user"]["followers"] <52> return RawFollows.parse_obj(output_dict) <53>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 1=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(days=365), end_date: datetime = datetime.now(), ) -> RawCalendar: """Gets contribution calendar for a given time period (max one year)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ contributionCalendar{ weeks{ contributionDays{ date weekday contributionCount } } totalContributions } } } } """, } - output = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionCalendar" - ] + raw_data = get_template(query, access_token) + output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"] return RawCalendar.parse_obj(output) ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: """Fetches user contributions (commits, issues, prs, reviews)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } issueContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, end</s> ===========changed ref 3=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: # offset: 1 <s> after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } } pullRequestReviewContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, endCursor } } }, repositoryContributions(first: $maxRepos){ totalCount nodes{ repository{ nameWithOwner, } occurredAt, } }, }, } } """, } + raw_data = get_template(query, access_token) + output = raw_data["data"]["user"]["contributionsCollection"] - output = get_template(query)["data"]["user"]["contributionsCollection"] return RawEvents.parse_obj(output) ===========changed ref 4=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar)
backend.external.github_api.graphql.user/get_user_following
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<51>:<add> output_dict = get_template(query, access_token)["data"]["user"]["following"] <del> output_dict = get_template(query)["data"]["user"]["following"]
# module: backend.external.github_api.graphql.user + def get_user_following( + user_id: str, access_token: str, first: int = 10, after: str = "" + ) -> RawFollows: - def get_user_following(user_id: str, first: int = 10, after: str = "") -> RawFollows: <0> """gets user's followers and users following'""" <1> <2> variables: Dict[str, Union[str, int]] = ( <3> {"login": user_id, "first": first, "after": after} <4> if after != "" <5> else {"login": user_id, "first": first} <6> ) <7> <8> query_str: str = ( <9> """ <10> query getUser($login: String!, $first: Int!, $after: String!) { <11> user(login: $login){ <12> following(first: $first, after: $after){ <13> nodes{ <14> name, <15> login, <16> url <17> } <18> pageInfo{ <19> hasNextPage, <20> endCursor <21> } <22> } <23> } <24> } <25> """ <26> if after != "" <27> else """ <28> query getUser($login: String!, $first: Int!) { <29> user(login: $login){ <30> following(first: $first){ <31> nodes{ <32> name, <33> login, <34> url <35> } <36> pageInfo{ <37> hasNextPage, <38> endCursor <39> } <40> } <41> } <42> } <43> """ <44> ) <45> <46> query = { <47> "variables": variables, <48> "query": query_str, <49> } <50> <51> output_dict = get_template(query)["data"]["user"]["following"] <52> return RawFollows.parse_obj(output_dict) <53>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.graphql.user + def get_user_followers( + user_id: str, access_token: str, first: int = 100, after: str = "" + ) -> RawFollows: - def get_user_followers(user_id: str, first: int = 100, after: str = "") -> RawFollows: """gets user's followers and users following'""" variables: Dict[str, Union[str, int]] = ( {"login": user_id, "first": first, "after": after} if after != "" else {"login": user_id, "first": first} ) query_str: str = ( """ query getUser($login: String!, $first: Int!, $after: String!) { user(login: $login){ followers(first: $first, after: $after){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ if after != "" else """ query getUser($login: String!, $first: Int!) { user(login: $login){ followers(first: $first){ nodes{ name, login, url } pageInfo{ hasNextPage, endCursor } } } } """ ) query = { "variables": variables, "query": query_str, } + output_dict = get_template(query, access_token)["data"]["user"]["followers"] - output_dict = get_template(query)["data"]["user"]["followers"] return RawFollows.parse_obj(output_dict) ===========changed ref 1=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 2=========== # module: backend.external.github_api.graphql.user def get_user_contribution_calendar( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(days=365), end_date: datetime = datetime.now(), ) -> RawCalendar: """Gets contribution calendar for a given time period (max one year)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!){ user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ contributionCalendar{ weeks{ contributionDays{ date weekday contributionCount } } totalContributions } } } } """, } - output = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionCalendar" - ] + raw_data = get_template(query, access_token) + output = raw_data["data"]["user"]["contributionsCollection"]["contributionCalendar"] return RawCalendar.parse_obj(output) ===========changed ref 3=========== # module: backend.external.github_api.graphql.user def get_user_contribution_events( user_id: str, + access_token: str, start_date: datetime = datetime.now() - timedelta(365), end_date: datetime = datetime.now(), max_repos: int = 100, first: int = 100, after: str = "", ) -> RawEvents: """Fetches user contributions (commits, issues, prs, reviews)""" if (end_date - start_date).days > 365: raise ValueError("date range can be at most 1 year") query = { "variables": { "login": user_id, "startDate": start_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "endDate": end_date.strftime("%Y-%m-%dT%H:%M:%SZ"), "maxRepos": max_repos, "first": first, "after": after, }, "query": """ query getUser($login: String!, $startDate: DateTime!, $endDate: DateTime!, $maxRepos: Int!, $first: Int!, $after: String!) { user(login: $login){ contributionsCollection(from: $startDate, to: $endDate){ commitContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner, }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ commitCount, occurredAt, } pageInfo{ hasNextPage, endCursor } } } issueContributionsByRepository(maxRepositories: $maxRepos){ repository{ nameWithOwner }, totalCount:contributions(first: 1){ totalCount } contributions(first: $first, after: $after){ nodes{ occurredAt, } pageInfo{ hasNextPage, end</s>
backend.tests.external.github_api.graphql.test_template/TestTemplate.test_get_template
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<14>:<add> response = get_template(query, TOKEN) <del> response = get_template(query)
# module: backend.tests.external.github_api.graphql.test_template class TestTemplate(unittest.TestCase): def test_get_template(self): <0> query = { <1> "variables": {"login": "avgupta456"}, <2> "query": """ <3> query getUser($login: String!) { <4> user(login: $login){ <5> contributionsCollection{ <6> contributionCalendar{ <7> totalContributions <8> } <9> } <10> } <11> } <12> """, <13> } <14> response = get_template(query) <15> <16> self.assertIn("data", response) <17> data = response["data"] <18> self.assertIn("user", data) <19> user = data["user"] <20> self.assertIn("contributionsCollection", user) <21> contributionsCollection = user["contributionsCollection"] <22> self.assertIn("contributionCalendar", contributionsCollection) <23> contributionCalendar = contributionsCollection["contributionCalendar"] <24> self.assertIn("totalContributions", contributionCalendar) <25> totalContributions = contributionCalendar["totalContributions"] <26> self.assertGreater(totalContributions, 0) <27>
===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 7=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 8=========== # module: backend.processing.user.follows + def get_user_follows(user_id: str, access_token: str) -> UserFollows: - def get_user_follows(user_id: str) -> UserFollows: """get user followers and users following for given user""" followers: List[User] = [] following: List[User] = [] for user_list, get_func in zip( [followers, following], [_get_user_followers, _get_user_following] ): after: Optional[str] = "" index, cont = 0, True # initialize variables while cont and index < 10: after_str: str = after if isinstance(after, str) else "" + data = get_func(user_id, access_token, after=after_str) - data = get_func(user_id, after=after_str) cont = False user_list.extend( map( lambda x: User(name=x.name, login=x.login, url=x.url), data.nodes, ) ) if data.page_info.has_next_page: after = data.page_info.end_cursor cont = True index += 1 output = UserFollows(followers=followers, following=following) return output
backend.processing.commit/get_all_commit_info
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<7>:<add> access_token=access_token,
# module: backend.processing.commit def get_all_commit_info( user_id: str, + access_token: str, name_with_owner: str, start_date: datetime = datetime.now(), end_date: datetime = datetime.now(), ) -> List[datetime]: <0> """Gets all user's commit times for a given repository""" <1> owner, repo = name_with_owner.split("/") <2> data: List[Any] = [] <3> index = 0 <4> while index in range(10) and len(data) == 100 * index: <5> data.extend( <6> get_repo_commits( <7> owner=owner, <8> repo=repo, <9> user=user_id, <10> since=start_date, <11> until=end_date, <12> page=index + 1, <13> ) <14> ) <15> index += 1 <16> <17> data = list( <18> map( <19> lambda x: [ <20> datetime.strptime( <21> x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" <22> ), <23> x["node_id"], <24> ], <25> data, <26> ) <27> ) <28> <29> # sort ascending <30> data = sorted(data, key=lambda x: x[0]) <31> return data <32>
===========unchanged ref 0=========== at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S strptime(date_string: _Text, format: _Text) -> datetime __radd__ = __add__ at: external.github_api.rest.repo get_repo_commits(access_token: str, owner: str, repo: str, user: Optional[str]=None, since: Optional[datetime]=None, until: Optional[datetime]=None, page: int=1) -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 7=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_template class TestTemplate(unittest.TestCase): def test_get_template(self): query = { "variables": {"login": "avgupta456"}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions } } } } """, } + response = get_template(query, TOKEN) - response = get_template(query) self.assertIn("data", response) data = response["data"] self.assertIn("user", data) user = data["user"] self.assertIn("contributionsCollection", user) contributionsCollection = user["contributionsCollection"] self.assertIn("contributionCalendar", contributionsCollection) contributionCalendar = contributionsCollection["contributionCalendar"] self.assertIn("totalContributions", contributionCalendar) totalContributions = contributionCalendar["totalContributions"] self.assertGreater(totalContributions, 0)
backend.processing.commit/_get_commits_languages
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<6>:<add> raw_data = get_commits(access_token, node_ids[i:cutoff]) <del> raw_data = get_commits(node_ids[i:cutoff]) <12>:<add> all_data.extend(_get_commits_languages(access_token, curr)) <del> all_data.extend(_get_commits_languages(curr)) <17>:<add> all_data.extend( <add> _get_commits_languages(access_token, node_ids[i:midpoint]) <del> all_data.extend(_get_commits_languages(node_ids[i:midpoint])) <18>:<add> ) <add> all_data.extend( <add> _get_commits_languages(access_token, node_ids[midpoint:cutoff]) <del> all_data.extend(_get_commits_languages(node_ids[midpoint:cutoff])) <19>:<add> )
# module: backend.processing.commit def _get_commits_languages( + access_token: str, node_ids: List[str], per_page: int = NODE_CHUNK_SIZE - node_ids: List[str], per_page: int = NODE_CHUNK_SIZE ) -> List[Dict[str, Any]]: <0> all_data: List[Dict[str, Any]] = [] <1> for i in range(0, len(node_ids), per_page): <2> # TODO: alert user/display if some nodes omitted <3> # TODO: figure out why Auth error code appears <4> cutoff = min(len(node_ids), i + per_page) <5> try: <6> raw_data = get_commits(node_ids[i:cutoff]) <7> data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore <8> all_data.extend(data) <9> except GraphQLErrorMissingNode as e: <10> curr = node_ids[i:cutoff] <11> curr.pop(e.node) <12> all_data.extend(_get_commits_languages(curr)) <13> except GraphQLErrorTimeout: <14> length = cutoff - i <15> if length == per_page: <16> midpoint = i + int(per_page / 2) <17> all_data.extend(_get_commits_languages(node_ids[i:midpoint])) <18> all_data.extend(_get_commits_languages(node_ids[midpoint:cutoff])) <19> else: <20> print("Commit Timeout Exception:", length, " nodes lost") <21> all_data.extend([{} for _ in range(length)]) <22> except GraphQLErrorAuth: <23> length = cutoff - i <24> print("Commit Auth Exception:", length, " nodes lost") <25> all_data.extend([{} for _ in range(length)]) <26> <27> return all_data <28>
===========unchanged ref 0=========== at: constants NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100) at: external.github_api.graphql.commit get_commits(access_token: str, node_ids: List[str]) -> Union[Dict[str, Any], List[Any]] at: external.github_api.graphql.template GraphQLErrorMissingNode(node: int) GraphQLErrorTimeout(*args: object) at: external.github_api.graphql.template.GraphQLErrorMissingNode.__init__ self.node = node at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.processing.commit def get_all_commit_info( user_id: str, + access_token: str, name_with_owner: str, start_date: datetime = datetime.now(), end_date: datetime = datetime.now(), ) -> List[datetime]: """Gets all user's commit times for a given repository""" owner, repo = name_with_owner.split("/") data: List[Any] = [] index = 0 while index in range(10) and len(data) == 100 * index: data.extend( get_repo_commits( + access_token=access_token, owner=owner, repo=repo, user=user_id, since=start_date, until=end_date, page=index + 1, ) ) index += 1 data = list( map( lambda x: [ datetime.strptime( x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" ), x["node_id"], ], data, ) ) # sort ascending data = sorted(data, key=lambda x: x[0]) return data ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 8=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years
backend.processing.commit/get_commits_languages
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> all_data = _get_commits_languages(access_token, node_ids, per_page=NODE_CHUNK_SIZE) <del> all_data = _get_commits_languages(node_ids, per_page=NODE_CHUNK_SIZE)
# module: backend.processing.commit + def get_commits_languages(access_token: str, node_ids: List[str], cutoff: int = CUTOFF): - def get_commits_languages(node_ids: List[str], cutoff: int = CUTOFF): <0> all_data = _get_commits_languages(node_ids, per_page=NODE_CHUNK_SIZE) <1> <2> out: List[Dict[str, Dict[str, int]]] = [] <3> for commit in all_data: <4> out.append({}) <5> if ( <6> "additions" in commit <7> and "deletions" in commit <8> and "changedFiles" in commit <9> and commit["additions"] + commit["deletions"] < cutoff <10> ): <11> languages = [ <12> x <13> for x in commit["repository"]["languages"]["edges"] <14> if x["node"]["name"] not in BLACKLIST <15> ] <16> num_langs = min(len(languages), commit["changedFiles"]) <17> total_repo_size = sum( <18> [language["size"] for language in languages[:num_langs]] <19> ) <20> for language in languages[:num_langs]: <21> lang_name = language["node"]["name"] <22> additions = round( <23> commit["additions"] * language["size"] / total_repo_size <24> ) <25> deletions = round( <26> commit["deletions"] * language["size"] / total_repo_size <27> ) <28> if additions > 0 or deletions > 0: <29> out[-1][lang_name] = { <30> "additions": additions, <31> "deletions": deletions, <32> } <33> <34> return out <35>
===========unchanged ref 0=========== at: backend.processing.commit _get_commits_languages(access_token: str, node_ids: List[str], per_page: int=NODE_CHUNK_SIZE) -> List[Dict[str, Any]] at: backend.processing.commit._get_commits_languages all_data: List[Dict[str, Any]] = [] length = cutoff - i at: constants NODE_CHUNK_SIZE = 50 # number of nodes (commits) to query (max 100) BLACKLIST = ["Jupyter Notebook", "HTML"] # languages to ignore CUTOFF = 1000 # if > cutoff lines, assume imported, don't count at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.processing.commit def _get_commits_languages( + access_token: str, node_ids: List[str], per_page: int = NODE_CHUNK_SIZE - node_ids: List[str], per_page: int = NODE_CHUNK_SIZE ) -> List[Dict[str, Any]]: all_data: List[Dict[str, Any]] = [] for i in range(0, len(node_ids), per_page): # TODO: alert user/display if some nodes omitted # TODO: figure out why Auth error code appears cutoff = min(len(node_ids), i + per_page) try: + raw_data = get_commits(access_token, node_ids[i:cutoff]) - raw_data = get_commits(node_ids[i:cutoff]) data: List[Dict[str, Any]] = raw_data["data"]["nodes"] # type: ignore all_data.extend(data) except GraphQLErrorMissingNode as e: curr = node_ids[i:cutoff] curr.pop(e.node) + all_data.extend(_get_commits_languages(access_token, curr)) - all_data.extend(_get_commits_languages(curr)) except GraphQLErrorTimeout: length = cutoff - i if length == per_page: midpoint = i + int(per_page / 2) + all_data.extend( + _get_commits_languages(access_token, node_ids[i:midpoint]) - all_data.extend(_get_commits_languages(node_ids[i:midpoint])) + ) + all_data.extend( + _get_commits_languages(access_token, node_ids[midpoint:cutoff]) - all_data.extend(_get_commits_languages(node_ids[midpoint:cutoff])) + ) else: print("Commit Timeout Exception:", length, " nodes lost") all_data.extend([{} for _ in range(length)]) except GraphQLErrorAuth</s> ===========changed ref 1=========== # module: backend.processing.commit def _get_commits_languages( + access_token: str, node_ids: List[str], per_page: int = NODE_CHUNK_SIZE - node_ids: List[str], per_page: int = NODE_CHUNK_SIZE ) -> List[Dict[str, Any]]: # offset: 1 <s>, length, " nodes lost") all_data.extend([{} for _ in range(length)]) except GraphQLErrorAuth: length = cutoff - i print("Commit Auth Exception:", length, " nodes lost") all_data.extend([{} for _ in range(length)]) return all_data ===========changed ref 2=========== # module: backend.processing.commit def get_all_commit_info( user_id: str, + access_token: str, name_with_owner: str, start_date: datetime = datetime.now(), end_date: datetime = datetime.now(), ) -> List[datetime]: """Gets all user's commit times for a given repository""" owner, repo = name_with_owner.split("/") data: List[Any] = [] index = 0 while index in range(10) and len(data) == 100 * index: data.extend( get_repo_commits( + access_token=access_token, owner=owner, repo=repo, user=user_id, since=start_date, until=end_date, page=index + 1, ) ) index += 1 data = list( map( lambda x: [ datetime.strptime( x["commit"]["committer"]["date"], "%Y-%m-%dT%H:%M:%SZ" ), x["node_id"], ], data, ) ) # sort ascending data = sorted(data, key=lambda x: x[0]) return data ===========changed ref 3=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.external.github_api.rest.template/_get_template
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<5>:<add> "Authorization": "bearer " + access_token, <del> "Authorization": "bearer " + TOKEN,
# module: backend.external.github_api.rest.template + def _get_template( + query: str, params: Dict[str, Any], access_token: str, accept_header: str + ) -> Any: - def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: <0> """Internal template for interacting with the GitHub REST API""" <1> start = datetime.now() <2> <3> headers: Dict[str, str] = { <4> "Accept": str(accept_header), <5> "Authorization": "bearer " + TOKEN, <6> } <7> <8> try: <9> r = s.get(query, params=params, headers=headers, timeout=TIMEOUT) <10> except ReadTimeout: <11> raise RESTErrorTimeout("REST Error: Request Timeout") <12> <13> if r.status_code == 200: <14> print("REST API", datetime.now() - start) <15> return r.json() # type: ignore <16> <17> if r.status_code == 409: <18> raise RESTErrorEmptyRepo("REST Error: Empty Repository") <19> <20> raise RESTError("REST Error: " + str(r.status_code)) <21>
===========unchanged ref 0=========== at: backend.external.github_api.rest.template s = requests.session() RESTErrorEmptyRepo(*args: object) RESTErrorTimeout(*args: object) at: constants TIMEOUT = 3 # max seconds to wait for api response at: datetime datetime() at: datetime.datetime __slots__ = date.__slots__ + time.__slots__ now(tz: Optional[_tzinfo]=...) -> _S __radd__ = __add__ at: requests.exceptions ReadTimeout(*args, **kwargs) at: requests.models.Response __attrs__ = [ "_content", "status_code", "headers", "url", "history", "encoding", "reason", "cookies", "elapsed", "request", ] json(**kwargs) -> Any at: requests.models.Response.__init__ self.status_code = None at: requests.sessions.Session __attrs__ = [ "headers", "cookies", "auth", "proxies", "hooks", "params", "verify", "cert", "adapters", "stream", "trust_env", "max_redirects", ] get(url: Union[Text, bytes], **kwargs) -> Response at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 7=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_template class TestTemplate(unittest.TestCase): def test_get_template(self): query = { "variables": {"login": "avgupta456"}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions } } } } """, } + response = get_template(query, TOKEN) - response = get_template(query) self.assertIn("data", response) data = response["data"] self.assertIn("user", data) user = data["user"] self.assertIn("contributionsCollection", user) contributionsCollection = user["contributionsCollection"] self.assertIn("contributionCalendar", contributionsCollection) contributionCalendar = contributionsCollection["contributionCalendar"] self.assertIn("totalContributions", contributionCalendar) totalContributions = contributionCalendar["totalContributions"] self.assertGreater(totalContributions, 0)
backend.external.github_api.rest.template/get_template
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<3>:<add> return _get_template(query, {}, access_token, accept_header) <del> return _get_template(query, {}, accept_header)
# module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: <0> """Template for interacting with the GitHub REST API (singular)""" <1> <2> try: <3> return _get_template(query, {}, accept_header) <4> except Exception as e: <5> raise e <6>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.template + def _get_template( + query: str, params: Dict[str, Any], access_token: str, accept_header: str + ) -> Any: - def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: """Internal template for interacting with the GitHub REST API""" start = datetime.now() headers: Dict[str, str] = { "Accept": str(accept_header), + "Authorization": "bearer " + access_token, - "Authorization": "bearer " + TOKEN, } try: r = s.get(query, params=params, headers=headers, timeout=TIMEOUT) except ReadTimeout: raise RESTErrorTimeout("REST Error: Request Timeout") if r.status_code == 200: print("REST API", datetime.now() - start) return r.json() # type: ignore if r.status_code == 409: raise RESTErrorEmptyRepo("REST Error: Empty Repository") raise RESTError("REST Error: " + str(r.status_code)) ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 8=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_template class TestTemplate(unittest.TestCase): def test_get_template(self): query = { "variables": {"login": "avgupta456"}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionCalendar{ totalContributions } } } } """, } + response = get_template(query, TOKEN) - response = get_template(query) self.assertIn("data", response) data = response["data"] self.assertIn("user", data) user = data["user"] self.assertIn("contributionsCollection", user) contributionsCollection = user["contributionsCollection"] self.assertIn("contributionCalendar", contributionsCollection) contributionCalendar = contributionsCollection["contributionCalendar"] self.assertIn("totalContributions", contributionCalendar) totalContributions = contributionCalendar["totalContributions"] self.assertGreater(totalContributions, 0)
backend.external.github_api.rest.template/get_template_plural
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<3>:<add> return _get_template(query, params, access_token, accept_header) <del> return _get_template(query, params, accept_header)
# module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: <0> """Template for interacting with the GitHub REST API (plural)""" <1> params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} <2> try: <3> return _get_template(query, params, accept_header) <4> except Exception as e: <5> raise e <6>
===========unchanged ref 0=========== at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 1=========== # module: backend.external.github_api.rest.template + def _get_template( + query: str, params: Dict[str, Any], access_token: str, accept_header: str + ) -> Any: - def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: """Internal template for interacting with the GitHub REST API""" start = datetime.now() headers: Dict[str, str] = { "Accept": str(accept_header), + "Authorization": "bearer " + access_token, - "Authorization": "bearer " + TOKEN, } try: r = s.get(query, params=params, headers=headers, timeout=TIMEOUT) except ReadTimeout: raise RESTErrorTimeout("REST Error: Request Timeout") if r.status_code == 200: print("REST API", datetime.now() - start) return r.json() # type: ignore if r.status_code == 409: raise RESTErrorEmptyRepo("REST Error: Empty Repository") raise RESTError("REST Error: " + str(r.status_code)) ===========changed ref 2=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 8=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 9=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years
backend.external.github_api.graphql.repo/get_repo
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<38>:<add> return get_template(query, access_token) <del> return get_template(query)
# module: backend.external.github_api.graphql.repo + def get_repo( + access_token: str, owner: str, repo: str + ) -> Union[Dict[str, Any], List[Any]]: - def get_repo(owner: str, repo: str) -> Union[Dict[str, Any], List[Any]]: <0> """gets all repository data from graphql""" <1> query = { <2> "variables": {"owner": owner, "repo": repo}, <3> "query": """ <4> query getRepo($owner: String!, $repo: String!) { <5> repository(owner: $owner, name: $repo) { <6> createdAt, <7> updatedAt, <8> forkCount, <9> forks(first: 10){ <10> nodes{ <11> createdAt, <12> }, <13> }, <14> stargazerCount, <15> stargazers(first: 10){ <16> nodes{ <17> createdAt, <18> }, <19> }, <20> primaryLanguage{ <21> name <22> }, <23> languages(first: 5){ <24> totalCount, <25> totalSize, <26> edges{ <27> node { <28> name, <29> }, <30> size, <31> }, <32> }, <33> } <34> } <35> """, <36> } <37> <38> return get_template(query) <39>
===========unchanged ref 0=========== at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 5=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 8=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 9=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years ===========changed ref 10=========== # module: backend.external.github_api.rest.template + def _get_template( + query: str, params: Dict[str, Any], access_token: str, accept_header: str + ) -> Any: - def _get_template(query: str, params: Dict[str, Any], accept_header: str) -> Any: """Internal template for interacting with the GitHub REST API""" start = datetime.now() headers: Dict[str, str] = { "Accept": str(accept_header), + "Authorization": "bearer " + access_token, - "Authorization": "bearer " + TOKEN, } try: r = s.get(query, params=params, headers=headers, timeout=TIMEOUT) except ReadTimeout: raise RESTErrorTimeout("REST Error: Request Timeout") if r.status_code == 200: print("REST API", datetime.now() - start) return r.json() # type: ignore if r.status_code == 409: raise RESTErrorEmptyRepo("REST Error: Empty Repository") raise RESTError("REST Error: " + str(r.status_code))
backend.external.github_api.rest.user/get_user
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template(BASE_URL + user_id, access_token) <del> return get_template(BASE_URL + user_id)
# module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: <0> """Returns raw user data""" <1> return get_template(BASE_URL + user_id) <2>
===========unchanged ref 0=========== at: backend.external.github_api.rest.user BASE_URL = "https://api.github.com/users/" at: external.github_api.rest.template get_template(query: str, access_token: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 1=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 2=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 5=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 8=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 9=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years
backend.external.github_api.rest.user/get_user_starred_repos
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<3>:<add> access_token,
# module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: <0> """Returns list of starred repos""" <1> return get_template_plural( <2> BASE_URL + user_id + "/starred", <3> per_page=per_page, <4> accept_header="application/vnd.github.v3.star+json", <5> ) <6>
===========unchanged ref 0=========== at: backend.external.github_api.rest.user BASE_URL = "https://api.github.com/users/" at: external.github_api.rest.template get_template_plural(query: str, access_token: str, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 6=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 9=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 10=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years
backend.tests.processing.user.test_follows/TestTemplate.test_get_contributions
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<0>:<add> response = get_user_follows("avgupta456", TOKEN) <del> response = get_user_follows("avgupta456")
# module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): <0> response = get_user_follows("avgupta456") <1> self.assertIsInstance(response, UserFollows) <2>
===========changed ref 0=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 3=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 5=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 7=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 10=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1]) ===========changed ref 11=========== # module: backend.external.github_api.graphql.user + def get_user_contribution_years(user_id: str, access_token: str) -> List[int]: - def get_user_contribution_years(user_id: str) -> List[int]: """Gets years where the user had activity""" query = { "variables": {"login": user_id}, "query": """ query getUser($login: String!) { user(login: $login){ contributionsCollection{ contributionYears } } } """, } - years = get_template(query)["data"]["user"]["contributionsCollection"][ - "contributionYears" - ] - + raw_data = get_template(query, access_token) + years = raw_data["data"]["user"]["contributionsCollection"]["contributionYears"] return years
backend.external.github_api.rest.repo/get_repo
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template(BASE_URL + owner + "/" + repo, access_token) <del> return get_template(BASE_URL + owner + "/" + repo)
# module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns raw repository data""" <1> return get_template(BASE_URL + owner + "/" + repo) <2>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: external.github_api.rest.template get_template(query: str, access_token: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 1=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 2=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 3=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 4=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 6=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 8=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 10=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 11=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1])
backend.external.github_api.rest.repo/get_repo_languages
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template_plural( <add> BASE_URL + owner + "/" + repo + "/languages", access_token <add> ) <del> return get_template_plural(BASE_URL + owner + "/" + repo + "/languages")
# module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: <0> """Returns repository language breakdown""" <1> return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") <2>
===========unchanged ref 0=========== at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 1=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 2=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 3=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 4=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 5=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 7=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 9=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 10=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 11=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 12=========== # module: backend.packaging.user def main( user_id: str, + access_token: str, start_date: date = date.today() - timedelta(365), end_date: date = date.today(), timezone_str: str = "US/Eastern", ) -> UserPackage: """packages all processing steps for the user query""" data = gather( funcs=[get_contributions, get_user_follows], args_dicts=[ { "user_id": user_id, + "access_token": access_token, "start_date": start_date, "end_date": end_date, "timezone_str": timezone_str, }, + {"user_id": user_id, "access_token": access_token}, - {"user_id": user_id}, ], ) return UserPackage(contribs=data[0], follows=data[1])
backend.external.github_api.rest.repo/get_repo_stargazers
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<3>:<add> access_token,
# module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: <0> """Returns stargazers with timestamp for repository""" <1> return get_template_plural( <2> BASE_URL + owner + "/" + repo + "/stargazers", <3> per_page=per_page, <4> accept_header="applicaiton/vnd.github.v3.star+json", <5> ) <6>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: external.github_api.rest.template get_template_plural(query: str, access_token: str, per_page: int=100, page: int=1, accept_header: str="application/vnd.github.v3+json") -> List[Dict[str, Any]] at: typing List = _alias(list, 1, inst=False, name='List') Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 2=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 3=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 4=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 5=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 6=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 8=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 10=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 11=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 12=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.external.github_api.rest.repo/get_repo_code_frequency
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template( <add> BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token <del> return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") <2>:<add> )
# module: backend.external.github_api.rest.repo # does not accept per page, exceeds if necessary + def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns code frequency for repository""" <1> return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") <2>
===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 2=========== # module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: """Returns stargazers with timestamp for repository""" return get_template_plural( BASE_URL + owner + "/" + repo + "/stargazers", + access_token, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 3=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 4=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 5=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 6=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 7=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 9=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 10=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 11=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 12=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1) ===========changed ref 13=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): # TODO: Add more validation here def test_get_user_followers(self): + response = get_user_followers(user_id="avgupta456", access_token=TOKEN) - response = get_user_followers(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_followers(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_followers(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.external.github_api.rest.repo/get_repo_commit_activity
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template( <add> BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token <del> return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity") <2>:<add> )
# module: backend.external.github_api.rest.repo + def get_repo_commit_activity( + access_token: str, owner: str, repo: str + ) -> Dict[str, Any]: - def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns commit activity for past year, broken by week""" <1> return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity") <2>
===========unchanged ref 0=========== at: external.github_api.rest.template get_template(query: str, access_token: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any] at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo # does not accept per page, exceeds if necessary + def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]: """Returns code frequency for repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") + ) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 3=========== # module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: """Returns stargazers with timestamp for repository""" return get_template_plural( BASE_URL + owner + "/" + repo + "/stargazers", + access_token, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 4=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 5=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 6=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 7=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 8=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 10=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 11=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 12=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e ===========changed ref 13=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_following(self): + response = get_user_following(user_id="avgupta456", access_token=TOKEN) - response = get_user_following(user_id="avgupta456") self.assertIsInstance(response, RawFollows) + response = get_user_following(user_id="avgupta456", access_token=TOKEN, first=1) - response = get_user_following(user_id="avgupta456", first=1) self.assertLessEqual(len(response.nodes), 1)
backend.external.github_api.rest.repo/get_repo_contributors
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template( <add> BASE_URL + owner + "/" + repo + "/stats/contributors", access_token <del> return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors") <2>:<add> )
# module: backend.external.github_api.rest.repo + def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns contributors for a repository""" <1> return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors") <2>
===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_commit_activity( + access_token: str, owner: str, repo: str + ) -> Dict[str, Any]: - def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]: """Returns commit activity for past year, broken by week""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity") + ) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo # does not accept per page, exceeds if necessary + def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]: """Returns code frequency for repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") + ) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 3=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 4=========== # module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: """Returns stargazers with timestamp for repository""" return get_template_plural( BASE_URL + owner + "/" + repo + "/stargazers", + access_token, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 5=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 6=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 7=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 8=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 9=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 10=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 11=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 12=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list) ===========changed ref 13=========== # module: backend.external.github_api.rest.template def get_template_plural( query: str, + access_token: str, per_page: int = 100, page: int = 1, accept_header: str = "application/vnd.github.v3+json", ) -> List[Dict[str, Any]]: """Template for interacting with the GitHub REST API (plural)""" params: Dict[str, str] = {"per_page": str(per_page), "page": str(page)} try: + return _get_template(query, params, access_token, accept_header) - return _get_template(query, params, accept_header) except Exception as e: raise e
backend.external.github_api.rest.repo/get_repo_weekly_commits
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template( <add> BASE_URL + owner + "/" + repo + "/stats/participation", access_token <del> return get_template(BASE_URL + owner + "/" + repo + "/stats/participation") <2>:<add> )
# module: backend.external.github_api.rest.repo + def get_repo_weekly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_weekly_commits(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns contributions by week, owner/non-owner""" <1> return get_template(BASE_URL + owner + "/" + repo + "/stats/participation") <2>
===========unchanged ref 0=========== at: backend.external.github_api.rest.repo BASE_URL = "https://api.github.com/repos/" at: external.github_api.rest.template get_template(query: str, access_token: str, accept_header: str="application/vnd.github.v3+json") -> Dict[str, Any] ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]: """Returns contributors for a repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/contributors", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors") + ) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_commit_activity( + access_token: str, owner: str, repo: str + ) -> Dict[str, Any]: - def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]: """Returns commit activity for past year, broken by week""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity") + ) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo # does not accept per page, exceeds if necessary + def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]: """Returns code frequency for repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") + ) ===========changed ref 3=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 4=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 5=========== # module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: """Returns stargazers with timestamp for repository""" return get_template_plural( BASE_URL + owner + "/" + repo + "/stargazers", + access_token, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 6=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 7=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 8=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 9=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 10=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 11=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 12=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 13=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list)
backend.external.github_api.rest.repo/get_repo_hourly_commits
Modified
avgupta456~github-trends
b720f9b077adb8a7457621406db08b85792414fa
propagate access_token
<1>:<add> return get_template( <add> BASE_URL + owner + "/" + repo + "/stats/punch_card", access_token <del> return get_template(BASE_URL + owner + "/" + repo + "/stats/punch_card") <2>:<add> )
# module: backend.external.github_api.rest.repo + def get_repo_hourly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_hourly_commits(owner: str, repo: str) -> Dict[str, Any]: <0> """Returns contributions by day, hour for repository""" <1> return get_template(BASE_URL + owner + "/" + repo + "/stats/punch_card") <2>
===========unchanged ref 0=========== at: typing Dict = _alias(dict, 2, inst=False, name='Dict') ===========changed ref 0=========== # module: backend.external.github_api.rest.repo + def get_repo_contributors(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_contributors(owner: str, repo: str) -> Dict[str, Any]: """Returns contributors for a repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/contributors", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/contributors") + ) ===========changed ref 1=========== # module: backend.external.github_api.rest.repo + def get_repo_weekly_commits(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_weekly_commits(owner: str, repo: str) -> Dict[str, Any]: """Returns contributions by week, owner/non-owner""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/participation", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/participation") + ) ===========changed ref 2=========== # module: backend.external.github_api.rest.repo + def get_repo_commit_activity( + access_token: str, owner: str, repo: str + ) -> Dict[str, Any]: - def get_repo_commit_activity(owner: str, repo: str) -> Dict[str, Any]: """Returns commit activity for past year, broken by week""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/commit_activity", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/commit_activity") + ) ===========changed ref 3=========== # module: backend.external.github_api.rest.repo # does not accept per page, exceeds if necessary + def get_repo_code_frequency(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo_code_frequency(owner: str, repo: str) -> Dict[str, Any]: """Returns code frequency for repository""" + return get_template( + BASE_URL + owner + "/" + repo + "/stats/code_frequency", access_token - return get_template(BASE_URL + owner + "/" + repo + "/stats/code_frequency") + ) ===========changed ref 4=========== # module: backend.external.github_api.rest.repo + def get_repo(access_token: str, owner: str, repo: str) -> Dict[str, Any]: - def get_repo(owner: str, repo: str) -> Dict[str, Any]: """Returns raw repository data""" + return get_template(BASE_URL + owner + "/" + repo, access_token) - return get_template(BASE_URL + owner + "/" + repo) ===========changed ref 5=========== # module: backend.external.github_api.rest.repo + def get_repo_languages( + access_token: str, owner: str, repo: str + ) -> List[Dict[str, Any]]: - def get_repo_languages(owner: str, repo: str) -> List[Dict[str, Any]]: """Returns repository language breakdown""" + return get_template_plural( + BASE_URL + owner + "/" + repo + "/languages", access_token + ) - return get_template_plural(BASE_URL + owner + "/" + repo + "/languages") ===========changed ref 6=========== # module: backend.external.github_api.rest.repo def get_repo_stargazers( + access_token: str, owner: str, repo: str, per_page: int = 100 - owner: str, repo: str, per_page: int = 100 ) -> List[Dict[str, Any]]: """Returns stargazers with timestamp for repository""" return get_template_plural( BASE_URL + owner + "/" + repo + "/stargazers", + access_token, per_page=per_page, accept_header="applicaiton/vnd.github.v3.star+json", ) ===========changed ref 7=========== # module: backend.external.github_api.rest.user + def get_user(user_id: str, access_token: str) -> Dict[str, Any]: - def get_user(user_id: str) -> Dict[str, Any]: """Returns raw user data""" + return get_template(BASE_URL + user_id, access_token) - return get_template(BASE_URL + user_id) ===========changed ref 8=========== # module: backend.tests.processing.user.test_contributions class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_contributions("avgupta456", TOKEN) - response = get_contributions("avgupta456") self.assertIsInstance(response, UserContributions) ===========changed ref 9=========== # module: backend.tests.processing.user.test_follows class TestTemplate(unittest.TestCase): def test_get_contributions(self): + response = get_user_follows("avgupta456", TOKEN) - response = get_user_follows("avgupta456") self.assertIsInstance(response, UserFollows) ===========changed ref 10=========== # module: backend.external.github_api.rest.template def get_template( query: str, + access_token: str, accept_header: str = "application/vnd.github.v3+json", ) -> Dict[str, Any]: """Template for interacting with the GitHub REST API (singular)""" try: + return _get_template(query, {}, access_token, accept_header) - return _get_template(query, {}, accept_header) except Exception as e: raise e ===========changed ref 11=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_events(self): + response = get_user_contribution_events( - response = get_user_contribution_events(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawEvents) ===========changed ref 12=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_calendar(self): + response = get_user_contribution_calendar( - response = get_user_contribution_calendar(user_id="avgupta456") + user_id="avgupta456", access_token=TOKEN + ) self.assertIsInstance(response, RawCalendar) ===========changed ref 13=========== # module: backend.external.github_api.rest.user + def get_user_starred_repos( + user_id: str, access_token: str, per_page: int = 100 + ) -> List[Dict[str, Any]]: - def get_user_starred_repos(user_id: str, per_page: int = 100) -> List[Dict[str, Any]]: """Returns list of starred repos""" return get_template_plural( BASE_URL + user_id + "/starred", + access_token, per_page=per_page, accept_header="application/vnd.github.v3.star+json", ) ===========changed ref 14=========== # module: backend.tests.external.github_api.graphql.test_user class TestTemplate(unittest.TestCase): def test_get_user_contribution_years(self): + response = get_user_contribution_years(user_id="avgupta456", access_token=TOKEN) - response = get_user_contribution_years(user_id="avgupta456") # aside from validating APIResponse class, pydantic will validate tree self.assertIsInstance(response, list)