discussions.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. # Copyright 2026 The HuggingFace Team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Contains commands to interact with discussions and pull requests on the Hugging Face Hub."""
  15. import enum
  16. import sys
  17. from pathlib import Path
  18. from typing import Annotated
  19. import typer
  20. from huggingface_hub import constants
  21. from ._cli_utils import (
  22. AuthorOpt,
  23. FormatWithAutoOpt,
  24. LimitOpt,
  25. RepoIdArg,
  26. RepoType,
  27. RepoTypeOpt,
  28. TokenOpt,
  29. api_object_to_dict,
  30. get_hf_api,
  31. typer_factory,
  32. )
  33. from ._output import OutputFormatWithAuto, out
  34. class DiscussionStatus(str, enum.Enum):
  35. open = "open"
  36. closed = "closed"
  37. merged = "merged"
  38. draft = "draft"
  39. all = "all"
  40. class DiscussionKind(str, enum.Enum):
  41. all = "all"
  42. discussion = "discussion"
  43. pull_request = "pull_request"
  44. # "merged" and "draft" are valid Discussion statuses but the Hub API filter
  45. # (DiscussionStatusFilter) only accepts "all", "open", "closed". When the user
  46. # asks for merged/draft we fetch with api_status=None (i.e. all) and filter
  47. # client-side.
  48. _CLIENT_SIDE_STATUSES = {"merged", "draft"}
  49. DiscussionNumArg = Annotated[
  50. int,
  51. typer.Argument(
  52. help="The discussion or pull request number.",
  53. min=1,
  54. ),
  55. ]
  56. def _read_body(body: str | None, body_file: Path | None) -> str | None:
  57. """Resolve body text from --body or --body-file (supports '-' for stdin)."""
  58. if body is not None and body_file is not None:
  59. raise typer.BadParameter("Cannot use both --body and --body-file.")
  60. if body_file is not None:
  61. if str(body_file) == "-":
  62. return sys.stdin.read()
  63. return body_file.read_text(encoding="utf-8")
  64. return body
  65. discussions_cli = typer_factory(help="Manage discussions and pull requests on the Hub.")
  66. @discussions_cli.command(
  67. "list | ls",
  68. examples=[
  69. "hf discussions list username/my-model",
  70. "hf discussions list username/my-model --kind pull_request --status merged",
  71. "hf discussions list username/my-dataset --type dataset --status closed",
  72. "hf discussions list username/my-model --author alice --format json",
  73. ],
  74. )
  75. def discussion_list(
  76. repo_id: RepoIdArg,
  77. status: Annotated[
  78. DiscussionStatus,
  79. typer.Option(
  80. "-s",
  81. "--status",
  82. help="Filter by status (open, closed, merged, draft, all).",
  83. ),
  84. ] = DiscussionStatus.open,
  85. kind: Annotated[
  86. DiscussionKind,
  87. typer.Option(
  88. "-k",
  89. "--kind",
  90. help="Filter by kind (discussion, pull_request, all).",
  91. ),
  92. ] = DiscussionKind.all,
  93. author: AuthorOpt = None,
  94. limit: LimitOpt = 30,
  95. repo_type: RepoTypeOpt = RepoType.model,
  96. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  97. token: TokenOpt = None,
  98. ) -> None:
  99. """List discussions and pull requests on a repo."""
  100. api = get_hf_api(token=token)
  101. api_status: constants.DiscussionStatusFilter | None
  102. if status == DiscussionStatus.open:
  103. api_status = "open"
  104. elif status == DiscussionStatus.closed:
  105. api_status = "closed"
  106. else:
  107. api_status = None
  108. api_discussion_type: constants.DiscussionTypeFilter | None
  109. if kind == DiscussionKind.all:
  110. api_discussion_type = None
  111. else:
  112. api_discussion_type = kind.value # type: ignore[assignment]
  113. discussions = []
  114. for d in api.get_repo_discussions(
  115. repo_id=repo_id,
  116. author=author,
  117. discussion_type=api_discussion_type,
  118. discussion_status=api_status,
  119. repo_type=repo_type.value,
  120. ):
  121. if status.value in _CLIENT_SIDE_STATUSES and d.status != status.value:
  122. continue
  123. discussions.append(d)
  124. if len(discussions) >= limit:
  125. break
  126. items = [api_object_to_dict(d) for d in discussions]
  127. out.table(
  128. items,
  129. headers=["num", "title", "is_pull_request", "status", "author", "created_at"],
  130. id_key="num",
  131. alignments={"num": "right"},
  132. )
  133. @discussions_cli.command(
  134. "info",
  135. examples=[
  136. "hf discussions info username/my-model 5",
  137. "hf discussions info username/my-model 5 --format json",
  138. ],
  139. )
  140. def discussion_info(
  141. repo_id: RepoIdArg,
  142. num: DiscussionNumArg,
  143. repo_type: RepoTypeOpt = RepoType.model,
  144. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  145. token: TokenOpt = None,
  146. ) -> None:
  147. """Get info about a discussion or pull request."""
  148. api = get_hf_api(token=token)
  149. details = api.get_discussion_details(
  150. repo_id=repo_id,
  151. discussion_num=num,
  152. repo_type=repo_type.value,
  153. )
  154. out.dict(details)
  155. @discussions_cli.command(
  156. "create",
  157. examples=[
  158. 'hf discussions create username/my-model --title "Bug report"',
  159. 'hf discussions create username/my-model --title "Feature request" --body "Please add X"',
  160. 'hf discussions create username/my-model --title "Fix typo" --pull-request',
  161. 'hf discussions create username/my-dataset --type dataset --title "Data quality issue"',
  162. ],
  163. )
  164. def discussion_create(
  165. repo_id: RepoIdArg,
  166. title: Annotated[
  167. str,
  168. typer.Option(
  169. "--title",
  170. help="The title of the discussion or pull request.",
  171. ),
  172. ],
  173. body: Annotated[
  174. str | None,
  175. typer.Option(
  176. "--body",
  177. help="The description (supports Markdown).",
  178. ),
  179. ] = None,
  180. body_file: Annotated[
  181. Path | None,
  182. typer.Option(
  183. "--body-file",
  184. help="Read the description from a file. Use '-' for stdin.",
  185. ),
  186. ] = None,
  187. pull_request: Annotated[
  188. bool,
  189. typer.Option(
  190. "--pull-request",
  191. "--pr",
  192. help="Create a pull request instead of a discussion.",
  193. ),
  194. ] = False,
  195. repo_type: RepoTypeOpt = RepoType.model,
  196. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  197. token: TokenOpt = None,
  198. ) -> None:
  199. """Create a new discussion or pull request on a repo."""
  200. description = _read_body(body, body_file)
  201. api = get_hf_api(token=token)
  202. discussion = api.create_discussion(
  203. repo_id=repo_id,
  204. title=title,
  205. description=description,
  206. repo_type=repo_type.value,
  207. pull_request=pull_request,
  208. )
  209. kind = "pull request" if pull_request else "discussion"
  210. ref = f"refs/pr/{discussion.num}" if pull_request else None
  211. out.result(f"Created {kind} #{discussion.num} on {repo_id}", num=discussion.num, url=discussion.url, ref=ref)
  212. @discussions_cli.command(
  213. "comment",
  214. examples=[
  215. 'hf discussions comment username/my-model 5 --body "Thanks for reporting!"',
  216. 'hf discussions comment username/my-model 5 --body "LGTM!"',
  217. ],
  218. )
  219. def discussion_comment(
  220. repo_id: RepoIdArg,
  221. num: DiscussionNumArg,
  222. body: Annotated[
  223. str | None,
  224. typer.Option(
  225. "--body",
  226. help="The comment text (supports Markdown).",
  227. ),
  228. ] = None,
  229. body_file: Annotated[
  230. Path | None,
  231. typer.Option(
  232. "--body-file",
  233. help="Read the comment from a file. Use '-' for stdin.",
  234. ),
  235. ] = None,
  236. repo_type: RepoTypeOpt = RepoType.model,
  237. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  238. token: TokenOpt = None,
  239. ) -> None:
  240. """Comment on a discussion or pull request."""
  241. comment = _read_body(body, body_file)
  242. if comment is None:
  243. raise typer.BadParameter("Either --body or --body-file is required.")
  244. api = get_hf_api(token=token)
  245. api.comment_discussion(
  246. repo_id=repo_id,
  247. discussion_num=num,
  248. comment=comment,
  249. repo_type=repo_type.value,
  250. )
  251. out.result(f"Commented on #{num} in {repo_id}", num=num, repo=repo_id)
  252. @discussions_cli.command(
  253. "close",
  254. examples=[
  255. "hf discussions close username/my-model 5",
  256. 'hf discussions close username/my-model 5 --comment "Closing as resolved."',
  257. ],
  258. )
  259. def discussion_close(
  260. repo_id: RepoIdArg,
  261. num: DiscussionNumArg,
  262. comment: Annotated[
  263. str | None,
  264. typer.Option(
  265. "--comment",
  266. help="An optional comment to post when closing.",
  267. ),
  268. ] = None,
  269. yes: Annotated[
  270. bool,
  271. typer.Option(
  272. "--yes",
  273. "-y",
  274. help="Skip confirmation prompt.",
  275. ),
  276. ] = False,
  277. repo_type: RepoTypeOpt = RepoType.model,
  278. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  279. token: TokenOpt = None,
  280. ) -> None:
  281. """Close a discussion or pull request."""
  282. out.confirm(f"Close #{num} on '{repo_id}'?", yes=yes)
  283. api = get_hf_api(token=token)
  284. api.change_discussion_status(
  285. repo_id=repo_id,
  286. discussion_num=num,
  287. new_status="closed",
  288. comment=comment,
  289. repo_type=repo_type.value,
  290. )
  291. out.result(f"Closed #{num} in {repo_id}", num=num, repo=repo_id)
  292. @discussions_cli.command(
  293. "reopen",
  294. examples=[
  295. "hf discussions reopen username/my-model 5",
  296. 'hf discussions reopen username/my-model 5 --comment "Reopening for further investigation."',
  297. ],
  298. )
  299. def discussion_reopen(
  300. repo_id: RepoIdArg,
  301. num: DiscussionNumArg,
  302. comment: Annotated[
  303. str | None,
  304. typer.Option(
  305. "--comment",
  306. help="An optional comment to post when reopening.",
  307. ),
  308. ] = None,
  309. yes: Annotated[
  310. bool,
  311. typer.Option(
  312. "--yes",
  313. "-y",
  314. help="Skip confirmation prompt.",
  315. ),
  316. ] = False,
  317. repo_type: RepoTypeOpt = RepoType.model,
  318. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  319. token: TokenOpt = None,
  320. ) -> None:
  321. """Reopen a closed discussion or pull request."""
  322. out.confirm(f"Reopen #{num} on '{repo_id}'?", yes=yes)
  323. api = get_hf_api(token=token)
  324. api.change_discussion_status(
  325. repo_id=repo_id,
  326. discussion_num=num,
  327. new_status="open",
  328. comment=comment,
  329. repo_type=repo_type.value,
  330. )
  331. out.result(f"Reopened #{num} in {repo_id}", num=num, repo=repo_id)
  332. @discussions_cli.command(
  333. "rename",
  334. examples=[
  335. 'hf discussions rename username/my-model 5 "Updated title"',
  336. ],
  337. )
  338. def discussion_rename(
  339. repo_id: RepoIdArg,
  340. num: DiscussionNumArg,
  341. new_title: Annotated[
  342. str,
  343. typer.Argument(
  344. help="The new title.",
  345. ),
  346. ],
  347. repo_type: RepoTypeOpt = RepoType.model,
  348. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  349. token: TokenOpt = None,
  350. ) -> None:
  351. """Rename a discussion or pull request."""
  352. api = get_hf_api(token=token)
  353. api.rename_discussion(
  354. repo_id=repo_id,
  355. discussion_num=num,
  356. new_title=new_title,
  357. repo_type=repo_type.value,
  358. )
  359. out.result(f"Renamed #{num} in {repo_id}", num=num, repo=repo_id, title=new_title)
  360. @discussions_cli.command(
  361. "merge",
  362. examples=[
  363. "hf discussions merge username/my-model 5",
  364. 'hf discussions merge username/my-model 5 --comment "Merging, thanks!"',
  365. ],
  366. )
  367. def discussion_merge(
  368. repo_id: RepoIdArg,
  369. num: DiscussionNumArg,
  370. comment: Annotated[
  371. str | None,
  372. typer.Option(
  373. "--comment",
  374. help="An optional comment to post when merging.",
  375. ),
  376. ] = None,
  377. yes: Annotated[
  378. bool,
  379. typer.Option(
  380. "--yes",
  381. "-y",
  382. help="Skip confirmation prompt.",
  383. ),
  384. ] = False,
  385. repo_type: RepoTypeOpt = RepoType.model,
  386. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  387. token: TokenOpt = None,
  388. ) -> None:
  389. """Merge a pull request."""
  390. out.confirm(f"Merge #{num} on '{repo_id}'?", yes=yes)
  391. api = get_hf_api(token=token)
  392. api.merge_pull_request(
  393. repo_id=repo_id,
  394. discussion_num=num,
  395. comment=comment,
  396. repo_type=repo_type.value,
  397. )
  398. out.result(f"Merged #{num} in {repo_id}", num=num, repo=repo_id)
  399. @discussions_cli.command(
  400. "diff",
  401. examples=[
  402. "hf discussions diff username/my-model 5",
  403. ],
  404. )
  405. def discussion_diff(
  406. repo_id: RepoIdArg,
  407. num: DiscussionNumArg,
  408. repo_type: RepoTypeOpt = RepoType.model,
  409. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  410. token: TokenOpt = None,
  411. ) -> None:
  412. """Show the diff of a pull request."""
  413. api = get_hf_api(token=token)
  414. details = api.get_discussion_details(
  415. repo_id=repo_id,
  416. discussion_num=num,
  417. repo_type=repo_type.value,
  418. )
  419. if details.diff:
  420. out.text(details.diff)
  421. else:
  422. out.text("No diff available.")