Skip to content

Commit c9d7865

Browse files
Use proper logging in auth module (#2604)
* use proper logging in auth module * update command docstring * change logging severity message from info -> warning
1 parent 8cb81ac commit c9d7865

File tree

3 files changed

+53
-25
lines changed

3 files changed

+53
-25
lines changed

src/huggingface_hub/_login.py

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515

1616
import os
1717
import subprocess
18-
import warnings
1918
from functools import partial
2019
from getpass import getpass
2120
from pathlib import Path
@@ -111,7 +110,7 @@ def login(
111110
"""
112111
if token is not None:
113112
if not add_to_git_credential:
114-
print(
113+
logger.info(
115114
"The token has not been saved to the git credentials helper. Pass "
116115
"`add_to_git_credential=True` in this function directly or "
117116
"`--add-to-git-credential` if using via `huggingface-cli` if "
@@ -137,7 +136,7 @@ def logout(token_name: Optional[str] = None) -> None:
137136
If the access token name is not found.
138137
"""
139138
if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens
140-
print("Not logged in!")
139+
logger.warning("Not logged in!")
141140
return
142141
if not token_name:
143142
# Delete all saved access tokens and token
@@ -146,10 +145,10 @@ def logout(token_name: Optional[str] = None) -> None:
146145
Path(file_path).unlink()
147146
except FileNotFoundError:
148147
pass
149-
print("Successfully logged out from all access tokens.")
148+
logger.info("Successfully logged out from all access tokens.")
150149
else:
151150
_logout_from_token(token_name)
152-
print(f"Successfully logged out from access token: {token_name}.")
151+
logger.info(f"Successfully logged out from access token: {token_name}.")
153152

154153
unset_git_credential()
155154

@@ -187,10 +186,10 @@ def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None:
187186
raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
188187
# Write token to HF_TOKEN_PATH
189188
_set_active_token(token_name, add_to_git_credential)
190-
print(f"The current active token is: {token_name}")
189+
logger.info(f"The current active token is: {token_name}")
191190
token_from_environment = _get_token_from_environment()
192191
if token_from_environment is not None and token_from_environment != token:
193-
warnings.warn(
192+
logger.warning(
194193
"The environment variable `HF_TOKEN` is set and will override the access token you've just switched to."
195194
)
196195

@@ -200,7 +199,7 @@ def auth_list() -> None:
200199
tokens = get_stored_tokens()
201200

202201
if not tokens:
203-
print("No access tokens found.")
202+
logger.info("No access tokens found.")
204203
return
205204
# Find current token
206205
current_token = get_token()
@@ -222,11 +221,11 @@ def auth_list() -> None:
222221
print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token))
223222

224223
if _get_token_from_environment():
225-
print(
224+
logger.warning(
226225
"\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above."
227226
)
228227
elif current_token_name is None:
229-
print(
228+
logger.warning(
230229
"\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `huggingface-cli login` to log in."
231230
)
232231

@@ -254,23 +253,25 @@ def interpreter_login(new_session: bool = True, write_permission: bool = False)
254253
255254
"""
256255
if not new_session and _current_token_okay(write_permission=write_permission):
257-
print("User is already logged in.")
256+
logger.info("User is already logged in.")
258257
return
259258

260259
from .commands.delete_cache import _ask_for_confirmation_no_tui
261260

262261
print(_HF_LOGO_ASCII)
263262
if get_token() is not None:
264-
print(
263+
logger.info(
265264
" A token is already saved on your machine. Run `huggingface-cli"
266265
" whoami` to get more information or `huggingface-cli logout` if you want"
267266
" to log out."
268267
)
269-
print(" Setting a new token will erase the existing one.")
268+
logger.info(" Setting a new token will erase the existing one.")
270269

271-
print(" To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .")
270+
logger.info(
271+
" To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ."
272+
)
272273
if os.name == "nt":
273-
print("Token can be pasted using 'Right-Click'.")
274+
logger.info("Token can be pasted using 'Right-Click'.")
274275
token = getpass("Enter your token (input will not be visible): ")
275276
add_to_git_credential = _ask_for_confirmation_no_tui("Add token as git credential?")
276277

@@ -330,7 +331,7 @@ def notebook_login(new_session: bool = True, write_permission: bool = False) ->
330331
" Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
331332
)
332333
if not new_session and _current_token_okay(write_permission=write_permission):
333-
print("User is already logged in.")
334+
logger.info("User is already logged in.")
334335
return
335336

336337
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
@@ -400,20 +401,20 @@ def _login(
400401
"Token is valid but is 'read-only' and a 'write' token is required.\nPlease provide a new token with"
401402
" correct permission."
402403
)
403-
print(f"Token is valid (permission: {permission}).")
404+
logger.info(f"Token is valid (permission: {permission}).")
404405

405406
token_name = token_info["auth"]["accessToken"]["displayName"]
406407
# Store token locally
407408
_save_token(token=token, token_name=token_name)
408409
# Set active token
409410
_set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential)
410-
print("Login successful.")
411+
logger.info("Login successful.")
411412
if _get_token_from_environment():
412-
print(
413+
logger.warning(
413414
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured."
414415
)
415416
else:
416-
print(f"The current active token is: `{token_name}`")
417+
logger.info(f"The current active token is: `{token_name}`")
417418

418419

419420
def _logout_from_token(token_name: str) -> None:
@@ -435,7 +436,7 @@ def _logout_from_token(token_name: str) -> None:
435436
_save_stored_tokens(stored_tokens)
436437

437438
if token == _get_token_from_file():
438-
warnings.warn(f"Active token '{token_name}' has been deleted.")
439+
logger.warning(f"Active token '{token_name}' has been deleted.")
439440
Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
440441

441442

@@ -455,17 +456,17 @@ def _set_active_token(
455456
if add_to_git_credential:
456457
if _is_git_credential_helper_configured():
457458
set_git_credential(token)
458-
print(
459+
logger.info(
459460
"Your token has been saved in your configured git credential helpers"
460461
+ f" ({','.join(list_credential_helpers())})."
461462
)
462463
else:
463-
print("Token has not been saved to git credential helper.")
464+
logger.warning("Token has not been saved to git credential helper.")
464465
# Write token to HF_TOKEN_PATH
465466
path = Path(constants.HF_TOKEN_PATH)
466467
path.parent.mkdir(parents=True, exist_ok=True)
467468
path.write_text(token)
468-
print(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
469+
logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
469470

470471

471472
def _current_token_okay(write_permission: bool = False):

src/huggingface_hub/commands/user.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,29 @@
1111
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
14+
"""Contains commands to authenticate to the Hugging Face Hub and interact with your repositories.
15+
16+
Usage:
17+
# login and save token locally.
18+
huggingface-cli login --token=hf_*** --add-to-git-credential
19+
20+
# switch between tokens
21+
huggingface-cli auth switch
22+
23+
# list all tokens
24+
huggingface-cli auth list
25+
26+
# logout from a specific token, if no token-name is provided, all tokens will be deleted from your machine.
27+
huggingface-cli logout --token-name=your_token_name
28+
29+
# find out which huggingface.co account you are logged in as
30+
huggingface-cli whoami
31+
32+
# create a new dataset repo on the Hub
33+
huggingface-cli repo create mydataset --type=dataset
34+
35+
"""
36+
1437
import subprocess
1538
from argparse import _SubParsersAction
1639
from typing import Optional
@@ -126,6 +149,7 @@ def __init__(self, args):
126149

127150
class LoginCommand(BaseUserCommand):
128151
def run(self):
152+
logging.set_verbosity_info()
129153
login(
130154
token=self.args.token,
131155
add_to_git_credential=self.args.add_to_git_credential,
@@ -134,11 +158,13 @@ def run(self):
134158

135159
class LogoutCommand(BaseUserCommand):
136160
def run(self):
161+
logging.set_verbosity_info()
137162
logout(token_name=self.args.token_name)
138163

139164

140165
class AuthSwitchCommand(BaseUserCommand):
141166
def run(self):
167+
logging.set_verbosity_info()
142168
token_name = self.args.token_name
143169
if token_name is None:
144170
token_name = self._select_token_name()
@@ -189,6 +215,7 @@ def _select_token_name_tui(self, token_names: list[str]) -> Optional[str]:
189215

190216
class AuthListCommand(BaseUserCommand):
191217
def run(self):
218+
logging.set_verbosity_info()
192219
auth_list()
193220

194221

src/huggingface_hub/utils/_auth.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,7 @@ def _save_token(token: str, token_name: str) -> None:
201201
stored_tokens = get_stored_tokens()
202202
stored_tokens[token_name] = token
203203
_save_stored_tokens(stored_tokens)
204-
print(f"The token `{token_name}` has been saved to {tokens_path}")
204+
logger.info(f"The token `{token_name}` has been saved to {tokens_path}")
205205

206206

207207
def _clean_token(token: Optional[str]) -> Optional[str]:

0 commit comments

Comments
 (0)