porcelain.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440
  1. # porcelain.py -- Porcelain-like layer on top of Dulwich
  2. # Copyright (C) 2013 Jelmer Vernooij <jelmer@jelmer.uk>
  3. #
  4. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  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. """Simple wrapper that provides porcelain-like functions on top of Dulwich.
  22. Currently implemented:
  23. * archive
  24. * add
  25. * branch{_create,_delete,_list}
  26. * check-ignore
  27. * checkout_branch
  28. * clone
  29. * cone mode{_init, _set, _add}
  30. * commit
  31. * commit-tree
  32. * daemon
  33. * describe
  34. * diff-tree
  35. * fetch
  36. * for-each-ref
  37. * init
  38. * ls-files
  39. * ls-remote
  40. * ls-tree
  41. * pull
  42. * push
  43. * rm
  44. * remote{_add}
  45. * receive-pack
  46. * reset
  47. * sparse_checkout
  48. * submodule_add
  49. * submodule_init
  50. * submodule_list
  51. * rev-list
  52. * tag{_create,_delete,_list}
  53. * upload-pack
  54. * update-server-info
  55. * status
  56. * symbolic-ref
  57. These functions are meant to behave similarly to the git subcommands.
  58. Differences in behaviour are considered bugs.
  59. Note: one of the consequences of this is that paths tend to be
  60. interpreted relative to the current working directory rather than relative
  61. to the repository root.
  62. Functions should generally accept both unicode strings and bytestrings
  63. """
  64. import datetime
  65. import fnmatch
  66. import os
  67. import posixpath
  68. import stat
  69. import sys
  70. import time
  71. from collections import namedtuple
  72. from contextlib import closing, contextmanager
  73. from io import BytesIO, RawIOBase
  74. from pathlib import Path
  75. from typing import Optional, Union
  76. from .archive import tar_stream
  77. from .client import get_transport_and_path
  78. from .config import Config, ConfigFile, StackedConfig, read_submodules
  79. from .diff_tree import (
  80. CHANGE_ADD,
  81. CHANGE_COPY,
  82. CHANGE_DELETE,
  83. CHANGE_MODIFY,
  84. CHANGE_RENAME,
  85. RENAME_CHANGE_TYPES,
  86. )
  87. from .errors import SendPackError
  88. from .file import ensure_dir_exists
  89. from .graph import can_fast_forward
  90. from .ignore import IgnoreFilterManager
  91. from .index import (
  92. _fs_to_tree_path,
  93. blob_from_path_and_stat,
  94. build_file_from_blob,
  95. get_unstaged_changes,
  96. index_entry_from_stat,
  97. )
  98. from .object_store import iter_tree_contents, tree_lookup_path
  99. from .objects import (
  100. Commit,
  101. Tag,
  102. format_timezone,
  103. parse_timezone,
  104. pretty_format_tree_entry,
  105. )
  106. from .objectspec import (
  107. parse_commit,
  108. parse_object,
  109. parse_ref,
  110. parse_reftuples,
  111. parse_tree,
  112. to_bytes,
  113. )
  114. from .pack import write_pack_from_container, write_pack_index
  115. from .patch import write_tree_diff
  116. from .protocol import ZERO_SHA, Protocol
  117. from .refs import (
  118. LOCAL_BRANCH_PREFIX,
  119. LOCAL_REMOTE_PREFIX,
  120. LOCAL_TAG_PREFIX,
  121. Ref,
  122. _import_remote_refs,
  123. )
  124. from .repo import BaseRepo, Repo, get_user_identity
  125. from .server import (
  126. FileSystemBackend,
  127. ReceivePackHandler,
  128. TCPGitServer,
  129. UploadPackHandler,
  130. )
  131. from .server import update_server_info as server_update_server_info
  132. from .sparse_patterns import (
  133. SparseCheckoutConflictError,
  134. apply_included_paths,
  135. determine_included_paths,
  136. )
  137. # Module level tuple definition for status output
  138. GitStatus = namedtuple("GitStatus", "staged unstaged untracked")
  139. class NoneStream(RawIOBase):
  140. """Fallback if stdout or stderr are unavailable, does nothing."""
  141. def read(self, size=-1) -> None:
  142. return None
  143. def readall(self) -> bytes:
  144. return b""
  145. def readinto(self, b) -> None:
  146. return None
  147. def write(self, b) -> None:
  148. return None
  149. default_bytes_out_stream = getattr(sys.stdout, "buffer", None) or NoneStream()
  150. default_bytes_err_stream = getattr(sys.stderr, "buffer", None) or NoneStream()
  151. DEFAULT_ENCODING = "utf-8"
  152. class Error(Exception):
  153. """Porcelain-based error."""
  154. def __init__(self, msg) -> None:
  155. super().__init__(msg)
  156. class RemoteExists(Error):
  157. """Raised when the remote already exists."""
  158. class TimezoneFormatError(Error):
  159. """Raised when the timezone cannot be determined from a given string."""
  160. class CheckoutError(Error):
  161. """Indicates that a checkout cannot be performed."""
  162. def parse_timezone_format(tz_str):
  163. """Parse given string and attempt to return a timezone offset.
  164. Different formats are considered in the following order:
  165. - Git internal format: <unix timestamp> <timezone offset>
  166. - RFC 2822: e.g. Mon, 20 Nov 1995 19:12:08 -0500
  167. - ISO 8601: e.g. 1995-11-20T19:12:08-0500
  168. Args:
  169. tz_str: datetime string
  170. Returns: Timezone offset as integer
  171. Raises:
  172. TimezoneFormatError: if timezone information cannot be extracted
  173. """
  174. import re
  175. # Git internal format
  176. internal_format_pattern = re.compile("^[0-9]+ [+-][0-9]{,4}$")
  177. if re.match(internal_format_pattern, tz_str):
  178. try:
  179. tz_internal = parse_timezone(tz_str.split(" ")[1].encode(DEFAULT_ENCODING))
  180. return tz_internal[0]
  181. except ValueError:
  182. pass
  183. # RFC 2822
  184. import email.utils
  185. rfc_2822 = email.utils.parsedate_tz(tz_str)
  186. if rfc_2822:
  187. return rfc_2822[9]
  188. # ISO 8601
  189. # Supported offsets:
  190. # sHHMM, sHH:MM, sHH
  191. iso_8601_pattern = re.compile(
  192. "[0-9] ?([+-])([0-9]{2})(?::(?=[0-9]{2}))?([0-9]{2})?$"
  193. )
  194. match = re.search(iso_8601_pattern, tz_str)
  195. total_secs = 0
  196. if match:
  197. sign, hours, minutes = match.groups()
  198. total_secs += int(hours) * 3600
  199. if minutes:
  200. total_secs += int(minutes) * 60
  201. total_secs = -total_secs if sign == "-" else total_secs
  202. return total_secs
  203. # YYYY.MM.DD, MM/DD/YYYY, DD.MM.YYYY contain no timezone information
  204. raise TimezoneFormatError(tz_str)
  205. def get_user_timezones():
  206. """Retrieve local timezone as described in
  207. https://raw.githubusercontent.com/git/git/v2.3.0/Documentation/date-formats.txt
  208. Returns: A tuple containing author timezone, committer timezone.
  209. """
  210. local_timezone = time.localtime().tm_gmtoff
  211. if os.environ.get("GIT_AUTHOR_DATE"):
  212. author_timezone = parse_timezone_format(os.environ["GIT_AUTHOR_DATE"])
  213. else:
  214. author_timezone = local_timezone
  215. if os.environ.get("GIT_COMMITTER_DATE"):
  216. commit_timezone = parse_timezone_format(os.environ["GIT_COMMITTER_DATE"])
  217. else:
  218. commit_timezone = local_timezone
  219. return author_timezone, commit_timezone
  220. def open_repo(path_or_repo):
  221. """Open an argument that can be a repository or a path for a repository."""
  222. if isinstance(path_or_repo, BaseRepo):
  223. return path_or_repo
  224. return Repo(path_or_repo)
  225. @contextmanager
  226. def _noop_context_manager(obj):
  227. """Context manager that has the same api as closing but does nothing."""
  228. yield obj
  229. def open_repo_closing(path_or_repo):
  230. """Open an argument that can be a repository or a path for a repository.
  231. returns a context manager that will close the repo on exit if the argument
  232. is a path, else does nothing if the argument is a repo.
  233. """
  234. if isinstance(path_or_repo, BaseRepo):
  235. return _noop_context_manager(path_or_repo)
  236. return closing(Repo(path_or_repo))
  237. def path_to_tree_path(repopath, path, tree_encoding=DEFAULT_ENCODING):
  238. """Convert a path to a path usable in an index, e.g. bytes and relative to
  239. the repository root.
  240. Args:
  241. repopath: Repository path, absolute or relative to the cwd
  242. path: A path, absolute or relative to the cwd
  243. Returns: A path formatted for use in e.g. an index
  244. """
  245. # Resolve might returns a relative path on Windows
  246. # https://bugs.python.org/issue38671
  247. if sys.platform == "win32":
  248. path = os.path.abspath(path)
  249. path = Path(path)
  250. resolved_path = path.resolve()
  251. # Resolve and abspath seems to behave differently regarding symlinks,
  252. # as we are doing abspath on the file path, we need to do the same on
  253. # the repo path or they might not match
  254. if sys.platform == "win32":
  255. repopath = os.path.abspath(repopath)
  256. repopath = Path(repopath).resolve()
  257. try:
  258. relpath = resolved_path.relative_to(repopath)
  259. except ValueError:
  260. # If path is a symlink that points to a file outside the repo, we
  261. # want the relpath for the link itself, not the resolved target
  262. if path.is_symlink():
  263. parent = path.parent.resolve()
  264. relpath = (parent / path.name).relative_to(repopath)
  265. else:
  266. raise
  267. if sys.platform == "win32":
  268. return str(relpath).replace(os.path.sep, "/").encode(tree_encoding)
  269. else:
  270. return bytes(relpath)
  271. class DivergedBranches(Error):
  272. """Branches have diverged and fast-forward is not possible."""
  273. def __init__(self, current_sha, new_sha) -> None:
  274. self.current_sha = current_sha
  275. self.new_sha = new_sha
  276. def check_diverged(repo, current_sha, new_sha) -> None:
  277. """Check if updating to a sha can be done with fast forwarding.
  278. Args:
  279. repo: Repository object
  280. current_sha: Current head sha
  281. new_sha: New head sha
  282. """
  283. try:
  284. can = can_fast_forward(repo, current_sha, new_sha)
  285. except KeyError:
  286. can = False
  287. if not can:
  288. raise DivergedBranches(current_sha, new_sha)
  289. def archive(
  290. repo,
  291. committish=None,
  292. outstream=default_bytes_out_stream,
  293. errstream=default_bytes_err_stream,
  294. ) -> None:
  295. """Create an archive.
  296. Args:
  297. repo: Path of repository for which to generate an archive.
  298. committish: Commit SHA1 or ref to use
  299. outstream: Output stream (defaults to stdout)
  300. errstream: Error stream (defaults to stderr)
  301. """
  302. if committish is None:
  303. committish = "HEAD"
  304. with open_repo_closing(repo) as repo_obj:
  305. c = parse_commit(repo_obj, committish)
  306. for chunk in tar_stream(
  307. repo_obj.object_store, repo_obj.object_store[c.tree], c.commit_time
  308. ):
  309. outstream.write(chunk)
  310. def update_server_info(repo=".") -> None:
  311. """Update server info files for a repository.
  312. Args:
  313. repo: path to the repository
  314. """
  315. with open_repo_closing(repo) as r:
  316. server_update_server_info(r)
  317. def symbolic_ref(repo, ref_name, force=False) -> None:
  318. """Set git symbolic ref into HEAD.
  319. Args:
  320. repo: path to the repository
  321. ref_name: short name of the new ref
  322. force: force settings without checking if it exists in refs/heads
  323. """
  324. with open_repo_closing(repo) as repo_obj:
  325. ref_path = _make_branch_ref(ref_name)
  326. if not force and ref_path not in repo_obj.refs.keys():
  327. raise Error(f"fatal: ref `{ref_name}` is not a ref")
  328. repo_obj.refs.set_symbolic_ref(b"HEAD", ref_path)
  329. def pack_refs(repo, all=False) -> None:
  330. with open_repo_closing(repo) as repo_obj:
  331. refs = repo_obj.refs
  332. packed_refs = {
  333. ref: refs[ref]
  334. for ref in refs
  335. if (all or ref.startswith(LOCAL_TAG_PREFIX)) and ref != b"HEAD"
  336. }
  337. refs.add_packed_refs(packed_refs)
  338. def commit(
  339. repo=".",
  340. message=None,
  341. author=None,
  342. author_timezone=None,
  343. committer=None,
  344. commit_timezone=None,
  345. encoding=None,
  346. no_verify=False,
  347. signoff=False,
  348. ):
  349. """Create a new commit.
  350. Args:
  351. repo: Path to repository
  352. message: Optional commit message
  353. author: Optional author name and email
  354. author_timezone: Author timestamp timezone
  355. committer: Optional committer name and email
  356. commit_timezone: Commit timestamp timezone
  357. no_verify: Skip pre-commit and commit-msg hooks
  358. signoff: GPG Sign the commit (bool, defaults to False,
  359. pass True to use default GPG key,
  360. pass a str containing Key ID to use a specific GPG key)
  361. Returns: SHA1 of the new commit
  362. """
  363. # FIXME: Support --all argument
  364. if getattr(message, "encode", None):
  365. message = message.encode(encoding or DEFAULT_ENCODING)
  366. if getattr(author, "encode", None):
  367. author = author.encode(encoding or DEFAULT_ENCODING)
  368. if getattr(committer, "encode", None):
  369. committer = committer.encode(encoding or DEFAULT_ENCODING)
  370. local_timezone = get_user_timezones()
  371. if author_timezone is None:
  372. author_timezone = local_timezone[0]
  373. if commit_timezone is None:
  374. commit_timezone = local_timezone[1]
  375. with open_repo_closing(repo) as r:
  376. return r.do_commit(
  377. message=message,
  378. author=author,
  379. author_timezone=author_timezone,
  380. committer=committer,
  381. commit_timezone=commit_timezone,
  382. encoding=encoding,
  383. no_verify=no_verify,
  384. sign=signoff if isinstance(signoff, (str, bool)) else None,
  385. )
  386. def commit_tree(repo, tree, message=None, author=None, committer=None):
  387. """Create a new commit object.
  388. Args:
  389. repo: Path to repository
  390. tree: An existing tree object
  391. author: Optional author name and email
  392. committer: Optional committer name and email
  393. """
  394. with open_repo_closing(repo) as r:
  395. return r.do_commit(
  396. message=message, tree=tree, committer=committer, author=author
  397. )
  398. def init(path=".", *, bare=False, symlinks: Optional[bool] = None):
  399. """Create a new git repository.
  400. Args:
  401. path: Path to repository.
  402. bare: Whether to create a bare repository.
  403. symlinks: Whether to create actual symlinks (defaults to autodetect)
  404. Returns: A Repo instance
  405. """
  406. if not os.path.exists(path):
  407. os.mkdir(path)
  408. if bare:
  409. return Repo.init_bare(path)
  410. else:
  411. return Repo.init(path, symlinks=symlinks)
  412. def clone(
  413. source,
  414. target=None,
  415. bare=False,
  416. checkout=None,
  417. errstream=default_bytes_err_stream,
  418. outstream=None,
  419. origin: Optional[str] = "origin",
  420. depth: Optional[int] = None,
  421. branch: Optional[Union[str, bytes]] = None,
  422. config: Optional[Config] = None,
  423. filter_spec=None,
  424. protocol_version: Optional[int] = None,
  425. **kwargs,
  426. ):
  427. """Clone a local or remote git repository.
  428. Args:
  429. source: Path or URL for source repository
  430. target: Path to target repository (optional)
  431. bare: Whether or not to create a bare repository
  432. checkout: Whether or not to check-out HEAD after cloning
  433. errstream: Optional stream to write progress to
  434. outstream: Optional stream to write progress to (deprecated)
  435. origin: Name of remote from the repository used to clone
  436. depth: Depth to fetch at
  437. branch: Optional branch or tag to be used as HEAD in the new repository
  438. instead of the cloned repository's HEAD.
  439. config: Configuration to use
  440. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  441. bytestring/string.
  442. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  443. Only used if the server supports the Git protocol-v2 'filter'
  444. feature, and ignored otherwise.
  445. protocol_version: desired Git protocol version. By default the highest
  446. mutually supported protocol version will be used.
  447. Returns: The new repository
  448. """
  449. if outstream is not None:
  450. import warnings
  451. warnings.warn(
  452. "outstream= has been deprecated in favour of errstream=.",
  453. DeprecationWarning,
  454. stacklevel=3,
  455. )
  456. # TODO(jelmer): Capture logging output and stream to errstream
  457. if config is None:
  458. config = StackedConfig.default()
  459. if checkout is None:
  460. checkout = not bare
  461. if checkout and bare:
  462. raise Error("checkout and bare are incompatible")
  463. if target is None:
  464. target = source.split("/")[-1]
  465. if isinstance(branch, str):
  466. branch = branch.encode(DEFAULT_ENCODING)
  467. mkdir = not os.path.exists(target)
  468. (client, path) = get_transport_and_path(source, config=config, **kwargs)
  469. if filter_spec:
  470. filter_spec = filter_spec.encode("ascii")
  471. return client.clone(
  472. path,
  473. target,
  474. mkdir=mkdir,
  475. bare=bare,
  476. origin=origin,
  477. checkout=checkout,
  478. branch=branch,
  479. progress=errstream.write,
  480. depth=depth,
  481. filter_spec=filter_spec,
  482. protocol_version=protocol_version,
  483. )
  484. def add(repo=".", paths=None):
  485. """Add files to the staging area.
  486. Args:
  487. repo: Repository for the files
  488. paths: Paths to add. No value passed stages all modified files.
  489. Returns: Tuple with set of added files and ignored files
  490. If the repository contains ignored directories, the returned set will
  491. contain the path to an ignored directory (with trailing slash). Individual
  492. files within ignored directories will not be returned.
  493. """
  494. ignored = set()
  495. with open_repo_closing(repo) as r:
  496. repo_path = Path(r.path).resolve()
  497. ignore_manager = IgnoreFilterManager.from_repo(r)
  498. if not paths:
  499. paths = list(
  500. get_untracked_paths(
  501. str(Path(os.getcwd()).resolve()),
  502. str(repo_path),
  503. r.open_index(),
  504. )
  505. )
  506. relpaths = []
  507. if not isinstance(paths, list):
  508. paths = [paths]
  509. for p in paths:
  510. path = Path(p)
  511. relpath = str(path.resolve().relative_to(repo_path))
  512. # FIXME: Support patterns
  513. if path.is_dir():
  514. relpath = os.path.join(relpath, "")
  515. if ignore_manager.is_ignored(relpath):
  516. ignored.add(relpath)
  517. continue
  518. relpaths.append(relpath)
  519. r.stage(relpaths)
  520. return (relpaths, ignored)
  521. def _is_subdir(subdir, parentdir):
  522. """Check whether subdir is parentdir or a subdir of parentdir.
  523. If parentdir or subdir is a relative path, it will be disamgibuated
  524. relative to the pwd.
  525. """
  526. parentdir_abs = os.path.realpath(parentdir) + os.path.sep
  527. subdir_abs = os.path.realpath(subdir) + os.path.sep
  528. return subdir_abs.startswith(parentdir_abs)
  529. # TODO: option to remove ignored files also, in line with `git clean -fdx`
  530. def clean(repo=".", target_dir=None) -> None:
  531. """Remove any untracked files from the target directory recursively.
  532. Equivalent to running ``git clean -fd`` in target_dir.
  533. Args:
  534. repo: Repository where the files may be tracked
  535. target_dir: Directory to clean - current directory if None
  536. """
  537. if target_dir is None:
  538. target_dir = os.getcwd()
  539. with open_repo_closing(repo) as r:
  540. if not _is_subdir(target_dir, r.path):
  541. raise Error("target_dir must be in the repo's working dir")
  542. config = r.get_config_stack()
  543. config.get_boolean((b"clean",), b"requireForce", True)
  544. # TODO(jelmer): if require_force is set, then make sure that -f, -i or
  545. # -n is specified.
  546. index = r.open_index()
  547. ignore_manager = IgnoreFilterManager.from_repo(r)
  548. paths_in_wd = _walk_working_dir_paths(target_dir, r.path)
  549. # Reverse file visit order, so that files and subdirectories are
  550. # removed before containing directory
  551. for ap, is_dir in reversed(list(paths_in_wd)):
  552. if is_dir:
  553. # All subdirectories and files have been removed if untracked,
  554. # so dir contains no tracked files iff it is empty.
  555. is_empty = len(os.listdir(ap)) == 0
  556. if is_empty:
  557. os.rmdir(ap)
  558. else:
  559. ip = path_to_tree_path(r.path, ap)
  560. is_tracked = ip in index
  561. rp = os.path.relpath(ap, r.path)
  562. is_ignored = ignore_manager.is_ignored(rp)
  563. if not is_tracked and not is_ignored:
  564. os.remove(ap)
  565. def remove(repo=".", paths=None, cached=False) -> None:
  566. """Remove files from the staging area.
  567. Args:
  568. repo: Repository for the files
  569. paths: Paths to remove
  570. """
  571. with open_repo_closing(repo) as r:
  572. index = r.open_index()
  573. for p in paths:
  574. full_path = os.fsencode(os.path.abspath(p))
  575. tree_path = path_to_tree_path(r.path, p)
  576. try:
  577. index_sha = index[tree_path].sha
  578. except KeyError as exc:
  579. raise Error(f"{p} did not match any files") from exc
  580. if not cached:
  581. try:
  582. st = os.lstat(full_path)
  583. except OSError:
  584. pass
  585. else:
  586. try:
  587. blob = blob_from_path_and_stat(full_path, st)
  588. except OSError:
  589. pass
  590. else:
  591. try:
  592. committed_sha = tree_lookup_path(
  593. r.__getitem__, r[r.head()].tree, tree_path
  594. )[1]
  595. except KeyError:
  596. committed_sha = None
  597. if blob.id != index_sha and index_sha != committed_sha:
  598. raise Error(
  599. "file has staged content differing "
  600. f"from both the file and head: {p}"
  601. )
  602. if index_sha != committed_sha:
  603. raise Error(f"file has staged changes: {p}")
  604. os.remove(full_path)
  605. del index[tree_path]
  606. index.write()
  607. rm = remove
  608. def commit_decode(commit, contents, default_encoding=DEFAULT_ENCODING):
  609. if commit.encoding:
  610. encoding = commit.encoding.decode("ascii")
  611. else:
  612. encoding = default_encoding
  613. return contents.decode(encoding, "replace")
  614. def commit_encode(commit, contents, default_encoding=DEFAULT_ENCODING):
  615. if commit.encoding:
  616. encoding = commit.encoding.decode("ascii")
  617. else:
  618. encoding = default_encoding
  619. return contents.encode(encoding)
  620. def print_commit(commit, decode, outstream=sys.stdout) -> None:
  621. """Write a human-readable commit log entry.
  622. Args:
  623. commit: A `Commit` object
  624. outstream: A stream file to write to
  625. """
  626. outstream.write("-" * 50 + "\n")
  627. outstream.write("commit: " + commit.id.decode("ascii") + "\n")
  628. if len(commit.parents) > 1:
  629. outstream.write(
  630. "merge: "
  631. + "...".join([c.decode("ascii") for c in commit.parents[1:]])
  632. + "\n"
  633. )
  634. outstream.write("Author: " + decode(commit.author) + "\n")
  635. if commit.author != commit.committer:
  636. outstream.write("Committer: " + decode(commit.committer) + "\n")
  637. time_tuple = time.gmtime(commit.author_time + commit.author_timezone)
  638. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  639. timezone_str = format_timezone(commit.author_timezone).decode("ascii")
  640. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  641. if commit.message is not None:
  642. outstream.write("\n")
  643. outstream.write(decode(commit.message) + "\n")
  644. outstream.write("\n")
  645. def print_tag(tag, decode, outstream=sys.stdout) -> None:
  646. """Write a human-readable tag.
  647. Args:
  648. tag: A `Tag` object
  649. decode: Function for decoding bytes to unicode string
  650. outstream: A stream to write to
  651. """
  652. outstream.write("Tagger: " + decode(tag.tagger) + "\n")
  653. time_tuple = time.gmtime(tag.tag_time + tag.tag_timezone)
  654. time_str = time.strftime("%a %b %d %Y %H:%M:%S", time_tuple)
  655. timezone_str = format_timezone(tag.tag_timezone).decode("ascii")
  656. outstream.write("Date: " + time_str + " " + timezone_str + "\n")
  657. outstream.write("\n")
  658. outstream.write(decode(tag.message))
  659. outstream.write("\n")
  660. def show_blob(repo, blob, decode, outstream=sys.stdout) -> None:
  661. """Write a blob to a stream.
  662. Args:
  663. repo: A `Repo` object
  664. blob: A `Blob` object
  665. decode: Function for decoding bytes to unicode string
  666. outstream: A stream file to write to
  667. """
  668. outstream.write(decode(blob.data))
  669. def show_commit(repo, commit, decode, outstream=sys.stdout) -> None:
  670. """Show a commit to a stream.
  671. Args:
  672. repo: A `Repo` object
  673. commit: A `Commit` object
  674. decode: Function for decoding bytes to unicode string
  675. outstream: Stream to write to
  676. """
  677. print_commit(commit, decode=decode, outstream=outstream)
  678. if commit.parents:
  679. parent_commit = repo[commit.parents[0]]
  680. base_tree = parent_commit.tree
  681. else:
  682. base_tree = None
  683. diffstream = BytesIO()
  684. write_tree_diff(diffstream, repo.object_store, base_tree, commit.tree)
  685. diffstream.seek(0)
  686. outstream.write(commit_decode(commit, diffstream.getvalue()))
  687. def show_tree(repo, tree, decode, outstream=sys.stdout) -> None:
  688. """Print a tree to a stream.
  689. Args:
  690. repo: A `Repo` object
  691. tree: A `Tree` object
  692. decode: Function for decoding bytes to unicode string
  693. outstream: Stream to write to
  694. """
  695. for n in tree:
  696. outstream.write(decode(n) + "\n")
  697. def show_tag(repo, tag, decode, outstream=sys.stdout) -> None:
  698. """Print a tag to a stream.
  699. Args:
  700. repo: A `Repo` object
  701. tag: A `Tag` object
  702. decode: Function for decoding bytes to unicode string
  703. outstream: Stream to write to
  704. """
  705. print_tag(tag, decode, outstream)
  706. show_object(repo, repo[tag.object[1]], decode, outstream)
  707. def show_object(repo, obj, decode, outstream):
  708. return {
  709. b"tree": show_tree,
  710. b"blob": show_blob,
  711. b"commit": show_commit,
  712. b"tag": show_tag,
  713. }[obj.type_name](repo, obj, decode, outstream)
  714. def print_name_status(changes):
  715. """Print a simple status summary, listing changed files."""
  716. for change in changes:
  717. if not change:
  718. continue
  719. if isinstance(change, list):
  720. change = change[0]
  721. if change.type == CHANGE_ADD:
  722. path1 = change.new.path
  723. path2 = ""
  724. kind = "A"
  725. elif change.type == CHANGE_DELETE:
  726. path1 = change.old.path
  727. path2 = ""
  728. kind = "D"
  729. elif change.type == CHANGE_MODIFY:
  730. path1 = change.new.path
  731. path2 = ""
  732. kind = "M"
  733. elif change.type in RENAME_CHANGE_TYPES:
  734. path1 = change.old.path
  735. path2 = change.new.path
  736. if change.type == CHANGE_RENAME:
  737. kind = "R"
  738. elif change.type == CHANGE_COPY:
  739. kind = "C"
  740. yield "%-8s%-20s%-20s" % (kind, path1, path2) # noqa: UP031
  741. def log(
  742. repo=".",
  743. paths=None,
  744. outstream=sys.stdout,
  745. max_entries=None,
  746. reverse=False,
  747. name_status=False,
  748. ) -> None:
  749. """Write commit logs.
  750. Args:
  751. repo: Path to repository
  752. paths: Optional set of specific paths to print entries for
  753. outstream: Stream to write log output to
  754. reverse: Reverse order in which entries are printed
  755. name_status: Print name status
  756. max_entries: Optional maximum number of entries to display
  757. """
  758. with open_repo_closing(repo) as r:
  759. walker = r.get_walker(max_entries=max_entries, paths=paths, reverse=reverse)
  760. for entry in walker:
  761. def decode(x):
  762. return commit_decode(entry.commit, x)
  763. print_commit(entry.commit, decode, outstream)
  764. if name_status:
  765. outstream.writelines(
  766. [line + "\n" for line in print_name_status(entry.changes())]
  767. )
  768. # TODO(jelmer): better default for encoding?
  769. def show(
  770. repo=".",
  771. objects=None,
  772. outstream=sys.stdout,
  773. default_encoding=DEFAULT_ENCODING,
  774. ) -> None:
  775. """Print the changes in a commit.
  776. Args:
  777. repo: Path to repository
  778. objects: Objects to show (defaults to [HEAD])
  779. outstream: Stream to write to
  780. default_encoding: Default encoding to use if none is set in the
  781. commit
  782. """
  783. if objects is None:
  784. objects = ["HEAD"]
  785. if not isinstance(objects, list):
  786. objects = [objects]
  787. with open_repo_closing(repo) as r:
  788. for objectish in objects:
  789. o = parse_object(r, objectish)
  790. if isinstance(o, Commit):
  791. def decode(x):
  792. return commit_decode(o, x, default_encoding)
  793. else:
  794. def decode(x):
  795. return x.decode(default_encoding)
  796. show_object(r, o, decode, outstream)
  797. def diff_tree(repo, old_tree, new_tree, outstream=default_bytes_out_stream) -> None:
  798. """Compares the content and mode of blobs found via two tree objects.
  799. Args:
  800. repo: Path to repository
  801. old_tree: Id of old tree
  802. new_tree: Id of new tree
  803. outstream: Stream to write to
  804. """
  805. with open_repo_closing(repo) as r:
  806. write_tree_diff(outstream, r.object_store, old_tree, new_tree)
  807. def rev_list(repo, commits, outstream=sys.stdout) -> None:
  808. """Lists commit objects in reverse chronological order.
  809. Args:
  810. repo: Path to repository
  811. commits: Commits over which to iterate
  812. outstream: Stream to write to
  813. """
  814. with open_repo_closing(repo) as r:
  815. for entry in r.get_walker(include=[r[c].id for c in commits]):
  816. outstream.write(entry.commit.id + b"\n")
  817. def _canonical_part(url: str) -> str:
  818. name = url.rsplit("/", 1)[-1]
  819. if name.endswith(".git"):
  820. name = name[:-4]
  821. return name
  822. def submodule_add(repo, url, path=None, name=None) -> None:
  823. """Add a new submodule.
  824. Args:
  825. repo: Path to repository
  826. url: URL of repository to add as submodule
  827. path: Path where submodule should live
  828. """
  829. with open_repo_closing(repo) as r:
  830. if path is None:
  831. path = os.path.relpath(_canonical_part(url), r.path)
  832. if name is None:
  833. name = path
  834. # TODO(jelmer): Move this logic to dulwich.submodule
  835. gitmodules_path = os.path.join(r.path, ".gitmodules")
  836. try:
  837. config = ConfigFile.from_path(gitmodules_path)
  838. except FileNotFoundError:
  839. config = ConfigFile()
  840. config.path = gitmodules_path
  841. config.set(("submodule", name), "url", url)
  842. config.set(("submodule", name), "path", path)
  843. config.write_to_path()
  844. def submodule_init(repo) -> None:
  845. """Initialize submodules.
  846. Args:
  847. repo: Path to repository
  848. """
  849. with open_repo_closing(repo) as r:
  850. config = r.get_config()
  851. gitmodules_path = os.path.join(r.path, ".gitmodules")
  852. for path, url, name in read_submodules(gitmodules_path):
  853. config.set((b"submodule", name), b"active", True)
  854. config.set((b"submodule", name), b"url", url)
  855. config.write_to_path()
  856. def submodule_list(repo):
  857. """List submodules.
  858. Args:
  859. repo: Path to repository
  860. """
  861. from .submodule import iter_cached_submodules
  862. with open_repo_closing(repo) as r:
  863. for path, sha in iter_cached_submodules(r.object_store, r[r.head()].tree):
  864. yield path, sha.decode(DEFAULT_ENCODING)
  865. def tag_create(
  866. repo,
  867. tag: Union[str, bytes],
  868. author: Optional[Union[str, bytes]] = None,
  869. message: Optional[Union[str, bytes]] = None,
  870. annotated=False,
  871. objectish: Union[str, bytes] = "HEAD",
  872. tag_time=None,
  873. tag_timezone=None,
  874. sign: bool = False,
  875. encoding: str = DEFAULT_ENCODING,
  876. ) -> None:
  877. """Creates a tag in git via dulwich calls.
  878. Args:
  879. repo: Path to repository
  880. tag: tag string
  881. author: tag author (optional, if annotated is set)
  882. message: tag message (optional)
  883. annotated: whether to create an annotated tag
  884. objectish: object the tag should point at, defaults to HEAD
  885. tag_time: Optional time for annotated tag
  886. tag_timezone: Optional timezone for annotated tag
  887. sign: GPG Sign the tag (bool, defaults to False,
  888. pass True to use default GPG key,
  889. pass a str containing Key ID to use a specific GPG key)
  890. """
  891. with open_repo_closing(repo) as r:
  892. object = parse_object(r, objectish)
  893. if isinstance(tag, str):
  894. tag = tag.encode(encoding)
  895. if annotated:
  896. # Create the tag object
  897. tag_obj = Tag()
  898. if author is None:
  899. author = get_user_identity(r.get_config_stack())
  900. elif isinstance(author, str):
  901. author = author.encode(encoding)
  902. else:
  903. assert isinstance(author, bytes)
  904. tag_obj.tagger = author
  905. if isinstance(message, str):
  906. message = message.encode(encoding)
  907. elif isinstance(message, bytes):
  908. pass
  909. else:
  910. message = b""
  911. tag_obj.message = message + "\n".encode(encoding)
  912. tag_obj.name = tag
  913. tag_obj.object = (type(object), object.id)
  914. if tag_time is None:
  915. tag_time = int(time.time())
  916. tag_obj.tag_time = tag_time
  917. if tag_timezone is None:
  918. tag_timezone = get_user_timezones()[1]
  919. elif isinstance(tag_timezone, str):
  920. tag_timezone = parse_timezone(tag_timezone)
  921. tag_obj.tag_timezone = tag_timezone
  922. if sign:
  923. tag_obj.sign(sign if isinstance(sign, str) else None)
  924. r.object_store.add_object(tag_obj)
  925. tag_id = tag_obj.id
  926. else:
  927. tag_id = object.id
  928. r.refs[_make_tag_ref(tag)] = tag_id
  929. def tag_list(repo, outstream=sys.stdout):
  930. """List all tags.
  931. Args:
  932. repo: Path to repository
  933. outstream: Stream to write tags to
  934. """
  935. with open_repo_closing(repo) as r:
  936. tags = sorted(r.refs.as_dict(b"refs/tags"))
  937. return tags
  938. def tag_delete(repo, name) -> None:
  939. """Remove a tag.
  940. Args:
  941. repo: Path to repository
  942. name: Name of tag to remove
  943. """
  944. with open_repo_closing(repo) as r:
  945. if isinstance(name, bytes):
  946. names = [name]
  947. elif isinstance(name, list):
  948. names = name
  949. else:
  950. raise Error(f"Unexpected tag name type {name!r}")
  951. for name in names:
  952. del r.refs[_make_tag_ref(name)]
  953. def reset(repo, mode, treeish="HEAD") -> None:
  954. """Reset current HEAD to the specified state.
  955. Args:
  956. repo: Path to repository
  957. mode: Mode ("hard", "soft", "mixed")
  958. treeish: Treeish to reset to
  959. """
  960. if mode != "hard":
  961. raise Error("hard is the only mode currently supported")
  962. with open_repo_closing(repo) as r:
  963. tree = parse_tree(r, treeish)
  964. r.reset_index(tree.id)
  965. def get_remote_repo(
  966. repo: Repo, remote_location: Optional[Union[str, bytes]] = None
  967. ) -> tuple[Optional[str], str]:
  968. config = repo.get_config()
  969. if remote_location is None:
  970. remote_location = get_branch_remote(repo)
  971. if isinstance(remote_location, str):
  972. encoded_location = remote_location.encode()
  973. else:
  974. encoded_location = remote_location
  975. section = (b"remote", encoded_location)
  976. remote_name: Optional[str] = None
  977. if config.has_section(section):
  978. remote_name = encoded_location.decode()
  979. encoded_location = config.get(section, "url")
  980. else:
  981. remote_name = None
  982. return (remote_name, encoded_location.decode())
  983. def push(
  984. repo,
  985. remote_location=None,
  986. refspecs=None,
  987. outstream=default_bytes_out_stream,
  988. errstream=default_bytes_err_stream,
  989. force=False,
  990. **kwargs,
  991. ) -> None:
  992. """Remote push with dulwich via dulwich.client.
  993. Args:
  994. repo: Path to repository
  995. remote_location: Location of the remote
  996. refspecs: Refs to push to remote
  997. outstream: A stream file to write output
  998. errstream: A stream file to write errors
  999. force: Force overwriting refs
  1000. """
  1001. # Open the repo
  1002. with open_repo_closing(repo) as r:
  1003. if refspecs is None:
  1004. refspecs = [active_branch(r)]
  1005. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1006. # Get the client and path
  1007. client, path = get_transport_and_path(
  1008. remote_location, config=r.get_config_stack(), **kwargs
  1009. )
  1010. selected_refs = []
  1011. remote_changed_refs = {}
  1012. def update_refs(refs):
  1013. selected_refs.extend(parse_reftuples(r.refs, refs, refspecs, force=force))
  1014. new_refs = {}
  1015. # TODO: Handle selected_refs == {None: None}
  1016. for lh, rh, force_ref in selected_refs:
  1017. if lh is None:
  1018. new_refs[rh] = ZERO_SHA
  1019. remote_changed_refs[rh] = None
  1020. else:
  1021. try:
  1022. localsha = r.refs[lh]
  1023. except KeyError as exc:
  1024. raise Error(f"No valid ref {lh} in local repository") from exc
  1025. if not force_ref and rh in refs:
  1026. check_diverged(r, refs[rh], localsha)
  1027. new_refs[rh] = localsha
  1028. remote_changed_refs[rh] = localsha
  1029. return new_refs
  1030. err_encoding = getattr(errstream, "encoding", None) or DEFAULT_ENCODING
  1031. remote_location = client.get_url(path)
  1032. try:
  1033. result = client.send_pack(
  1034. path,
  1035. update_refs,
  1036. generate_pack_data=r.generate_pack_data,
  1037. progress=errstream.write,
  1038. )
  1039. except SendPackError as exc:
  1040. raise Error(
  1041. "Push to " + remote_location + " failed -> " + exc.args[0].decode(),
  1042. ) from exc
  1043. else:
  1044. errstream.write(
  1045. b"Push to " + remote_location.encode(err_encoding) + b" successful.\n"
  1046. )
  1047. for ref, error in (result.ref_status or {}).items():
  1048. if error is not None:
  1049. errstream.write(
  1050. b"Push of ref %s failed: %s\n" % (ref, error.encode(err_encoding))
  1051. )
  1052. else:
  1053. errstream.write(b"Ref %s updated\n" % ref)
  1054. if remote_name is not None:
  1055. _import_remote_refs(r.refs, remote_name, remote_changed_refs)
  1056. def pull(
  1057. repo,
  1058. remote_location=None,
  1059. refspecs=None,
  1060. outstream=default_bytes_out_stream,
  1061. errstream=default_bytes_err_stream,
  1062. fast_forward=True,
  1063. force=False,
  1064. filter_spec=None,
  1065. protocol_version=None,
  1066. **kwargs,
  1067. ) -> None:
  1068. """Pull from remote via dulwich.client.
  1069. Args:
  1070. repo: Path to repository
  1071. remote_location: Location of the remote
  1072. refspecs: refspecs to fetch. Can be a bytestring, a string, or a list of
  1073. bytestring/string.
  1074. outstream: A stream file to write to output
  1075. errstream: A stream file to write to errors
  1076. filter_spec: A git-rev-list-style object filter spec, as an ASCII string.
  1077. Only used if the server supports the Git protocol-v2 'filter'
  1078. feature, and ignored otherwise.
  1079. protocol_version: desired Git protocol version. By default the highest
  1080. mutually supported protocol version will be used
  1081. """
  1082. # Open the repo
  1083. with open_repo_closing(repo) as r:
  1084. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1085. selected_refs = []
  1086. if refspecs is None:
  1087. refspecs = [b"HEAD"]
  1088. def determine_wants(remote_refs, *args, **kwargs):
  1089. selected_refs.extend(
  1090. parse_reftuples(remote_refs, r.refs, refspecs, force=force)
  1091. )
  1092. return [
  1093. remote_refs[lh]
  1094. for (lh, rh, force_ref) in selected_refs
  1095. if remote_refs[lh] not in r.object_store
  1096. ]
  1097. client, path = get_transport_and_path(
  1098. remote_location, config=r.get_config_stack(), **kwargs
  1099. )
  1100. if filter_spec:
  1101. filter_spec = filter_spec.encode("ascii")
  1102. fetch_result = client.fetch(
  1103. path,
  1104. r,
  1105. progress=errstream.write,
  1106. determine_wants=determine_wants,
  1107. filter_spec=filter_spec,
  1108. protocol_version=protocol_version,
  1109. )
  1110. for lh, rh, force_ref in selected_refs:
  1111. if not force_ref and rh in r.refs:
  1112. try:
  1113. check_diverged(r, r.refs.follow(rh)[1], fetch_result.refs[lh])
  1114. except DivergedBranches as exc:
  1115. if fast_forward:
  1116. raise
  1117. else:
  1118. raise NotImplementedError("merge is not yet supported") from exc
  1119. r.refs[rh] = fetch_result.refs[lh]
  1120. if selected_refs:
  1121. r[b"HEAD"] = fetch_result.refs[selected_refs[0][1]]
  1122. # Perform 'git checkout .' - syncs staged changes
  1123. tree = r[b"HEAD"].tree
  1124. r.reset_index(tree=tree)
  1125. if remote_name is not None:
  1126. _import_remote_refs(r.refs, remote_name, fetch_result.refs)
  1127. def status(repo=".", ignored=False, untracked_files="all"):
  1128. """Returns staged, unstaged, and untracked changes relative to the HEAD.
  1129. Args:
  1130. repo: Path to repository or repository object
  1131. ignored: Whether to include ignored files in untracked
  1132. untracked_files: How to handle untracked files, defaults to "all":
  1133. "no": do not return untracked files
  1134. "all": include all files in untracked directories
  1135. Using untracked_files="no" can be faster than "all" when the worktreee
  1136. contains many untracked files/directories.
  1137. Note: untracked_files="normal" (git's default) is not implemented.
  1138. Returns: GitStatus tuple,
  1139. staged - dict with lists of staged paths (diff index/HEAD)
  1140. unstaged - list of unstaged paths (diff index/working-tree)
  1141. untracked - list of untracked, un-ignored & non-.git paths
  1142. """
  1143. with open_repo_closing(repo) as r:
  1144. # 1. Get status of staged
  1145. tracked_changes = get_tree_changes(r)
  1146. # 2. Get status of unstaged
  1147. index = r.open_index()
  1148. normalizer = r.get_blob_normalizer()
  1149. filter_callback = normalizer.checkin_normalize
  1150. unstaged_changes = list(get_unstaged_changes(index, r.path, filter_callback))
  1151. untracked_paths = get_untracked_paths(
  1152. r.path,
  1153. r.path,
  1154. index,
  1155. exclude_ignored=not ignored,
  1156. untracked_files=untracked_files,
  1157. )
  1158. if sys.platform == "win32":
  1159. untracked_changes = [
  1160. path.replace(os.path.sep, "/") for path in untracked_paths
  1161. ]
  1162. else:
  1163. untracked_changes = list(untracked_paths)
  1164. return GitStatus(tracked_changes, unstaged_changes, untracked_changes)
  1165. def _walk_working_dir_paths(frompath, basepath, prune_dirnames=None):
  1166. """Get path, is_dir for files in working dir from frompath.
  1167. Args:
  1168. frompath: Path to begin walk
  1169. basepath: Path to compare to
  1170. prune_dirnames: Optional callback to prune dirnames during os.walk
  1171. dirnames will be set to result of prune_dirnames(dirpath, dirnames)
  1172. """
  1173. for dirpath, dirnames, filenames in os.walk(frompath):
  1174. # Skip .git and below.
  1175. if ".git" in dirnames:
  1176. dirnames.remove(".git")
  1177. if dirpath != basepath:
  1178. continue
  1179. if ".git" in filenames:
  1180. filenames.remove(".git")
  1181. if dirpath != basepath:
  1182. continue
  1183. if dirpath != frompath:
  1184. yield dirpath, True
  1185. for filename in filenames:
  1186. filepath = os.path.join(dirpath, filename)
  1187. yield filepath, False
  1188. if prune_dirnames:
  1189. dirnames[:] = prune_dirnames(dirpath, dirnames)
  1190. def get_untracked_paths(
  1191. frompath, basepath, index, exclude_ignored=False, untracked_files="all"
  1192. ):
  1193. """Get untracked paths.
  1194. Args:
  1195. frompath: Path to walk
  1196. basepath: Path to compare to
  1197. index: Index to check against
  1198. exclude_ignored: Whether to exclude ignored paths
  1199. untracked_files: How to handle untracked files:
  1200. - "no": return an empty list
  1201. - "all": return all files in untracked directories
  1202. - "normal": Not implemented
  1203. Note: ignored directories will never be walked for performance reasons.
  1204. If exclude_ignored is False, only the path to an ignored directory will
  1205. be yielded, no files inside the directory will be returned
  1206. """
  1207. if untracked_files == "normal":
  1208. raise NotImplementedError("normal is not yet supported")
  1209. if untracked_files not in ("no", "all"):
  1210. raise ValueError("untracked_files must be one of (no, all)")
  1211. if untracked_files == "no":
  1212. return
  1213. with open_repo_closing(basepath) as r:
  1214. ignore_manager = IgnoreFilterManager.from_repo(r)
  1215. ignored_dirs = []
  1216. def prune_dirnames(dirpath, dirnames):
  1217. for i in range(len(dirnames) - 1, -1, -1):
  1218. path = os.path.join(dirpath, dirnames[i])
  1219. ip = os.path.join(os.path.relpath(path, basepath), "")
  1220. if ignore_manager.is_ignored(ip):
  1221. if not exclude_ignored:
  1222. ignored_dirs.append(
  1223. os.path.join(os.path.relpath(path, frompath), "")
  1224. )
  1225. del dirnames[i]
  1226. return dirnames
  1227. for ap, is_dir in _walk_working_dir_paths(
  1228. frompath, basepath, prune_dirnames=prune_dirnames
  1229. ):
  1230. if not is_dir:
  1231. ip = path_to_tree_path(basepath, ap)
  1232. if ip not in index:
  1233. if not exclude_ignored or not ignore_manager.is_ignored(
  1234. os.path.relpath(ap, basepath)
  1235. ):
  1236. yield os.path.relpath(ap, frompath)
  1237. yield from ignored_dirs
  1238. def get_tree_changes(repo):
  1239. """Return add/delete/modify changes to tree by comparing index to HEAD.
  1240. Args:
  1241. repo: repo path or object
  1242. Returns: dict with lists for each type of change
  1243. """
  1244. with open_repo_closing(repo) as r:
  1245. index = r.open_index()
  1246. # Compares the Index to the HEAD & determines changes
  1247. # Iterate through the changes and report add/delete/modify
  1248. # TODO: call out to dulwich.diff_tree somehow.
  1249. tracked_changes = {
  1250. "add": [],
  1251. "delete": [],
  1252. "modify": [],
  1253. }
  1254. try:
  1255. tree_id = r[b"HEAD"].tree
  1256. except KeyError:
  1257. tree_id = None
  1258. for change in index.changes_from_tree(r.object_store, tree_id):
  1259. if not change[0][0]:
  1260. tracked_changes["add"].append(change[0][1])
  1261. elif not change[0][1]:
  1262. tracked_changes["delete"].append(change[0][0])
  1263. elif change[0][0] == change[0][1]:
  1264. tracked_changes["modify"].append(change[0][0])
  1265. else:
  1266. raise NotImplementedError("git mv ops not yet supported")
  1267. return tracked_changes
  1268. def daemon(path=".", address=None, port=None) -> None:
  1269. """Run a daemon serving Git requests over TCP/IP.
  1270. Args:
  1271. path: Path to the directory to serve.
  1272. address: Optional address to listen on (defaults to ::)
  1273. port: Optional port to listen on (defaults to TCP_GIT_PORT)
  1274. """
  1275. # TODO(jelmer): Support git-daemon-export-ok and --export-all.
  1276. backend = FileSystemBackend(path)
  1277. server = TCPGitServer(backend, address, port)
  1278. server.serve_forever()
  1279. def web_daemon(path=".", address=None, port=None) -> None:
  1280. """Run a daemon serving Git requests over HTTP.
  1281. Args:
  1282. path: Path to the directory to serve
  1283. address: Optional address to listen on (defaults to ::)
  1284. port: Optional port to listen on (defaults to 80)
  1285. """
  1286. from .web import (
  1287. WSGIRequestHandlerLogger,
  1288. WSGIServerLogger,
  1289. make_server,
  1290. make_wsgi_chain,
  1291. )
  1292. backend = FileSystemBackend(path)
  1293. app = make_wsgi_chain(backend)
  1294. server = make_server(
  1295. address,
  1296. port,
  1297. app,
  1298. handler_class=WSGIRequestHandlerLogger,
  1299. server_class=WSGIServerLogger,
  1300. )
  1301. server.serve_forever()
  1302. def upload_pack(path=".", inf=None, outf=None) -> int:
  1303. """Upload a pack file after negotiating its contents using smart protocol.
  1304. Args:
  1305. path: Path to the repository
  1306. inf: Input stream to communicate with client
  1307. outf: Output stream to communicate with client
  1308. """
  1309. if outf is None:
  1310. outf = getattr(sys.stdout, "buffer", sys.stdout)
  1311. if inf is None:
  1312. inf = getattr(sys.stdin, "buffer", sys.stdin)
  1313. path = os.path.expanduser(path)
  1314. backend = FileSystemBackend(path)
  1315. def send_fn(data) -> None:
  1316. outf.write(data)
  1317. outf.flush()
  1318. proto = Protocol(inf.read, send_fn)
  1319. handler = UploadPackHandler(backend, [path], proto)
  1320. # FIXME: Catch exceptions and write a single-line summary to outf.
  1321. handler.handle()
  1322. return 0
  1323. def receive_pack(path=".", inf=None, outf=None) -> int:
  1324. """Receive a pack file after negotiating its contents using smart protocol.
  1325. Args:
  1326. path: Path to the repository
  1327. inf: Input stream to communicate with client
  1328. outf: Output stream to communicate with client
  1329. """
  1330. if outf is None:
  1331. outf = getattr(sys.stdout, "buffer", sys.stdout)
  1332. if inf is None:
  1333. inf = getattr(sys.stdin, "buffer", sys.stdin)
  1334. path = os.path.expanduser(path)
  1335. backend = FileSystemBackend(path)
  1336. def send_fn(data) -> None:
  1337. outf.write(data)
  1338. outf.flush()
  1339. proto = Protocol(inf.read, send_fn)
  1340. handler = ReceivePackHandler(backend, [path], proto)
  1341. # FIXME: Catch exceptions and write a single-line summary to outf.
  1342. handler.handle()
  1343. return 0
  1344. def _make_branch_ref(name: Union[str, bytes]) -> Ref:
  1345. if isinstance(name, str):
  1346. name = name.encode(DEFAULT_ENCODING)
  1347. return LOCAL_BRANCH_PREFIX + name
  1348. def _make_tag_ref(name: Union[str, bytes]) -> Ref:
  1349. if isinstance(name, str):
  1350. name = name.encode(DEFAULT_ENCODING)
  1351. return LOCAL_TAG_PREFIX + name
  1352. def branch_delete(repo, name) -> None:
  1353. """Delete a branch.
  1354. Args:
  1355. repo: Path to the repository
  1356. name: Name of the branch
  1357. """
  1358. with open_repo_closing(repo) as r:
  1359. if isinstance(name, list):
  1360. names = name
  1361. else:
  1362. names = [name]
  1363. for name in names:
  1364. del r.refs[_make_branch_ref(name)]
  1365. def branch_create(repo, name, objectish=None, force=False) -> None:
  1366. """Create a branch.
  1367. Args:
  1368. repo: Path to the repository
  1369. name: Name of the new branch
  1370. objectish: Target object to point new branch at (defaults to HEAD)
  1371. force: Force creation of branch, even if it already exists
  1372. """
  1373. with open_repo_closing(repo) as r:
  1374. if objectish is None:
  1375. objectish = "HEAD"
  1376. object = parse_object(r, objectish)
  1377. refname = _make_branch_ref(name)
  1378. ref_message = b"branch: Created from " + objectish.encode(DEFAULT_ENCODING)
  1379. if force:
  1380. r.refs.set_if_equals(refname, None, object.id, message=ref_message)
  1381. else:
  1382. if not r.refs.add_if_new(refname, object.id, message=ref_message):
  1383. raise Error(f"Branch with name {name} already exists.")
  1384. def branch_list(repo):
  1385. """List all branches.
  1386. Args:
  1387. repo: Path to the repository
  1388. """
  1389. with open_repo_closing(repo) as r:
  1390. return r.refs.keys(base=LOCAL_BRANCH_PREFIX)
  1391. def active_branch(repo):
  1392. """Return the active branch in the repository, if any.
  1393. Args:
  1394. repo: Repository to open
  1395. Returns:
  1396. branch name
  1397. Raises:
  1398. KeyError: if the repository does not have a working tree
  1399. IndexError: if HEAD is floating
  1400. """
  1401. with open_repo_closing(repo) as r:
  1402. active_ref = r.refs.follow(b"HEAD")[0][1]
  1403. if not active_ref.startswith(LOCAL_BRANCH_PREFIX):
  1404. raise ValueError(active_ref)
  1405. return active_ref[len(LOCAL_BRANCH_PREFIX) :]
  1406. def get_branch_remote(repo):
  1407. """Return the active branch's remote name, if any.
  1408. Args:
  1409. repo: Repository to open
  1410. Returns:
  1411. remote name
  1412. Raises:
  1413. KeyError: if the repository does not have a working tree
  1414. """
  1415. with open_repo_closing(repo) as r:
  1416. branch_name = active_branch(r.path)
  1417. config = r.get_config()
  1418. try:
  1419. remote_name = config.get((b"branch", branch_name), b"remote")
  1420. except KeyError:
  1421. remote_name = b"origin"
  1422. return remote_name
  1423. def fetch(
  1424. repo,
  1425. remote_location=None,
  1426. outstream=sys.stdout,
  1427. errstream=default_bytes_err_stream,
  1428. message=None,
  1429. depth=None,
  1430. prune=False,
  1431. prune_tags=False,
  1432. force=False,
  1433. **kwargs,
  1434. ):
  1435. """Fetch objects from a remote server.
  1436. Args:
  1437. repo: Path to the repository
  1438. remote_location: String identifying a remote server
  1439. outstream: Output stream (defaults to stdout)
  1440. errstream: Error stream (defaults to stderr)
  1441. message: Reflog message (defaults to b"fetch: from <remote_name>")
  1442. depth: Depth to fetch at
  1443. prune: Prune remote removed refs
  1444. prune_tags: Prune reomte removed tags
  1445. Returns:
  1446. Dictionary with refs on the remote
  1447. """
  1448. with open_repo_closing(repo) as r:
  1449. (remote_name, remote_location) = get_remote_repo(r, remote_location)
  1450. if message is None:
  1451. message = b"fetch: from " + remote_location.encode(DEFAULT_ENCODING)
  1452. client, path = get_transport_and_path(
  1453. remote_location, config=r.get_config_stack(), **kwargs
  1454. )
  1455. fetch_result = client.fetch(path, r, progress=errstream.write, depth=depth)
  1456. if remote_name is not None:
  1457. _import_remote_refs(
  1458. r.refs,
  1459. remote_name,
  1460. fetch_result.refs,
  1461. message,
  1462. prune=prune,
  1463. prune_tags=prune_tags,
  1464. )
  1465. return fetch_result
  1466. def for_each_ref(
  1467. repo: Union[Repo, str] = ".",
  1468. pattern: Optional[Union[str, bytes]] = None,
  1469. ) -> list[tuple[bytes, bytes, bytes]]:
  1470. """Iterate over all refs that match the (optional) pattern.
  1471. Args:
  1472. repo: Path to the repository
  1473. pattern: Optional glob (7) patterns to filter the refs with
  1474. Returns:
  1475. List of bytes tuples with: (sha, object_type, ref_name)
  1476. """
  1477. if isinstance(pattern, str):
  1478. pattern = os.fsencode(pattern)
  1479. with open_repo_closing(repo) as r:
  1480. refs = r.get_refs()
  1481. if pattern:
  1482. matching_refs: dict[bytes, bytes] = {}
  1483. pattern_parts = pattern.split(b"/")
  1484. for ref, sha in refs.items():
  1485. matches = False
  1486. # git for-each-ref uses glob (7) style patterns, but fnmatch
  1487. # is greedy and also matches slashes, unlike glob.glob.
  1488. # We have to check parts of the pattern individually.
  1489. # See https://github.com/python/cpython/issues/72904
  1490. ref_parts = ref.split(b"/")
  1491. if len(ref_parts) > len(pattern_parts):
  1492. continue
  1493. for pat, ref_part in zip(pattern_parts, ref_parts):
  1494. matches = fnmatch.fnmatchcase(ref_part, pat)
  1495. if not matches:
  1496. break
  1497. if matches:
  1498. matching_refs[ref] = sha
  1499. refs = matching_refs
  1500. ret: list[tuple[bytes, bytes, bytes]] = [
  1501. (sha, r.get_object(sha).type_name, ref)
  1502. for ref, sha in sorted(
  1503. refs.items(),
  1504. key=lambda ref_sha: ref_sha[0],
  1505. )
  1506. if ref != b"HEAD"
  1507. ]
  1508. return ret
  1509. def ls_remote(remote, config: Optional[Config] = None, **kwargs):
  1510. """List the refs in a remote.
  1511. Args:
  1512. remote: Remote repository location
  1513. config: Configuration to use
  1514. Returns:
  1515. Dictionary with remote refs
  1516. """
  1517. if config is None:
  1518. config = StackedConfig.default()
  1519. client, host_path = get_transport_and_path(remote, config=config, **kwargs)
  1520. return client.get_refs(host_path)
  1521. def repack(repo) -> None:
  1522. """Repack loose files in a repository.
  1523. Currently this only packs loose objects.
  1524. Args:
  1525. repo: Path to the repository
  1526. """
  1527. with open_repo_closing(repo) as r:
  1528. r.object_store.pack_loose_objects()
  1529. def pack_objects(
  1530. repo,
  1531. object_ids,
  1532. packf,
  1533. idxf,
  1534. delta_window_size=None,
  1535. deltify=None,
  1536. reuse_deltas=True,
  1537. ) -> None:
  1538. """Pack objects into a file.
  1539. Args:
  1540. repo: Path to the repository
  1541. object_ids: List of object ids to write
  1542. packf: File-like object to write to
  1543. idxf: File-like object to write to (can be None)
  1544. delta_window_size: Sliding window size for searching for deltas;
  1545. Set to None for default window size.
  1546. deltify: Whether to deltify objects
  1547. reuse_deltas: Allow reuse of existing deltas while deltifying
  1548. """
  1549. with open_repo_closing(repo) as r:
  1550. entries, data_sum = write_pack_from_container(
  1551. packf.write,
  1552. r.object_store,
  1553. [(oid, None) for oid in object_ids],
  1554. deltify=deltify,
  1555. delta_window_size=delta_window_size,
  1556. reuse_deltas=reuse_deltas,
  1557. )
  1558. if idxf is not None:
  1559. entries = sorted([(k, v[0], v[1]) for (k, v) in entries.items()])
  1560. write_pack_index(idxf, entries, data_sum)
  1561. def ls_tree(
  1562. repo,
  1563. treeish=b"HEAD",
  1564. outstream=sys.stdout,
  1565. recursive=False,
  1566. name_only=False,
  1567. ) -> None:
  1568. """List contents of a tree.
  1569. Args:
  1570. repo: Path to the repository
  1571. treeish: Tree id to list
  1572. outstream: Output stream (defaults to stdout)
  1573. recursive: Whether to recursively list files
  1574. name_only: Only print item name
  1575. """
  1576. def list_tree(store, treeid, base) -> None:
  1577. for name, mode, sha in store[treeid].iteritems():
  1578. if base:
  1579. name = posixpath.join(base, name)
  1580. if name_only:
  1581. outstream.write(name + b"\n")
  1582. else:
  1583. outstream.write(pretty_format_tree_entry(name, mode, sha))
  1584. if stat.S_ISDIR(mode) and recursive:
  1585. list_tree(store, sha, name)
  1586. with open_repo_closing(repo) as r:
  1587. tree = parse_tree(r, treeish)
  1588. list_tree(r.object_store, tree.id, "")
  1589. def remote_add(repo, name: Union[bytes, str], url: Union[bytes, str]) -> None:
  1590. """Add a remote.
  1591. Args:
  1592. repo: Path to the repository
  1593. name: Remote name
  1594. url: Remote URL
  1595. """
  1596. if not isinstance(name, bytes):
  1597. name = name.encode(DEFAULT_ENCODING)
  1598. if not isinstance(url, bytes):
  1599. url = url.encode(DEFAULT_ENCODING)
  1600. with open_repo_closing(repo) as r:
  1601. c = r.get_config()
  1602. section = (b"remote", name)
  1603. if c.has_section(section):
  1604. raise RemoteExists(section)
  1605. c.set(section, b"url", url)
  1606. c.write_to_path()
  1607. def remote_remove(repo: Repo, name: Union[bytes, str]) -> None:
  1608. """Remove a remote.
  1609. Args:
  1610. repo: Path to the repository
  1611. name: Remote name
  1612. """
  1613. if not isinstance(name, bytes):
  1614. name = name.encode(DEFAULT_ENCODING)
  1615. with open_repo_closing(repo) as r:
  1616. c = r.get_config()
  1617. section = (b"remote", name)
  1618. del c[section]
  1619. c.write_to_path()
  1620. def check_ignore(repo, paths, no_index=False):
  1621. """Debug gitignore files.
  1622. Args:
  1623. repo: Path to the repository
  1624. paths: List of paths to check for
  1625. no_index: Don't check index
  1626. Returns: List of ignored files
  1627. """
  1628. with open_repo_closing(repo) as r:
  1629. index = r.open_index()
  1630. ignore_manager = IgnoreFilterManager.from_repo(r)
  1631. for path in paths:
  1632. if not no_index and path_to_tree_path(r.path, path) in index:
  1633. continue
  1634. if os.path.isabs(path):
  1635. path = os.path.relpath(path, r.path)
  1636. if ignore_manager.is_ignored(path):
  1637. yield path
  1638. def update_head(repo, target, detached=False, new_branch=None) -> None:
  1639. """Update HEAD to point at a new branch/commit.
  1640. Note that this does not actually update the working tree.
  1641. Args:
  1642. repo: Path to the repository
  1643. detached: Create a detached head
  1644. target: Branch or committish to switch to
  1645. new_branch: New branch to create
  1646. """
  1647. with open_repo_closing(repo) as r:
  1648. if new_branch is not None:
  1649. to_set = _make_branch_ref(new_branch)
  1650. else:
  1651. to_set = b"HEAD"
  1652. if detached:
  1653. # TODO(jelmer): Provide some way so that the actual ref gets
  1654. # updated rather than what it points to, so the delete isn't
  1655. # necessary.
  1656. del r.refs[to_set]
  1657. r.refs[to_set] = parse_commit(r, target).id
  1658. else:
  1659. r.refs.set_symbolic_ref(to_set, parse_ref(r, target))
  1660. if new_branch is not None:
  1661. r.refs.set_symbolic_ref(b"HEAD", to_set)
  1662. def reset_file(repo, file_path: str, target: bytes = b"HEAD", symlink_fn=None) -> None:
  1663. """Reset the file to specific commit or branch.
  1664. Args:
  1665. repo: dulwich Repo object
  1666. file_path: file to reset, relative to the repository path
  1667. target: branch or commit or b'HEAD' to reset
  1668. """
  1669. tree = parse_tree(repo, treeish=target)
  1670. tree_path = _fs_to_tree_path(file_path)
  1671. file_entry = tree.lookup_path(repo.object_store.__getitem__, tree_path)
  1672. full_path = os.path.join(os.fsencode(repo.path), tree_path)
  1673. blob = repo.object_store[file_entry[1]]
  1674. mode = file_entry[0]
  1675. build_file_from_blob(blob, mode, full_path, symlink_fn=symlink_fn)
  1676. def _update_head_during_checkout_branch(repo, target):
  1677. checkout_target = None
  1678. if target == b"HEAD": # Do not update head while trying to checkout to HEAD.
  1679. pass
  1680. elif target in repo.refs.keys(base=LOCAL_BRANCH_PREFIX):
  1681. update_head(repo, target)
  1682. else:
  1683. # If checking out a remote branch, create a local one without the remote name prefix.
  1684. config = repo.get_config()
  1685. name = target.split(b"/")[0]
  1686. section = (b"remote", name)
  1687. if config.has_section(section):
  1688. checkout_target = target.replace(name + b"/", b"")
  1689. try:
  1690. branch_create(
  1691. repo, checkout_target, (LOCAL_REMOTE_PREFIX + target).decode()
  1692. )
  1693. except Error:
  1694. pass
  1695. update_head(repo, LOCAL_BRANCH_PREFIX + checkout_target)
  1696. else:
  1697. update_head(repo, target, detached=True)
  1698. return checkout_target
  1699. def checkout_branch(repo, target: Union[bytes, str], force: bool = False) -> None:
  1700. """Switch branches or restore working tree files.
  1701. The implementation of this function will probably not scale well
  1702. for branches with lots of local changes.
  1703. This is due to the analysis of a diff between branches before any
  1704. changes are applied.
  1705. Args:
  1706. repo: dulwich Repo object
  1707. target: branch name or commit sha to checkout
  1708. force: true or not to force checkout
  1709. """
  1710. target = to_bytes(target)
  1711. current_tree = parse_tree(repo, repo.head())
  1712. target_tree = parse_tree(repo, target)
  1713. if force:
  1714. repo.reset_index(target_tree.id)
  1715. _update_head_during_checkout_branch(repo, target)
  1716. else:
  1717. status_report = status(repo)
  1718. changes = list(
  1719. set(
  1720. status_report[0]["add"]
  1721. + status_report[0]["delete"]
  1722. + status_report[0]["modify"]
  1723. + status_report[1]
  1724. )
  1725. )
  1726. index = 0
  1727. while index < len(changes):
  1728. change = changes[index]
  1729. try:
  1730. current_tree.lookup_path(repo.object_store.__getitem__, change)
  1731. try:
  1732. target_tree.lookup_path(repo.object_store.__getitem__, change)
  1733. index += 1
  1734. except KeyError:
  1735. raise CheckoutError(
  1736. "Your local changes to the following files would be overwritten by checkout: "
  1737. + change.decode()
  1738. )
  1739. except KeyError:
  1740. changes.pop(index)
  1741. # Update head.
  1742. checkout_target = _update_head_during_checkout_branch(repo, target)
  1743. if checkout_target is not None:
  1744. target_tree = parse_tree(repo, checkout_target)
  1745. dealt_with = set()
  1746. repo_index = repo.open_index()
  1747. for entry in iter_tree_contents(repo.object_store, target_tree.id):
  1748. dealt_with.add(entry.path)
  1749. if entry.path in changes:
  1750. continue
  1751. full_path = os.path.join(os.fsencode(repo.path), entry.path)
  1752. blob = repo.object_store[entry.sha]
  1753. ensure_dir_exists(os.path.dirname(full_path))
  1754. st = build_file_from_blob(blob, entry.mode, full_path)
  1755. repo_index[entry.path] = index_entry_from_stat(st, entry.sha)
  1756. repo_index.write()
  1757. for entry in iter_tree_contents(repo.object_store, current_tree.id):
  1758. if entry.path not in dealt_with:
  1759. repo.unstage([entry.path])
  1760. # Remove the untracked files which are in the current_file_set.
  1761. repo_index = repo.open_index()
  1762. for change in repo_index.changes_from_tree(repo.object_store, current_tree.id):
  1763. path_change = change[0]
  1764. if path_change[1] is None:
  1765. file_name = path_change[0]
  1766. full_path = os.path.join(repo.path, file_name.decode())
  1767. if os.path.isfile(full_path):
  1768. os.remove(full_path)
  1769. dir_path = os.path.dirname(full_path)
  1770. while dir_path != repo.path:
  1771. is_empty = len(os.listdir(dir_path)) == 0
  1772. if is_empty:
  1773. os.rmdir(dir_path)
  1774. dir_path = os.path.dirname(dir_path)
  1775. def sparse_checkout(
  1776. repo, patterns=None, force: bool = False, cone: Union[bool, None] = None
  1777. ):
  1778. """Perform a sparse checkout in the repository (either 'full' or 'cone mode').
  1779. Perform sparse checkout in either 'cone' (directory-based) mode or
  1780. 'full pattern' (.gitignore) mode, depending on the ``cone`` parameter.
  1781. If ``cone`` is ``None``, the mode is inferred from the repository's
  1782. ``core.sparseCheckoutCone`` config setting.
  1783. Steps:
  1784. 1) If ``patterns`` is provided, write them to ``.git/info/sparse-checkout``.
  1785. 2) Determine which paths in the index are included vs. excluded.
  1786. - If ``cone=True``, use "cone-compatible" directory-based logic.
  1787. - If ``cone=False``, use standard .gitignore-style matching.
  1788. 3) Update the index's skip-worktree bits and add/remove files in
  1789. the working tree accordingly.
  1790. 4) If ``force=False``, refuse to remove files that have local modifications.
  1791. Args:
  1792. repo: Path to the repository or a Repo object.
  1793. patterns: Optional list of sparse-checkout patterns to write.
  1794. force: Whether to force removal of locally modified files (default False).
  1795. cone: Boolean indicating cone mode (True/False). If None, read from config.
  1796. Returns:
  1797. None
  1798. """
  1799. with open_repo_closing(repo) as repo_obj:
  1800. # --- 0) Possibly infer 'cone' from config ---
  1801. if cone is None:
  1802. cone = repo_obj.infer_cone_mode()
  1803. # --- 1) Read or write patterns ---
  1804. if patterns is None:
  1805. lines = repo_obj.get_sparse_checkout_patterns()
  1806. if lines is None:
  1807. raise Error("No sparse checkout patterns found.")
  1808. else:
  1809. lines = patterns
  1810. repo_obj.set_sparse_checkout_patterns(patterns)
  1811. # --- 2) Determine the set of included paths ---
  1812. included_paths = determine_included_paths(repo_obj, lines, cone)
  1813. # --- 3) Apply those results to the index & working tree ---
  1814. try:
  1815. apply_included_paths(repo_obj, included_paths, force=force)
  1816. except SparseCheckoutConflictError as exc:
  1817. raise CheckoutError(*exc.args) from exc
  1818. def cone_mode_init(repo):
  1819. """Initialize a repository to use sparse checkout in 'cone' mode.
  1820. Sets ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` in the config.
  1821. Writes an initial ``.git/info/sparse-checkout`` file that includes only
  1822. top-level files (and excludes all subdirectories), e.g. ``["/*", "!/*/"]``.
  1823. Then performs a sparse checkout to update the working tree accordingly.
  1824. If no directories are specified, then only top-level files are included:
  1825. https://git-scm.com/docs/git-sparse-checkout#_internalscone_mode_handling
  1826. Args:
  1827. repo: Path to the repository or a Repo object.
  1828. Returns:
  1829. None
  1830. """
  1831. with open_repo_closing(repo) as repo_obj:
  1832. repo_obj.configure_for_cone_mode()
  1833. patterns = ["/*", "!/*/"] # root-level files only
  1834. sparse_checkout(repo_obj, patterns, force=True, cone=True)
  1835. def cone_mode_set(repo, dirs, force=False):
  1836. """Overwrite the existing 'cone-mode' sparse patterns with a new set of directories.
  1837. Ensures ``core.sparseCheckout`` and ``core.sparseCheckoutCone`` are enabled.
  1838. Writes new patterns so that only the specified directories (and top-level files)
  1839. remain in the working tree, and applies the sparse checkout update.
  1840. Args:
  1841. repo: Path to the repository or a Repo object.
  1842. dirs: List of directory names to include.
  1843. force: Whether to forcibly discard local modifications (default False).
  1844. Returns:
  1845. None
  1846. """
  1847. with open_repo_closing(repo) as repo_obj:
  1848. repo_obj.configure_for_cone_mode()
  1849. repo_obj.set_cone_mode_patterns(dirs=dirs)
  1850. new_patterns = repo_obj.get_sparse_checkout_patterns()
  1851. # Finally, apply the patterns and update the working tree
  1852. sparse_checkout(repo_obj, new_patterns, force=force, cone=True)
  1853. def cone_mode_add(repo, dirs, force=False):
  1854. """Add new directories to the existing 'cone-mode' sparse-checkout patterns.
  1855. Reads the current patterns from ``.git/info/sparse-checkout``, adds pattern
  1856. lines to include the specified directories, and then performs a sparse
  1857. checkout to update the working tree accordingly.
  1858. Args:
  1859. repo: Path to the repository or a Repo object.
  1860. dirs: List of directory names to add to the sparse-checkout.
  1861. force: Whether to forcibly discard local modifications (default False).
  1862. Returns:
  1863. None
  1864. """
  1865. with open_repo_closing(repo) as repo_obj:
  1866. repo_obj.configure_for_cone_mode()
  1867. # Do not pass base patterns as dirs
  1868. base_patterns = ["/*", "!/*/"]
  1869. existing_dirs = [
  1870. pat.strip("/")
  1871. for pat in repo_obj.get_sparse_checkout_patterns()
  1872. if pat not in base_patterns
  1873. ]
  1874. added_dirs = existing_dirs + (dirs or [])
  1875. repo_obj.set_cone_mode_patterns(dirs=added_dirs)
  1876. new_patterns = repo_obj.get_sparse_checkout_patterns()
  1877. sparse_checkout(repo_obj, patterns=new_patterns, force=force, cone=True)
  1878. def check_mailmap(repo, contact):
  1879. """Check canonical name and email of contact.
  1880. Args:
  1881. repo: Path to the repository
  1882. contact: Contact name and/or email
  1883. Returns: Canonical contact data
  1884. """
  1885. with open_repo_closing(repo) as r:
  1886. from .mailmap import Mailmap
  1887. try:
  1888. mailmap = Mailmap.from_path(os.path.join(r.path, ".mailmap"))
  1889. except FileNotFoundError:
  1890. mailmap = Mailmap()
  1891. return mailmap.lookup(contact)
  1892. def fsck(repo):
  1893. """Check a repository.
  1894. Args:
  1895. repo: A path to the repository
  1896. Returns: Iterator over errors/warnings
  1897. """
  1898. with open_repo_closing(repo) as r:
  1899. # TODO(jelmer): check pack files
  1900. # TODO(jelmer): check graph
  1901. # TODO(jelmer): check refs
  1902. for sha in r.object_store:
  1903. o = r.object_store[sha]
  1904. try:
  1905. o.check()
  1906. except Exception as e:
  1907. yield (sha, e)
  1908. def stash_list(repo):
  1909. """List all stashes in a repository."""
  1910. with open_repo_closing(repo) as r:
  1911. from .stash import Stash
  1912. stash = Stash.from_repo(r)
  1913. return enumerate(list(stash.stashes()))
  1914. def stash_push(repo) -> None:
  1915. """Push a new stash onto the stack."""
  1916. with open_repo_closing(repo) as r:
  1917. from .stash import Stash
  1918. stash = Stash.from_repo(r)
  1919. stash.push()
  1920. def stash_pop(repo) -> None:
  1921. """Pop a stash from the stack."""
  1922. with open_repo_closing(repo) as r:
  1923. from .stash import Stash
  1924. stash = Stash.from_repo(r)
  1925. stash.pop()
  1926. def stash_drop(repo, index) -> None:
  1927. """Drop a stash from the stack."""
  1928. with open_repo_closing(repo) as r:
  1929. from .stash import Stash
  1930. stash = Stash.from_repo(r)
  1931. stash.drop(index)
  1932. def ls_files(repo):
  1933. """List all files in an index."""
  1934. with open_repo_closing(repo) as r:
  1935. return sorted(r.open_index())
  1936. def find_unique_abbrev(object_store, object_id):
  1937. """For now, just return 7 characters."""
  1938. # TODO(jelmer): Add some logic here to return a number of characters that
  1939. # scales relative with the size of the repository
  1940. return object_id.decode("ascii")[:7]
  1941. def describe(repo, abbrev=None):
  1942. """Describe the repository version.
  1943. Args:
  1944. repo: git repository
  1945. abbrev: number of characters of commit to take, default is 7
  1946. Returns: a string description of the current git revision
  1947. Examples: "gabcdefh", "v0.1" or "v0.1-5-gabcdefh".
  1948. """
  1949. abbrev_slice = slice(0, abbrev if abbrev is not None else 7)
  1950. # Get the repository
  1951. with open_repo_closing(repo) as r:
  1952. # Get a list of all tags
  1953. refs = r.get_refs()
  1954. tags = {}
  1955. for key, value in refs.items():
  1956. key = key.decode()
  1957. obj = r.get_object(value)
  1958. if "tags" not in key:
  1959. continue
  1960. _, tag = key.rsplit("/", 1)
  1961. try:
  1962. commit = obj.object
  1963. except AttributeError:
  1964. continue
  1965. else:
  1966. commit = r.get_object(commit[1])
  1967. tags[tag] = [
  1968. datetime.datetime(*time.gmtime(commit.commit_time)[:6]),
  1969. commit.id.decode("ascii"),
  1970. ]
  1971. sorted_tags = sorted(tags.items(), key=lambda tag: tag[1][0], reverse=True)
  1972. # Get the latest commit
  1973. latest_commit = r[r.head()]
  1974. # If there are no tags, return the latest commit
  1975. if len(sorted_tags) == 0:
  1976. if abbrev is not None:
  1977. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  1978. return f"g{find_unique_abbrev(r.object_store, latest_commit.id)}"
  1979. # We're now 0 commits from the top
  1980. commit_count = 0
  1981. # Walk through all commits
  1982. walker = r.get_walker()
  1983. for entry in walker:
  1984. # Check if tag
  1985. commit_id = entry.commit.id.decode("ascii")
  1986. for tag in sorted_tags:
  1987. tag_name = tag[0]
  1988. tag_commit = tag[1][1]
  1989. if commit_id == tag_commit:
  1990. if commit_count == 0:
  1991. return tag_name
  1992. else:
  1993. return "{}-{}-g{}".format(
  1994. tag_name,
  1995. commit_count,
  1996. latest_commit.id.decode("ascii")[abbrev_slice],
  1997. )
  1998. commit_count += 1
  1999. # Return plain commit if no parent tag can be found
  2000. return "g{}".format(latest_commit.id.decode("ascii")[abbrev_slice])
  2001. def get_object_by_path(repo, path, committish=None):
  2002. """Get an object by path.
  2003. Args:
  2004. repo: A path to the repository
  2005. path: Path to look up
  2006. committish: Commit to look up path in
  2007. Returns: A `ShaFile` object
  2008. """
  2009. if committish is None:
  2010. committish = "HEAD"
  2011. # Get the repository
  2012. with open_repo_closing(repo) as r:
  2013. commit = parse_commit(r, committish)
  2014. base_tree = commit.tree
  2015. if not isinstance(path, bytes):
  2016. path = commit_encode(commit, path)
  2017. (mode, sha) = tree_lookup_path(r.object_store.__getitem__, base_tree, path)
  2018. return r[sha]
  2019. def write_tree(repo):
  2020. """Write a tree object from the index.
  2021. Args:
  2022. repo: Repository for which to write tree
  2023. Returns: tree id for the tree that was written
  2024. """
  2025. with open_repo_closing(repo) as r:
  2026. return r.open_index().commit(r.object_store)