Skip to content

Commit 60214b9

Browse files
committed
Fix: refactor github methods out of contributor mod
1 parent a0cfaa8 commit 60214b9

File tree

5 files changed

+86
-41
lines changed

5 files changed

+86
-41
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,9 @@
99
- Fix: Rename and organize `clean.py` module into `utils_parse` and `utils_clean` (@lwasser, @willingc, #121)
1010
- Fix: Add tests for all utils functions (@lwasser, #122)
1111
- Fix: Bug where date_accepted is removed (@lwasser, #129)
12-
- Fix: Refactor all GitHub related methods move to gh_client module (@lwasser, #125)
12+
- Fix: Refactor all issue related GitHub methods to gh_client module (@lwasser, #125)
1313
- Add: support for partners and emeritus_editor in contributor model (@lwasser, #133)
14+
- Fix: Refactor all contributor GitHub related methods into gh_client module from contributors module (@lwasser, #125)
1415

1516

1617
## [v0.2.3] - 2024-02-29

src/pyosmeta/cli/update_contributors.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
from pyosmeta.contributors import ProcessContributors
88
from pyosmeta.file_io import create_paths, load_pickle, open_yml_file
9+
from pyosmeta.github_api import GitHubAPI
910
from pyosmeta.models import PersonModel
1011

1112
# TODO - https://stackoverflow.com
@@ -62,7 +63,8 @@ def main():
6263
print("Done processing all-contribs")
6364

6465
# Create a list of all contributors across repositories
65-
process_contribs = ProcessContributors(json_files)
66+
github_api = GitHubAPI()
67+
process_contribs = ProcessContributors(github_api, json_files)
6668
bot_all_contribs = process_contribs.combine_json_data()
6769

6870
print("Updating contrib types and searching for new users now")
@@ -71,7 +73,7 @@ def main():
7173
# Find and populate data for any new contributors
7274
if gh_user not in all_contribs.keys():
7375
print("Missing", gh_user, "Adding them now")
74-
new_contrib = process_contribs.get_user_info(gh_user)
76+
new_contrib = process_contribs.return_user_info(gh_user)
7577
new_contrib["date_added"] = datetime.now().strftime("%Y-%m-%d")
7678
all_contribs[gh_user] = PersonModel(**new_contrib)
7779

@@ -81,7 +83,7 @@ def main():
8183
if update_all:
8284
for user in all_contribs.keys():
8385
print("Updating all user info from github", user)
84-
new_gh_data = process_contribs.get_user_info(user)
86+
new_gh_data = process_contribs.return_user_info(user)
8587

8688
# TODO: turn this into a small update method
8789
existing = all_contribs[user].model_dump()

src/pyosmeta/contributors.py

Lines changed: 31 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,29 @@
11
import json
2-
import os
32

43
import requests
54
from dataclasses import dataclass
6-
from dotenv import load_dotenv
7-
from typing import List, Optional, Tuple
5+
from typing import Any, List, Optional, Tuple
6+
7+
from .github_api import GitHubAPI
88

99

1010
@dataclass
1111
class ProcessContributors:
1212
"""A class that contains some basic methods to support populating and
1313
updating contributor data."""
1414

15-
def __init__(self, json_files: List) -> None:
15+
def __init__(self, github_api: GitHubAPI, json_files: List) -> None:
1616
"""
1717
Parameters
1818
----------
19-
19+
github_api : str
20+
Instantiated instance of a GitHubAPI object
2021
json_files : list
2122
A list of string objects each of which represents a URL to a JSON
2223
file to be parsed
23-
GITHUB_TOKEN : str
24-
A string containing your API token needed to access the github API
2524
"""
2625

26+
self.github_api = github_api
2727
self.json_files = json_files
2828
# self.GITHUB_TOKEN = GITHUB_TOKEN
2929
self.update_keys = [
@@ -52,17 +52,18 @@ def __init__(self, json_files: List) -> None:
5252
],
5353
}
5454

55-
def get_token(self) -> str:
56-
"""Fetches the GitHub API key from the users environment. If running
57-
local from an .env file.
55+
# This is already in the github api module
56+
# def get_token(self) -> str:
57+
# """Fetches the GitHub API key from the users environment. If running
58+
# local from an .env file.
5859

59-
Returns
60-
-------
61-
str
62-
The provided API key in the .env file.
63-
"""
64-
load_dotenv()
65-
return os.environ["GITHUB_TOKEN"]
60+
# Returns
61+
# -------
62+
# str
63+
# The provided API key in the .env file.
64+
# """
65+
# load_dotenv()
66+
# return os.environ["GITHUB_TOKEN"]
6667

6768
def check_contrib_type(self, json_file: str):
6869
"""
@@ -94,6 +95,7 @@ def check_contrib_type(self, json_file: str):
9495
contrib_type = "community"
9596
return contrib_type
9697

98+
# Possibly github it is a get request but it says json path
9799
def load_json(self, json_path: str) -> dict:
98100
"""
99101
Helper function that deserializes a json file to a dict.
@@ -153,19 +155,19 @@ def combine_json_data(self) -> dict:
153155
print("Oops - can't process", json_file, e)
154156
return combined_data
155157

156-
def get_user_info(
157-
self, username: str, aname: Optional[str] = None
158-
) -> dict:
158+
def return_user_info(
159+
self, gh_handle: str, name: Optional[str] = None
160+
) -> dict[str, Any]:
159161
"""
160162
Get a single user's information from their GitHub username using the
161163
GitHub API
162164
# https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-the-authenticated-user
163165
164166
Parameters
165167
----------
166-
username : string
168+
gh_handle : string
167169
Github username to retrieve data for
168-
aname : str default=None
170+
name : str default=None
169171
A user's name from the contributors.yml file.
170172
https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-a-user
171173
@@ -174,12 +176,13 @@ def get_user_info(
174176
Dict with updated user data grabbed from the GH API
175177
"""
176178

177-
url = f"https://api.github.com/users/{username}"
178-
headers = {"Authorization": f"Bearer {self.get_token()}"}
179-
response = requests.get(url, headers=headers)
180-
# TODO: add check here for if credentials are bad
181-
# if message = Bad credentials
182-
response_json = response.json()
179+
response_json = self.github_api.get_user_info(gh_handle, name)
180+
# url = f"https://api.github.com/users/{username}"
181+
# headers = {"Authorization": f"Bearer {self.get_token()}"}
182+
# response = requests.get(url, headers=headers)
183+
# # TODO: add check here for if credentials are bad
184+
# # if message = Bad credentials
185+
# response_json = response.json()
183186

184187
# TODO: make an attribute and call it here?
185188
update_keys = {

src/pyosmeta/file_io.py

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,16 +29,24 @@ def _list_to_dict(a_list: List, a_key: str) -> Dict:
2929

3030

3131
def create_paths(repos: Union[list[str], str]) -> Union[list[str], str]:
32-
""" """
32+
"""Construct URLs for .all-contributorsrc file on GitHub for pyos repos.
33+
34+
We add new contributors to each repo using the all contributors bot. This
35+
generates urls for all of the files across all of our repos where people
36+
contribute to our content and processes.
37+
38+
Parameters:
39+
----------
40+
repos : Union[List[str], str]
41+
A list of GitHub repository names or a single repository name.
42+
43+
Returns:
44+
-------
45+
Union[List[str], str]
46+
A list of URLs if `repos` is a list, or a single URL if `repos` is a string.
47+
"""
3348
base_url = "https://raw.githubusercontent.com/pyOpenSci/"
3449
end_url = "/main/.all-contributorsrc"
35-
repos = [
36-
"python-package-guide",
37-
"software-peer-review",
38-
"pyopensci.github.io",
39-
"software-review",
40-
"update-web-metadata",
41-
]
4250
if isinstance(repos, list):
4351
all_paths = [base_url + repo + end_url for repo in repos]
4452
else:

src/pyosmeta/github_api.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import requests
1616
from dataclasses import dataclass
1717
from dotenv import load_dotenv
18-
from typing import Any
18+
from typing import Any, Optional, Union
1919

2020

2121
@dataclass
@@ -224,3 +224,34 @@ def get_last_commit(self, repo: str) -> str:
224224
date = response[0]["commit"]["author"]["date"]
225225

226226
return date
227+
228+
def get_user_info(
229+
self, gh_handle: str, name: Optional[str] = None
230+
) -> dict[str, Union[str, Any]]:
231+
"""
232+
Get a single user's information from their GitHub username using the
233+
GitHub API
234+
# https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-the-authenticated-user
235+
236+
Parameters
237+
----------
238+
gh_handle : string
239+
Github username to retrieve data for
240+
name : str default=None
241+
A user's name from the contributors.yml file.
242+
https://docs.github.com/en/rest/users/users?apiVersion=2022-11-28#get-a-user
243+
244+
Returns
245+
-------
246+
Dict with updated user data grabbed from the GH API
247+
"""
248+
249+
url = f"https://api.github.com/users/{gh_handle}"
250+
headers = {"Authorization": f"Bearer {self.get_token()}"}
251+
response = requests.get(url, headers=headers)
252+
253+
if response.status_code == 401:
254+
raise ValueError(
255+
"Bad credentials. Please check your authentication token."
256+
)
257+
return response.json()

0 commit comments

Comments
 (0)