2
0

porcelain.py 101 KB

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