repository.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471
  1. import atexit
  2. import os
  3. import re
  4. import subprocess
  5. import threading
  6. import time
  7. from contextlib import contextmanager
  8. from pathlib import Path
  9. from typing import Callable, Dict, Iterator, List, Optional, Tuple, TypedDict, Union
  10. from urllib.parse import urlparse
  11. from huggingface_hub import constants
  12. from huggingface_hub.repocard import metadata_load, metadata_save
  13. from .hf_api import HfApi, repo_type_and_id_from_hf_id
  14. from .lfs import LFS_MULTIPART_UPLOAD_COMMAND
  15. from .utils import (
  16. SoftTemporaryDirectory,
  17. get_token,
  18. logging,
  19. run_subprocess,
  20. tqdm,
  21. validate_hf_hub_args,
  22. )
  23. from .utils._deprecation import _deprecate_method
  24. logger = logging.get_logger(__name__)
  25. class CommandInProgress:
  26. """
  27. Utility to follow commands launched asynchronously.
  28. """
  29. def __init__(
  30. self,
  31. title: str,
  32. is_done_method: Callable,
  33. status_method: Callable,
  34. process: subprocess.Popen,
  35. post_method: Optional[Callable] = None,
  36. ):
  37. self.title = title
  38. self._is_done = is_done_method
  39. self._status = status_method
  40. self._process = process
  41. self._stderr = ""
  42. self._stdout = ""
  43. self._post_method = post_method
  44. @property
  45. def is_done(self) -> bool:
  46. """
  47. Whether the process is done.
  48. """
  49. result = self._is_done()
  50. if result and self._post_method is not None:
  51. self._post_method()
  52. self._post_method = None
  53. return result
  54. @property
  55. def status(self) -> int:
  56. """
  57. The exit code/status of the current action. Will return `0` if the
  58. command has completed successfully, and a number between 1 and 255 if
  59. the process errored-out.
  60. Will return -1 if the command is still ongoing.
  61. """
  62. return self._status()
  63. @property
  64. def failed(self) -> bool:
  65. """
  66. Whether the process errored-out.
  67. """
  68. return self.status > 0
  69. @property
  70. def stderr(self) -> str:
  71. """
  72. The current output message on the standard error.
  73. """
  74. if self._process.stderr is not None:
  75. self._stderr += self._process.stderr.read()
  76. return self._stderr
  77. @property
  78. def stdout(self) -> str:
  79. """
  80. The current output message on the standard output.
  81. """
  82. if self._process.stdout is not None:
  83. self._stdout += self._process.stdout.read()
  84. return self._stdout
  85. def __repr__(self):
  86. status = self.status
  87. if status == -1:
  88. status = "running"
  89. return (
  90. f"[{self.title} command, status code: {status},"
  91. f" {'in progress.' if not self.is_done else 'finished.'} PID:"
  92. f" {self._process.pid}]"
  93. )
  94. def is_git_repo(folder: Union[str, Path]) -> bool:
  95. """
  96. Check if the folder is the root or part of a git repository
  97. Args:
  98. folder (`str`):
  99. The folder in which to run the command.
  100. Returns:
  101. `bool`: `True` if the repository is part of a repository, `False`
  102. otherwise.
  103. """
  104. folder_exists = os.path.exists(os.path.join(folder, ".git"))
  105. git_branch = subprocess.run("git branch".split(), cwd=folder, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  106. return folder_exists and git_branch.returncode == 0
  107. def is_local_clone(folder: Union[str, Path], remote_url: str) -> bool:
  108. """
  109. Check if the folder is a local clone of the remote_url
  110. Args:
  111. folder (`str` or `Path`):
  112. The folder in which to run the command.
  113. remote_url (`str`):
  114. The url of a git repository.
  115. Returns:
  116. `bool`: `True` if the repository is a local clone of the remote
  117. repository specified, `False` otherwise.
  118. """
  119. if not is_git_repo(folder):
  120. return False
  121. remotes = run_subprocess("git remote -v", folder).stdout
  122. # Remove token for the test with remotes.
  123. remote_url = re.sub(r"https://.*@", "https://", remote_url)
  124. remotes = [re.sub(r"https://.*@", "https://", remote) for remote in remotes.split()]
  125. return remote_url in remotes
  126. def is_tracked_with_lfs(filename: Union[str, Path]) -> bool:
  127. """
  128. Check if the file passed is tracked with git-lfs.
  129. Args:
  130. filename (`str` or `Path`):
  131. The filename to check.
  132. Returns:
  133. `bool`: `True` if the file passed is tracked with git-lfs, `False`
  134. otherwise.
  135. """
  136. folder = Path(filename).parent
  137. filename = Path(filename).name
  138. try:
  139. p = run_subprocess("git check-attr -a".split() + [filename], folder)
  140. attributes = p.stdout.strip()
  141. except subprocess.CalledProcessError as exc:
  142. if not is_git_repo(folder):
  143. return False
  144. else:
  145. raise OSError(exc.stderr)
  146. if len(attributes) == 0:
  147. return False
  148. found_lfs_tag = {"diff": False, "merge": False, "filter": False}
  149. for attribute in attributes.split("\n"):
  150. for tag in found_lfs_tag.keys():
  151. if tag in attribute and "lfs" in attribute:
  152. found_lfs_tag[tag] = True
  153. return all(found_lfs_tag.values())
  154. def is_git_ignored(filename: Union[str, Path]) -> bool:
  155. """
  156. Check if file is git-ignored. Supports nested .gitignore files.
  157. Args:
  158. filename (`str` or `Path`):
  159. The filename to check.
  160. Returns:
  161. `bool`: `True` if the file passed is ignored by `git`, `False`
  162. otherwise.
  163. """
  164. folder = Path(filename).parent
  165. filename = Path(filename).name
  166. try:
  167. p = run_subprocess("git check-ignore".split() + [filename], folder, check=False)
  168. # Will return exit code 1 if not gitignored
  169. is_ignored = not bool(p.returncode)
  170. except subprocess.CalledProcessError as exc:
  171. raise OSError(exc.stderr)
  172. return is_ignored
  173. def is_binary_file(filename: Union[str, Path]) -> bool:
  174. """
  175. Check if file is a binary file.
  176. Args:
  177. filename (`str` or `Path`):
  178. The filename to check.
  179. Returns:
  180. `bool`: `True` if the file passed is a binary file, `False` otherwise.
  181. """
  182. try:
  183. with open(filename, "rb") as f:
  184. content = f.read(10 * (1024**2)) # Read a maximum of 10MB
  185. # Code sample taken from the following stack overflow thread
  186. # https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python/7392391#7392391
  187. text_chars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7F})
  188. return bool(content.translate(None, text_chars))
  189. except UnicodeDecodeError:
  190. return True
  191. def files_to_be_staged(pattern: str = ".", folder: Union[str, Path, None] = None) -> List[str]:
  192. """
  193. Returns a list of filenames that are to be staged.
  194. Args:
  195. pattern (`str` or `Path`):
  196. The pattern of filenames to check. Put `.` to get all files.
  197. folder (`str` or `Path`):
  198. The folder in which to run the command.
  199. Returns:
  200. `List[str]`: List of files that are to be staged.
  201. """
  202. try:
  203. p = run_subprocess("git ls-files --exclude-standard -mo".split() + [pattern], folder)
  204. if len(p.stdout.strip()):
  205. files = p.stdout.strip().split("\n")
  206. else:
  207. files = []
  208. except subprocess.CalledProcessError as exc:
  209. raise EnvironmentError(exc.stderr)
  210. return files
  211. def is_tracked_upstream(folder: Union[str, Path]) -> bool:
  212. """
  213. Check if the current checked-out branch is tracked upstream.
  214. Args:
  215. folder (`str` or `Path`):
  216. The folder in which to run the command.
  217. Returns:
  218. `bool`: `True` if the current checked-out branch is tracked upstream,
  219. `False` otherwise.
  220. """
  221. try:
  222. run_subprocess("git rev-parse --symbolic-full-name --abbrev-ref @{u}", folder)
  223. return True
  224. except subprocess.CalledProcessError as exc:
  225. if "HEAD" in exc.stderr:
  226. raise OSError("No branch checked out")
  227. return False
  228. def commits_to_push(folder: Union[str, Path], upstream: Optional[str] = None) -> int:
  229. """
  230. Check the number of commits that would be pushed upstream
  231. Args:
  232. folder (`str` or `Path`):
  233. The folder in which to run the command.
  234. upstream (`str`, *optional*):
  235. The name of the upstream repository with which the comparison should be
  236. made.
  237. Returns:
  238. `int`: Number of commits that would be pushed upstream were a `git
  239. push` to proceed.
  240. """
  241. try:
  242. result = run_subprocess(f"git cherry -v {upstream or ''}", folder)
  243. return len(result.stdout.split("\n")) - 1
  244. except subprocess.CalledProcessError as exc:
  245. raise EnvironmentError(exc.stderr)
  246. class PbarT(TypedDict):
  247. # Used to store an opened progress bar in `_lfs_log_progress`
  248. bar: tqdm
  249. past_bytes: int
  250. @contextmanager
  251. def _lfs_log_progress():
  252. """
  253. This is a context manager that will log the Git LFS progress of cleaning,
  254. smudging, pulling and pushing.
  255. """
  256. if logger.getEffectiveLevel() >= logging.ERROR:
  257. try:
  258. yield
  259. except Exception:
  260. pass
  261. return
  262. def output_progress(stopping_event: threading.Event):
  263. """
  264. To be launched as a separate thread with an event meaning it should stop
  265. the tail.
  266. """
  267. # Key is tuple(state, filename), value is a dict(tqdm bar and a previous value)
  268. pbars: Dict[Tuple[str, str], PbarT] = {}
  269. def close_pbars():
  270. for pbar in pbars.values():
  271. pbar["bar"].update(pbar["bar"].total - pbar["past_bytes"])
  272. pbar["bar"].refresh()
  273. pbar["bar"].close()
  274. def tail_file(filename) -> Iterator[str]:
  275. """
  276. Creates a generator to be iterated through, which will return each
  277. line one by one. Will stop tailing the file if the stopping_event is
  278. set.
  279. """
  280. with open(filename, "r") as file:
  281. current_line = ""
  282. while True:
  283. if stopping_event.is_set():
  284. close_pbars()
  285. break
  286. line_bit = file.readline()
  287. if line_bit is not None and not len(line_bit.strip()) == 0:
  288. current_line += line_bit
  289. if current_line.endswith("\n"):
  290. yield current_line
  291. current_line = ""
  292. else:
  293. time.sleep(1)
  294. # If the file isn't created yet, wait for a few seconds before trying again.
  295. # Can be interrupted with the stopping_event.
  296. while not os.path.exists(os.environ["GIT_LFS_PROGRESS"]):
  297. if stopping_event.is_set():
  298. close_pbars()
  299. return
  300. time.sleep(2)
  301. for line in tail_file(os.environ["GIT_LFS_PROGRESS"]):
  302. try:
  303. state, file_progress, byte_progress, filename = line.split()
  304. except ValueError as error:
  305. # Try/except to ease debugging. See https://github.com/huggingface/huggingface_hub/issues/1373.
  306. raise ValueError(f"Cannot unpack LFS progress line:\n{line}") from error
  307. description = f"{state.capitalize()} file {filename}"
  308. current_bytes, total_bytes = byte_progress.split("/")
  309. current_bytes_int = int(current_bytes)
  310. total_bytes_int = int(total_bytes)
  311. pbar = pbars.get((state, filename))
  312. if pbar is None:
  313. # Initialize progress bar
  314. pbars[(state, filename)] = {
  315. "bar": tqdm(
  316. desc=description,
  317. initial=current_bytes_int,
  318. total=total_bytes_int,
  319. unit="B",
  320. unit_scale=True,
  321. unit_divisor=1024,
  322. name="huggingface_hub.lfs_upload",
  323. ),
  324. "past_bytes": int(current_bytes),
  325. }
  326. else:
  327. # Update progress bar
  328. pbar["bar"].update(current_bytes_int - pbar["past_bytes"])
  329. pbar["past_bytes"] = current_bytes_int
  330. current_lfs_progress_value = os.environ.get("GIT_LFS_PROGRESS", "")
  331. with SoftTemporaryDirectory() as tmpdir:
  332. os.environ["GIT_LFS_PROGRESS"] = os.path.join(tmpdir, "lfs_progress")
  333. logger.debug(f"Following progress in {os.environ['GIT_LFS_PROGRESS']}")
  334. exit_event = threading.Event()
  335. x = threading.Thread(target=output_progress, args=(exit_event,), daemon=True)
  336. x.start()
  337. try:
  338. yield
  339. finally:
  340. exit_event.set()
  341. x.join()
  342. os.environ["GIT_LFS_PROGRESS"] = current_lfs_progress_value
  343. class Repository:
  344. """
  345. Helper class to wrap the git and git-lfs commands.
  346. The aim is to facilitate interacting with huggingface.co hosted model or
  347. dataset repos, though not a lot here (if any) is actually specific to
  348. huggingface.co.
  349. > [!WARNING]
  350. > [`Repository`] is deprecated in favor of the http-based alternatives implemented in
  351. > [`HfApi`]. Given its large adoption in legacy code, the complete removal of
  352. > [`Repository`] will only happen in release `v1.0`. For more details, please read
  353. > https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http.
  354. """
  355. command_queue: List[CommandInProgress]
  356. @validate_hf_hub_args
  357. @_deprecate_method(
  358. version="1.0",
  359. message=(
  360. "Please prefer the http-based alternatives instead. Given its large adoption in legacy code, the complete"
  361. " removal is only planned on next major release.\nFor more details, please read"
  362. " https://huggingface.co/docs/huggingface_hub/concepts/git_vs_http."
  363. ),
  364. )
  365. def __init__(
  366. self,
  367. local_dir: Union[str, Path],
  368. clone_from: Optional[str] = None,
  369. repo_type: Optional[str] = None,
  370. token: Union[bool, str] = True,
  371. git_user: Optional[str] = None,
  372. git_email: Optional[str] = None,
  373. revision: Optional[str] = None,
  374. skip_lfs_files: bool = False,
  375. client: Optional[HfApi] = None,
  376. ):
  377. """
  378. Instantiate a local clone of a git repo.
  379. If `clone_from` is set, the repo will be cloned from an existing remote repository.
  380. If the remote repo does not exist, a `EnvironmentError` exception will be thrown.
  381. Please create the remote repo first using [`create_repo`].
  382. `Repository` uses the local git credentials by default. If explicitly set, the `token`
  383. or the `git_user`/`git_email` pair will be used instead.
  384. Args:
  385. local_dir (`str` or `Path`):
  386. path (e.g. `'my_trained_model/'`) to the local directory, where
  387. the `Repository` will be initialized.
  388. clone_from (`str`, *optional*):
  389. Either a repository url or `repo_id`.
  390. Example:
  391. - `"https://huggingface.co/philschmid/playground-tests"`
  392. - `"philschmid/playground-tests"`
  393. repo_type (`str`, *optional*):
  394. To set when cloning a repo from a repo_id. Default is model.
  395. token (`bool` or `str`, *optional*):
  396. A valid authentication token (see https://huggingface.co/settings/token).
  397. If `None` or `True` and machine is logged in (through `hf auth login`
  398. or [`~huggingface_hub.login`]), token will be retrieved from the cache.
  399. If `False`, token is not sent in the request header.
  400. git_user (`str`, *optional*):
  401. will override the `git config user.name` for committing and
  402. pushing files to the hub.
  403. git_email (`str`, *optional*):
  404. will override the `git config user.email` for committing and
  405. pushing files to the hub.
  406. revision (`str`, *optional*):
  407. Revision to checkout after initializing the repository. If the
  408. revision doesn't exist, a branch will be created with that
  409. revision name from the default branch's current HEAD.
  410. skip_lfs_files (`bool`, *optional*, defaults to `False`):
  411. whether to skip git-LFS files or not.
  412. client (`HfApi`, *optional*):
  413. Instance of [`HfApi`] to use when calling the HF Hub API. A new
  414. instance will be created if this is left to `None`.
  415. Raises:
  416. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  417. If the remote repository set in `clone_from` does not exist.
  418. """
  419. if isinstance(local_dir, Path):
  420. local_dir = str(local_dir)
  421. os.makedirs(local_dir, exist_ok=True)
  422. self.local_dir = os.path.join(os.getcwd(), local_dir)
  423. self._repo_type = repo_type
  424. self.command_queue = []
  425. self.skip_lfs_files = skip_lfs_files
  426. self.client = client if client is not None else HfApi()
  427. self.check_git_versions()
  428. if isinstance(token, str):
  429. self.huggingface_token: Optional[str] = token
  430. elif token is False:
  431. self.huggingface_token = None
  432. else:
  433. # if `True` -> explicit use of the cached token
  434. # if `None` -> implicit use of the cached token
  435. self.huggingface_token = get_token()
  436. if clone_from is not None:
  437. self.clone_from(repo_url=clone_from)
  438. else:
  439. if is_git_repo(self.local_dir):
  440. logger.debug("[Repository] is a valid git repo")
  441. else:
  442. raise ValueError("If not specifying `clone_from`, you need to pass Repository a valid git clone.")
  443. if self.huggingface_token is not None and (git_email is None or git_user is None):
  444. user = self.client.whoami(self.huggingface_token)
  445. if git_email is None:
  446. git_email = user.get("email")
  447. if git_user is None:
  448. git_user = user.get("fullname")
  449. if git_user is not None or git_email is not None:
  450. self.git_config_username_and_email(git_user, git_email)
  451. self.lfs_enable_largefiles()
  452. self.git_credential_helper_store()
  453. if revision is not None:
  454. self.git_checkout(revision, create_branch_ok=True)
  455. # This ensures that all commands exit before exiting the Python runtime.
  456. # This will ensure all pushes register on the hub, even if other errors happen in subsequent operations.
  457. atexit.register(self.wait_for_commands)
  458. @property
  459. def current_branch(self) -> str:
  460. """
  461. Returns the current checked out branch.
  462. Returns:
  463. `str`: Current checked out branch.
  464. """
  465. try:
  466. result = run_subprocess("git rev-parse --abbrev-ref HEAD", self.local_dir).stdout.strip()
  467. except subprocess.CalledProcessError as exc:
  468. raise EnvironmentError(exc.stderr)
  469. return result
  470. def check_git_versions(self):
  471. """
  472. Checks that `git` and `git-lfs` can be run.
  473. Raises:
  474. [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  475. If `git` or `git-lfs` are not installed.
  476. """
  477. try:
  478. git_version = run_subprocess("git --version", self.local_dir).stdout.strip()
  479. except FileNotFoundError:
  480. raise EnvironmentError("Looks like you do not have git installed, please install.")
  481. try:
  482. lfs_version = run_subprocess("git-lfs --version", self.local_dir).stdout.strip()
  483. except FileNotFoundError:
  484. raise EnvironmentError(
  485. "Looks like you do not have git-lfs installed, please install."
  486. " You can install from https://git-lfs.github.com/."
  487. " Then run `git lfs install` (you only have to do this once)."
  488. )
  489. logger.info(git_version + "\n" + lfs_version)
  490. @validate_hf_hub_args
  491. def clone_from(self, repo_url: str, token: Union[bool, str, None] = None):
  492. """
  493. Clone from a remote. If the folder already exists, will try to clone the
  494. repository within it.
  495. If this folder is a git repository with linked history, will try to
  496. update the repository.
  497. Args:
  498. repo_url (`str`):
  499. The URL from which to clone the repository
  500. token (`Union[str, bool]`, *optional*):
  501. Whether to use the authentication token. It can be:
  502. - a string which is the token itself
  503. - `False`, which would not use the authentication token
  504. - `True`, which would fetch the authentication token from the
  505. local folder and use it (you should be logged in for this to
  506. work).
  507. - `None`, which would retrieve the value of
  508. `self.huggingface_token`.
  509. > [!TIP]
  510. > Raises the following error:
  511. >
  512. > - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  513. > if an organization token (starts with "api_org") is passed. Use must use
  514. > your own personal access token (see https://hf.co/settings/tokens).
  515. >
  516. > - [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
  517. > if you are trying to clone the repository in a non-empty folder, or if the
  518. > `git` operations raise errors.
  519. """
  520. token = (
  521. token # str -> use it
  522. if isinstance(token, str)
  523. else (
  524. None # `False` -> explicit no token
  525. if token is False
  526. else self.huggingface_token # `None` or `True` -> use default
  527. )
  528. )
  529. if token is not None and token.startswith("api_org"):
  530. raise ValueError(
  531. "You must use your personal access token, not an Organization token"
  532. " (see https://hf.co/settings/tokens)."
  533. )
  534. hub_url = self.client.endpoint
  535. if hub_url in repo_url or ("http" not in repo_url and len(repo_url.split("/")) <= 2):
  536. repo_type, namespace, repo_name = repo_type_and_id_from_hf_id(repo_url, hub_url=hub_url)
  537. repo_id = f"{namespace}/{repo_name}" if namespace is not None else repo_name
  538. if repo_type is not None:
  539. self._repo_type = repo_type
  540. repo_url = hub_url + "/"
  541. if self._repo_type in constants.REPO_TYPES_URL_PREFIXES:
  542. repo_url += constants.REPO_TYPES_URL_PREFIXES[self._repo_type]
  543. if token is not None:
  544. # Add token in git url when provided
  545. scheme = urlparse(repo_url).scheme
  546. repo_url = repo_url.replace(f"{scheme}://", f"{scheme}://user:{token}@")
  547. repo_url += repo_id
  548. # For error messages, it's cleaner to show the repo url without the token.
  549. clean_repo_url = re.sub(r"(https?)://.*@", r"\1://", repo_url)
  550. try:
  551. run_subprocess("git lfs install", self.local_dir)
  552. # checks if repository is initialized in a empty repository or in one with files
  553. if len(os.listdir(self.local_dir)) == 0:
  554. logger.warning(f"Cloning {clean_repo_url} into local empty directory.")
  555. with _lfs_log_progress():
  556. env = os.environ.copy()
  557. if self.skip_lfs_files:
  558. env.update({"GIT_LFS_SKIP_SMUDGE": "1"})
  559. run_subprocess(
  560. # 'git lfs clone' is deprecated (will display a warning in the terminal)
  561. # but we still use it as it provides a nicer UX when downloading large
  562. # files (shows progress).
  563. f"{'git clone' if self.skip_lfs_files else 'git lfs clone'} {repo_url} .",
  564. self.local_dir,
  565. env=env,
  566. )
  567. else:
  568. # Check if the folder is the root of a git repository
  569. if not is_git_repo(self.local_dir):
  570. raise EnvironmentError(
  571. "Tried to clone a repository in a non-empty folder that isn't"
  572. f" a git repository ('{self.local_dir}'). If you really want to"
  573. f" do this, do it manually:\n cd {self.local_dir} && git init"
  574. " && git remote add origin && git pull origin main\n or clone"
  575. " repo to a new folder and move your existing files there"
  576. " afterwards."
  577. )
  578. if is_local_clone(self.local_dir, repo_url):
  579. logger.warning(
  580. f"{self.local_dir} is already a clone of {clean_repo_url}."
  581. " Make sure you pull the latest changes with"
  582. " `repo.git_pull()`."
  583. )
  584. else:
  585. output = run_subprocess("git remote get-url origin", self.local_dir, check=False)
  586. error_msg = (
  587. f"Tried to clone {clean_repo_url} in an unrelated git"
  588. " repository.\nIf you believe this is an error, please add"
  589. f" a remote with the following URL: {clean_repo_url}."
  590. )
  591. if output.returncode == 0:
  592. clean_local_remote_url = re.sub(r"https://.*@", "https://", output.stdout)
  593. error_msg += f"\nLocal path has its origin defined as: {clean_local_remote_url}"
  594. raise EnvironmentError(error_msg)
  595. except subprocess.CalledProcessError as exc:
  596. raise EnvironmentError(exc.stderr)
  597. def git_config_username_and_email(self, git_user: Optional[str] = None, git_email: Optional[str] = None):
  598. """
  599. Sets git username and email (only in the current repo).
  600. Args:
  601. git_user (`str`, *optional*):
  602. The username to register through `git`.
  603. git_email (`str`, *optional*):
  604. The email to register through `git`.
  605. """
  606. try:
  607. if git_user is not None:
  608. run_subprocess("git config user.name".split() + [git_user], self.local_dir)
  609. if git_email is not None:
  610. run_subprocess(f"git config user.email {git_email}".split(), self.local_dir)
  611. except subprocess.CalledProcessError as exc:
  612. raise EnvironmentError(exc.stderr)
  613. def git_credential_helper_store(self):
  614. """
  615. Sets the git credential helper to `store`
  616. """
  617. try:
  618. run_subprocess("git config credential.helper store", self.local_dir)
  619. except subprocess.CalledProcessError as exc:
  620. raise EnvironmentError(exc.stderr)
  621. def git_head_hash(self) -> str:
  622. """
  623. Get commit sha on top of HEAD.
  624. Returns:
  625. `str`: The current checked out commit SHA.
  626. """
  627. try:
  628. p = run_subprocess("git rev-parse HEAD", self.local_dir)
  629. return p.stdout.strip()
  630. except subprocess.CalledProcessError as exc:
  631. raise EnvironmentError(exc.stderr)
  632. def git_remote_url(self) -> str:
  633. """
  634. Get URL to origin remote.
  635. Returns:
  636. `str`: The URL of the `origin` remote.
  637. """
  638. try:
  639. p = run_subprocess("git config --get remote.origin.url", self.local_dir)
  640. url = p.stdout.strip()
  641. # Strip basic auth info.
  642. return re.sub(r"https://.*@", "https://", url)
  643. except subprocess.CalledProcessError as exc:
  644. raise EnvironmentError(exc.stderr)
  645. def git_head_commit_url(self) -> str:
  646. """
  647. Get URL to last commit on HEAD. We assume it's been pushed, and the url
  648. scheme is the same one as for GitHub or HuggingFace.
  649. Returns:
  650. `str`: The URL to the current checked-out commit.
  651. """
  652. sha = self.git_head_hash()
  653. url = self.git_remote_url()
  654. if url.endswith("/"):
  655. url = url[:-1]
  656. return f"{url}/commit/{sha}"
  657. def list_deleted_files(self) -> List[str]:
  658. """
  659. Returns a list of the files that are deleted in the working directory or
  660. index.
  661. Returns:
  662. `List[str]`: A list of files that have been deleted in the working
  663. directory or index.
  664. """
  665. try:
  666. git_status = run_subprocess("git status -s", self.local_dir).stdout.strip()
  667. except subprocess.CalledProcessError as exc:
  668. raise EnvironmentError(exc.stderr)
  669. if len(git_status) == 0:
  670. return []
  671. # Receives a status like the following
  672. # D .gitignore
  673. # D new_file.json
  674. # AD new_file1.json
  675. # ?? new_file2.json
  676. # ?? new_file4.json
  677. # Strip each line of whitespaces
  678. modified_files_statuses = [status.strip() for status in git_status.split("\n")]
  679. # Only keep files that are deleted using the D prefix
  680. deleted_files_statuses = [status for status in modified_files_statuses if "D" in status.split()[0]]
  681. # Remove the D prefix and strip to keep only the relevant filename
  682. deleted_files = [status.split()[-1].strip() for status in deleted_files_statuses]
  683. return deleted_files
  684. def lfs_track(self, patterns: Union[str, List[str]], filename: bool = False):
  685. """
  686. Tell git-lfs to track files according to a pattern.
  687. Setting the `filename` argument to `True` will treat the arguments as
  688. literal filenames, not as patterns. Any special glob characters in the
  689. filename will be escaped when writing to the `.gitattributes` file.
  690. Args:
  691. patterns (`Union[str, List[str]]`):
  692. The pattern, or list of patterns, to track with git-lfs.
  693. filename (`bool`, *optional*, defaults to `False`):
  694. Whether to use the patterns as literal filenames.
  695. """
  696. if isinstance(patterns, str):
  697. patterns = [patterns]
  698. try:
  699. for pattern in patterns:
  700. run_subprocess(
  701. f"git lfs track {'--filename' if filename else ''} {pattern}",
  702. self.local_dir,
  703. )
  704. except subprocess.CalledProcessError as exc:
  705. raise EnvironmentError(exc.stderr)
  706. def lfs_untrack(self, patterns: Union[str, List[str]]):
  707. """
  708. Tell git-lfs to untrack those files.
  709. Args:
  710. patterns (`Union[str, List[str]]`):
  711. The pattern, or list of patterns, to untrack with git-lfs.
  712. """
  713. if isinstance(patterns, str):
  714. patterns = [patterns]
  715. try:
  716. for pattern in patterns:
  717. run_subprocess("git lfs untrack".split() + [pattern], self.local_dir)
  718. except subprocess.CalledProcessError as exc:
  719. raise EnvironmentError(exc.stderr)
  720. def lfs_enable_largefiles(self):
  721. """
  722. HF-specific. This enables upload support of files >5GB.
  723. """
  724. try:
  725. lfs_config = "git config lfs.customtransfer.multipart"
  726. run_subprocess(f"{lfs_config}.path hf", self.local_dir)
  727. run_subprocess(
  728. f"{lfs_config}.args {LFS_MULTIPART_UPLOAD_COMMAND}",
  729. self.local_dir,
  730. )
  731. except subprocess.CalledProcessError as exc:
  732. raise EnvironmentError(exc.stderr)
  733. def auto_track_binary_files(self, pattern: str = ".") -> List[str]:
  734. """
  735. Automatically track binary files with git-lfs.
  736. Args:
  737. pattern (`str`, *optional*, defaults to "."):
  738. The pattern with which to track files that are binary.
  739. Returns:
  740. `List[str]`: List of filenames that are now tracked due to being
  741. binary files
  742. """
  743. files_to_be_tracked_with_lfs = []
  744. deleted_files = self.list_deleted_files()
  745. for filename in files_to_be_staged(pattern, folder=self.local_dir):
  746. if filename in deleted_files:
  747. continue
  748. path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
  749. if not (is_tracked_with_lfs(path_to_file) or is_git_ignored(path_to_file)):
  750. size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
  751. if size_in_mb >= 10:
  752. logger.warning(
  753. "Parsing a large file to check if binary or not. Tracking large"
  754. " files using `repository.auto_track_large_files` is"
  755. " recommended so as to not load the full file in memory."
  756. )
  757. is_binary = is_binary_file(path_to_file)
  758. if is_binary:
  759. self.lfs_track(filename)
  760. files_to_be_tracked_with_lfs.append(filename)
  761. # Cleanup the .gitattributes if files were deleted
  762. self.lfs_untrack(deleted_files)
  763. return files_to_be_tracked_with_lfs
  764. def auto_track_large_files(self, pattern: str = ".") -> List[str]:
  765. """
  766. Automatically track large files (files that weigh more than 10MBs) with
  767. git-lfs.
  768. Args:
  769. pattern (`str`, *optional*, defaults to "."):
  770. The pattern with which to track files that are above 10MBs.
  771. Returns:
  772. `List[str]`: List of filenames that are now tracked due to their
  773. size.
  774. """
  775. files_to_be_tracked_with_lfs = []
  776. deleted_files = self.list_deleted_files()
  777. for filename in files_to_be_staged(pattern, folder=self.local_dir):
  778. if filename in deleted_files:
  779. continue
  780. path_to_file = os.path.join(os.getcwd(), self.local_dir, filename)
  781. size_in_mb = os.path.getsize(path_to_file) / (1024 * 1024)
  782. if size_in_mb >= 10 and not is_tracked_with_lfs(path_to_file) and not is_git_ignored(path_to_file):
  783. self.lfs_track(filename)
  784. files_to_be_tracked_with_lfs.append(filename)
  785. # Cleanup the .gitattributes if files were deleted
  786. self.lfs_untrack(deleted_files)
  787. return files_to_be_tracked_with_lfs
  788. def lfs_prune(self, recent=False):
  789. """
  790. git lfs prune
  791. Args:
  792. recent (`bool`, *optional*, defaults to `False`):
  793. Whether to prune files even if they were referenced by recent
  794. commits. See the following
  795. [link](https://github.com/git-lfs/git-lfs/blob/f3d43f0428a84fc4f1e5405b76b5a73ec2437e65/docs/man/git-lfs-prune.1.ronn#recent-files)
  796. for more information.
  797. """
  798. try:
  799. with _lfs_log_progress():
  800. result = run_subprocess(f"git lfs prune {'--recent' if recent else ''}", self.local_dir)
  801. logger.info(result.stdout)
  802. except subprocess.CalledProcessError as exc:
  803. raise EnvironmentError(exc.stderr)
  804. def git_pull(self, rebase: bool = False, lfs: bool = False):
  805. """
  806. git pull
  807. Args:
  808. rebase (`bool`, *optional*, defaults to `False`):
  809. Whether to rebase the current branch on top of the upstream
  810. branch after fetching.
  811. lfs (`bool`, *optional*, defaults to `False`):
  812. Whether to fetch the LFS files too. This option only changes the
  813. behavior when a repository was cloned without fetching the LFS
  814. files; calling `repo.git_pull(lfs=True)` will then fetch the LFS
  815. file from the remote repository.
  816. """
  817. command = "git pull" if not lfs else "git lfs pull"
  818. if rebase:
  819. command += " --rebase"
  820. try:
  821. with _lfs_log_progress():
  822. result = run_subprocess(command, self.local_dir)
  823. logger.info(result.stdout)
  824. except subprocess.CalledProcessError as exc:
  825. raise EnvironmentError(exc.stderr)
  826. def git_add(self, pattern: str = ".", auto_lfs_track: bool = False):
  827. """
  828. git add
  829. Setting the `auto_lfs_track` parameter to `True` will automatically
  830. track files that are larger than 10MB with `git-lfs`.
  831. Args:
  832. pattern (`str`, *optional*, defaults to "."):
  833. The pattern with which to add files to staging.
  834. auto_lfs_track (`bool`, *optional*, defaults to `False`):
  835. Whether to automatically track large and binary files with
  836. git-lfs. Any file over 10MB in size, or in binary format, will
  837. be automatically tracked.
  838. """
  839. if auto_lfs_track:
  840. # Track files according to their size (>=10MB)
  841. tracked_files = self.auto_track_large_files(pattern)
  842. # Read the remaining files and track them if they're binary
  843. tracked_files.extend(self.auto_track_binary_files(pattern))
  844. if tracked_files:
  845. logger.warning(
  846. f"Adding files tracked by Git LFS: {tracked_files}. This may take a"
  847. " bit of time if the files are large."
  848. )
  849. try:
  850. result = run_subprocess("git add -v".split() + [pattern], self.local_dir)
  851. logger.info(f"Adding to index:\n{result.stdout}\n")
  852. except subprocess.CalledProcessError as exc:
  853. raise EnvironmentError(exc.stderr)
  854. def git_commit(self, commit_message: str = "commit files to HF hub"):
  855. """
  856. git commit
  857. Args:
  858. commit_message (`str`, *optional*, defaults to "commit files to HF hub"):
  859. The message attributed to the commit.
  860. """
  861. try:
  862. result = run_subprocess("git commit -v -m".split() + [commit_message], self.local_dir)
  863. logger.info(f"Committed:\n{result.stdout}\n")
  864. except subprocess.CalledProcessError as exc:
  865. if len(exc.stderr) > 0:
  866. raise EnvironmentError(exc.stderr)
  867. else:
  868. raise EnvironmentError(exc.stdout)
  869. def git_push(
  870. self,
  871. upstream: Optional[str] = None,
  872. blocking: bool = True,
  873. auto_lfs_prune: bool = False,
  874. ) -> Union[str, Tuple[str, CommandInProgress]]:
  875. """
  876. git push
  877. If used without setting `blocking`, will return url to commit on remote
  878. repo. If used with `blocking=True`, will return a tuple containing the
  879. url to commit and the command object to follow for information about the
  880. process.
  881. Args:
  882. upstream (`str`, *optional*):
  883. Upstream to which this should push. If not specified, will push
  884. to the lastly defined upstream or to the default one (`origin
  885. main`).
  886. blocking (`bool`, *optional*, defaults to `True`):
  887. Whether the function should return only when the push has
  888. finished. Setting this to `False` will return an
  889. `CommandInProgress` object which has an `is_done` property. This
  890. property will be set to `True` when the push is finished.
  891. auto_lfs_prune (`bool`, *optional*, defaults to `False`):
  892. Whether to automatically prune files once they have been pushed
  893. to the remote.
  894. """
  895. command = "git push"
  896. if upstream:
  897. command += f" --set-upstream {upstream}"
  898. number_of_commits = commits_to_push(self.local_dir, upstream)
  899. if number_of_commits > 1:
  900. logger.warning(f"Several commits ({number_of_commits}) will be pushed upstream.")
  901. if blocking:
  902. logger.warning("The progress bars may be unreliable.")
  903. try:
  904. with _lfs_log_progress():
  905. process = subprocess.Popen(
  906. command.split(),
  907. stderr=subprocess.PIPE,
  908. stdout=subprocess.PIPE,
  909. encoding="utf-8",
  910. cwd=self.local_dir,
  911. )
  912. if blocking:
  913. stdout, stderr = process.communicate()
  914. return_code = process.poll()
  915. process.kill()
  916. if len(stderr):
  917. logger.warning(stderr)
  918. if return_code:
  919. raise subprocess.CalledProcessError(return_code, process.args, output=stdout, stderr=stderr)
  920. except subprocess.CalledProcessError as exc:
  921. raise EnvironmentError(exc.stderr)
  922. if not blocking:
  923. def status_method():
  924. status = process.poll()
  925. if status is None:
  926. return -1
  927. else:
  928. return status
  929. command_in_progress = CommandInProgress(
  930. "push",
  931. is_done_method=lambda: process.poll() is not None,
  932. status_method=status_method,
  933. process=process,
  934. post_method=self.lfs_prune if auto_lfs_prune else None,
  935. )
  936. self.command_queue.append(command_in_progress)
  937. return self.git_head_commit_url(), command_in_progress
  938. if auto_lfs_prune:
  939. self.lfs_prune()
  940. return self.git_head_commit_url()
  941. def git_checkout(self, revision: str, create_branch_ok: bool = False):
  942. """
  943. git checkout a given revision
  944. Specifying `create_branch_ok` to `True` will create the branch to the
  945. given revision if that revision doesn't exist.
  946. Args:
  947. revision (`str`):
  948. The revision to checkout.
  949. create_branch_ok (`str`, *optional*, defaults to `False`):
  950. Whether creating a branch named with the `revision` passed at
  951. the current checked-out reference if `revision` isn't an
  952. existing revision is allowed.
  953. """
  954. try:
  955. result = run_subprocess(f"git checkout {revision}", self.local_dir)
  956. logger.warning(f"Checked out {revision} from {self.current_branch}.")
  957. logger.warning(result.stdout)
  958. except subprocess.CalledProcessError as exc:
  959. if not create_branch_ok:
  960. raise EnvironmentError(exc.stderr)
  961. else:
  962. try:
  963. result = run_subprocess(f"git checkout -b {revision}", self.local_dir)
  964. logger.warning(
  965. f"Revision `{revision}` does not exist. Created and checked out branch `{revision}`."
  966. )
  967. logger.warning(result.stdout)
  968. except subprocess.CalledProcessError as exc:
  969. raise EnvironmentError(exc.stderr)
  970. def tag_exists(self, tag_name: str, remote: Optional[str] = None) -> bool:
  971. """
  972. Check if a tag exists or not.
  973. Args:
  974. tag_name (`str`):
  975. The name of the tag to check.
  976. remote (`str`, *optional*):
  977. Whether to check if the tag exists on a remote. This parameter
  978. should be the identifier of the remote.
  979. Returns:
  980. `bool`: Whether the tag exists.
  981. """
  982. if remote:
  983. try:
  984. result = run_subprocess(f"git ls-remote origin refs/tags/{tag_name}", self.local_dir).stdout.strip()
  985. except subprocess.CalledProcessError as exc:
  986. raise EnvironmentError(exc.stderr)
  987. return len(result) != 0
  988. else:
  989. try:
  990. git_tags = run_subprocess("git tag", self.local_dir).stdout.strip()
  991. except subprocess.CalledProcessError as exc:
  992. raise EnvironmentError(exc.stderr)
  993. git_tags = git_tags.split("\n")
  994. return tag_name in git_tags
  995. def delete_tag(self, tag_name: str, remote: Optional[str] = None) -> bool:
  996. """
  997. Delete a tag, both local and remote, if it exists
  998. Args:
  999. tag_name (`str`):
  1000. The tag name to delete.
  1001. remote (`str`, *optional*):
  1002. The remote on which to delete the tag.
  1003. Returns:
  1004. `bool`: `True` if deleted, `False` if the tag didn't exist.
  1005. If remote is not passed, will just be updated locally
  1006. """
  1007. delete_locally = True
  1008. delete_remotely = True
  1009. if not self.tag_exists(tag_name):
  1010. delete_locally = False
  1011. if not self.tag_exists(tag_name, remote=remote):
  1012. delete_remotely = False
  1013. if delete_locally:
  1014. try:
  1015. run_subprocess(["git", "tag", "-d", tag_name], self.local_dir).stdout.strip()
  1016. except subprocess.CalledProcessError as exc:
  1017. raise EnvironmentError(exc.stderr)
  1018. if remote and delete_remotely:
  1019. try:
  1020. run_subprocess(f"git push {remote} --delete {tag_name}", self.local_dir).stdout.strip()
  1021. except subprocess.CalledProcessError as exc:
  1022. raise EnvironmentError(exc.stderr)
  1023. return True
  1024. def add_tag(self, tag_name: str, message: Optional[str] = None, remote: Optional[str] = None):
  1025. """
  1026. Add a tag at the current head and push it
  1027. If remote is None, will just be updated locally
  1028. If no message is provided, the tag will be lightweight. if a message is
  1029. provided, the tag will be annotated.
  1030. Args:
  1031. tag_name (`str`):
  1032. The name of the tag to be added.
  1033. message (`str`, *optional*):
  1034. The message that accompanies the tag. The tag will turn into an
  1035. annotated tag if a message is passed.
  1036. remote (`str`, *optional*):
  1037. The remote on which to add the tag.
  1038. """
  1039. if message:
  1040. tag_args = ["git", "tag", "-a", tag_name, "-m", message]
  1041. else:
  1042. tag_args = ["git", "tag", tag_name]
  1043. try:
  1044. run_subprocess(tag_args, self.local_dir).stdout.strip()
  1045. except subprocess.CalledProcessError as exc:
  1046. raise EnvironmentError(exc.stderr)
  1047. if remote:
  1048. try:
  1049. run_subprocess(f"git push {remote} {tag_name}", self.local_dir).stdout.strip()
  1050. except subprocess.CalledProcessError as exc:
  1051. raise EnvironmentError(exc.stderr)
  1052. def is_repo_clean(self) -> bool:
  1053. """
  1054. Return whether or not the git status is clean or not
  1055. Returns:
  1056. `bool`: `True` if the git status is clean, `False` otherwise.
  1057. """
  1058. try:
  1059. git_status = run_subprocess("git status --porcelain", self.local_dir).stdout.strip()
  1060. except subprocess.CalledProcessError as exc:
  1061. raise EnvironmentError(exc.stderr)
  1062. return len(git_status) == 0
  1063. def push_to_hub(
  1064. self,
  1065. commit_message: str = "commit files to HF hub",
  1066. blocking: bool = True,
  1067. clean_ok: bool = True,
  1068. auto_lfs_prune: bool = False,
  1069. ) -> Union[None, str, Tuple[str, CommandInProgress]]:
  1070. """
  1071. Helper to add, commit, and push files to remote repository on the
  1072. HuggingFace Hub. Will automatically track large files (>10MB).
  1073. Args:
  1074. commit_message (`str`):
  1075. Message to use for the commit.
  1076. blocking (`bool`, *optional*, defaults to `True`):
  1077. Whether the function should return only when the `git push` has
  1078. finished.
  1079. clean_ok (`bool`, *optional*, defaults to `True`):
  1080. If True, this function will return None if the repo is
  1081. untouched. Default behavior is to fail because the git command
  1082. fails.
  1083. auto_lfs_prune (`bool`, *optional*, defaults to `False`):
  1084. Whether to automatically prune files once they have been pushed
  1085. to the remote.
  1086. """
  1087. if clean_ok and self.is_repo_clean():
  1088. logger.info("Repo currently clean. Ignoring push_to_hub")
  1089. return None
  1090. self.git_add(auto_lfs_track=True)
  1091. self.git_commit(commit_message)
  1092. return self.git_push(
  1093. upstream=f"origin {self.current_branch}",
  1094. blocking=blocking,
  1095. auto_lfs_prune=auto_lfs_prune,
  1096. )
  1097. @contextmanager
  1098. def commit(
  1099. self,
  1100. commit_message: str,
  1101. branch: Optional[str] = None,
  1102. track_large_files: bool = True,
  1103. blocking: bool = True,
  1104. auto_lfs_prune: bool = False,
  1105. ):
  1106. """
  1107. Context manager utility to handle committing to a repository. This
  1108. automatically tracks large files (>10Mb) with git-lfs. Set the
  1109. `track_large_files` argument to `False` if you wish to ignore that
  1110. behavior.
  1111. Args:
  1112. commit_message (`str`):
  1113. Message to use for the commit.
  1114. branch (`str`, *optional*):
  1115. The branch on which the commit will appear. This branch will be
  1116. checked-out before any operation.
  1117. track_large_files (`bool`, *optional*, defaults to `True`):
  1118. Whether to automatically track large files or not. Will do so by
  1119. default.
  1120. blocking (`bool`, *optional*, defaults to `True`):
  1121. Whether the function should return only when the `git push` has
  1122. finished.
  1123. auto_lfs_prune (`bool`, defaults to `True`):
  1124. Whether to automatically prune files once they have been pushed
  1125. to the remote.
  1126. Examples:
  1127. ```python
  1128. >>> with Repository(
  1129. ... "text-files",
  1130. ... clone_from="<user>/text-files",
  1131. ... token=True,
  1132. >>> ).commit("My first file :)"):
  1133. ... with open("file.txt", "w+") as f:
  1134. ... f.write(json.dumps({"hey": 8}))
  1135. >>> import torch
  1136. >>> model = torch.nn.Transformer()
  1137. >>> with Repository(
  1138. ... "torch-model",
  1139. ... clone_from="<user>/torch-model",
  1140. ... token=True,
  1141. >>> ).commit("My cool model :)"):
  1142. ... torch.save(model.state_dict(), "model.pt")
  1143. ```
  1144. """
  1145. files_to_stage = files_to_be_staged(".", folder=self.local_dir)
  1146. if len(files_to_stage):
  1147. files_in_msg = str(files_to_stage[:5])[:-1] + ", ...]" if len(files_to_stage) > 5 else str(files_to_stage)
  1148. logger.error(
  1149. "There exists some updated files in the local repository that are not"
  1150. f" committed: {files_in_msg}. This may lead to errors if checking out"
  1151. " a branch. These files and their modifications will be added to the"
  1152. " current commit."
  1153. )
  1154. if branch is not None:
  1155. self.git_checkout(branch, create_branch_ok=True)
  1156. if is_tracked_upstream(self.local_dir):
  1157. logger.warning("Pulling changes ...")
  1158. self.git_pull(rebase=True)
  1159. else:
  1160. logger.warning(f"The current branch has no upstream branch. Will push to 'origin {self.current_branch}'")
  1161. current_working_directory = os.getcwd()
  1162. os.chdir(os.path.join(current_working_directory, self.local_dir))
  1163. try:
  1164. yield self
  1165. finally:
  1166. self.git_add(auto_lfs_track=track_large_files)
  1167. try:
  1168. self.git_commit(commit_message)
  1169. except OSError as e:
  1170. # If no changes are detected, there is nothing to commit.
  1171. if "nothing to commit" not in str(e):
  1172. raise e
  1173. try:
  1174. self.git_push(
  1175. upstream=f"origin {self.current_branch}",
  1176. blocking=blocking,
  1177. auto_lfs_prune=auto_lfs_prune,
  1178. )
  1179. except OSError as e:
  1180. # If no changes are detected, there is nothing to commit.
  1181. if "could not read Username" in str(e):
  1182. raise OSError("Couldn't authenticate user for push. Did you set `token` to `True`?") from e
  1183. else:
  1184. raise e
  1185. os.chdir(current_working_directory)
  1186. def repocard_metadata_load(self) -> Optional[Dict]:
  1187. filepath = os.path.join(self.local_dir, constants.REPOCARD_NAME)
  1188. if os.path.isfile(filepath):
  1189. return metadata_load(filepath)
  1190. return None
  1191. def repocard_metadata_save(self, data: Dict) -> None:
  1192. return metadata_save(os.path.join(self.local_dir, constants.REPOCARD_NAME), data)
  1193. @property
  1194. def commands_failed(self):
  1195. """
  1196. Returns the asynchronous commands that failed.
  1197. """
  1198. return [c for c in self.command_queue if c.status > 0]
  1199. @property
  1200. def commands_in_progress(self):
  1201. """
  1202. Returns the asynchronous commands that are currently in progress.
  1203. """
  1204. return [c for c in self.command_queue if not c.is_done]
  1205. def wait_for_commands(self):
  1206. """
  1207. Blocking method: blocks all subsequent execution until all commands have
  1208. been processed.
  1209. """
  1210. index = 0
  1211. for command_failed in self.commands_failed:
  1212. logger.error(f"The {command_failed.title} command with PID {command_failed._process.pid} failed.")
  1213. logger.error(command_failed.stderr)
  1214. while self.commands_in_progress:
  1215. if index % 10 == 0:
  1216. logger.warning(
  1217. f"Waiting for the following commands to finish before shutting down: {self.commands_in_progress}."
  1218. )
  1219. index += 1
  1220. time.sleep(1)