repo.py 62 KB

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