repo.py 43 KB

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