porcelain.py 80 KB

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