repo.py 45 KB

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