Skip to content

Commit 9af8603

Browse files
committed
✨If token is not specified, try to get it from netrc file
1 parent 4b8cf95 commit 9af8603

File tree

1 file changed

+18
-3
lines changed

1 file changed

+18
-3
lines changed

cramer/main.py

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
from dataclasses import dataclass
2+
from netrc import netrc
23
import os
4+
from pathlib import Path
5+
import platform
36
from typing import List, Set
47

58
import click
@@ -74,14 +77,26 @@ def crame(g: Github, pr_id: int, repo_name_or_id: str | int, depth: int = 200) -
7477
)
7578

7679

80+
def read_token_from_netrc_file() -> Auth.Token | None:
81+
filename = ".netrc" if platform.system == "Windows" else "_netrc"
82+
netrc_path = Path.home() / filename
83+
if netrc_path.exists():
84+
for machine, auth_data in netrc(netrc_path).hosts.items():
85+
if machine == 'github.com':
86+
print(auth_data)
87+
_, _, token = auth_data
88+
return Auth.Token(token)
89+
return None
90+
91+
7792
def deduce_token() -> Auth.Token | None:
7893
"""
7994
If the token was not specified, look for the env variable GITHUB_TOKEN
95+
or the file ~/.netrc (~/_netrc on windows) with a machine named 'github.com'
8096
"""
8197
token = os.environ.get("GITHUB_TOKEN")
82-
if token:
83-
return Auth.Token(token)
84-
return None
98+
return Auth.Token(token) if token else read_token_from_netrc_file()
99+
85100

86101
@click.command()
87102
@click.option("--repo", "-r", required=True, type=str, help="Github repository. Example: 'Baduit/Cramer'")

0 commit comments

Comments
 (0)