repo.py 58 KB

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