repo.py 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893
  1. # repo.py -- For dealing with git repositories.
  2. # Copyright (C) 2007 James Westby <jw+debian@jameswestby.net>
  3. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@jelmer.uk>
  4. #
  5. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  6. # General Public License as public by the Free Software Foundation; version 2.0
  7. # or (at your option) any later version. You can redistribute it and/or
  8. # modify it under the terms of either of these two licenses.
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. # You should have received a copy of the licenses; if not, see
  17. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  18. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  19. # License, Version 2.0.
  20. #
  21. """Repository access.
  22. This module contains the base class for git repositories
  23. (BaseRepo) and an implementation which uses a repository on
  24. local disk (Repo).
  25. """
  26. import os
  27. import stat
  28. import sys
  29. import time
  30. import warnings
  31. from io import BytesIO
  32. from typing import (
  33. TYPE_CHECKING,
  34. BinaryIO,
  35. Callable,
  36. Dict,
  37. FrozenSet,
  38. Iterable,
  39. List,
  40. Optional,
  41. Set,
  42. Tuple,
  43. Union,
  44. )
  45. if TYPE_CHECKING:
  46. # There are no circular imports here, but we try to defer imports as long
  47. # as possible to reduce start-up time for anything that doesn't need
  48. # these imports.
  49. from .config import ConfigFile, StackedConfig
  50. from .index import Index
  51. from .errors import (
  52. CommitError,
  53. HookError,
  54. NoIndexPresent,
  55. NotBlobError,
  56. NotCommitError,
  57. NotGitRepository,
  58. NotTagError,
  59. NotTreeError,
  60. RefFormatError,
  61. )
  62. from .file import GitFile
  63. from .hooks import (
  64. CommitMsgShellHook,
  65. Hook,
  66. PostCommitShellHook,
  67. PostReceiveShellHook,
  68. PreCommitShellHook,
  69. )
  70. from .line_ending import BlobNormalizer, TreeBlobNormalizer
  71. from .object_store import (
  72. DiskObjectStore,
  73. MemoryObjectStore,
  74. MissingObjectFinder,
  75. ObjectStoreGraphWalker,
  76. PackBasedObjectStore,
  77. peel_sha,
  78. )
  79. from .objects import (
  80. Blob,
  81. Commit,
  82. ObjectID,
  83. ShaFile,
  84. Tag,
  85. Tree,
  86. check_hexsha,
  87. valid_hexsha,
  88. )
  89. from .pack import generate_unpacked_objects
  90. from .refs import ( # noqa: F401
  91. ANNOTATED_TAG_SUFFIX,
  92. LOCAL_BRANCH_PREFIX,
  93. LOCAL_TAG_PREFIX,
  94. SYMREF,
  95. DictRefsContainer,
  96. DiskRefsContainer,
  97. InfoRefsContainer,
  98. Ref,
  99. RefsContainer,
  100. _set_default_branch,
  101. _set_head,
  102. _set_origin_head,
  103. check_ref_format,
  104. read_packed_refs,
  105. read_packed_refs_with_peeled,
  106. serialize_refs,
  107. write_packed_refs,
  108. )
  109. CONTROLDIR = ".git"
  110. OBJECTDIR = "objects"
  111. REFSDIR = "refs"
  112. REFSDIR_TAGS = "tags"
  113. REFSDIR_HEADS = "heads"
  114. INDEX_FILENAME = "index"
  115. COMMONDIR = "commondir"
  116. GITDIR = "gitdir"
  117. WORKTREES = "worktrees"
  118. BASE_DIRECTORIES = [
  119. ["branches"],
  120. [REFSDIR],
  121. [REFSDIR, REFSDIR_TAGS],
  122. [REFSDIR, REFSDIR_HEADS],
  123. ["hooks"],
  124. ["info"],
  125. ]
  126. DEFAULT_BRANCH = b"master"
  127. class InvalidUserIdentity(Exception):
  128. """User identity is not of the format 'user <email>'."""
  129. def __init__(self, identity) -> None:
  130. self.identity = identity
  131. # TODO(jelmer): Cache?
  132. def _get_default_identity() -> Tuple[str, str]:
  133. import socket
  134. for name in ('LOGNAME', 'USER', 'LNAME', 'USERNAME'):
  135. username = os.environ.get(name)
  136. if username:
  137. break
  138. else:
  139. username = None
  140. try:
  141. import pwd
  142. except ImportError:
  143. fullname = None
  144. else:
  145. try:
  146. entry = pwd.getpwuid(os.getuid()) # type: ignore
  147. except KeyError:
  148. fullname = None
  149. else:
  150. if getattr(entry, 'gecos', None):
  151. fullname = entry.pw_gecos.split(",")[0]
  152. else:
  153. fullname = None
  154. if username is None:
  155. username = entry.pw_name
  156. if not fullname:
  157. fullname = username
  158. email = os.environ.get("EMAIL")
  159. if email is None:
  160. email = f"{username}@{socket.gethostname()}"
  161. return (fullname, email) # type: ignore
  162. def get_user_identity(config: "StackedConfig", kind: Optional[str] = None) -> bytes:
  163. """Determine the identity to use for new commits.
  164. If kind is set, this first checks
  165. GIT_${KIND}_NAME and GIT_${KIND}_EMAIL.
  166. If those variables are not set, then it will fall back
  167. to reading the user.name and user.email settings from
  168. the specified configuration.
  169. If that also fails, then it will fall back to using
  170. the current users' identity as obtained from the host
  171. system (e.g. the gecos field, $EMAIL, $USER@$(hostname -f).
  172. Args:
  173. kind: Optional kind to return identity for,
  174. usually either "AUTHOR" or "COMMITTER".
  175. Returns:
  176. A user identity
  177. """
  178. user: Optional[bytes] = None
  179. email: Optional[bytes] = None
  180. if kind:
  181. user_uc = os.environ.get("GIT_" + kind + "_NAME")
  182. if user_uc is not None:
  183. user = user_uc.encode("utf-8")
  184. email_uc = os.environ.get("GIT_" + kind + "_EMAIL")
  185. if email_uc is not None:
  186. email = email_uc.encode("utf-8")
  187. if user is None:
  188. try:
  189. user = config.get(("user",), "name")
  190. except KeyError:
  191. user = None
  192. if email is None:
  193. try:
  194. email = config.get(("user",), "email")
  195. except KeyError:
  196. email = None
  197. default_user, default_email = _get_default_identity()
  198. if user is None:
  199. user = default_user.encode("utf-8")
  200. if email is None:
  201. email = default_email.encode("utf-8")
  202. if email.startswith(b"<") and email.endswith(b">"):
  203. email = email[1:-1]
  204. return user + b" <" + email + b">"
  205. def check_user_identity(identity):
  206. """Verify that a user identity is formatted correctly.
  207. Args:
  208. identity: User identity bytestring
  209. Raises:
  210. InvalidUserIdentity: Raised when identity is invalid
  211. """
  212. try:
  213. fst, snd = identity.split(b" <", 1)
  214. except ValueError as exc:
  215. raise InvalidUserIdentity(identity) from exc
  216. if b">" not in snd:
  217. raise InvalidUserIdentity(identity)
  218. if b'\0' in identity or b'\n' in identity:
  219. raise InvalidUserIdentity(identity)
  220. def parse_graftpoints(
  221. graftpoints: Iterable[bytes],
  222. ) -> Dict[bytes, List[bytes]]:
  223. """Convert a list of graftpoints into a dict.
  224. Args:
  225. graftpoints: Iterator of graftpoint lines
  226. Each line is formatted as:
  227. <commit sha1> <parent sha1> [<parent sha1>]*
  228. Resulting dictionary is:
  229. <commit sha1>: [<parent sha1>*]
  230. https://git.wiki.kernel.org/index.php/GraftPoint
  231. """
  232. grafts = {}
  233. for line in graftpoints:
  234. raw_graft = line.split(None, 1)
  235. commit = raw_graft[0]
  236. if len(raw_graft) == 2:
  237. parents = raw_graft[1].split()
  238. else:
  239. parents = []
  240. for sha in [commit] + parents:
  241. check_hexsha(sha, "Invalid graftpoint")
  242. grafts[commit] = parents
  243. return grafts
  244. def serialize_graftpoints(graftpoints: Dict[bytes, List[bytes]]) -> bytes:
  245. """Convert a dictionary of grafts into string.
  246. The graft dictionary is:
  247. <commit sha1>: [<parent sha1>*]
  248. Each line is formatted as:
  249. <commit sha1> <parent sha1> [<parent sha1>]*
  250. https://git.wiki.kernel.org/index.php/GraftPoint
  251. """
  252. graft_lines = []
  253. for commit, parents in graftpoints.items():
  254. if parents:
  255. graft_lines.append(commit + b" " + b" ".join(parents))
  256. else:
  257. graft_lines.append(commit)
  258. return b"\n".join(graft_lines)
  259. def _set_filesystem_hidden(path):
  260. """Mark path as to be hidden if supported by platform and filesystem.
  261. On win32 uses SetFileAttributesW api:
  262. <https://docs.microsoft.com/windows/desktop/api/fileapi/nf-fileapi-setfileattributesw>
  263. """
  264. if sys.platform == "win32":
  265. import ctypes
  266. from ctypes.wintypes import BOOL, DWORD, LPCWSTR
  267. FILE_ATTRIBUTE_HIDDEN = 2
  268. SetFileAttributesW = ctypes.WINFUNCTYPE(BOOL, LPCWSTR, DWORD)(
  269. ("SetFileAttributesW", ctypes.windll.kernel32)
  270. )
  271. if isinstance(path, bytes):
  272. path = os.fsdecode(path)
  273. if not SetFileAttributesW(path, FILE_ATTRIBUTE_HIDDEN):
  274. pass # Could raise or log `ctypes.WinError()` here
  275. # Could implement other platform specific filesystem hiding here
  276. class ParentsProvider:
  277. def __init__(self, store, grafts={}, shallows=[]) -> None:
  278. self.store = store
  279. self.grafts = grafts
  280. self.shallows = set(shallows)
  281. def get_parents(self, commit_id, commit=None):
  282. try:
  283. return self.grafts[commit_id]
  284. except KeyError:
  285. pass
  286. if commit_id in self.shallows:
  287. return []
  288. if commit is None:
  289. commit = self.store[commit_id]
  290. return commit.parents
  291. class BaseRepo:
  292. """Base class for a git repository.
  293. This base class is meant to be used for Repository implementations that e.g.
  294. work on top of a different transport than a standard filesystem path.
  295. Attributes:
  296. object_store: Dictionary-like object for accessing
  297. the objects
  298. refs: Dictionary-like object with the refs in this
  299. repository
  300. """
  301. def __init__(self, object_store: PackBasedObjectStore, refs: RefsContainer) -> None:
  302. """Open a repository.
  303. This shouldn't be called directly, but rather through one of the
  304. base classes, such as MemoryRepo or Repo.
  305. Args:
  306. object_store: Object store to use
  307. refs: Refs container to use
  308. """
  309. self.object_store = object_store
  310. self.refs = refs
  311. self._graftpoints: Dict[bytes, List[bytes]] = {}
  312. self.hooks: Dict[str, Hook] = {}
  313. def _determine_file_mode(self) -> bool:
  314. """Probe the file-system to determine whether permissions can be trusted.
  315. Returns: True if permissions can be trusted, False otherwise.
  316. """
  317. raise NotImplementedError(self._determine_file_mode)
  318. def _determine_symlinks(self) -> bool:
  319. """Probe the filesystem to determine whether symlinks can be created.
  320. Returns: True if symlinks can be created, False otherwise.
  321. """
  322. raise NotImplementedError(self._determine_symlinks)
  323. def _init_files(self, bare: bool, symlinks: Optional[bool] = None) -> None:
  324. """Initialize a default set of named files."""
  325. from .config import ConfigFile
  326. self._put_named_file("description", b"Unnamed repository")
  327. f = BytesIO()
  328. cf = ConfigFile()
  329. cf.set("core", "repositoryformatversion", "0")
  330. if self._determine_file_mode():
  331. cf.set("core", "filemode", True)
  332. else:
  333. cf.set("core", "filemode", False)
  334. if symlinks is None and not bare:
  335. symlinks = self._determine_symlinks()
  336. if symlinks is False:
  337. cf.set("core", "symlinks", symlinks)
  338. cf.set("core", "bare", bare)
  339. cf.set("core", "logallrefupdates", True)
  340. cf.write_to_file(f)
  341. self._put_named_file("config", f.getvalue())
  342. self._put_named_file(os.path.join("info", "exclude"), b"")
  343. def get_named_file(self, path: str) -> Optional[BinaryIO]:
  344. """Get a file from the control dir with a specific name.
  345. Although the filename should be interpreted as a filename relative to
  346. the control dir in a disk-based Repo, the object returned need not be
  347. pointing to a file in that location.
  348. Args:
  349. path: The path to the file, relative to the control dir.
  350. Returns: An open file object, or None if the file does not exist.
  351. """
  352. raise NotImplementedError(self.get_named_file)
  353. def _put_named_file(self, path: str, contents: bytes):
  354. """Write a file to the control dir with the given name and contents.
  355. Args:
  356. path: The path to the file, relative to the control dir.
  357. contents: A string to write to the file.
  358. """
  359. raise NotImplementedError(self._put_named_file)
  360. def _del_named_file(self, path: str):
  361. """Delete a file in the control directory with the given name."""
  362. raise NotImplementedError(self._del_named_file)
  363. def open_index(self) -> "Index":
  364. """Open the index for this repository.
  365. Raises:
  366. NoIndexPresent: If no index is present
  367. Returns: The matching `Index`
  368. """
  369. raise NotImplementedError(self.open_index)
  370. def fetch(self, target, determine_wants=None, progress=None, depth=None):
  371. """Fetch objects into another repository.
  372. Args:
  373. target: The target repository
  374. determine_wants: Optional function to determine what refs to
  375. fetch.
  376. progress: Optional progress function
  377. depth: Optional shallow fetch depth
  378. Returns: The local refs
  379. """
  380. if determine_wants is None:
  381. determine_wants = target.object_store.determine_wants_all
  382. count, pack_data = self.fetch_pack_data(
  383. determine_wants,
  384. target.get_graph_walker(),
  385. progress=progress,
  386. depth=depth,
  387. )
  388. target.object_store.add_pack_data(count, pack_data, progress)
  389. return self.get_refs()
  390. def fetch_pack_data(
  391. self,
  392. determine_wants,
  393. graph_walker,
  394. progress,
  395. get_tagged=None,
  396. depth=None,
  397. ):
  398. """Fetch the pack data required for a set of revisions.
  399. Args:
  400. determine_wants: Function that takes a dictionary with heads
  401. and returns the list of heads to fetch.
  402. graph_walker: Object that can iterate over the list of revisions
  403. to fetch and has an "ack" method that will be called to acknowledge
  404. that a revision is present.
  405. progress: Simple progress function that will be called with
  406. updated progress strings.
  407. get_tagged: Function that returns a dict of pointed-to sha ->
  408. tag sha for including tags.
  409. depth: Shallow fetch depth
  410. Returns: count and iterator over pack data
  411. """
  412. missing_objects = self.find_missing_objects(
  413. determine_wants, graph_walker, progress, get_tagged, depth=depth
  414. )
  415. remote_has = missing_objects.get_remote_has()
  416. object_ids = list(missing_objects)
  417. return len(object_ids), generate_unpacked_objects(
  418. self.object_store, object_ids, progress=progress,
  419. other_haves=remote_has)
  420. def find_missing_objects(
  421. self,
  422. determine_wants,
  423. graph_walker,
  424. progress,
  425. get_tagged=None,
  426. depth=None,
  427. ) -> Optional[MissingObjectFinder]:
  428. """Fetch the missing objects required for a set of revisions.
  429. Args:
  430. determine_wants: Function that takes a dictionary with heads
  431. and returns the list of heads to fetch.
  432. graph_walker: Object that can iterate over the list of revisions
  433. to fetch and has an "ack" method that will be called to acknowledge
  434. that a revision is present.
  435. progress: Simple progress function that will be called with
  436. updated progress strings.
  437. get_tagged: Function that returns a dict of pointed-to sha ->
  438. tag sha for including tags.
  439. depth: Shallow fetch depth
  440. Returns: iterator over objects, with __len__ implemented
  441. """
  442. if depth not in (None, 0):
  443. raise NotImplementedError("depth not supported yet")
  444. refs = serialize_refs(self.object_store, self.get_refs())
  445. wants = determine_wants(refs)
  446. if not isinstance(wants, list):
  447. raise TypeError("determine_wants() did not return a list")
  448. shallows: FrozenSet[ObjectID] = getattr(graph_walker, "shallow", frozenset())
  449. unshallows: FrozenSet[ObjectID] = getattr(graph_walker, "unshallow", frozenset())
  450. if wants == []:
  451. # TODO(dborowitz): find a way to short-circuit that doesn't change
  452. # this interface.
  453. if shallows or unshallows:
  454. # Do not send a pack in shallow short-circuit path
  455. return None
  456. class DummyMissingObjectFinder:
  457. def get_remote_has(self):
  458. return None
  459. def __len__(self) -> int:
  460. return 0
  461. def __iter__(self):
  462. yield from []
  463. return DummyMissingObjectFinder() # type: ignore
  464. # If the graph walker is set up with an implementation that can
  465. # ACK/NAK to the wire, it will write data to the client through
  466. # this call as a side-effect.
  467. haves = self.object_store.find_common_revisions(graph_walker)
  468. # Deal with shallow requests separately because the haves do
  469. # not reflect what objects are missing
  470. if shallows or unshallows:
  471. # TODO: filter the haves commits from iter_shas. the specific
  472. # commits aren't missing.
  473. haves = []
  474. parents_provider = ParentsProvider(self.object_store, shallows=shallows)
  475. def get_parents(commit):
  476. return parents_provider.get_parents(commit.id, commit)
  477. return MissingObjectFinder(
  478. self.object_store,
  479. haves=haves,
  480. wants=wants,
  481. shallow=self.get_shallow(),
  482. progress=progress,
  483. get_tagged=get_tagged,
  484. get_parents=get_parents)
  485. def generate_pack_data(self, have: List[ObjectID], want: List[ObjectID],
  486. progress: Optional[Callable[[str], None]] = None,
  487. ofs_delta: Optional[bool] = None):
  488. """Generate pack data objects for a set of wants/haves.
  489. Args:
  490. have: List of SHA1s of objects that should not be sent
  491. want: List of SHA1s of objects that should be sent
  492. ofs_delta: Whether OFS deltas can be included
  493. progress: Optional progress reporting method
  494. """
  495. return self.object_store.generate_pack_data(
  496. have,
  497. want,
  498. shallow=self.get_shallow(),
  499. progress=progress,
  500. ofs_delta=ofs_delta,
  501. )
  502. def get_graph_walker(
  503. self,
  504. heads: Optional[List[ObjectID]] = None) -> ObjectStoreGraphWalker:
  505. """Retrieve a graph walker.
  506. A graph walker is used by a remote repository (or proxy)
  507. to find out which objects are present in this repository.
  508. Args:
  509. heads: Repository heads to use (optional)
  510. Returns: A graph walker object
  511. """
  512. if heads is None:
  513. heads = [
  514. sha
  515. for sha in self.refs.as_dict(b"refs/heads").values()
  516. if sha in self.object_store
  517. ]
  518. parents_provider = ParentsProvider(self.object_store)
  519. return ObjectStoreGraphWalker(
  520. heads, parents_provider.get_parents, shallow=self.get_shallow()
  521. )
  522. def get_refs(self) -> Dict[bytes, bytes]:
  523. """Get dictionary with all refs.
  524. Returns: A ``dict`` mapping ref names to SHA1s
  525. """
  526. return self.refs.as_dict()
  527. def head(self) -> bytes:
  528. """Return the SHA1 pointed at by HEAD."""
  529. return self.refs[b"HEAD"]
  530. def _get_object(self, sha, cls):
  531. assert len(sha) in (20, 40)
  532. ret = self.get_object(sha)
  533. if not isinstance(ret, cls):
  534. if cls is Commit:
  535. raise NotCommitError(ret)
  536. elif cls is Blob:
  537. raise NotBlobError(ret)
  538. elif cls is Tree:
  539. raise NotTreeError(ret)
  540. elif cls is Tag:
  541. raise NotTagError(ret)
  542. else:
  543. raise Exception(
  544. "Type invalid: {!r} != {!r}".format(ret.type_name, cls.type_name)
  545. )
  546. return ret
  547. def get_object(self, sha: bytes) -> ShaFile:
  548. """Retrieve the object with the specified SHA.
  549. Args:
  550. sha: SHA to retrieve
  551. Returns: A ShaFile object
  552. Raises:
  553. KeyError: when the object can not be found
  554. """
  555. return self.object_store[sha]
  556. def parents_provider(self) -> ParentsProvider:
  557. return ParentsProvider(
  558. self.object_store,
  559. grafts=self._graftpoints,
  560. shallows=self.get_shallow(),
  561. )
  562. def get_parents(self, sha: bytes,
  563. commit: Optional[Commit] = None) -> List[bytes]:
  564. """Retrieve the parents of a specific commit.
  565. If the specific commit is a graftpoint, the graft parents
  566. will be returned instead.
  567. Args:
  568. sha: SHA of the commit for which to retrieve the parents
  569. commit: Optional commit matching the sha
  570. Returns: List of parents
  571. """
  572. return self.parents_provider().get_parents(sha, commit)
  573. def get_config(self) -> "ConfigFile":
  574. """Retrieve the config object.
  575. Returns: `ConfigFile` object for the ``.git/config`` file.
  576. """
  577. raise NotImplementedError(self.get_config)
  578. def get_worktree_config(self) -> "ConfigFile":
  579. """Retrieve the worktree config object."""
  580. raise NotImplementedError(self.get_worktree_config)
  581. def get_description(self):
  582. """Retrieve the description for this repository.
  583. Returns: String with the description of the repository
  584. as set by the user.
  585. """
  586. raise NotImplementedError(self.get_description)
  587. def set_description(self, description):
  588. """Set the description for this repository.
  589. Args:
  590. description: Text to set as description for this repository.
  591. """
  592. raise NotImplementedError(self.set_description)
  593. def get_config_stack(self) -> "StackedConfig":
  594. """Return a config stack for this repository.
  595. This stack accesses the configuration for both this repository
  596. itself (.git/config) and the global configuration, which usually
  597. lives in ~/.gitconfig.
  598. Returns: `Config` instance for this repository
  599. """
  600. from .config import ConfigFile, StackedConfig
  601. local_config = self.get_config()
  602. backends: List[ConfigFile] = [local_config]
  603. if local_config.get_boolean((b"extensions", ), b"worktreeconfig", False):
  604. backends.append(self.get_worktree_config())
  605. backends += StackedConfig.default_backends()
  606. return StackedConfig(backends, writable=local_config)
  607. def get_shallow(self) -> Set[ObjectID]:
  608. """Get the set of shallow commits.
  609. Returns: Set of shallow commits.
  610. """
  611. f = self.get_named_file("shallow")
  612. if f is None:
  613. return set()
  614. with f:
  615. return {line.strip() for line in f}
  616. def update_shallow(self, new_shallow, new_unshallow):
  617. """Update the list of shallow objects.
  618. Args:
  619. new_shallow: Newly shallow objects
  620. new_unshallow: Newly no longer shallow objects
  621. """
  622. shallow = self.get_shallow()
  623. if new_shallow:
  624. shallow.update(new_shallow)
  625. if new_unshallow:
  626. shallow.difference_update(new_unshallow)
  627. if shallow:
  628. self._put_named_file(
  629. "shallow", b"".join([sha + b"\n" for sha in shallow])
  630. )
  631. else:
  632. self._del_named_file("shallow")
  633. def get_peeled(self, ref: Ref) -> ObjectID:
  634. """Get the peeled value of a ref.
  635. Args:
  636. ref: The refname to peel.
  637. Returns: The fully-peeled SHA1 of a tag object, after peeling all
  638. intermediate tags; if the original ref does not point to a tag,
  639. this will equal the original SHA1.
  640. """
  641. cached = self.refs.get_peeled(ref)
  642. if cached is not None:
  643. return cached
  644. return peel_sha(self.object_store, self.refs[ref])[1].id
  645. def get_walker(self, include: Optional[List[bytes]] = None,
  646. *args, **kwargs):
  647. """Obtain a walker for this repository.
  648. Args:
  649. include: Iterable of SHAs of commits to include along with their
  650. ancestors. Defaults to [HEAD]
  651. exclude: Iterable of SHAs of commits to exclude along with their
  652. ancestors, overriding includes.
  653. order: ORDER_* constant specifying the order of results.
  654. Anything other than ORDER_DATE may result in O(n) memory usage.
  655. reverse: If True, reverse the order of output, requiring O(n)
  656. memory.
  657. max_entries: The maximum number of entries to yield, or None for
  658. no limit.
  659. paths: Iterable of file or subtree paths to show entries for.
  660. rename_detector: diff.RenameDetector object for detecting
  661. renames.
  662. follow: If True, follow path across renames/copies. Forces a
  663. default rename_detector.
  664. since: Timestamp to list commits after.
  665. until: Timestamp to list commits before.
  666. queue_cls: A class to use for a queue of commits, supporting the
  667. iterator protocol. The constructor takes a single argument, the
  668. Walker.
  669. Returns: A `Walker` object
  670. """
  671. from .walk import Walker
  672. if include is None:
  673. include = [self.head()]
  674. kwargs["get_parents"] = lambda commit: self.get_parents(commit.id, commit)
  675. return Walker(self.object_store, include, *args, **kwargs)
  676. def __getitem__(self, name: Union[ObjectID, Ref]):
  677. """Retrieve a Git object by SHA1 or ref.
  678. Args:
  679. name: A Git object SHA1 or a ref name
  680. Returns: A `ShaFile` object, such as a Commit or Blob
  681. Raises:
  682. KeyError: when the specified ref or object does not exist
  683. """
  684. if not isinstance(name, bytes):
  685. raise TypeError(
  686. "'name' must be bytestring, not %.80s" % type(name).__name__
  687. )
  688. if len(name) in (20, 40):
  689. try:
  690. return self.object_store[name]
  691. except (KeyError, ValueError):
  692. pass
  693. try:
  694. return self.object_store[self.refs[name]]
  695. except RefFormatError as exc:
  696. raise KeyError(name) from exc
  697. def __contains__(self, name: bytes) -> bool:
  698. """Check if a specific Git object or ref is present.
  699. Args:
  700. name: Git object SHA1 or ref name
  701. """
  702. if len(name) == 20 or (len(name) == 40 and valid_hexsha(name)):
  703. return name in self.object_store or name in self.refs
  704. else:
  705. return name in self.refs
  706. def __setitem__(self, name: bytes, value: Union[ShaFile, bytes]) -> None:
  707. """Set a ref.
  708. Args:
  709. name: ref name
  710. value: Ref value - either a ShaFile object, or a hex sha
  711. """
  712. if name.startswith(b"refs/") or name == b"HEAD":
  713. if isinstance(value, ShaFile):
  714. self.refs[name] = value.id
  715. elif isinstance(value, bytes):
  716. self.refs[name] = value
  717. else:
  718. raise TypeError(value)
  719. else:
  720. raise ValueError(name)
  721. def __delitem__(self, name: bytes) -> None:
  722. """Remove a ref.
  723. Args:
  724. name: Name of the ref to remove
  725. """
  726. if name.startswith(b"refs/") or name == b"HEAD":
  727. del self.refs[name]
  728. else:
  729. raise ValueError(name)
  730. def _get_user_identity(self, config: "StackedConfig",
  731. kind: Optional[str] = None) -> bytes:
  732. """Determine the identity to use for new commits."""
  733. # TODO(jelmer): Deprecate this function in favor of get_user_identity
  734. return get_user_identity(config)
  735. def _add_graftpoints(self, updated_graftpoints: Dict[bytes, List[bytes]]):
  736. """Add or modify graftpoints.
  737. Args:
  738. updated_graftpoints: Dict of commit shas to list of parent shas
  739. """
  740. # Simple validation
  741. for commit, parents in updated_graftpoints.items():
  742. for sha in [commit] + parents:
  743. check_hexsha(sha, "Invalid graftpoint")
  744. self._graftpoints.update(updated_graftpoints)
  745. def _remove_graftpoints(self, to_remove: List[bytes] = []) -> None:
  746. """Remove graftpoints.
  747. Args:
  748. to_remove: List of commit shas
  749. """
  750. for sha in to_remove:
  751. del self._graftpoints[sha]
  752. def _read_heads(self, name):
  753. f = self.get_named_file(name)
  754. if f is None:
  755. return []
  756. with f:
  757. return [line.strip() for line in f.readlines() if line.strip()]
  758. def do_commit( # noqa: C901
  759. self,
  760. message: Optional[bytes] = None,
  761. committer: Optional[bytes] = None,
  762. author: Optional[bytes] = None,
  763. commit_timestamp=None,
  764. commit_timezone=None,
  765. author_timestamp=None,
  766. author_timezone=None,
  767. tree: Optional[ObjectID] = None,
  768. encoding: Optional[bytes] = None,
  769. ref: Ref = b"HEAD",
  770. merge_heads: Optional[List[ObjectID]] = None,
  771. no_verify: bool = False,
  772. sign: bool = False,
  773. ):
  774. """Create a new commit.
  775. If not specified, committer and author default to
  776. get_user_identity(..., 'COMMITTER')
  777. and get_user_identity(..., 'AUTHOR') respectively.
  778. Args:
  779. message: Commit message
  780. committer: Committer fullname
  781. author: Author fullname
  782. commit_timestamp: Commit timestamp (defaults to now)
  783. commit_timezone: Commit timestamp timezone (defaults to GMT)
  784. author_timestamp: Author timestamp (defaults to commit
  785. timestamp)
  786. author_timezone: Author timestamp timezone
  787. (defaults to commit timestamp timezone)
  788. tree: SHA1 of the tree root to use (if not specified the
  789. current index will be committed).
  790. encoding: Encoding
  791. ref: Optional ref to commit to (defaults to current branch)
  792. merge_heads: Merge heads (defaults to .git/MERGE_HEAD)
  793. no_verify: Skip pre-commit and commit-msg hooks
  794. sign: GPG Sign the commit (bool, defaults to False,
  795. pass True to use default GPG key,
  796. pass a str containing Key ID to use a specific GPG key)
  797. Returns:
  798. New commit SHA1
  799. """
  800. try:
  801. if not no_verify:
  802. self.hooks["pre-commit"].execute()
  803. except HookError as exc:
  804. raise CommitError(exc) from exc
  805. except KeyError: # no hook defined, silent fallthrough
  806. pass
  807. c = Commit()
  808. if tree is None:
  809. index = self.open_index()
  810. c.tree = index.commit(self.object_store)
  811. else:
  812. if len(tree) != 40:
  813. raise ValueError("tree must be a 40-byte hex sha string")
  814. c.tree = tree
  815. config = self.get_config_stack()
  816. if merge_heads is None:
  817. merge_heads = self._read_heads("MERGE_HEAD")
  818. if committer is None:
  819. committer = get_user_identity(config, kind="COMMITTER")
  820. check_user_identity(committer)
  821. c.committer = committer
  822. if commit_timestamp is None:
  823. # FIXME: Support GIT_COMMITTER_DATE environment variable
  824. commit_timestamp = time.time()
  825. c.commit_time = int(commit_timestamp)
  826. if commit_timezone is None:
  827. # FIXME: Use current user timezone rather than UTC
  828. commit_timezone = 0
  829. c.commit_timezone = commit_timezone
  830. if author is None:
  831. author = get_user_identity(config, kind="AUTHOR")
  832. c.author = author
  833. check_user_identity(author)
  834. if author_timestamp is None:
  835. # FIXME: Support GIT_AUTHOR_DATE environment variable
  836. author_timestamp = commit_timestamp
  837. c.author_time = int(author_timestamp)
  838. if author_timezone is None:
  839. author_timezone = commit_timezone
  840. c.author_timezone = author_timezone
  841. if encoding is None:
  842. try:
  843. encoding = config.get(("i18n",), "commitEncoding")
  844. except KeyError:
  845. pass # No dice
  846. if encoding is not None:
  847. c.encoding = encoding
  848. if message is None:
  849. # FIXME: Try to read commit message from .git/MERGE_MSG
  850. raise ValueError("No commit message specified")
  851. try:
  852. if no_verify:
  853. c.message = message
  854. else:
  855. c.message = self.hooks["commit-msg"].execute(message)
  856. if c.message is None:
  857. c.message = message
  858. except HookError as exc:
  859. raise CommitError(exc) from exc
  860. except KeyError: # no hook defined, message not modified
  861. c.message = message
  862. keyid = sign if isinstance(sign, str) else None
  863. if ref is None:
  864. # Create a dangling commit
  865. c.parents = merge_heads
  866. if sign:
  867. c.sign(keyid)
  868. self.object_store.add_object(c)
  869. else:
  870. try:
  871. old_head = self.refs[ref]
  872. c.parents = [old_head] + merge_heads
  873. if sign:
  874. c.sign(keyid)
  875. self.object_store.add_object(c)
  876. ok = self.refs.set_if_equals(
  877. ref,
  878. old_head,
  879. c.id,
  880. message=b"commit: " + message,
  881. committer=committer,
  882. timestamp=commit_timestamp,
  883. timezone=commit_timezone,
  884. )
  885. except KeyError:
  886. c.parents = merge_heads
  887. if sign:
  888. c.sign(keyid)
  889. self.object_store.add_object(c)
  890. ok = self.refs.add_if_new(
  891. ref,
  892. c.id,
  893. message=b"commit: " + message,
  894. committer=committer,
  895. timestamp=commit_timestamp,
  896. timezone=commit_timezone,
  897. )
  898. if not ok:
  899. # Fail if the atomic compare-and-swap failed, leaving the
  900. # commit and all its objects as garbage.
  901. raise CommitError(f"{ref!r} changed during commit")
  902. self._del_named_file("MERGE_HEAD")
  903. try:
  904. self.hooks["post-commit"].execute()
  905. except HookError as e: # silent failure
  906. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  907. except KeyError: # no hook defined, silent fallthrough
  908. pass
  909. return c.id
  910. def read_gitfile(f):
  911. """Read a ``.git`` file.
  912. The first line of the file should start with "gitdir: "
  913. Args:
  914. f: File-like object to read from
  915. Returns: A path
  916. """
  917. cs = f.read()
  918. if not cs.startswith("gitdir: "):
  919. raise ValueError("Expected file to start with 'gitdir: '")
  920. return cs[len("gitdir: ") :].rstrip("\n")
  921. class UnsupportedVersion(Exception):
  922. """Unsupported repository version."""
  923. def __init__(self, version) -> None:
  924. self.version = version
  925. class UnsupportedExtension(Exception):
  926. """Unsupported repository extension."""
  927. def __init__(self, extension) -> None:
  928. self.extension = extension
  929. class Repo(BaseRepo):
  930. """A git repository backed by local disk.
  931. To open an existing repository, call the constructor with
  932. the path of the repository.
  933. To create a new repository, use the Repo.init class method.
  934. Note that a repository object may hold on to resources such
  935. as file handles for performance reasons; call .close() to free
  936. up those resources.
  937. Attributes:
  938. path: Path to the working copy (if it exists) or repository control
  939. directory (if the repository is bare)
  940. bare: Whether this is a bare repository
  941. """
  942. path: str
  943. bare: bool
  944. def __init__(
  945. self,
  946. root: str,
  947. object_store: Optional[PackBasedObjectStore] = None,
  948. bare: Optional[bool] = None
  949. ) -> None:
  950. hidden_path = os.path.join(root, CONTROLDIR)
  951. if bare is None:
  952. if (os.path.isfile(hidden_path)
  953. or os.path.isdir(os.path.join(hidden_path, OBJECTDIR))):
  954. bare = False
  955. elif (os.path.isdir(os.path.join(root, OBJECTDIR))
  956. and os.path.isdir(os.path.join(root, REFSDIR))):
  957. bare = True
  958. else:
  959. raise NotGitRepository(
  960. "No git repository was found at %(path)s" % dict(path=root)
  961. )
  962. self.bare = bare
  963. if bare is False:
  964. if os.path.isfile(hidden_path):
  965. with open(hidden_path) as f:
  966. path = read_gitfile(f)
  967. self._controldir = os.path.join(root, path)
  968. else:
  969. self._controldir = hidden_path
  970. else:
  971. self._controldir = root
  972. commondir = self.get_named_file(COMMONDIR)
  973. if commondir is not None:
  974. with commondir:
  975. self._commondir = os.path.join(
  976. self.controldir(),
  977. os.fsdecode(commondir.read().rstrip(b"\r\n")),
  978. )
  979. else:
  980. self._commondir = self._controldir
  981. self.path = root
  982. config = self.get_config()
  983. try:
  984. repository_format_version = config.get(
  985. "core",
  986. "repositoryformatversion"
  987. )
  988. format_version = (
  989. 0
  990. if repository_format_version is None
  991. else int(repository_format_version)
  992. )
  993. except KeyError:
  994. format_version = 0
  995. if format_version not in (0, 1):
  996. raise UnsupportedVersion(format_version)
  997. for extension, _value in config.items((b"extensions", )):
  998. if extension not in (b'worktreeconfig', ):
  999. raise UnsupportedExtension(extension)
  1000. if object_store is None:
  1001. object_store = DiskObjectStore.from_config(
  1002. os.path.join(self.commondir(), OBJECTDIR), config
  1003. )
  1004. refs = DiskRefsContainer(
  1005. self.commondir(), self._controldir, logger=self._write_reflog
  1006. )
  1007. BaseRepo.__init__(self, object_store, refs)
  1008. self._graftpoints = {}
  1009. graft_file = self.get_named_file(
  1010. os.path.join("info", "grafts"), basedir=self.commondir()
  1011. )
  1012. if graft_file:
  1013. with graft_file:
  1014. self._graftpoints.update(parse_graftpoints(graft_file))
  1015. graft_file = self.get_named_file("shallow", basedir=self.commondir())
  1016. if graft_file:
  1017. with graft_file:
  1018. self._graftpoints.update(parse_graftpoints(graft_file))
  1019. self.hooks["pre-commit"] = PreCommitShellHook(self.path, self.controldir())
  1020. self.hooks["commit-msg"] = CommitMsgShellHook(self.controldir())
  1021. self.hooks["post-commit"] = PostCommitShellHook(self.controldir())
  1022. self.hooks["post-receive"] = PostReceiveShellHook(self.controldir())
  1023. def _write_reflog(
  1024. self, ref, old_sha, new_sha, committer, timestamp, timezone, message
  1025. ):
  1026. from .reflog import format_reflog_line
  1027. path = os.path.join(self.controldir(), "logs", os.fsdecode(ref))
  1028. try:
  1029. os.makedirs(os.path.dirname(path))
  1030. except FileExistsError:
  1031. pass
  1032. if committer is None:
  1033. config = self.get_config_stack()
  1034. committer = self._get_user_identity(config)
  1035. check_user_identity(committer)
  1036. if timestamp is None:
  1037. timestamp = int(time.time())
  1038. if timezone is None:
  1039. timezone = 0 # FIXME
  1040. with open(path, "ab") as f:
  1041. f.write(
  1042. format_reflog_line(
  1043. old_sha, new_sha, committer, timestamp, timezone, message
  1044. )
  1045. + b"\n"
  1046. )
  1047. @classmethod
  1048. def discover(cls, start="."):
  1049. """Iterate parent directories to discover a repository.
  1050. Return a Repo object for the first parent directory that looks like a
  1051. Git repository.
  1052. Args:
  1053. start: The directory to start discovery from (defaults to '.')
  1054. """
  1055. remaining = True
  1056. path = os.path.abspath(start)
  1057. while remaining:
  1058. try:
  1059. return cls(path)
  1060. except NotGitRepository:
  1061. path, remaining = os.path.split(path)
  1062. raise NotGitRepository(
  1063. "No git repository was found at %(path)s" % dict(path=start)
  1064. )
  1065. def controldir(self):
  1066. """Return the path of the control directory."""
  1067. return self._controldir
  1068. def commondir(self):
  1069. """Return the path of the common directory.
  1070. For a main working tree, it is identical to controldir().
  1071. For a linked working tree, it is the control directory of the
  1072. main working tree.
  1073. """
  1074. return self._commondir
  1075. def _determine_file_mode(self):
  1076. """Probe the file-system to determine whether permissions can be trusted.
  1077. Returns: True if permissions can be trusted, False otherwise.
  1078. """
  1079. fname = os.path.join(self.path, ".probe-permissions")
  1080. with open(fname, "w") as f:
  1081. f.write("")
  1082. st1 = os.lstat(fname)
  1083. try:
  1084. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  1085. except PermissionError:
  1086. return False
  1087. st2 = os.lstat(fname)
  1088. os.unlink(fname)
  1089. mode_differs = st1.st_mode != st2.st_mode
  1090. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  1091. return mode_differs and st2_has_exec
  1092. def _determine_symlinks(self):
  1093. """Probe the filesystem to determine whether symlinks can be created.
  1094. Returns: True if symlinks can be created, False otherwise.
  1095. """
  1096. # TODO(jelmer): Actually probe disk / look at filesystem
  1097. return sys.platform != "win32"
  1098. def _put_named_file(self, path, contents):
  1099. """Write a file to the control dir with the given name and contents.
  1100. Args:
  1101. path: The path to the file, relative to the control dir.
  1102. contents: A string to write to the file.
  1103. """
  1104. path = path.lstrip(os.path.sep)
  1105. with GitFile(os.path.join(self.controldir(), path), "wb") as f:
  1106. f.write(contents)
  1107. def _del_named_file(self, path):
  1108. try:
  1109. os.unlink(os.path.join(self.controldir(), path))
  1110. except FileNotFoundError:
  1111. return
  1112. def get_named_file(self, path, basedir=None):
  1113. """Get a file from the control dir with a specific name.
  1114. Although the filename should be interpreted as a filename relative to
  1115. the control dir in a disk-based Repo, the object returned need not be
  1116. pointing to a file in that location.
  1117. Args:
  1118. path: The path to the file, relative to the control dir.
  1119. basedir: Optional argument that specifies an alternative to the
  1120. control dir.
  1121. Returns: An open file object, or None if the file does not exist.
  1122. """
  1123. # TODO(dborowitz): sanitize filenames, since this is used directly by
  1124. # the dumb web serving code.
  1125. if basedir is None:
  1126. basedir = self.controldir()
  1127. path = path.lstrip(os.path.sep)
  1128. try:
  1129. return open(os.path.join(basedir, path), "rb")
  1130. except FileNotFoundError:
  1131. return None
  1132. def index_path(self):
  1133. """Return path to the index file."""
  1134. return os.path.join(self.controldir(), INDEX_FILENAME)
  1135. def open_index(self) -> "Index":
  1136. """Open the index for this repository.
  1137. Raises:
  1138. NoIndexPresent: If no index is present
  1139. Returns: The matching `Index`
  1140. """
  1141. from .index import Index
  1142. if not self.has_index():
  1143. raise NoIndexPresent()
  1144. return Index(self.index_path())
  1145. def has_index(self):
  1146. """Check if an index is present."""
  1147. # Bare repos must never have index files; non-bare repos may have a
  1148. # missing index file, which is treated as empty.
  1149. return not self.bare
  1150. def stage(self, fs_paths: Union[str, bytes, os.PathLike, Iterable[Union[str, bytes, os.PathLike]]]) -> None:
  1151. """Stage a set of paths.
  1152. Args:
  1153. fs_paths: List of paths, relative to the repository path
  1154. """
  1155. root_path_bytes = os.fsencode(self.path)
  1156. if isinstance(fs_paths, (str, bytes, os.PathLike)):
  1157. fs_paths = [fs_paths]
  1158. fs_paths = list(fs_paths)
  1159. from .index import (
  1160. _fs_to_tree_path,
  1161. blob_from_path_and_stat,
  1162. index_entry_from_directory,
  1163. index_entry_from_stat,
  1164. )
  1165. index = self.open_index()
  1166. blob_normalizer = self.get_blob_normalizer()
  1167. for fs_path in fs_paths:
  1168. if not isinstance(fs_path, bytes):
  1169. fs_path = os.fsencode(fs_path)
  1170. if os.path.isabs(fs_path):
  1171. raise ValueError(
  1172. "path %r should be relative to "
  1173. "repository root, not absolute" % fs_path
  1174. )
  1175. tree_path = _fs_to_tree_path(fs_path)
  1176. full_path = os.path.join(root_path_bytes, fs_path)
  1177. try:
  1178. st = os.lstat(full_path)
  1179. except OSError:
  1180. # File no longer exists
  1181. try:
  1182. del index[tree_path]
  1183. except KeyError:
  1184. pass # already removed
  1185. else:
  1186. if stat.S_ISDIR(st.st_mode):
  1187. entry = index_entry_from_directory(st, full_path)
  1188. if entry:
  1189. index[tree_path] = entry
  1190. else:
  1191. try:
  1192. del index[tree_path]
  1193. except KeyError:
  1194. pass
  1195. elif not stat.S_ISREG(st.st_mode) and not stat.S_ISLNK(st.st_mode):
  1196. try:
  1197. del index[tree_path]
  1198. except KeyError:
  1199. pass
  1200. else:
  1201. blob = blob_from_path_and_stat(full_path, st)
  1202. blob = blob_normalizer.checkin_normalize(blob, fs_path)
  1203. self.object_store.add_object(blob)
  1204. index[tree_path] = index_entry_from_stat(st, blob.id, 0)
  1205. index.write()
  1206. def unstage(self, fs_paths: List[str]):
  1207. """Unstage specific file in the index
  1208. Args:
  1209. fs_paths: a list of files to unstage,
  1210. relative to the repository path.
  1211. """
  1212. from .index import IndexEntry, _fs_to_tree_path
  1213. index = self.open_index()
  1214. try:
  1215. tree_id = self[b'HEAD'].tree
  1216. except KeyError:
  1217. # no head mean no commit in the repo
  1218. for fs_path in fs_paths:
  1219. tree_path = _fs_to_tree_path(fs_path)
  1220. del index[tree_path]
  1221. index.write()
  1222. return
  1223. for fs_path in fs_paths:
  1224. tree_path = _fs_to_tree_path(fs_path)
  1225. try:
  1226. tree = self.object_store[tree_id]
  1227. assert isinstance(tree, Tree)
  1228. tree_entry = tree.lookup_path(
  1229. self.object_store.__getitem__, tree_path)
  1230. except KeyError:
  1231. # if tree_entry didn't exist, this file was being added, so
  1232. # remove index entry
  1233. try:
  1234. del index[tree_path]
  1235. continue
  1236. except KeyError as exc:
  1237. raise KeyError(
  1238. "file '%s' not in index" % (tree_path.decode())
  1239. ) from exc
  1240. st = None
  1241. try:
  1242. st = os.lstat(os.path.join(self.path, fs_path))
  1243. except FileNotFoundError:
  1244. pass
  1245. index_entry = IndexEntry(
  1246. ctime=(self[b'HEAD'].commit_time, 0),
  1247. mtime=(self[b'HEAD'].commit_time, 0),
  1248. dev=st.st_dev if st else 0,
  1249. ino=st.st_ino if st else 0,
  1250. mode=tree_entry[0],
  1251. uid=st.st_uid if st else 0,
  1252. gid=st.st_gid if st else 0,
  1253. size=len(self[tree_entry[1]].data),
  1254. sha=tree_entry[1],
  1255. flags=0,
  1256. extended_flags=0
  1257. )
  1258. index[tree_path] = index_entry
  1259. index.write()
  1260. def clone(
  1261. self,
  1262. target_path,
  1263. *,
  1264. mkdir=True,
  1265. bare=False,
  1266. origin=b"origin",
  1267. checkout=None,
  1268. branch=None,
  1269. progress=None,
  1270. depth=None,
  1271. symlinks=None,
  1272. ) -> "Repo":
  1273. """Clone this repository.
  1274. Args:
  1275. target_path: Target path
  1276. mkdir: Create the target directory
  1277. bare: Whether to create a bare repository
  1278. checkout: Whether or not to check-out HEAD after cloning
  1279. origin: Base name for refs in target repository
  1280. cloned from this repository
  1281. branch: Optional branch or tag to be used as HEAD in the new repository
  1282. instead of this repository's HEAD.
  1283. progress: Optional progress function
  1284. depth: Depth at which to fetch
  1285. symlinks: Symlinks setting (default to autodetect)
  1286. Returns: Created repository as `Repo`
  1287. """
  1288. encoded_path = os.fsencode(self.path)
  1289. if mkdir:
  1290. os.mkdir(target_path)
  1291. try:
  1292. if not bare:
  1293. target = Repo.init(target_path, symlinks=symlinks)
  1294. if checkout is None:
  1295. checkout = True
  1296. else:
  1297. if checkout:
  1298. raise ValueError("checkout and bare are incompatible")
  1299. target = Repo.init_bare(target_path)
  1300. try:
  1301. target_config = target.get_config()
  1302. target_config.set((b"remote", origin), b"url", encoded_path)
  1303. target_config.set(
  1304. (b"remote", origin),
  1305. b"fetch",
  1306. b"+refs/heads/*:refs/remotes/" + origin + b"/*",
  1307. )
  1308. target_config.write_to_path()
  1309. ref_message = b"clone: from " + encoded_path
  1310. self.fetch(target, depth=depth)
  1311. target.refs.import_refs(
  1312. b"refs/remotes/" + origin,
  1313. self.refs.as_dict(b"refs/heads"),
  1314. message=ref_message,
  1315. )
  1316. target.refs.import_refs(
  1317. b"refs/tags", self.refs.as_dict(b"refs/tags"), message=ref_message
  1318. )
  1319. head_chain, origin_sha = self.refs.follow(b"HEAD")
  1320. origin_head = head_chain[-1] if head_chain else None
  1321. if origin_sha and not origin_head:
  1322. # set detached HEAD
  1323. target.refs[b"HEAD"] = origin_sha
  1324. else:
  1325. _set_origin_head(target.refs, origin, origin_head)
  1326. head_ref = _set_default_branch(
  1327. target.refs, origin, origin_head, branch, ref_message
  1328. )
  1329. # Update target head
  1330. if head_ref:
  1331. head = _set_head(target.refs, head_ref, ref_message)
  1332. else:
  1333. head = None
  1334. if checkout and head is not None:
  1335. target.reset_index()
  1336. except BaseException:
  1337. target.close()
  1338. raise
  1339. except BaseException:
  1340. if mkdir:
  1341. import shutil
  1342. shutil.rmtree(target_path)
  1343. raise
  1344. return target
  1345. def reset_index(self, tree: Optional[bytes] = None):
  1346. """Reset the index back to a specific tree.
  1347. Args:
  1348. tree: Tree SHA to reset to, None for current HEAD tree.
  1349. """
  1350. from .index import (
  1351. build_index_from_tree,
  1352. symlink,
  1353. validate_path_element_default,
  1354. validate_path_element_ntfs,
  1355. )
  1356. if tree is None:
  1357. head = self[b"HEAD"]
  1358. if isinstance(head, Tag):
  1359. _cls, obj = head.object
  1360. head = self.get_object(obj)
  1361. tree = head.tree
  1362. config = self.get_config()
  1363. honor_filemode = config.get_boolean(b"core", b"filemode", os.name != "nt")
  1364. if config.get_boolean(b"core", b"core.protectNTFS", os.name == "nt"):
  1365. validate_path_element = validate_path_element_ntfs
  1366. else:
  1367. validate_path_element = validate_path_element_default
  1368. if config.get_boolean(b"core", b"symlinks", True):
  1369. symlink_fn = symlink
  1370. else:
  1371. def symlink_fn(source, target): # type: ignore
  1372. with open(target, 'w' + ('b' if isinstance(source, bytes) else '')) as f:
  1373. f.write(source)
  1374. return build_index_from_tree(
  1375. self.path,
  1376. self.index_path(),
  1377. self.object_store,
  1378. tree,
  1379. honor_filemode=honor_filemode,
  1380. validate_path_element=validate_path_element,
  1381. symlink_fn=symlink_fn
  1382. )
  1383. def get_worktree_config(self) -> "ConfigFile":
  1384. from .config import ConfigFile
  1385. path = os.path.join(self.commondir(), "config.worktree")
  1386. try:
  1387. return ConfigFile.from_path(path)
  1388. except FileNotFoundError:
  1389. cf = ConfigFile()
  1390. cf.path = path
  1391. return cf
  1392. def get_config(self) -> "ConfigFile":
  1393. """Retrieve the config object.
  1394. Returns: `ConfigFile` object for the ``.git/config`` file.
  1395. """
  1396. from .config import ConfigFile
  1397. path = os.path.join(self._commondir, "config")
  1398. try:
  1399. return ConfigFile.from_path(path)
  1400. except FileNotFoundError:
  1401. ret = ConfigFile()
  1402. ret.path = path
  1403. return ret
  1404. def get_description(self):
  1405. """Retrieve the description of this repository.
  1406. Returns: A string describing the repository or None.
  1407. """
  1408. path = os.path.join(self._controldir, "description")
  1409. try:
  1410. with GitFile(path, "rb") as f:
  1411. return f.read()
  1412. except FileNotFoundError:
  1413. return None
  1414. def __repr__(self) -> str:
  1415. return "<Repo at %r>" % self.path
  1416. def set_description(self, description):
  1417. """Set the description for this repository.
  1418. Args:
  1419. description: Text to set as description for this repository.
  1420. """
  1421. self._put_named_file("description", description)
  1422. @classmethod
  1423. def _init_maybe_bare(
  1424. cls, path, controldir, bare, object_store=None, config=None,
  1425. default_branch=None, symlinks: Optional[bool] = None):
  1426. for d in BASE_DIRECTORIES:
  1427. os.mkdir(os.path.join(controldir, *d))
  1428. if object_store is None:
  1429. object_store = DiskObjectStore.init(os.path.join(controldir, OBJECTDIR))
  1430. ret = cls(path, bare=bare, object_store=object_store)
  1431. if default_branch is None:
  1432. if config is None:
  1433. from .config import StackedConfig
  1434. config = StackedConfig.default()
  1435. try:
  1436. default_branch = config.get("init", "defaultBranch")
  1437. except KeyError:
  1438. default_branch = DEFAULT_BRANCH
  1439. ret.refs.set_symbolic_ref(b"HEAD", LOCAL_BRANCH_PREFIX + default_branch)
  1440. ret._init_files(bare=bare, symlinks=symlinks)
  1441. return ret
  1442. @classmethod
  1443. def init(cls, path: str, *, mkdir: bool = False, config=None, default_branch=None, symlinks: Optional[bool] = None) -> "Repo":
  1444. """Create a new repository.
  1445. Args:
  1446. path: Path in which to create the repository
  1447. mkdir: Whether to create the directory
  1448. Returns: `Repo` instance
  1449. """
  1450. if mkdir:
  1451. os.mkdir(path)
  1452. controldir = os.path.join(path, CONTROLDIR)
  1453. os.mkdir(controldir)
  1454. _set_filesystem_hidden(controldir)
  1455. return cls._init_maybe_bare(
  1456. path, controldir, False, config=config,
  1457. default_branch=default_branch,
  1458. symlinks=symlinks)
  1459. @classmethod
  1460. def _init_new_working_directory(cls, path, main_repo, identifier=None, mkdir=False):
  1461. """Create a new working directory linked to a repository.
  1462. Args:
  1463. path: Path in which to create the working tree.
  1464. main_repo: Main repository to reference
  1465. identifier: Worktree identifier
  1466. mkdir: Whether to create the directory
  1467. Returns: `Repo` instance
  1468. """
  1469. if mkdir:
  1470. os.mkdir(path)
  1471. if identifier is None:
  1472. identifier = os.path.basename(path)
  1473. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  1474. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1475. gitdirfile = os.path.join(path, CONTROLDIR)
  1476. with open(gitdirfile, "wb") as f:
  1477. f.write(b"gitdir: " + os.fsencode(worktree_controldir) + b"\n")
  1478. try:
  1479. os.mkdir(main_worktreesdir)
  1480. except FileExistsError:
  1481. pass
  1482. try:
  1483. os.mkdir(worktree_controldir)
  1484. except FileExistsError:
  1485. pass
  1486. with open(os.path.join(worktree_controldir, GITDIR), "wb") as f:
  1487. f.write(os.fsencode(gitdirfile) + b"\n")
  1488. with open(os.path.join(worktree_controldir, COMMONDIR), "wb") as f:
  1489. f.write(b"../..\n")
  1490. with open(os.path.join(worktree_controldir, "HEAD"), "wb") as f:
  1491. f.write(main_repo.head() + b"\n")
  1492. r = cls(path)
  1493. r.reset_index()
  1494. return r
  1495. @classmethod
  1496. def init_bare(cls, path, *, mkdir=False, object_store=None, config=None, default_branch=None):
  1497. """Create a new bare repository.
  1498. ``path`` should already exist and be an empty directory.
  1499. Args:
  1500. path: Path to create bare repository in
  1501. Returns: a `Repo` instance
  1502. """
  1503. if mkdir:
  1504. os.mkdir(path)
  1505. return cls._init_maybe_bare(path, path, True, object_store=object_store, config=config, default_branch=default_branch)
  1506. create = init_bare
  1507. def close(self):
  1508. """Close any files opened by this repository."""
  1509. self.object_store.close()
  1510. def __enter__(self):
  1511. return self
  1512. def __exit__(self, exc_type, exc_val, exc_tb):
  1513. self.close()
  1514. def get_blob_normalizer(self):
  1515. """Return a BlobNormalizer object."""
  1516. # TODO Parse the git attributes files
  1517. git_attributes = {}
  1518. config_stack = self.get_config_stack()
  1519. try:
  1520. tree = self.object_store[self.refs[b"HEAD"]].tree
  1521. return TreeBlobNormalizer(
  1522. config_stack,
  1523. git_attributes,
  1524. self.object_store,
  1525. tree,
  1526. )
  1527. except KeyError:
  1528. return BlobNormalizer(config_stack, git_attributes)
  1529. class MemoryRepo(BaseRepo):
  1530. """Repo that stores refs, objects, and named files in memory.
  1531. MemoryRepos are always bare: they have no working tree and no index, since
  1532. those have a stronger dependency on the filesystem.
  1533. """
  1534. def __init__(self) -> None:
  1535. from .config import ConfigFile
  1536. self._reflog = []
  1537. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1538. BaseRepo.__init__(self, MemoryObjectStore(), refs_container)
  1539. self._named_files = {}
  1540. self.bare = True
  1541. self._config = ConfigFile()
  1542. self._description = None
  1543. def _append_reflog(self, *args):
  1544. self._reflog.append(args)
  1545. def set_description(self, description):
  1546. self._description = description
  1547. def get_description(self):
  1548. return self._description
  1549. def _determine_file_mode(self):
  1550. """Probe the file-system to determine whether permissions can be trusted.
  1551. Returns: True if permissions can be trusted, False otherwise.
  1552. """
  1553. return sys.platform != "win32"
  1554. def _determine_symlinks(self):
  1555. """Probe the file-system to determine whether permissions can be trusted.
  1556. Returns: True if permissions can be trusted, False otherwise.
  1557. """
  1558. return sys.platform != "win32"
  1559. def _put_named_file(self, path, contents):
  1560. """Write a file to the control dir with the given name and contents.
  1561. Args:
  1562. path: The path to the file, relative to the control dir.
  1563. contents: A string to write to the file.
  1564. """
  1565. self._named_files[path] = contents
  1566. def _del_named_file(self, path):
  1567. try:
  1568. del self._named_files[path]
  1569. except KeyError:
  1570. pass
  1571. def get_named_file(self, path, basedir=None):
  1572. """Get a file from the control dir with a specific name.
  1573. Although the filename should be interpreted as a filename relative to
  1574. the control dir in a disk-baked Repo, the object returned need not be
  1575. pointing to a file in that location.
  1576. Args:
  1577. path: The path to the file, relative to the control dir.
  1578. Returns: An open file object, or None if the file does not exist.
  1579. """
  1580. contents = self._named_files.get(path, None)
  1581. if contents is None:
  1582. return None
  1583. return BytesIO(contents)
  1584. def open_index(self):
  1585. """Fail to open index for this repo, since it is bare.
  1586. Raises:
  1587. NoIndexPresent: Raised when no index is present
  1588. """
  1589. raise NoIndexPresent()
  1590. def get_config(self):
  1591. """Retrieve the config object.
  1592. Returns: `ConfigFile` object.
  1593. """
  1594. return self._config
  1595. @classmethod
  1596. def init_bare(cls, objects, refs):
  1597. """Create a new bare repository in memory.
  1598. Args:
  1599. objects: Objects for the new repository,
  1600. as iterable
  1601. refs: Refs as dictionary, mapping names
  1602. to object SHA1s
  1603. """
  1604. ret = cls()
  1605. for obj in objects:
  1606. ret.object_store.add_object(obj)
  1607. for refname, sha in refs.items():
  1608. ret.refs.add_if_new(refname, sha)
  1609. ret._init_files(bare=True)
  1610. return ret