repo.py 58 KB

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