client.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380
  1. # client.py -- Implementation of the client side git protocols
  2. # Copyright (C) 2008-2013 Jelmer Vernooij <jelmer@samba.org>
  3. #
  4. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  5. # General Public License as public by the Free Software Foundation; version 2.0
  6. # or (at your option) any later version. You can redistribute it and/or
  7. # modify it under the terms of either of these two licenses.
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # You should have received a copy of the licenses; if not, see
  16. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  17. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  18. # License, Version 2.0.
  19. #
  20. """Client side support for the Git protocol.
  21. The Dulwich client supports the following capabilities:
  22. * thin-pack
  23. * multi_ack_detailed
  24. * multi_ack
  25. * side-band-64k
  26. * ofs-delta
  27. * quiet
  28. * report-status
  29. * delete-refs
  30. Known capabilities that are not supported:
  31. * shallow
  32. * no-progress
  33. * include-tag
  34. """
  35. from contextlib import closing
  36. from io import BytesIO, BufferedReader
  37. import dulwich
  38. import select
  39. import socket
  40. import subprocess
  41. import sys
  42. try:
  43. from urllib import quote as urlquote
  44. from urllib import unquote as urlunquote
  45. except ImportError:
  46. from urllib.parse import quote as urlquote
  47. from urllib.parse import unquote as urlunquote
  48. try:
  49. import urllib2
  50. import urlparse
  51. except ImportError:
  52. import urllib.request as urllib2
  53. import urllib.parse as urlparse
  54. from dulwich.errors import (
  55. GitProtocolError,
  56. NotGitRepository,
  57. SendPackError,
  58. UpdateRefsError,
  59. )
  60. from dulwich.protocol import (
  61. _RBUFSIZE,
  62. capability_agent,
  63. extract_capability_names,
  64. CAPABILITY_DELETE_REFS,
  65. CAPABILITY_MULTI_ACK,
  66. CAPABILITY_MULTI_ACK_DETAILED,
  67. CAPABILITY_OFS_DELTA,
  68. CAPABILITY_QUIET,
  69. CAPABILITY_REPORT_STATUS,
  70. CAPABILITY_SIDE_BAND_64K,
  71. CAPABILITY_SYMREF,
  72. CAPABILITY_THIN_PACK,
  73. CAPABILITIES_REF,
  74. KNOWN_RECEIVE_CAPABILITIES,
  75. KNOWN_UPLOAD_CAPABILITIES,
  76. COMMAND_DONE,
  77. COMMAND_HAVE,
  78. COMMAND_WANT,
  79. SIDE_BAND_CHANNEL_DATA,
  80. SIDE_BAND_CHANNEL_PROGRESS,
  81. SIDE_BAND_CHANNEL_FATAL,
  82. PktLineParser,
  83. Protocol,
  84. ProtocolFile,
  85. TCP_GIT_PORT,
  86. ZERO_SHA,
  87. extract_capabilities,
  88. )
  89. from dulwich.pack import (
  90. write_pack_objects,
  91. )
  92. from dulwich.refs import (
  93. read_info_refs,
  94. )
  95. def _fileno_can_read(fileno):
  96. """Check if a file descriptor is readable."""
  97. return len(select.select([fileno], [], [], 0)[0]) > 0
  98. def _win32_peek_avail(handle):
  99. """Wrapper around PeekNamedPipe to check how many bytes are available."""
  100. from ctypes import byref, wintypes, windll
  101. c_avail = wintypes.DWORD()
  102. c_message = wintypes.DWORD()
  103. success = windll.kernel32.PeekNamedPipe(
  104. handle, None, 0, None, byref(c_avail),
  105. byref(c_message))
  106. if not success:
  107. raise OSError(wintypes.GetLastError())
  108. return c_avail.value
  109. COMMON_CAPABILITIES = [CAPABILITY_OFS_DELTA, CAPABILITY_SIDE_BAND_64K]
  110. UPLOAD_CAPABILITIES = ([CAPABILITY_THIN_PACK, CAPABILITY_MULTI_ACK,
  111. CAPABILITY_MULTI_ACK_DETAILED] +
  112. COMMON_CAPABILITIES)
  113. RECEIVE_CAPABILITIES = [CAPABILITY_REPORT_STATUS] + COMMON_CAPABILITIES
  114. class ReportStatusParser(object):
  115. """Handle status as reported by servers with 'report-status' capability.
  116. """
  117. def __init__(self):
  118. self._done = False
  119. self._pack_status = None
  120. self._ref_status_ok = True
  121. self._ref_statuses = []
  122. def check(self):
  123. """Check if there were any errors and, if so, raise exceptions.
  124. :raise SendPackError: Raised when the server could not unpack
  125. :raise UpdateRefsError: Raised when refs could not be updated
  126. """
  127. if self._pack_status not in (b'unpack ok', None):
  128. raise SendPackError(self._pack_status)
  129. if not self._ref_status_ok:
  130. ref_status = {}
  131. ok = set()
  132. for status in self._ref_statuses:
  133. if b' ' not in status:
  134. # malformed response, move on to the next one
  135. continue
  136. status, ref = status.split(b' ', 1)
  137. if status == b'ng':
  138. if b' ' in ref:
  139. ref, status = ref.split(b' ', 1)
  140. else:
  141. ok.add(ref)
  142. ref_status[ref] = status
  143. # TODO(jelmer): don't assume encoding of refs is ascii.
  144. raise UpdateRefsError(', '.join([
  145. refname.decode('ascii') for refname in ref_status
  146. if refname not in ok]) +
  147. ' failed to update', ref_status=ref_status)
  148. def handle_packet(self, pkt):
  149. """Handle a packet.
  150. :raise GitProtocolError: Raised when packets are received after a
  151. flush packet.
  152. """
  153. if self._done:
  154. raise GitProtocolError("received more data after status report")
  155. if pkt is None:
  156. self._done = True
  157. return
  158. if self._pack_status is None:
  159. self._pack_status = pkt.strip()
  160. else:
  161. ref_status = pkt.strip()
  162. self._ref_statuses.append(ref_status)
  163. if not ref_status.startswith(b'ok '):
  164. self._ref_status_ok = False
  165. def read_pkt_refs(proto):
  166. server_capabilities = None
  167. refs = {}
  168. # Receive refs from server
  169. for pkt in proto.read_pkt_seq():
  170. (sha, ref) = pkt.rstrip(b'\n').split(None, 1)
  171. if sha == b'ERR':
  172. raise GitProtocolError(ref)
  173. if server_capabilities is None:
  174. (ref, server_capabilities) = extract_capabilities(ref)
  175. refs[ref] = sha
  176. if len(refs) == 0:
  177. return None, set([])
  178. if refs == {CAPABILITIES_REF: ZERO_SHA}:
  179. refs = {}
  180. return refs, set(server_capabilities)
  181. # TODO(durin42): this doesn't correctly degrade if the server doesn't
  182. # support some capabilities. This should work properly with servers
  183. # that don't support multi_ack.
  184. class GitClient(object):
  185. """Git smart server client.
  186. """
  187. def __init__(self, thin_packs=True, report_activity=None, quiet=False):
  188. """Create a new GitClient instance.
  189. :param thin_packs: Whether or not thin packs should be retrieved
  190. :param report_activity: Optional callback for reporting transport
  191. activity.
  192. """
  193. self._report_activity = report_activity
  194. self._report_status_parser = None
  195. self._fetch_capabilities = set(UPLOAD_CAPABILITIES)
  196. self._fetch_capabilities.add(capability_agent())
  197. self._send_capabilities = set(RECEIVE_CAPABILITIES)
  198. self._send_capabilities.add(capability_agent())
  199. if quiet:
  200. self._send_capabilities.add(CAPABILITY_QUIET)
  201. if not thin_packs:
  202. self._fetch_capabilities.remove(CAPABILITY_THIN_PACK)
  203. def get_url(self, path):
  204. """Retrieves full url to given path.
  205. :param path: Repository path (as string)
  206. :return: Url to path (as string)
  207. """
  208. raise NotImplementedError(self.get_url)
  209. @classmethod
  210. def from_parsedurl(cls, parsedurl, **kwargs):
  211. """Create an instance of this client from a urlparse.parsed object.
  212. :param parsedurl: Result of urlparse.urlparse()
  213. :return: A `GitClient` object
  214. """
  215. raise NotImplementedError(cls.from_parsedurl)
  216. def send_pack(self, path, update_refs, generate_pack_contents,
  217. progress=None, write_pack=write_pack_objects):
  218. """Upload a pack to a remote repository.
  219. :param path: Repository path (as bytestring)
  220. :param update_refs: Function to determine changes to remote refs.
  221. Receive dict with existing remote refs, returns dict with
  222. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  223. :param generate_pack_contents: Function that can return a sequence of
  224. the shas of the objects to upload.
  225. :param progress: Optional progress function
  226. :param write_pack: Function called with (file, iterable of objects) to
  227. write the objects returned by generate_pack_contents to the server.
  228. :raises SendPackError: if server rejects the pack data
  229. :raises UpdateRefsError: if the server supports report-status
  230. and rejects ref updates
  231. :return: new_refs dictionary containing the changes that were made
  232. {refname: new_ref}, including deleted refs.
  233. """
  234. raise NotImplementedError(self.send_pack)
  235. def fetch(self, path, target, determine_wants=None, progress=None):
  236. """Fetch into a target repository.
  237. :param path: Path to fetch from (as bytestring)
  238. :param target: Target repository to fetch into
  239. :param determine_wants: Optional function to determine what refs
  240. to fetch. Receives dictionary of name->sha, should return
  241. list of shas to fetch. Defaults to all shas.
  242. :param progress: Optional progress function
  243. :return: Dictionary with all remote refs (not just those fetched)
  244. """
  245. if determine_wants is None:
  246. determine_wants = target.object_store.determine_wants_all
  247. if CAPABILITY_THIN_PACK in self._fetch_capabilities:
  248. # TODO(jelmer): Avoid reading entire file into memory and
  249. # only processing it after the whole file has been fetched.
  250. f = BytesIO()
  251. def commit():
  252. if f.tell():
  253. f.seek(0)
  254. target.object_store.add_thin_pack(f.read, None)
  255. def abort():
  256. pass
  257. else:
  258. f, commit, abort = target.object_store.add_pack()
  259. try:
  260. result = self.fetch_pack(
  261. path, determine_wants, target.get_graph_walker(), f.write,
  262. progress)
  263. except:
  264. abort()
  265. raise
  266. else:
  267. commit()
  268. return result
  269. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  270. progress=None):
  271. """Retrieve a pack from a git smart server.
  272. :param path: Remote path to fetch from
  273. :param determine_wants: Function determine what refs
  274. to fetch. Receives dictionary of name->sha, should return
  275. list of shas to fetch.
  276. :param graph_walker: Object with next() and ack().
  277. :param pack_data: Callback called for each bit of data in the pack
  278. :param progress: Callback for progress reports (strings)
  279. :return: Dictionary with all remote refs (not just those fetched)
  280. """
  281. raise NotImplementedError(self.fetch_pack)
  282. def get_refs(self, path):
  283. """Retrieve the current refs from a git smart server.
  284. :param path: Path to the repo to fetch from. (as bytestring)
  285. """
  286. raise NotImplementedError(self.get_refs)
  287. def _parse_status_report(self, proto):
  288. unpack = proto.read_pkt_line().strip()
  289. if unpack != b'unpack ok':
  290. st = True
  291. # flush remaining error data
  292. while st is not None:
  293. st = proto.read_pkt_line()
  294. raise SendPackError(unpack)
  295. statuses = []
  296. errs = False
  297. ref_status = proto.read_pkt_line()
  298. while ref_status:
  299. ref_status = ref_status.strip()
  300. statuses.append(ref_status)
  301. if not ref_status.startswith(b'ok '):
  302. errs = True
  303. ref_status = proto.read_pkt_line()
  304. if errs:
  305. ref_status = {}
  306. ok = set()
  307. for status in statuses:
  308. if b' ' not in status:
  309. # malformed response, move on to the next one
  310. continue
  311. status, ref = status.split(b' ', 1)
  312. if status == b'ng':
  313. if b' ' in ref:
  314. ref, status = ref.split(b' ', 1)
  315. else:
  316. ok.add(ref)
  317. ref_status[ref] = status
  318. raise UpdateRefsError(', '.join([
  319. refname for refname in ref_status if refname not in ok]) +
  320. b' failed to update', ref_status=ref_status)
  321. def _read_side_band64k_data(self, proto, channel_callbacks):
  322. """Read per-channel data.
  323. This requires the side-band-64k capability.
  324. :param proto: Protocol object to read from
  325. :param channel_callbacks: Dictionary mapping channels to packet
  326. handlers to use. None for a callback discards channel data.
  327. """
  328. for pkt in proto.read_pkt_seq():
  329. channel = ord(pkt[:1])
  330. pkt = pkt[1:]
  331. try:
  332. cb = channel_callbacks[channel]
  333. except KeyError:
  334. raise AssertionError('Invalid sideband channel %d' % channel)
  335. else:
  336. if cb is not None:
  337. cb(pkt)
  338. def _handle_receive_pack_head(self, proto, capabilities, old_refs,
  339. new_refs):
  340. """Handle the head of a 'git-receive-pack' request.
  341. :param proto: Protocol object to read from
  342. :param capabilities: List of negotiated capabilities
  343. :param old_refs: Old refs, as received from the server
  344. :param new_refs: Refs to change
  345. :return: (have, want) tuple
  346. """
  347. want = []
  348. have = [x for x in old_refs.values() if not x == ZERO_SHA]
  349. sent_capabilities = False
  350. for refname in new_refs:
  351. if not isinstance(refname, bytes):
  352. raise TypeError('refname is not a bytestring: %r' % refname)
  353. old_sha1 = old_refs.get(refname, ZERO_SHA)
  354. if not isinstance(old_sha1, bytes):
  355. raise TypeError('old sha1 for %s is not a bytestring: %r' %
  356. (refname, old_sha1))
  357. new_sha1 = new_refs.get(refname, ZERO_SHA)
  358. if not isinstance(new_sha1, bytes):
  359. raise TypeError('old sha1 for %s is not a bytestring %r' %
  360. (refname, new_sha1))
  361. if old_sha1 != new_sha1:
  362. if sent_capabilities:
  363. proto.write_pkt_line(old_sha1 + b' ' + new_sha1 + b' ' +
  364. refname)
  365. else:
  366. proto.write_pkt_line(
  367. old_sha1 + b' ' + new_sha1 + b' ' + refname + b'\0' +
  368. b' '.join(capabilities))
  369. sent_capabilities = True
  370. if new_sha1 not in have and new_sha1 != ZERO_SHA:
  371. want.append(new_sha1)
  372. proto.write_pkt_line(None)
  373. return (have, want)
  374. def _handle_receive_pack_tail(self, proto, capabilities, progress=None):
  375. """Handle the tail of a 'git-receive-pack' request.
  376. :param proto: Protocol object to read from
  377. :param capabilities: List of negotiated capabilities
  378. :param progress: Optional progress reporting function
  379. """
  380. if b"side-band-64k" in capabilities:
  381. if progress is None:
  382. def progress(x):
  383. pass
  384. channel_callbacks = {2: progress}
  385. if CAPABILITY_REPORT_STATUS in capabilities:
  386. channel_callbacks[1] = PktLineParser(
  387. self._report_status_parser.handle_packet).parse
  388. self._read_side_band64k_data(proto, channel_callbacks)
  389. else:
  390. if CAPABILITY_REPORT_STATUS in capabilities:
  391. for pkt in proto.read_pkt_seq():
  392. self._report_status_parser.handle_packet(pkt)
  393. if self._report_status_parser is not None:
  394. self._report_status_parser.check()
  395. def _handle_upload_pack_head(self, proto, capabilities, graph_walker,
  396. wants, can_read):
  397. """Handle the head of a 'git-upload-pack' request.
  398. :param proto: Protocol object to read from
  399. :param capabilities: List of negotiated capabilities
  400. :param graph_walker: GraphWalker instance to call .ack() on
  401. :param wants: List of commits to fetch
  402. :param can_read: function that returns a boolean that indicates
  403. whether there is extra graph data to read on proto
  404. """
  405. assert isinstance(wants, list) and isinstance(wants[0], bytes)
  406. proto.write_pkt_line(COMMAND_WANT + b' ' + wants[0] + b' ' +
  407. b' '.join(capabilities) + b'\n')
  408. for want in wants[1:]:
  409. proto.write_pkt_line(COMMAND_WANT + b' ' + want + b'\n')
  410. proto.write_pkt_line(None)
  411. have = next(graph_walker)
  412. while have:
  413. proto.write_pkt_line(COMMAND_HAVE + b' ' + have + b'\n')
  414. if can_read():
  415. pkt = proto.read_pkt_line()
  416. parts = pkt.rstrip(b'\n').split(b' ')
  417. if parts[0] == b'ACK':
  418. graph_walker.ack(parts[1])
  419. if parts[2] in (b'continue', b'common'):
  420. pass
  421. elif parts[2] == b'ready':
  422. break
  423. else:
  424. raise AssertionError(
  425. "%s not in ('continue', 'ready', 'common)" %
  426. parts[2])
  427. have = next(graph_walker)
  428. proto.write_pkt_line(COMMAND_DONE + b'\n')
  429. def _handle_upload_pack_tail(self, proto, capabilities, graph_walker,
  430. pack_data, progress=None, rbufsize=_RBUFSIZE):
  431. """Handle the tail of a 'git-upload-pack' request.
  432. :param proto: Protocol object to read from
  433. :param capabilities: List of negotiated capabilities
  434. :param graph_walker: GraphWalker instance to call .ack() on
  435. :param pack_data: Function to call with pack data
  436. :param progress: Optional progress reporting function
  437. :param rbufsize: Read buffer size
  438. """
  439. pkt = proto.read_pkt_line()
  440. while pkt:
  441. parts = pkt.rstrip(b'\n').split(b' ')
  442. if parts[0] == b'ACK':
  443. graph_walker.ack(parts[1])
  444. if len(parts) < 3 or parts[2] not in (
  445. b'ready', b'continue', b'common'):
  446. break
  447. pkt = proto.read_pkt_line()
  448. if CAPABILITY_SIDE_BAND_64K in capabilities:
  449. if progress is None:
  450. # Just ignore progress data
  451. def progress(x):
  452. pass
  453. self._read_side_band64k_data(proto, {
  454. SIDE_BAND_CHANNEL_DATA: pack_data,
  455. SIDE_BAND_CHANNEL_PROGRESS: progress}
  456. )
  457. else:
  458. while True:
  459. data = proto.read(rbufsize)
  460. if data == b"":
  461. break
  462. pack_data(data)
  463. class TraditionalGitClient(GitClient):
  464. """Traditional Git client."""
  465. DEFAULT_ENCODING = 'utf-8'
  466. def __init__(self, path_encoding=DEFAULT_ENCODING, **kwargs):
  467. self._remote_path_encoding = path_encoding
  468. super(TraditionalGitClient, self).__init__(**kwargs)
  469. def _connect(self, cmd, path):
  470. """Create a connection to the server.
  471. This method is abstract - concrete implementations should
  472. implement their own variant which connects to the server and
  473. returns an initialized Protocol object with the service ready
  474. for use and a can_read function which may be used to see if
  475. reads would block.
  476. :param cmd: The git service name to which we should connect.
  477. :param path: The path we should pass to the service. (as bytestirng)
  478. """
  479. raise NotImplementedError()
  480. def send_pack(self, path, update_refs, generate_pack_contents,
  481. progress=None, write_pack=write_pack_objects):
  482. """Upload a pack to a remote repository.
  483. :param path: Repository path (as bytestring)
  484. :param update_refs: Function to determine changes to remote refs.
  485. Receive dict with existing remote refs, returns dict with
  486. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  487. :param generate_pack_contents: Function that can return a sequence of
  488. the shas of the objects to upload.
  489. :param progress: Optional callback called with progress updates
  490. :param write_pack: Function called with (file, iterable of objects) to
  491. write the objects returned by generate_pack_contents to the server.
  492. :raises SendPackError: if server rejects the pack data
  493. :raises UpdateRefsError: if the server supports report-status
  494. and rejects ref updates
  495. :return: new_refs dictionary containing the changes that were made
  496. {refname: new_ref}, including deleted refs.
  497. """
  498. proto, unused_can_read = self._connect(b'receive-pack', path)
  499. with proto:
  500. old_refs, server_capabilities = read_pkt_refs(proto)
  501. negotiated_capabilities = (
  502. self._send_capabilities & server_capabilities)
  503. unknown_capabilities = (
  504. extract_capability_names(server_capabilities) -
  505. KNOWN_RECEIVE_CAPABILITIES)
  506. # TODO(jelmer): warn about unknown capabilities
  507. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  508. self._report_status_parser = ReportStatusParser()
  509. report_status_parser = self._report_status_parser
  510. try:
  511. new_refs = orig_new_refs = update_refs(dict(old_refs))
  512. except:
  513. proto.write_pkt_line(None)
  514. raise
  515. if CAPABILITY_DELETE_REFS not in server_capabilities:
  516. # Server does not support deletions. Fail later.
  517. new_refs = dict(orig_new_refs)
  518. for ref, sha in orig_new_refs.items():
  519. if sha == ZERO_SHA:
  520. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  521. report_status_parser._ref_statuses.append(
  522. b'ng ' + sha +
  523. b' remote does not support deleting refs')
  524. report_status_parser._ref_status_ok = False
  525. del new_refs[ref]
  526. if new_refs is None:
  527. proto.write_pkt_line(None)
  528. return old_refs
  529. if len(new_refs) == 0 and len(orig_new_refs):
  530. # NOOP - Original new refs filtered out by policy
  531. proto.write_pkt_line(None)
  532. if report_status_parser is not None:
  533. report_status_parser.check()
  534. return old_refs
  535. (have, want) = self._handle_receive_pack_head(
  536. proto, negotiated_capabilities, old_refs, new_refs)
  537. if (not want and
  538. set(new_refs.items()).issubset(set(old_refs.items()))):
  539. return new_refs
  540. objects = generate_pack_contents(have, want)
  541. dowrite = len(objects) > 0
  542. dowrite = dowrite or any(old_refs.get(ref) != sha
  543. for (ref, sha) in new_refs.items()
  544. if sha != ZERO_SHA)
  545. if dowrite:
  546. write_pack(proto.write_file(), objects)
  547. self._handle_receive_pack_tail(
  548. proto, negotiated_capabilities, progress)
  549. return new_refs
  550. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  551. progress=None):
  552. """Retrieve a pack from a git smart server.
  553. :param path: Remote path to fetch from
  554. :param determine_wants: Function determine what refs
  555. to fetch. Receives dictionary of name->sha, should return
  556. list of shas to fetch.
  557. :param graph_walker: Object with next() and ack().
  558. :param pack_data: Callback called for each bit of data in the pack
  559. :param progress: Callback for progress reports (strings)
  560. :return: Dictionary with all remote refs (not just those fetched)
  561. """
  562. proto, can_read = self._connect(b'upload-pack', path)
  563. with proto:
  564. refs, server_capabilities = read_pkt_refs(proto)
  565. unknown_capabilities = (
  566. extract_capability_names(server_capabilities) -
  567. KNOWN_UPLOAD_CAPABILITIES)
  568. # TODO(jelmer): warn about unknown capabilities
  569. negotiated_capabilities = (
  570. self._fetch_capabilities & server_capabilities)
  571. if refs is None:
  572. proto.write_pkt_line(None)
  573. return refs
  574. try:
  575. wants = determine_wants(refs)
  576. except:
  577. proto.write_pkt_line(None)
  578. raise
  579. if wants is not None:
  580. wants = [cid for cid in wants if cid != ZERO_SHA]
  581. if not wants:
  582. proto.write_pkt_line(None)
  583. return refs
  584. self._handle_upload_pack_head(
  585. proto, negotiated_capabilities, graph_walker, wants, can_read)
  586. self._handle_upload_pack_tail(
  587. proto, negotiated_capabilities, graph_walker, pack_data,
  588. progress)
  589. return refs
  590. def get_refs(self, path):
  591. """Retrieve the current refs from a git smart server."""
  592. # stock `git ls-remote` uses upload-pack
  593. proto, _ = self._connect(b'upload-pack', path)
  594. with proto:
  595. refs, _ = read_pkt_refs(proto)
  596. proto.write_pkt_line(None)
  597. return refs
  598. def archive(self, path, committish, write_data, progress=None,
  599. write_error=None):
  600. proto, can_read = self._connect(b'upload-archive', path)
  601. with proto:
  602. proto.write_pkt_line(b"argument " + committish)
  603. proto.write_pkt_line(None)
  604. pkt = proto.read_pkt_line()
  605. if pkt == b"NACK\n":
  606. return
  607. elif pkt == b"ACK\n":
  608. pass
  609. elif pkt.startswith(b"ERR "):
  610. raise GitProtocolError(pkt[4:].rstrip(b"\n"))
  611. else:
  612. raise AssertionError("invalid response %r" % pkt)
  613. ret = proto.read_pkt_line()
  614. if ret is not None:
  615. raise AssertionError("expected pkt tail")
  616. self._read_side_band64k_data(proto, {
  617. SIDE_BAND_CHANNEL_DATA: write_data,
  618. SIDE_BAND_CHANNEL_PROGRESS: progress,
  619. SIDE_BAND_CHANNEL_FATAL: write_error})
  620. class TCPGitClient(TraditionalGitClient):
  621. """A Git Client that works over TCP directly (i.e. git://)."""
  622. def __init__(self, host, port=None, **kwargs):
  623. if port is None:
  624. port = TCP_GIT_PORT
  625. self._host = host
  626. self._port = port
  627. super(TCPGitClient, self).__init__(**kwargs)
  628. @classmethod
  629. def from_parsedurl(cls, parsedurl, **kwargs):
  630. return cls(parsedurl.hostname, port=parsedurl.port, **kwargs)
  631. def get_url(self, path):
  632. netloc = self._host
  633. if self._port is not None and self._port != TCP_GIT_PORT:
  634. netloc += ":%d" % self._port
  635. return urlparse.urlunsplit(("git", netloc, path, '', ''))
  636. def _connect(self, cmd, path):
  637. if not isinstance(cmd, bytes):
  638. raise TypeError(cmd)
  639. if not isinstance(path, bytes):
  640. path = path.encode(self._remote_path_encoding)
  641. sockaddrs = socket.getaddrinfo(
  642. self._host, self._port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  643. s = None
  644. err = socket.error("no address found for %s" % self._host)
  645. for (family, socktype, proto, canonname, sockaddr) in sockaddrs:
  646. s = socket.socket(family, socktype, proto)
  647. s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  648. try:
  649. s.connect(sockaddr)
  650. break
  651. except socket.error as err:
  652. if s is not None:
  653. s.close()
  654. s = None
  655. if s is None:
  656. raise err
  657. # -1 means system default buffering
  658. rfile = s.makefile('rb', -1)
  659. # 0 means unbuffered
  660. wfile = s.makefile('wb', 0)
  661. def close():
  662. rfile.close()
  663. wfile.close()
  664. s.close()
  665. proto = Protocol(rfile.read, wfile.write, close,
  666. report_activity=self._report_activity)
  667. if path.startswith(b"/~"):
  668. path = path[1:]
  669. # TODO(jelmer): Alternative to ascii?
  670. proto.send_cmd(
  671. b'git-' + cmd, path, b'host=' + self._host.encode('ascii'))
  672. return proto, lambda: _fileno_can_read(s)
  673. class SubprocessWrapper(object):
  674. """A socket-like object that talks to a subprocess via pipes."""
  675. def __init__(self, proc):
  676. self.proc = proc
  677. if sys.version_info[0] == 2:
  678. self.read = proc.stdout.read
  679. else:
  680. self.read = BufferedReader(proc.stdout).read
  681. self.write = proc.stdin.write
  682. def can_read(self):
  683. if sys.platform == 'win32':
  684. from msvcrt import get_osfhandle
  685. handle = get_osfhandle(self.proc.stdout.fileno())
  686. return _win32_peek_avail(handle) != 0
  687. else:
  688. return _fileno_can_read(self.proc.stdout.fileno())
  689. def close(self):
  690. self.proc.stdin.close()
  691. self.proc.stdout.close()
  692. if self.proc.stderr:
  693. self.proc.stderr.close()
  694. self.proc.wait()
  695. def find_git_command():
  696. """Find command to run for system Git (usually C Git).
  697. """
  698. if sys.platform == 'win32': # support .exe, .bat and .cmd
  699. try: # to avoid overhead
  700. import win32api
  701. except ImportError: # run through cmd.exe with some overhead
  702. return ['cmd', '/c', 'git']
  703. else:
  704. status, git = win32api.FindExecutable('git')
  705. return [git]
  706. else:
  707. return ['git']
  708. class SubprocessGitClient(TraditionalGitClient):
  709. """Git client that talks to a server using a subprocess."""
  710. def __init__(self, **kwargs):
  711. self._connection = None
  712. self._stderr = None
  713. self._stderr = kwargs.get('stderr')
  714. if 'stderr' in kwargs:
  715. del kwargs['stderr']
  716. super(SubprocessGitClient, self).__init__(**kwargs)
  717. @classmethod
  718. def from_parsedurl(cls, parsedurl, **kwargs):
  719. return cls(**kwargs)
  720. git_command = None
  721. def _connect(self, service, path):
  722. if not isinstance(service, bytes):
  723. raise TypeError(service)
  724. if isinstance(path, bytes):
  725. path = path.decode(self._remote_path_encoding)
  726. if self.git_command is None:
  727. git_command = find_git_command()
  728. argv = git_command + [service.decode('ascii'), path]
  729. p = SubprocessWrapper(
  730. subprocess.Popen(argv, bufsize=0, stdin=subprocess.PIPE,
  731. stdout=subprocess.PIPE,
  732. stderr=self._stderr))
  733. return Protocol(p.read, p.write, p.close,
  734. report_activity=self._report_activity), p.can_read
  735. class LocalGitClient(GitClient):
  736. """Git Client that just uses a local Repo."""
  737. def __init__(self, thin_packs=True, report_activity=None, config=None):
  738. """Create a new LocalGitClient instance.
  739. :param thin_packs: Whether or not thin packs should be retrieved
  740. :param report_activity: Optional callback for reporting transport
  741. activity.
  742. """
  743. self._report_activity = report_activity
  744. # Ignore the thin_packs argument
  745. def get_url(self, path):
  746. return urlparse.urlunsplit(('file', '', path, '', ''))
  747. @classmethod
  748. def from_parsedurl(cls, parsedurl, **kwargs):
  749. return cls(**kwargs)
  750. @classmethod
  751. def _open_repo(cls, path):
  752. from dulwich.repo import Repo
  753. if not isinstance(path, str):
  754. path = path.decode(sys.getfilesystemencoding())
  755. return closing(Repo(path))
  756. def send_pack(self, path, update_refs, generate_pack_contents,
  757. progress=None, write_pack=write_pack_objects):
  758. """Upload a pack to a remote repository.
  759. :param path: Repository path (as bytestring)
  760. :param update_refs: Function to determine changes to remote refs.
  761. Receive dict with existing remote refs, returns dict with
  762. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  763. :param generate_pack_contents: Function that can return a sequence of
  764. the shas of the objects to upload.
  765. :param progress: Optional progress function
  766. :param write_pack: Function called with (file, iterable of objects) to
  767. write the objects returned by generate_pack_contents to the server.
  768. :raises SendPackError: if server rejects the pack data
  769. :raises UpdateRefsError: if the server supports report-status
  770. and rejects ref updates
  771. :return: new_refs dictionary containing the changes that were made
  772. {refname: new_ref}, including deleted refs.
  773. """
  774. if not progress:
  775. def progress(x):
  776. pass
  777. with self._open_repo(path) as target:
  778. old_refs = target.get_refs()
  779. new_refs = update_refs(dict(old_refs))
  780. have = [sha1 for sha1 in old_refs.values() if sha1 != ZERO_SHA]
  781. want = []
  782. for refname, new_sha1 in new_refs.items():
  783. if (new_sha1 not in have and
  784. new_sha1 not in want and
  785. new_sha1 != ZERO_SHA):
  786. want.append(new_sha1)
  787. if (not want and
  788. set(new_refs.items()).issubset(set(old_refs.items()))):
  789. return new_refs
  790. target.object_store.add_objects(generate_pack_contents(have, want))
  791. for refname, new_sha1 in new_refs.items():
  792. old_sha1 = old_refs.get(refname, ZERO_SHA)
  793. if new_sha1 != ZERO_SHA:
  794. if not target.refs.set_if_equals(
  795. refname, old_sha1, new_sha1):
  796. progress('unable to set %s to %s' %
  797. (refname, new_sha1))
  798. else:
  799. if not target.refs.remove_if_equals(refname, old_sha1):
  800. progress('unable to remove %s' % refname)
  801. return new_refs
  802. def fetch(self, path, target, determine_wants=None, progress=None):
  803. """Fetch into a target repository.
  804. :param path: Path to fetch from (as bytestring)
  805. :param target: Target repository to fetch into
  806. :param determine_wants: Optional function determine what refs
  807. to fetch. Receives dictionary of name->sha, should return
  808. list of shas to fetch. Defaults to all shas.
  809. :param progress: Optional progress function
  810. :return: Dictionary with all remote refs (not just those fetched)
  811. """
  812. with self._open_repo(path) as r:
  813. return r.fetch(target, determine_wants=determine_wants,
  814. progress=progress)
  815. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  816. progress=None):
  817. """Retrieve a pack from a git smart server.
  818. :param path: Remote path to fetch from
  819. :param determine_wants: Function determine what refs
  820. to fetch. Receives dictionary of name->sha, should return
  821. list of shas to fetch.
  822. :param graph_walker: Object with next() and ack().
  823. :param pack_data: Callback called for each bit of data in the pack
  824. :param progress: Callback for progress reports (strings)
  825. :return: Dictionary with all remote refs (not just those fetched)
  826. """
  827. with self._open_repo(path) as r:
  828. objects_iter = r.fetch_objects(
  829. determine_wants, graph_walker, progress)
  830. # Did the process short-circuit (e.g. in a stateless RPC call)?
  831. # Note that the client still expects a 0-object pack in most cases.
  832. if objects_iter is None:
  833. return
  834. write_pack_objects(ProtocolFile(None, pack_data), objects_iter)
  835. return r.get_refs()
  836. def get_refs(self, path):
  837. """Retrieve the current refs from a git smart server."""
  838. with self._open_repo(path) as target:
  839. return target.get_refs()
  840. # What Git client to use for local access
  841. default_local_git_client_cls = LocalGitClient
  842. class SSHVendor(object):
  843. """A client side SSH implementation."""
  844. def connect_ssh(self, host, command, username=None, port=None):
  845. # This function was deprecated in 0.9.1
  846. import warnings
  847. warnings.warn(
  848. "SSHVendor.connect_ssh has been renamed to SSHVendor.run_command",
  849. DeprecationWarning)
  850. return self.run_command(host, command, username=username, port=port)
  851. def run_command(self, host, command, username=None, port=None):
  852. """Connect to an SSH server.
  853. Run a command remotely and return a file-like object for interaction
  854. with the remote command.
  855. :param host: Host name
  856. :param command: Command to run (as argv array)
  857. :param username: Optional ame of user to log in as
  858. :param port: Optional SSH port to use
  859. """
  860. raise NotImplementedError(self.run_command)
  861. class SubprocessSSHVendor(SSHVendor):
  862. """SSH vendor that shells out to the local 'ssh' command."""
  863. def run_command(self, host, command, username=None, port=None):
  864. # FIXME: This has no way to deal with passwords..
  865. args = ['ssh', '-x']
  866. if port is not None:
  867. args.extend(['-p', str(port)])
  868. if username is not None:
  869. host = '%s@%s' % (username, host)
  870. args.append(host)
  871. proc = subprocess.Popen(args + [command], bufsize=0,
  872. stdin=subprocess.PIPE,
  873. stdout=subprocess.PIPE)
  874. return SubprocessWrapper(proc)
  875. def ParamikoSSHVendor(**kwargs):
  876. import warnings
  877. warnings.warn(
  878. "ParamikoSSHVendor has been moved to dulwich.contrib.paramiko_vendor.",
  879. DeprecationWarning)
  880. from dulwich.contrib.paramiko_vendor import ParamikoSSHVendor
  881. return ParamikoSSHVendor(**kwargs)
  882. # Can be overridden by users
  883. get_ssh_vendor = SubprocessSSHVendor
  884. class SSHGitClient(TraditionalGitClient):
  885. def __init__(self, host, port=None, username=None, vendor=None,
  886. config=None, **kwargs):
  887. self.host = host
  888. self.port = port
  889. self.username = username
  890. super(SSHGitClient, self).__init__(**kwargs)
  891. self.alternative_paths = {}
  892. if vendor is not None:
  893. self.ssh_vendor = vendor
  894. else:
  895. self.ssh_vendor = get_ssh_vendor()
  896. def get_url(self, path):
  897. netloc = self.host
  898. if self.port is not None:
  899. netloc += ":%d" % self.port
  900. if self.username is not None:
  901. netloc = urlquote(self.username, '@/:') + "@" + netloc
  902. return urlparse.urlunsplit(('ssh', netloc, path, '', ''))
  903. @classmethod
  904. def from_parsedurl(cls, parsedurl, **kwargs):
  905. return cls(host=parsedurl.hostname, port=parsedurl.port,
  906. username=parsedurl.username, **kwargs)
  907. def _get_cmd_path(self, cmd):
  908. cmd = self.alternative_paths.get(cmd, b'git-' + cmd)
  909. assert isinstance(cmd, bytes)
  910. return cmd
  911. def _connect(self, cmd, path):
  912. if not isinstance(cmd, bytes):
  913. raise TypeError(cmd)
  914. if isinstance(path, bytes):
  915. path = path.decode(self._remote_path_encoding)
  916. if path.startswith("/~"):
  917. path = path[1:]
  918. argv = (self._get_cmd_path(cmd).decode(self._remote_path_encoding) +
  919. " '" + path + "'")
  920. con = self.ssh_vendor.run_command(
  921. self.host, argv, port=self.port, username=self.username)
  922. return (Protocol(con.read, con.write, con.close,
  923. report_activity=self._report_activity),
  924. con.can_read)
  925. def default_user_agent_string():
  926. return "dulwich/%s" % ".".join([str(x) for x in dulwich.__version__])
  927. def default_urllib2_opener(config):
  928. if config is not None:
  929. proxy_server = config.get("http", "proxy")
  930. else:
  931. proxy_server = None
  932. handlers = []
  933. if proxy_server is not None:
  934. handlers.append(urllib2.ProxyHandler({"http": proxy_server}))
  935. opener = urllib2.build_opener(*handlers)
  936. if config is not None:
  937. user_agent = config.get("http", "useragent")
  938. else:
  939. user_agent = None
  940. if user_agent is None:
  941. user_agent = default_user_agent_string()
  942. opener.addheaders = [('User-agent', user_agent)]
  943. return opener
  944. class HttpGitClient(GitClient):
  945. def __init__(self, base_url, dumb=None, opener=None, config=None,
  946. username=None, password=None, **kwargs):
  947. self._base_url = base_url.rstrip("/") + "/"
  948. self._username = username
  949. self._password = password
  950. self.dumb = dumb
  951. if opener is None:
  952. self.opener = default_urllib2_opener(config)
  953. else:
  954. self.opener = opener
  955. if username is not None:
  956. pass_man = urllib2.HTTPPasswordMgrWithDefaultRealm()
  957. pass_man.add_password(None, base_url, username, password)
  958. self.opener.add_handler(urllib2.HTTPBasicAuthHandler(pass_man))
  959. GitClient.__init__(self, **kwargs)
  960. def get_url(self, path):
  961. return self._get_url(path).rstrip("/")
  962. @classmethod
  963. def from_parsedurl(cls, parsedurl, **kwargs):
  964. auth, host = urllib2.splituser(parsedurl.netloc)
  965. password = parsedurl.password
  966. if password is not None:
  967. password = urlunquote(password)
  968. username = parsedurl.username
  969. if username is not None:
  970. username = urlunquote(username)
  971. # TODO(jelmer): This also strips the username
  972. parsedurl = parsedurl._replace(netloc=host)
  973. return cls(urlparse.urlunparse(parsedurl),
  974. password=password, username=username, **kwargs)
  975. def __repr__(self):
  976. return "%s(%r, dumb=%r)" % (
  977. type(self).__name__, self._base_url, self.dumb)
  978. def _get_url(self, path):
  979. if not isinstance(path, str):
  980. # TODO(jelmer): this is unrelated to the local filesystem;
  981. # This is not necessarily the right encoding to decode the path
  982. # with.
  983. path = path.decode(sys.getfilesystemencoding())
  984. return urlparse.urljoin(self._base_url, path).rstrip("/") + "/"
  985. def _http_request(self, url, headers={}, data=None):
  986. req = urllib2.Request(url, headers=headers, data=data)
  987. try:
  988. resp = self.opener.open(req)
  989. except urllib2.HTTPError as e:
  990. if e.code == 404:
  991. raise NotGitRepository()
  992. if e.code != 200:
  993. raise GitProtocolError("unexpected http response %d" % e.code)
  994. return resp
  995. def _discover_references(self, service, url):
  996. assert url[-1] == "/"
  997. url = urlparse.urljoin(url, "info/refs")
  998. headers = {}
  999. if self.dumb is not False:
  1000. url += "?service=%s" % service.decode('ascii')
  1001. headers["Content-Type"] = "application/x-%s-request" % (
  1002. service.decode('ascii'))
  1003. resp = self._http_request(url, headers)
  1004. try:
  1005. content_type = resp.info().gettype()
  1006. except AttributeError:
  1007. content_type = resp.info().get_content_type()
  1008. try:
  1009. self.dumb = (not content_type.startswith("application/x-git-"))
  1010. if not self.dumb:
  1011. proto = Protocol(resp.read, None)
  1012. # The first line should mention the service
  1013. try:
  1014. [pkt] = list(proto.read_pkt_seq())
  1015. except ValueError:
  1016. raise GitProtocolError(
  1017. "unexpected number of packets received")
  1018. if pkt.rstrip(b'\n') != (b'# service=' + service):
  1019. raise GitProtocolError(
  1020. "unexpected first line %r from smart server" % pkt)
  1021. return read_pkt_refs(proto)
  1022. else:
  1023. return read_info_refs(resp), set()
  1024. finally:
  1025. resp.close()
  1026. def _smart_request(self, service, url, data):
  1027. assert url[-1] == "/"
  1028. url = urlparse.urljoin(url, service)
  1029. headers = {
  1030. "Content-Type": "application/x-%s-request" % service
  1031. }
  1032. resp = self._http_request(url, headers, data)
  1033. try:
  1034. content_type = resp.info().gettype()
  1035. except AttributeError:
  1036. content_type = resp.info().get_content_type()
  1037. if content_type != (
  1038. "application/x-%s-result" % service):
  1039. raise GitProtocolError("Invalid content-type from server: %s"
  1040. % content_type)
  1041. return resp
  1042. def send_pack(self, path, update_refs, generate_pack_contents,
  1043. progress=None, write_pack=write_pack_objects):
  1044. """Upload a pack to a remote repository.
  1045. :param path: Repository path (as bytestring)
  1046. :param update_refs: Function to determine changes to remote refs.
  1047. Receive dict with existing remote refs, returns dict with
  1048. changed refs (name -> sha, where sha=ZERO_SHA for deletions)
  1049. :param generate_pack_contents: Function that can return a sequence of
  1050. the shas of the objects to upload.
  1051. :param progress: Optional progress function
  1052. :param write_pack: Function called with (file, iterable of objects) to
  1053. write the objects returned by generate_pack_contents to the server.
  1054. :raises SendPackError: if server rejects the pack data
  1055. :raises UpdateRefsError: if the server supports report-status
  1056. and rejects ref updates
  1057. :return: new_refs dictionary containing the changes that were made
  1058. {refname: new_ref}, including deleted refs.
  1059. """
  1060. url = self._get_url(path)
  1061. old_refs, server_capabilities = self._discover_references(
  1062. b"git-receive-pack", url)
  1063. unknown_capabilities = (
  1064. extract_capability_names(server_capabilities) -
  1065. KNOWN_RECEIVE_CAPABILITIES)
  1066. # TODO(jelmer): warn about unknown capabilities
  1067. negotiated_capabilities = self._send_capabilities & server_capabilities
  1068. if CAPABILITY_REPORT_STATUS in negotiated_capabilities:
  1069. self._report_status_parser = ReportStatusParser()
  1070. new_refs = update_refs(dict(old_refs))
  1071. if new_refs is None:
  1072. # Determine wants function is aborting the push.
  1073. return old_refs
  1074. if self.dumb:
  1075. raise NotImplementedError(self.fetch_pack)
  1076. req_data = BytesIO()
  1077. req_proto = Protocol(None, req_data.write)
  1078. (have, want) = self._handle_receive_pack_head(
  1079. req_proto, negotiated_capabilities, old_refs, new_refs)
  1080. if not want and set(new_refs.items()).issubset(set(old_refs.items())):
  1081. return new_refs
  1082. objects = generate_pack_contents(have, want)
  1083. if len(objects) > 0:
  1084. write_pack(req_proto.write_file(), objects)
  1085. resp = self._smart_request("git-receive-pack", url,
  1086. data=req_data.getvalue())
  1087. try:
  1088. resp_proto = Protocol(resp.read, None)
  1089. self._handle_receive_pack_tail(
  1090. resp_proto, negotiated_capabilities, progress)
  1091. return new_refs
  1092. finally:
  1093. resp.close()
  1094. def fetch_pack(self, path, determine_wants, graph_walker, pack_data,
  1095. progress=None):
  1096. """Retrieve a pack from a git smart server.
  1097. :param determine_wants: Callback that returns list of commits to fetch
  1098. :param graph_walker: Object with next() and ack().
  1099. :param pack_data: Callback called for each bit of data in the pack
  1100. :param progress: Callback for progress reports (strings)
  1101. :return: Dictionary with all remote refs (not just those fetched)
  1102. """
  1103. url = self._get_url(path)
  1104. refs, server_capabilities = self._discover_references(
  1105. b"git-upload-pack", url)
  1106. unknown_capabilities = (
  1107. extract_capability_names(server_capabilities) -
  1108. KNOWN_UPLOAD_CAPABILITIES)
  1109. # TODO(jelmer): warn about unknown capabilities
  1110. negotiated_capabilities = (
  1111. self._fetch_capabilities & server_capabilities)
  1112. wants = determine_wants(refs)
  1113. if wants is not None:
  1114. wants = [cid for cid in wants if cid != ZERO_SHA]
  1115. if not wants:
  1116. return refs
  1117. if self.dumb:
  1118. raise NotImplementedError(self.send_pack)
  1119. req_data = BytesIO()
  1120. req_proto = Protocol(None, req_data.write)
  1121. self._handle_upload_pack_head(
  1122. req_proto, negotiated_capabilities, graph_walker, wants,
  1123. lambda: False)
  1124. resp = self._smart_request(
  1125. "git-upload-pack", url, data=req_data.getvalue())
  1126. try:
  1127. resp_proto = Protocol(resp.read, None)
  1128. self._handle_upload_pack_tail(
  1129. resp_proto, negotiated_capabilities, graph_walker, pack_data,
  1130. progress)
  1131. return refs
  1132. finally:
  1133. resp.close()
  1134. def get_refs(self, path):
  1135. """Retrieve the current refs from a git smart server."""
  1136. url = self._get_url(path)
  1137. refs, _ = self._discover_references(
  1138. b"git-upload-pack", url)
  1139. return refs
  1140. def get_transport_and_path_from_url(url, config=None, **kwargs):
  1141. """Obtain a git client from a URL.
  1142. :param url: URL to open (a unicode string)
  1143. :param config: Optional config object
  1144. :param thin_packs: Whether or not thin packs should be retrieved
  1145. :param report_activity: Optional callback for reporting transport
  1146. activity.
  1147. :return: Tuple with client instance and relative path.
  1148. """
  1149. parsed = urlparse.urlparse(url)
  1150. if parsed.scheme == 'git':
  1151. return (TCPGitClient.from_parsedurl(parsed, **kwargs),
  1152. parsed.path)
  1153. elif parsed.scheme in ('git+ssh', 'ssh'):
  1154. return SSHGitClient.from_parsedurl(parsed, **kwargs), parsed.path
  1155. elif parsed.scheme in ('http', 'https'):
  1156. return HttpGitClient.from_parsedurl(
  1157. parsed, config=config, **kwargs), parsed.path
  1158. elif parsed.scheme == 'file':
  1159. return default_local_git_client_cls.from_parsedurl(
  1160. parsed, **kwargs), parsed.path
  1161. raise ValueError("unknown scheme '%s'" % parsed.scheme)
  1162. def get_transport_and_path(location, **kwargs):
  1163. """Obtain a git client from a URL.
  1164. :param location: URL or path (a string)
  1165. :param config: Optional config object
  1166. :param thin_packs: Whether or not thin packs should be retrieved
  1167. :param report_activity: Optional callback for reporting transport
  1168. activity.
  1169. :return: Tuple with client instance and relative path.
  1170. """
  1171. # First, try to parse it as a URL
  1172. try:
  1173. return get_transport_and_path_from_url(location, **kwargs)
  1174. except ValueError:
  1175. pass
  1176. if (sys.platform == 'win32' and
  1177. location[0].isalpha() and location[1:3] == ':\\'):
  1178. # Windows local path
  1179. return default_local_git_client_cls(**kwargs), location
  1180. if ':' in location and '@' not in location:
  1181. # SSH with no user@, zero or one leading slash.
  1182. (hostname, path) = location.split(':', 1)
  1183. return SSHGitClient(hostname, **kwargs), path
  1184. elif ':' in location:
  1185. # SSH with user@host:foo.
  1186. user_host, path = location.split(':', 1)
  1187. if '@' in user_host:
  1188. user, host = user_host.rsplit('@', 1)
  1189. else:
  1190. user = None
  1191. host = user_host
  1192. return SSHGitClient(host, username=user, **kwargs), path
  1193. # Otherwise, assume it's a local path.
  1194. return default_local_git_client_cls(**kwargs), location