repo.py 59 KB

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