repo.py 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320
  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 errno
  28. import os
  29. import sys
  30. import stat
  31. import time
  32. from dulwich.errors import (
  33. NoIndexPresent,
  34. NotBlobError,
  35. NotCommitError,
  36. NotGitRepository,
  37. NotTreeError,
  38. NotTagError,
  39. CommitError,
  40. RefFormatError,
  41. HookError,
  42. )
  43. from dulwich.file import (
  44. GitFile,
  45. )
  46. from dulwich.object_store import (
  47. DiskObjectStore,
  48. MemoryObjectStore,
  49. ObjectStoreGraphWalker,
  50. )
  51. from dulwich.objects import (
  52. check_hexsha,
  53. Blob,
  54. Commit,
  55. ShaFile,
  56. Tag,
  57. Tree,
  58. )
  59. from dulwich.pack import (
  60. pack_objects_to_data,
  61. )
  62. from dulwich.hooks import (
  63. PreCommitShellHook,
  64. PostCommitShellHook,
  65. CommitMsgShellHook,
  66. )
  67. from dulwich.refs import ( # noqa: F401
  68. check_ref_format,
  69. RefsContainer,
  70. DictRefsContainer,
  71. InfoRefsContainer,
  72. DiskRefsContainer,
  73. read_packed_refs,
  74. read_packed_refs_with_peeled,
  75. write_packed_refs,
  76. SYMREF,
  77. )
  78. import warnings
  79. CONTROLDIR = '.git'
  80. OBJECTDIR = 'objects'
  81. REFSDIR = 'refs'
  82. REFSDIR_TAGS = 'tags'
  83. REFSDIR_HEADS = 'heads'
  84. INDEX_FILENAME = "index"
  85. COMMONDIR = 'commondir'
  86. GITDIR = 'gitdir'
  87. WORKTREES = 'worktrees'
  88. BASE_DIRECTORIES = [
  89. ["branches"],
  90. [REFSDIR],
  91. [REFSDIR, REFSDIR_TAGS],
  92. [REFSDIR, REFSDIR_HEADS],
  93. ["hooks"],
  94. ["info"]
  95. ]
  96. DEFAULT_REF = b'refs/heads/master'
  97. class InvalidUserIdentity(Exception):
  98. """User identity is not of the format 'user <email>'"""
  99. def __init__(self, identity):
  100. self.identity = identity
  101. def check_user_identity(identity):
  102. """Verify that a user identity is formatted correctly.
  103. :param identity: User identity bytestring
  104. :raise InvalidUserIdentity: Raised when identity is invalid
  105. """
  106. try:
  107. fst, snd = identity.split(b' <', 1)
  108. except ValueError:
  109. raise InvalidUserIdentity(identity)
  110. if b'>' not in snd:
  111. raise InvalidUserIdentity(identity)
  112. def parse_graftpoints(graftpoints):
  113. """Convert a list of graftpoints into a dict
  114. :param graftpoints: Iterator of graftpoint lines
  115. Each line is formatted as:
  116. <commit sha1> <parent sha1> [<parent sha1>]*
  117. Resulting dictionary is:
  118. <commit sha1>: [<parent sha1>*]
  119. https://git.wiki.kernel.org/index.php/GraftPoint
  120. """
  121. grafts = {}
  122. for l in graftpoints:
  123. raw_graft = l.split(None, 1)
  124. commit = raw_graft[0]
  125. if len(raw_graft) == 2:
  126. parents = raw_graft[1].split()
  127. else:
  128. parents = []
  129. for sha in [commit] + parents:
  130. check_hexsha(sha, 'Invalid graftpoint')
  131. grafts[commit] = parents
  132. return grafts
  133. def serialize_graftpoints(graftpoints):
  134. """Convert a dictionary of grafts into string
  135. The graft dictionary is:
  136. <commit sha1>: [<parent sha1>*]
  137. Each line is formatted as:
  138. <commit sha1> <parent sha1> [<parent sha1>]*
  139. https://git.wiki.kernel.org/index.php/GraftPoint
  140. """
  141. graft_lines = []
  142. for commit, parents in graftpoints.items():
  143. if parents:
  144. graft_lines.append(commit + b' ' + b' '.join(parents))
  145. else:
  146. graft_lines.append(commit)
  147. return b'\n'.join(graft_lines)
  148. class BaseRepo(object):
  149. """Base class for a git repository.
  150. :ivar object_store: Dictionary-like object for accessing
  151. the objects
  152. :ivar refs: Dictionary-like object with the refs in this
  153. repository
  154. """
  155. def __init__(self, object_store, refs):
  156. """Open a repository.
  157. This shouldn't be called directly, but rather through one of the
  158. base classes, such as MemoryRepo or Repo.
  159. :param object_store: Object store to use
  160. :param refs: Refs container to use
  161. """
  162. self.object_store = object_store
  163. self.refs = refs
  164. self._graftpoints = {}
  165. self.hooks = {}
  166. def _determine_file_mode(self):
  167. """Probe the file-system to determine whether permissions can be trusted.
  168. :return: True if permissions can be trusted, False otherwise.
  169. """
  170. raise NotImplementedError(self._determine_file_mode)
  171. def _init_files(self, bare):
  172. """Initialize a default set of named files."""
  173. from dulwich.config import ConfigFile
  174. self._put_named_file('description', b"Unnamed repository")
  175. f = BytesIO()
  176. cf = ConfigFile()
  177. cf.set("core", "repositoryformatversion", "0")
  178. if self._determine_file_mode():
  179. cf.set("core", "filemode", True)
  180. else:
  181. cf.set("core", "filemode", False)
  182. cf.set("core", "bare", bare)
  183. cf.set("core", "logallrefupdates", True)
  184. cf.write_to_file(f)
  185. self._put_named_file('config', f.getvalue())
  186. self._put_named_file(os.path.join('info', 'exclude'), b'')
  187. def get_named_file(self, path):
  188. """Get a file from the control dir with a specific name.
  189. Although the filename should be interpreted as a filename relative to
  190. the control dir in a disk-based Repo, the object returned need not be
  191. pointing to a file in that location.
  192. :param path: The path to the file, relative to the control dir.
  193. :return: An open file object, or None if the file does not exist.
  194. """
  195. raise NotImplementedError(self.get_named_file)
  196. def _put_named_file(self, path, contents):
  197. """Write a file to the control dir with the given name and contents.
  198. :param path: The path to the file, relative to the control dir.
  199. :param contents: A string to write to the file.
  200. """
  201. raise NotImplementedError(self._put_named_file)
  202. def open_index(self):
  203. """Open the index for this repository.
  204. :raise NoIndexPresent: If no index is present
  205. :return: The matching `Index`
  206. """
  207. raise NotImplementedError(self.open_index)
  208. def fetch(self, target, determine_wants=None, progress=None, depth=None):
  209. """Fetch objects into another repository.
  210. :param target: The target repository
  211. :param determine_wants: Optional function to determine what refs to
  212. fetch.
  213. :param progress: Optional progress function
  214. :param depth: Optional shallow fetch depth
  215. :return: The local refs
  216. """
  217. if determine_wants is None:
  218. determine_wants = target.object_store.determine_wants_all
  219. count, pack_data = self.fetch_pack_data(
  220. determine_wants, target.get_graph_walker(), progress=progress,
  221. depth=depth)
  222. target.object_store.add_pack_data(count, pack_data, progress)
  223. return self.get_refs()
  224. def fetch_pack_data(self, determine_wants, graph_walker, progress,
  225. get_tagged=None, depth=None):
  226. """Fetch the pack data required for a set of revisions.
  227. :param determine_wants: Function that takes a dictionary with heads
  228. and returns the list of heads to fetch.
  229. :param graph_walker: Object that can iterate over the list of revisions
  230. to fetch and has an "ack" method that will be called to acknowledge
  231. that a revision is present.
  232. :param progress: Simple progress function that will be called with
  233. updated progress strings.
  234. :param get_tagged: Function that returns a dict of pointed-to sha ->
  235. tag sha for including tags.
  236. :param depth: Shallow fetch depth
  237. :return: count and iterator over pack data
  238. """
  239. # TODO(jelmer): Fetch pack data directly, don't create objects first.
  240. objects = self.fetch_objects(determine_wants, graph_walker, progress,
  241. get_tagged, depth=depth)
  242. return pack_objects_to_data(objects)
  243. def fetch_objects(self, determine_wants, graph_walker, progress,
  244. get_tagged=None, depth=None):
  245. """Fetch the missing objects required for a set of revisions.
  246. :param determine_wants: Function that takes a dictionary with heads
  247. and returns the list of heads to fetch.
  248. :param graph_walker: Object that can iterate over the list of revisions
  249. to fetch and has an "ack" method that will be called to acknowledge
  250. that a revision is present.
  251. :param progress: Simple progress function that will be called with
  252. updated progress strings.
  253. :param get_tagged: Function that returns a dict of pointed-to sha ->
  254. tag sha for including tags.
  255. :param depth: Shallow fetch depth
  256. :return: iterator over objects, with __len__ implemented
  257. """
  258. if depth not in (None, 0):
  259. raise NotImplementedError("depth not supported yet")
  260. wants = determine_wants(self.get_refs())
  261. if not isinstance(wants, list):
  262. raise TypeError("determine_wants() did not return a list")
  263. shallows = getattr(graph_walker, 'shallow', frozenset())
  264. unshallows = getattr(graph_walker, 'unshallow', frozenset())
  265. if wants == []:
  266. # TODO(dborowitz): find a way to short-circuit that doesn't change
  267. # this interface.
  268. if shallows or unshallows:
  269. # Do not send a pack in shallow short-circuit path
  270. return None
  271. return []
  272. # If the graph walker is set up with an implementation that can
  273. # ACK/NAK to the wire, it will write data to the client through
  274. # this call as a side-effect.
  275. haves = self.object_store.find_common_revisions(graph_walker)
  276. # Deal with shallow requests separately because the haves do
  277. # not reflect what objects are missing
  278. if shallows or unshallows:
  279. # TODO: filter the haves commits from iter_shas. the specific
  280. # commits aren't missing.
  281. haves = []
  282. def get_parents(commit):
  283. if commit.id in shallows:
  284. return []
  285. return self.get_parents(commit.id, commit)
  286. return self.object_store.iter_shas(
  287. self.object_store.find_missing_objects(
  288. haves, wants, progress,
  289. get_tagged,
  290. get_parents=get_parents))
  291. def get_graph_walker(self, heads=None):
  292. """Retrieve a graph walker.
  293. A graph walker is used by a remote repository (or proxy)
  294. to find out which objects are present in this repository.
  295. :param heads: Repository heads to use (optional)
  296. :return: A graph walker object
  297. """
  298. if heads is None:
  299. heads = self.refs.as_dict(b'refs/heads').values()
  300. return ObjectStoreGraphWalker(
  301. heads, self.get_parents, shallow=self.get_shallow())
  302. def get_refs(self):
  303. """Get dictionary with all refs.
  304. :return: A ``dict`` mapping ref names to SHA1s
  305. """
  306. return self.refs.as_dict()
  307. def head(self):
  308. """Return the SHA1 pointed at by HEAD."""
  309. return self.refs[b'HEAD']
  310. def _get_object(self, sha, cls):
  311. assert len(sha) in (20, 40)
  312. ret = self.get_object(sha)
  313. if not isinstance(ret, cls):
  314. if cls is Commit:
  315. raise NotCommitError(ret)
  316. elif cls is Blob:
  317. raise NotBlobError(ret)
  318. elif cls is Tree:
  319. raise NotTreeError(ret)
  320. elif cls is Tag:
  321. raise NotTagError(ret)
  322. else:
  323. raise Exception("Type invalid: %r != %r" % (
  324. ret.type_name, cls.type_name))
  325. return ret
  326. def get_object(self, sha):
  327. """Retrieve the object with the specified SHA.
  328. :param sha: SHA to retrieve
  329. :return: A ShaFile object
  330. :raise KeyError: when the object can not be found
  331. """
  332. return self.object_store[sha]
  333. def get_parents(self, sha, commit=None):
  334. """Retrieve the parents of a specific commit.
  335. If the specific commit is a graftpoint, the graft parents
  336. will be returned instead.
  337. :param sha: SHA of the commit for which to retrieve the parents
  338. :param commit: Optional commit matching the sha
  339. :return: List of parents
  340. """
  341. try:
  342. return self._graftpoints[sha]
  343. except KeyError:
  344. if commit is None:
  345. commit = self[sha]
  346. return commit.parents
  347. def get_config(self):
  348. """Retrieve the config object.
  349. :return: `ConfigFile` object for the ``.git/config`` file.
  350. """
  351. raise NotImplementedError(self.get_config)
  352. def get_description(self):
  353. """Retrieve the description for this repository.
  354. :return: String with the description of the repository
  355. as set by the user.
  356. """
  357. raise NotImplementedError(self.get_description)
  358. def set_description(self, description):
  359. """Set the description for this repository.
  360. :param description: Text to set as description for this repository.
  361. """
  362. raise NotImplementedError(self.set_description)
  363. def get_config_stack(self):
  364. """Return a config stack for this repository.
  365. This stack accesses the configuration for both this repository
  366. itself (.git/config) and the global configuration, which usually
  367. lives in ~/.gitconfig.
  368. :return: `Config` instance for this repository
  369. """
  370. from dulwich.config import StackedConfig
  371. backends = [self.get_config()] + StackedConfig.default_backends()
  372. return StackedConfig(backends, writable=backends[0])
  373. def get_shallow(self):
  374. """Get the set of shallow commits.
  375. :return: Set of shallow commits.
  376. """
  377. return set()
  378. def update_shallow(self, new_shallow, new_unshallow):
  379. """Update the list of shallow objects.
  380. :param new_shallow: Newly shallow objects
  381. :param new_unshallow: Newly no longer shallow objects
  382. """
  383. raise NotImplementedError(self.update_shallow)
  384. def get_peeled(self, ref):
  385. """Get the peeled value of a ref.
  386. :param ref: The refname to peel.
  387. :return: The fully-peeled SHA1 of a tag object, after peeling all
  388. intermediate tags; if the original ref does not point to a tag,
  389. this will equal the original SHA1.
  390. """
  391. cached = self.refs.get_peeled(ref)
  392. if cached is not None:
  393. return cached
  394. return self.object_store.peel_sha(self.refs[ref]).id
  395. def get_walker(self, include=None, *args, **kwargs):
  396. """Obtain a walker for this repository.
  397. :param include: Iterable of SHAs of commits to include along with their
  398. ancestors. Defaults to [HEAD]
  399. :param exclude: Iterable of SHAs of commits to exclude along with their
  400. ancestors, overriding includes.
  401. :param order: ORDER_* constant specifying the order of results.
  402. Anything other than ORDER_DATE may result in O(n) memory usage.
  403. :param reverse: If True, reverse the order of output, requiring O(n)
  404. memory.
  405. :param max_entries: The maximum number of entries to yield, or None for
  406. no limit.
  407. :param paths: Iterable of file or subtree paths to show entries for.
  408. :param rename_detector: diff.RenameDetector object for detecting
  409. renames.
  410. :param follow: If True, follow path across renames/copies. Forces a
  411. default rename_detector.
  412. :param since: Timestamp to list commits after.
  413. :param until: Timestamp to list commits before.
  414. :param queue_cls: A class to use for a queue of commits, supporting the
  415. iterator protocol. The constructor takes a single argument, the
  416. Walker.
  417. :return: A `Walker` object
  418. """
  419. from dulwich.walk import Walker
  420. if include is None:
  421. include = [self.head()]
  422. if isinstance(include, str):
  423. include = [include]
  424. kwargs['get_parents'] = lambda commit: self.get_parents(
  425. commit.id, commit)
  426. return Walker(self.object_store, include, *args, **kwargs)
  427. def __getitem__(self, name):
  428. """Retrieve a Git object by SHA1 or ref.
  429. :param name: A Git object SHA1 or a ref name
  430. :return: A `ShaFile` object, such as a Commit or Blob
  431. :raise KeyError: when the specified ref or object does not exist
  432. """
  433. if not isinstance(name, bytes):
  434. raise TypeError("'name' must be bytestring, not %.80s" %
  435. type(name).__name__)
  436. if len(name) in (20, 40):
  437. try:
  438. return self.object_store[name]
  439. except (KeyError, ValueError):
  440. pass
  441. try:
  442. return self.object_store[self.refs[name]]
  443. except RefFormatError:
  444. raise KeyError(name)
  445. def __contains__(self, name):
  446. """Check if a specific Git object or ref is present.
  447. :param name: Git object SHA1 or ref name
  448. """
  449. if len(name) in (20, 40):
  450. return name in self.object_store or name in self.refs
  451. else:
  452. return name in self.refs
  453. def __setitem__(self, name, value):
  454. """Set a ref.
  455. :param name: ref name
  456. :param value: Ref value - either a ShaFile object, or a hex sha
  457. """
  458. if name.startswith(b"refs/") or name == b'HEAD':
  459. if isinstance(value, ShaFile):
  460. self.refs[name] = value.id
  461. elif isinstance(value, bytes):
  462. self.refs[name] = value
  463. else:
  464. raise TypeError(value)
  465. else:
  466. raise ValueError(name)
  467. def __delitem__(self, name):
  468. """Remove a ref.
  469. :param name: Name of the ref to remove
  470. """
  471. if name.startswith(b"refs/") or name == b"HEAD":
  472. del self.refs[name]
  473. else:
  474. raise ValueError(name)
  475. def _get_user_identity(self, config):
  476. """Determine the identity to use for new commits.
  477. """
  478. user = os.environ.get("GIT_COMMITTER_NAME")
  479. email = os.environ.get("GIT_COMMITTER_EMAIL")
  480. if user is None:
  481. try:
  482. user = config.get(("user", ), "name")
  483. except KeyError:
  484. user = None
  485. if email is None:
  486. try:
  487. email = config.get(("user", ), "email")
  488. except KeyError:
  489. email = None
  490. if user is None:
  491. import getpass
  492. user = getpass.getuser().encode(sys.getdefaultencoding())
  493. if email is None:
  494. import getpass
  495. import socket
  496. email = ("{}@{}".format(getpass.getuser(), socket.gethostname())
  497. .encode(sys.getdefaultencoding()))
  498. return (user + b" <" + email + b">")
  499. def _add_graftpoints(self, updated_graftpoints):
  500. """Add or modify graftpoints
  501. :param updated_graftpoints: Dict of commit shas to list of parent shas
  502. """
  503. # Simple validation
  504. for commit, parents in updated_graftpoints.items():
  505. for sha in [commit] + parents:
  506. check_hexsha(sha, 'Invalid graftpoint')
  507. self._graftpoints.update(updated_graftpoints)
  508. def _remove_graftpoints(self, to_remove=[]):
  509. """Remove graftpoints
  510. :param to_remove: List of commit shas
  511. """
  512. for sha in to_remove:
  513. del self._graftpoints[sha]
  514. def do_commit(self, message=None, committer=None,
  515. author=None, commit_timestamp=None,
  516. commit_timezone=None, author_timestamp=None,
  517. author_timezone=None, tree=None, encoding=None,
  518. ref=b'HEAD', merge_heads=None):
  519. """Create a new commit.
  520. :param message: Commit message
  521. :param committer: Committer fullname
  522. :param author: Author fullname (defaults to committer)
  523. :param commit_timestamp: Commit timestamp (defaults to now)
  524. :param commit_timezone: Commit timestamp timezone (defaults to GMT)
  525. :param author_timestamp: Author timestamp (defaults to commit
  526. timestamp)
  527. :param author_timezone: Author timestamp timezone
  528. (defaults to commit timestamp timezone)
  529. :param tree: SHA1 of the tree root to use (if not specified the
  530. current index will be committed).
  531. :param encoding: Encoding
  532. :param ref: Optional ref to commit to (defaults to current branch)
  533. :param merge_heads: Merge heads (defaults to .git/MERGE_HEADS)
  534. :return: New commit SHA1
  535. """
  536. import time
  537. c = Commit()
  538. if tree is None:
  539. index = self.open_index()
  540. c.tree = index.commit(self.object_store)
  541. else:
  542. if len(tree) != 40:
  543. raise ValueError("tree must be a 40-byte hex sha string")
  544. c.tree = tree
  545. try:
  546. self.hooks['pre-commit'].execute()
  547. except HookError as e:
  548. raise CommitError(e)
  549. except KeyError: # no hook defined, silent fallthrough
  550. pass
  551. config = self.get_config_stack()
  552. if merge_heads is None:
  553. # FIXME: Read merge heads from .git/MERGE_HEADS
  554. merge_heads = []
  555. if committer is None:
  556. committer = self._get_user_identity(config)
  557. check_user_identity(committer)
  558. c.committer = committer
  559. if commit_timestamp is None:
  560. # FIXME: Support GIT_COMMITTER_DATE environment variable
  561. commit_timestamp = time.time()
  562. c.commit_time = int(commit_timestamp)
  563. if commit_timezone is None:
  564. # FIXME: Use current user timezone rather than UTC
  565. commit_timezone = 0
  566. c.commit_timezone = commit_timezone
  567. if author is None:
  568. # FIXME: Support GIT_AUTHOR_NAME/GIT_AUTHOR_EMAIL environment
  569. # variables
  570. author = committer
  571. c.author = author
  572. check_user_identity(author)
  573. if author_timestamp is None:
  574. # FIXME: Support GIT_AUTHOR_DATE environment variable
  575. author_timestamp = commit_timestamp
  576. c.author_time = int(author_timestamp)
  577. if author_timezone is None:
  578. author_timezone = commit_timezone
  579. c.author_timezone = author_timezone
  580. if encoding is None:
  581. try:
  582. encoding = config.get(('i18n', ), 'commitEncoding')
  583. except KeyError:
  584. pass # No dice
  585. if encoding is not None:
  586. c.encoding = encoding
  587. if message is None:
  588. # FIXME: Try to read commit message from .git/MERGE_MSG
  589. raise ValueError("No commit message specified")
  590. try:
  591. c.message = self.hooks['commit-msg'].execute(message)
  592. if c.message is None:
  593. c.message = message
  594. except HookError as e:
  595. raise CommitError(e)
  596. except KeyError: # no hook defined, message not modified
  597. c.message = message
  598. if ref is None:
  599. # Create a dangling commit
  600. c.parents = merge_heads
  601. self.object_store.add_object(c)
  602. else:
  603. try:
  604. old_head = self.refs[ref]
  605. c.parents = [old_head] + merge_heads
  606. self.object_store.add_object(c)
  607. ok = self.refs.set_if_equals(
  608. ref, old_head, c.id, message=b"commit: " + message,
  609. committer=committer, timestamp=commit_timestamp,
  610. timezone=commit_timezone)
  611. except KeyError:
  612. c.parents = merge_heads
  613. self.object_store.add_object(c)
  614. ok = self.refs.add_if_new(
  615. ref, c.id, message=b"commit: " + message,
  616. committer=committer, timestamp=commit_timestamp,
  617. timezone=commit_timezone)
  618. if not ok:
  619. # Fail if the atomic compare-and-swap failed, leaving the
  620. # commit and all its objects as garbage.
  621. raise CommitError("%s changed during commit" % (ref,))
  622. try:
  623. self.hooks['post-commit'].execute()
  624. except HookError as e: # silent failure
  625. warnings.warn("post-commit hook failed: %s" % e, UserWarning)
  626. except KeyError: # no hook defined, silent fallthrough
  627. pass
  628. return c.id
  629. def read_gitfile(f):
  630. """Read a ``.git`` file.
  631. The first line of the file should start with "gitdir: "
  632. :param f: File-like object to read from
  633. :return: A path
  634. """
  635. cs = f.read()
  636. if not cs.startswith("gitdir: "):
  637. raise ValueError("Expected file to start with 'gitdir: '")
  638. return cs[len("gitdir: "):].rstrip("\n")
  639. class Repo(BaseRepo):
  640. """A git repository backed by local disk.
  641. To open an existing repository, call the contructor with
  642. the path of the repository.
  643. To create a new repository, use the Repo.init class method.
  644. """
  645. def __init__(self, root):
  646. hidden_path = os.path.join(root, CONTROLDIR)
  647. if os.path.isdir(os.path.join(hidden_path, OBJECTDIR)):
  648. self.bare = False
  649. self._controldir = hidden_path
  650. elif (os.path.isdir(os.path.join(root, OBJECTDIR)) and
  651. os.path.isdir(os.path.join(root, REFSDIR))):
  652. self.bare = True
  653. self._controldir = root
  654. elif os.path.isfile(hidden_path):
  655. self.bare = False
  656. with open(hidden_path, 'r') as f:
  657. path = read_gitfile(f)
  658. self.bare = False
  659. self._controldir = os.path.join(root, path)
  660. else:
  661. raise NotGitRepository(
  662. "No git repository was found at %(path)s" % dict(path=root)
  663. )
  664. commondir = self.get_named_file(COMMONDIR)
  665. if commondir is not None:
  666. with commondir:
  667. self._commondir = os.path.join(
  668. self.controldir(),
  669. commondir.read().rstrip(b"\r\n").decode(
  670. sys.getfilesystemencoding()))
  671. else:
  672. self._commondir = self._controldir
  673. self.path = root
  674. object_store = DiskObjectStore(
  675. os.path.join(self.commondir(), OBJECTDIR))
  676. refs = DiskRefsContainer(self.commondir(), self._controldir,
  677. logger=self._write_reflog)
  678. BaseRepo.__init__(self, object_store, refs)
  679. self._graftpoints = {}
  680. graft_file = self.get_named_file(os.path.join("info", "grafts"),
  681. basedir=self.commondir())
  682. if graft_file:
  683. with graft_file:
  684. self._graftpoints.update(parse_graftpoints(graft_file))
  685. graft_file = self.get_named_file("shallow",
  686. basedir=self.commondir())
  687. if graft_file:
  688. with graft_file:
  689. self._graftpoints.update(parse_graftpoints(graft_file))
  690. self.hooks['pre-commit'] = PreCommitShellHook(self.controldir())
  691. self.hooks['commit-msg'] = CommitMsgShellHook(self.controldir())
  692. self.hooks['post-commit'] = PostCommitShellHook(self.controldir())
  693. def _write_reflog(self, ref, old_sha, new_sha, committer, timestamp,
  694. timezone, message):
  695. from .reflog import format_reflog_line
  696. path = os.path.join(
  697. self.controldir(), 'logs',
  698. ref.decode(sys.getfilesystemencoding()))
  699. try:
  700. os.makedirs(os.path.dirname(path))
  701. except OSError as e:
  702. if e.errno != errno.EEXIST:
  703. raise
  704. if committer is None:
  705. config = self.get_config_stack()
  706. committer = self._get_user_identity(config)
  707. check_user_identity(committer)
  708. if timestamp is None:
  709. timestamp = int(time.time())
  710. if timezone is None:
  711. timezone = 0 # FIXME
  712. with open(path, 'ab') as f:
  713. f.write(format_reflog_line(old_sha, new_sha, committer,
  714. timestamp, timezone, message) + b'\n')
  715. @classmethod
  716. def discover(cls, start='.'):
  717. """Iterate parent directories to discover a repository
  718. Return a Repo object for the first parent directory that looks like a
  719. Git repository.
  720. :param start: The directory to start discovery from (defaults to '.')
  721. """
  722. remaining = True
  723. path = os.path.abspath(start)
  724. while remaining:
  725. try:
  726. return cls(path)
  727. except NotGitRepository:
  728. path, remaining = os.path.split(path)
  729. raise NotGitRepository(
  730. "No git repository was found at %(path)s" % dict(path=start)
  731. )
  732. def controldir(self):
  733. """Return the path of the control directory."""
  734. return self._controldir
  735. def commondir(self):
  736. """Return the path of the common directory.
  737. For a main working tree, it is identical to controldir().
  738. For a linked working tree, it is the control directory of the
  739. main working tree."""
  740. return self._commondir
  741. def _determine_file_mode(self):
  742. """Probe the file-system to determine whether permissions can be trusted.
  743. :return: True if permissions can be trusted, False otherwise.
  744. """
  745. fname = os.path.join(self.path, '.probe-permissions')
  746. with open(fname, 'w') as f:
  747. f.write('')
  748. st1 = os.lstat(fname)
  749. os.chmod(fname, st1.st_mode ^ stat.S_IXUSR)
  750. st2 = os.lstat(fname)
  751. os.unlink(fname)
  752. mode_differs = st1.st_mode != st2.st_mode
  753. st2_has_exec = (st2.st_mode & stat.S_IXUSR) != 0
  754. return mode_differs and st2_has_exec
  755. def _put_named_file(self, path, contents):
  756. """Write a file to the control dir with the given name and contents.
  757. :param path: The path to the file, relative to the control dir.
  758. :param contents: A string to write to the file.
  759. """
  760. path = path.lstrip(os.path.sep)
  761. with GitFile(os.path.join(self.controldir(), path), 'wb') as f:
  762. f.write(contents)
  763. def get_named_file(self, path, basedir=None):
  764. """Get a file from the control dir with a specific name.
  765. Although the filename should be interpreted as a filename relative to
  766. the control dir in a disk-based Repo, the object returned need not be
  767. pointing to a file in that location.
  768. :param path: The path to the file, relative to the control dir.
  769. :param basedir: Optional argument that specifies an alternative to the
  770. control dir.
  771. :return: An open file object, or None if the file does not exist.
  772. """
  773. # TODO(dborowitz): sanitize filenames, since this is used directly by
  774. # the dumb web serving code.
  775. if basedir is None:
  776. basedir = self.controldir()
  777. path = path.lstrip(os.path.sep)
  778. try:
  779. return open(os.path.join(basedir, path), 'rb')
  780. except (IOError, OSError) as e:
  781. if e.errno == errno.ENOENT:
  782. return None
  783. raise
  784. def get_shallow(self):
  785. f = self.get_named_file('shallow')
  786. if f is None:
  787. return set()
  788. with f:
  789. return set(l.strip() for l in f)
  790. def update_shallow(self, new_shallow, new_unshallow):
  791. shallow = self.get_shallow()
  792. if new_shallow:
  793. shallow.update(new_shallow)
  794. if new_unshallow:
  795. shallow.difference_update(new_unshallow)
  796. self._put_named_file(
  797. 'shallow',
  798. b''.join([sha + b'\n' for sha in shallow]))
  799. def index_path(self):
  800. """Return path to the index file."""
  801. return os.path.join(self.controldir(), INDEX_FILENAME)
  802. def open_index(self):
  803. """Open the index for this repository.
  804. :raise NoIndexPresent: If no index is present
  805. :return: The matching `Index`
  806. """
  807. from dulwich.index import Index
  808. if not self.has_index():
  809. raise NoIndexPresent()
  810. return Index(self.index_path())
  811. def has_index(self):
  812. """Check if an index is present."""
  813. # Bare repos must never have index files; non-bare repos may have a
  814. # missing index file, which is treated as empty.
  815. return not self.bare
  816. def stage(self, fs_paths):
  817. """Stage a set of paths.
  818. :param fs_paths: List of paths, relative to the repository path
  819. """
  820. root_path_bytes = self.path.encode(sys.getfilesystemencoding())
  821. if not isinstance(fs_paths, list):
  822. fs_paths = [fs_paths]
  823. from dulwich.index import (
  824. blob_from_path_and_stat,
  825. index_entry_from_stat,
  826. _fs_to_tree_path,
  827. )
  828. index = self.open_index()
  829. for fs_path in fs_paths:
  830. if not isinstance(fs_path, bytes):
  831. fs_path = fs_path.encode(sys.getfilesystemencoding())
  832. if os.path.isabs(fs_path):
  833. raise ValueError(
  834. "path %r should be relative to "
  835. "repository root, not absolute" % fs_path)
  836. tree_path = _fs_to_tree_path(fs_path)
  837. full_path = os.path.join(root_path_bytes, fs_path)
  838. try:
  839. st = os.lstat(full_path)
  840. except OSError:
  841. # File no longer exists
  842. try:
  843. del index[tree_path]
  844. except KeyError:
  845. pass # already removed
  846. else:
  847. if not stat.S_ISDIR(st.st_mode):
  848. blob = blob_from_path_and_stat(full_path, st)
  849. self.object_store.add_object(blob)
  850. index[tree_path] = index_entry_from_stat(st, blob.id, 0)
  851. else:
  852. try:
  853. del index[tree_path]
  854. except KeyError:
  855. pass
  856. index.write()
  857. def clone(self, target_path, mkdir=True, bare=False,
  858. origin=b"origin", checkout=None):
  859. """Clone this repository.
  860. :param target_path: Target path
  861. :param mkdir: Create the target directory
  862. :param bare: Whether to create a bare repository
  863. :param origin: Base name for refs in target repository
  864. cloned from this repository
  865. :return: Created repository as `Repo`
  866. """
  867. if not bare:
  868. target = self.init(target_path, mkdir=mkdir)
  869. else:
  870. if checkout:
  871. raise ValueError("checkout and bare are incompatible")
  872. target = self.init_bare(target_path, mkdir=mkdir)
  873. self.fetch(target)
  874. encoded_path = self.path
  875. if not isinstance(encoded_path, bytes):
  876. encoded_path = encoded_path.encode(sys.getfilesystemencoding())
  877. ref_message = b"clone: from " + encoded_path
  878. target.refs.import_refs(
  879. b'refs/remotes/' + origin, self.refs.as_dict(b'refs/heads'),
  880. message=ref_message)
  881. target.refs.import_refs(
  882. b'refs/tags', self.refs.as_dict(b'refs/tags'),
  883. message=ref_message)
  884. try:
  885. target.refs.add_if_new(
  886. DEFAULT_REF, self.refs[DEFAULT_REF],
  887. message=ref_message)
  888. except KeyError:
  889. pass
  890. target_config = target.get_config()
  891. target_config.set(('remote', 'origin'), 'url', encoded_path)
  892. target_config.set(('remote', 'origin'), 'fetch',
  893. '+refs/heads/*:refs/remotes/origin/*')
  894. target_config.write_to_path()
  895. # Update target head
  896. head_chain, head_sha = self.refs.follow(b'HEAD')
  897. if head_chain and head_sha is not None:
  898. target.refs.set_symbolic_ref(b'HEAD', head_chain[-1],
  899. message=ref_message)
  900. target[b'HEAD'] = head_sha
  901. if checkout is None:
  902. checkout = (not bare)
  903. if checkout:
  904. # Checkout HEAD to target dir
  905. target.reset_index()
  906. return target
  907. def reset_index(self, tree=None):
  908. """Reset the index back to a specific tree.
  909. :param tree: Tree SHA to reset to, None for current HEAD tree.
  910. """
  911. from dulwich.index import (
  912. build_index_from_tree,
  913. validate_path_element_default,
  914. validate_path_element_ntfs,
  915. )
  916. if tree is None:
  917. tree = self[b'HEAD'].tree
  918. config = self.get_config()
  919. honor_filemode = config.get_boolean(
  920. b'core', b'filemode', os.name != "nt")
  921. if config.get_boolean(b'core', b'core.protectNTFS', os.name == "nt"):
  922. validate_path_element = validate_path_element_ntfs
  923. else:
  924. validate_path_element = validate_path_element_default
  925. return build_index_from_tree(
  926. self.path, self.index_path(), self.object_store, tree,
  927. honor_filemode=honor_filemode,
  928. validate_path_element=validate_path_element)
  929. def get_config(self):
  930. """Retrieve the config object.
  931. :return: `ConfigFile` object for the ``.git/config`` file.
  932. """
  933. from dulwich.config import ConfigFile
  934. path = os.path.join(self._controldir, 'config')
  935. try:
  936. return ConfigFile.from_path(path)
  937. except (IOError, OSError) as e:
  938. if e.errno != errno.ENOENT:
  939. raise
  940. ret = ConfigFile()
  941. ret.path = path
  942. return ret
  943. def get_description(self):
  944. """Retrieve the description of this repository.
  945. :return: A string describing the repository or None.
  946. """
  947. path = os.path.join(self._controldir, 'description')
  948. try:
  949. with GitFile(path, 'rb') as f:
  950. return f.read()
  951. except (IOError, OSError) as e:
  952. if e.errno != errno.ENOENT:
  953. raise
  954. return None
  955. def __repr__(self):
  956. return "<Repo at %r>" % self.path
  957. def set_description(self, description):
  958. """Set the description for this repository.
  959. :param description: Text to set as description for this repository.
  960. """
  961. self._put_named_file('description', description)
  962. @classmethod
  963. def _init_maybe_bare(cls, path, bare):
  964. for d in BASE_DIRECTORIES:
  965. os.mkdir(os.path.join(path, *d))
  966. DiskObjectStore.init(os.path.join(path, OBJECTDIR))
  967. ret = cls(path)
  968. ret.refs.set_symbolic_ref(b'HEAD', DEFAULT_REF)
  969. ret._init_files(bare)
  970. return ret
  971. @classmethod
  972. def init(cls, path, mkdir=False):
  973. """Create a new repository.
  974. :param path: Path in which to create the repository
  975. :param mkdir: Whether to create the directory
  976. :return: `Repo` instance
  977. """
  978. if mkdir:
  979. os.mkdir(path)
  980. controldir = os.path.join(path, CONTROLDIR)
  981. os.mkdir(controldir)
  982. cls._init_maybe_bare(controldir, False)
  983. return cls(path)
  984. @classmethod
  985. def _init_new_working_directory(cls, path, main_repo, identifier=None,
  986. mkdir=False):
  987. """Create a new working directory linked to a repository.
  988. :param path: Path in which to create the working tree.
  989. :param main_repo: Main repository to reference
  990. :param identifier: Worktree identifier
  991. :param mkdir: Whether to create the directory
  992. :return: `Repo` instance
  993. """
  994. if mkdir:
  995. os.mkdir(path)
  996. if identifier is None:
  997. identifier = os.path.basename(path)
  998. main_worktreesdir = os.path.join(main_repo.controldir(), WORKTREES)
  999. worktree_controldir = os.path.join(main_worktreesdir, identifier)
  1000. gitdirfile = os.path.join(path, CONTROLDIR)
  1001. with open(gitdirfile, 'wb') as f:
  1002. f.write(b'gitdir: ' +
  1003. worktree_controldir.encode(sys.getfilesystemencoding()) +
  1004. b'\n')
  1005. try:
  1006. os.mkdir(main_worktreesdir)
  1007. except OSError as e:
  1008. if e.errno != errno.EEXIST:
  1009. raise
  1010. try:
  1011. os.mkdir(worktree_controldir)
  1012. except OSError as e:
  1013. if e.errno != errno.EEXIST:
  1014. raise
  1015. with open(os.path.join(worktree_controldir, GITDIR), 'wb') as f:
  1016. f.write(gitdirfile.encode(sys.getfilesystemencoding()) + b'\n')
  1017. with open(os.path.join(worktree_controldir, COMMONDIR), 'wb') as f:
  1018. f.write(b'../..\n')
  1019. with open(os.path.join(worktree_controldir, 'HEAD'), 'wb') as f:
  1020. f.write(main_repo.head() + b'\n')
  1021. r = cls(path)
  1022. r.reset_index()
  1023. return r
  1024. @classmethod
  1025. def init_bare(cls, path, mkdir=False):
  1026. """Create a new bare repository.
  1027. ``path`` should already exist and be an empty directory.
  1028. :param path: Path to create bare repository in
  1029. :return: a `Repo` instance
  1030. """
  1031. if mkdir:
  1032. os.mkdir(path)
  1033. return cls._init_maybe_bare(path, True)
  1034. create = init_bare
  1035. def close(self):
  1036. """Close any files opened by this repository."""
  1037. self.object_store.close()
  1038. def __enter__(self):
  1039. return self
  1040. def __exit__(self, exc_type, exc_val, exc_tb):
  1041. self.close()
  1042. class MemoryRepo(BaseRepo):
  1043. """Repo that stores refs, objects, and named files in memory.
  1044. MemoryRepos are always bare: they have no working tree and no index, since
  1045. those have a stronger dependency on the filesystem.
  1046. """
  1047. def __init__(self):
  1048. from dulwich.config import ConfigFile
  1049. self._reflog = []
  1050. refs_container = DictRefsContainer({}, logger=self._append_reflog)
  1051. BaseRepo.__init__(self, MemoryObjectStore(), refs_container)
  1052. self._named_files = {}
  1053. self.bare = True
  1054. self._config = ConfigFile()
  1055. self._description = None
  1056. def _append_reflog(self, *args):
  1057. self._reflog.append(args)
  1058. def set_description(self, description):
  1059. self._description = description
  1060. def get_description(self):
  1061. return self._description
  1062. def _determine_file_mode(self):
  1063. """Probe the file-system to determine whether permissions can be trusted.
  1064. :return: True if permissions can be trusted, False otherwise.
  1065. """
  1066. return sys.platform != 'win32'
  1067. def _put_named_file(self, path, contents):
  1068. """Write a file to the control dir with the given name and contents.
  1069. :param path: The path to the file, relative to the control dir.
  1070. :param contents: A string to write to the file.
  1071. """
  1072. self._named_files[path] = contents
  1073. def get_named_file(self, path):
  1074. """Get a file from the control dir with a specific name.
  1075. Although the filename should be interpreted as a filename relative to
  1076. the control dir in a disk-baked Repo, the object returned need not be
  1077. pointing to a file in that location.
  1078. :param path: The path to the file, relative to the control dir.
  1079. :return: An open file object, or None if the file does not exist.
  1080. """
  1081. contents = self._named_files.get(path, None)
  1082. if contents is None:
  1083. return None
  1084. return BytesIO(contents)
  1085. def open_index(self):
  1086. """Fail to open index for this repo, since it is bare.
  1087. :raise NoIndexPresent: Raised when no index is present
  1088. """
  1089. raise NoIndexPresent()
  1090. def get_config(self):
  1091. """Retrieve the config object.
  1092. :return: `ConfigFile` object.
  1093. """
  1094. return self._config
  1095. @classmethod
  1096. def init_bare(cls, objects, refs):
  1097. """Create a new bare repository in memory.
  1098. :param objects: Objects for the new repository,
  1099. as iterable
  1100. :param refs: Refs as dictionary, mapping names
  1101. to object SHA1s
  1102. """
  1103. ret = cls()
  1104. for obj in objects:
  1105. ret.object_store.add_object(obj)
  1106. for refname, sha in refs.items():
  1107. ret.refs.add_if_new(refname, sha)
  1108. ret._init_files(bare=True)
  1109. return ret