The little things give you away... A collection of various small helper stuff
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

594 lines
21 KiB

  1. #!/usr/bin/env python3
  2. # Tiny tool for WARC stuff.
  3. # Operating modes:
  4. # warc-tiny colour FILES -- coloured output of the WARCs for easier reading
  5. # warc-tiny dump-responses [-m|--meta] FILES -- dump the HTTP response bodies to stdout
  6. # With --meta, prefix every line with the filename, record offset, record ID, and target URI; e.g. 'file.warc.gz:123:<urn:uuid:41b76f1f-f946-4723-91f8-cee6491e92f3>:<https://example.org/>: foobar'
  7. # The record offset may be -1 if it is not known.
  8. # The filename is wrapped in angled brackets if it contains a colon; the target URI is always wrapped in angled brackets (since it virtually always contains a colon).
  9. # warc-tiny scrape [-u|--urls] FILES -- extract all links and page requisites from the records; produces lines of filename, record offset, record URI, link type, inline flag, and URL as JSONL
  10. # With --urls, only the URL is printed.
  11. # wpull's scrapers are used for the extraction.
  12. # warc-tiny verify FILES -- verify the integrity of a WARC by comparing the digests
  13. import base64
  14. import contextlib
  15. import enum
  16. import gzip
  17. import hashlib
  18. import json
  19. import sys
  20. import tempfile
  21. import zlib
  22. try:
  23. import wpull.body
  24. import wpull.document.htmlparse.lxml_
  25. try:
  26. import wpull.protocol.http.request as wpull_protocol_http_request # wpull 2.x
  27. except ImportError:
  28. import wpull.http.request as wpull_protocol_http_request # wpull 1.x
  29. import wpull.scraper.base
  30. import wpull.scraper.css
  31. import wpull.scraper.html
  32. import wpull.scraper.javascript
  33. import wpull.scraper.sitemap
  34. except ImportError:
  35. wpull = None
  36. def GzipDecompressor():
  37. return zlib.decompressobj(16 + zlib.MAX_WBITS)
  38. class DummyDecompressor:
  39. def decompress(self, data):
  40. return data
  41. class Event:
  42. pass
  43. class FileEvent(Event):
  44. def __init__(self, filename):
  45. self._filename = filename
  46. @property
  47. def filename(self):
  48. return self._filename
  49. class NewFile(FileEvent):
  50. pass
  51. class BeginOfRecord(Event):
  52. def __init__(self, warcHeaders, rawData):
  53. self._warcHeaders = warcHeaders
  54. self._rawData = rawData
  55. @property
  56. def warcHeaders(self):
  57. return self._warcHeaders
  58. @property
  59. def rawData(self):
  60. return self._rawData
  61. class HTTPHeaders(Event):
  62. def __init__(self, headers):
  63. self._headers = headers
  64. @property
  65. def headers(self):
  66. return self._headers
  67. class _DataChunk(Event):
  68. def __init__(self, data):
  69. self._data = data
  70. @property
  71. def data(self):
  72. return self._data
  73. def __repr__(self):
  74. return '{}({!r}{})'.format(type(self).__name__, self._data[:50], '...' if len(self._data) > 50 else '')
  75. class WARCBlockChunk(_DataChunk):
  76. def __init__(self, data, isHttpHeader = None):
  77. super().__init__(data)
  78. self._isHttpHeader = isHttpHeader
  79. @property
  80. def isHttpHeader(self):
  81. # True: the chunk represents (part of) the HTTP header; False: the chunk represents (part of) the HTTP body; None: the chunk is not part of an HTTP record
  82. return self._isHttpHeader
  83. class RawHTTPBodyChunk(_DataChunk):
  84. '''
  85. Because many tools misunderstood the WARC specifications, the Payload-Digest was often implemented without stripping transfer encoding.
  86. This is like HTTPBodyChunk but without transfer encoding stripping.
  87. '''
  88. class HTTPBodyChunk(_DataChunk):
  89. '''
  90. Representing a part of the HTTP body with transfer encoding stripped.
  91. '''
  92. class EndOfRecord(Event):
  93. pass
  94. class WARCParsingIssue(enum.Enum):
  95. TRUNCATED_FILE = enum.auto()
  96. MALFORMED_HTTP_RECORD = enum.auto()
  97. class WARCParsingIssueEvent(Event):
  98. def __init__(self, issue, message = None):
  99. self.issue = issue
  100. self.message = message
  101. class EndOfFile(FileEvent):
  102. pass
  103. @contextlib.contextmanager
  104. def open_warc(f):
  105. if hasattr(f, 'read'):
  106. yield f
  107. else:
  108. with open(f, 'rb') as fp:
  109. yield fp
  110. def iter_warc(f):
  111. # Yields Events
  112. # BeginOfRecord's rawData does not include the CRLF CRLF at the end of the headers, and WARCBlockChunk does not contain the CRLF CRLF after the block either.
  113. with open_warc(f) as fp:
  114. buf = b''
  115. while True:
  116. # Read WARC header
  117. while b'\r\n\r\n' not in buf:
  118. try:
  119. d = fp.read(16777216)
  120. except EOFError:
  121. break
  122. if not d:
  123. break
  124. buf += d
  125. if not buf:
  126. break
  127. assert b'\r\n\r\n' in buf
  128. warcHeaderBuf, buf = buf.split(b'\r\n\r\n', 1)
  129. assert warcHeaderBuf.startswith(b'WARC/1.0\r\n') or warcHeaderBuf.startswith(b'WARC/1.1\r\n')
  130. assert b'\r\nContent-Length:' in warcHeaderBuf
  131. warcHeaders = tuple(tuple(map(bytes.strip, x.split(b':', 1))) for x in warcHeaderBuf.split(b'\r\n'))
  132. warcContentType = next(x[1] for x in warcHeaders if x[0] == b'Content-Type')
  133. warcContentLength = int(next(x[1] for x in warcHeaders if x[0] == b'Content-Length'))
  134. warcType = next(x[1] for x in warcHeaders if x[0] == b'WARC-Type')
  135. yield BeginOfRecord(warcHeaders, warcHeaderBuf)
  136. recordID = next(x[1] for x in warcHeaders if x[0] == b'WARC-Record-ID')
  137. # Read WARC block (and skip CRLFCRLF at the end of the record)
  138. if len(buf) < warcContentLength + 4:
  139. try:
  140. buf = buf + fp.read(warcContentLength + 4 - len(buf))
  141. except EOFError:
  142. pass
  143. if len(buf) < warcContentLength + 4:
  144. print('Error: truncated WARC', file = sys.stderr)
  145. yield WARCParsingIssueEvent(WARCParsingIssue.TRUNCATED_FILE)
  146. break
  147. warcContent = buf[:warcContentLength]
  148. buf = buf[warcContentLength + 4:]
  149. # Decode HTTP body if appropriate
  150. if warcContentType in (b'application/http;msgtype=request', b'application/http; msgtype=request') and warcType == b'request':
  151. httpType = 'request'
  152. elif warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response':
  153. httpType = 'response'
  154. else:
  155. httpType = None
  156. if httpType is not None:
  157. if b'\r\n\r\n' in warcContent:
  158. httpHeaders, httpBody = warcContent.split(b'\r\n\r\n', 1)
  159. # Parse headers and extract transfer encoding
  160. httpHeaderLines = [tuple(map(bytes.strip, x.split(b':', 1))) for x in httpHeaders.split(b'\r\n')]
  161. chunked = False
  162. gzipped = False
  163. if b'\r\ntransfer-encoding' in httpHeaders.lower():
  164. transferEncoding = next(x[1] for x in httpHeaderLines if x[0].lower() == b'transfer-encoding')
  165. transferEncodings = set(map(bytes.strip, transferEncoding.split(b',')))
  166. chunked = b'chunked' in transferEncodings
  167. gzipped = b'gzip' in transferEncodings
  168. yield WARCBlockChunk(httpHeaders + b'\r\n\r\n', isHttpHeader = True)
  169. yield HTTPHeaders(httpHeaderLines)
  170. yield WARCBlockChunk(httpBody, isHttpHeader = False)
  171. yield RawHTTPBodyChunk(httpBody)
  172. # Decode body
  173. if gzipped:
  174. httpDecompressor = GzipDecompressor()
  175. else:
  176. httpDecompressor = DummyDecompressor()
  177. if chunked:
  178. pos = 0
  179. while True:
  180. try:
  181. chunkLineEnd = httpBody.index(b'\r\n', pos)
  182. except ValueError:
  183. message = 'could not find chunk line end in record {}'.format(recordID)
  184. print('Error: {}, skipping'.format(message), file = sys.stderr)
  185. yield WARCParsingIssueEvent(WARCParsingIssue.MALFORMED_HTTP_RECORD, message)
  186. break
  187. chunkLine = httpBody[pos:chunkLineEnd]
  188. if b';' in chunkLine:
  189. chunkLength = chunkLine[:chunkLine.index(b';')].strip()
  190. else:
  191. chunkLength = chunkLine.strip()
  192. if chunkLength.lstrip(b'0123456789abcdefABCDEF') != b'':
  193. message = 'malformed chunk length {!r} in record {}'.format(chunkLength, recordID)
  194. print('Error: {}, skipping'.format(message), file = sys.stderr)
  195. yield WARCParsingIssueEvent(WARCParsingIssue.MALFORMED_HTTP_RECORD, message)
  196. break
  197. chunkLength = int(chunkLength, base = 16)
  198. if chunkLength == 0:
  199. break
  200. chunk = httpDecompressor.decompress(httpBody[chunkLineEnd + 2 : chunkLineEnd + 2 + chunkLength])
  201. yield HTTPBodyChunk(chunk)
  202. pos = chunkLineEnd + 2 + chunkLength + 2
  203. else:
  204. yield HTTPBodyChunk(httpDecompressor.decompress(httpBody))
  205. else:
  206. message = 'malformed HTTP request or response in record {}'.format(recordID)
  207. print('Warning: {}, skipping'.format(message), file = sys.stderr)
  208. yield WARCParsingIssueEvent(WARCParsingIssue.MALFORMED_HTTP_RECORD, message)
  209. yield WARCBlockChunk(warcContent)
  210. else:
  211. yield WARCBlockChunk(warcContent)
  212. yield EndOfRecord()
  213. class ProcessMode:
  214. @classmethod
  215. def split_args(cls, args):
  216. '''Split args into arguments to be passed into __init__ and filenames'''
  217. return (), args
  218. def process_event(self, event):
  219. raise NotImplementedError
  220. class Digest:
  221. def __init__(self, digest):
  222. self._digest = digest
  223. def format(self, digest = None):
  224. raise NotImplementedError
  225. def equals(self, digest):
  226. return self._digest == digest
  227. class Base32Digest(Digest):
  228. def format(self, digest = None):
  229. return base64.b32encode(digest if digest else self._digest)
  230. class HexDigest(Digest):
  231. def format(self, digest = None):
  232. return (digest if digest else self._digest).hex()
  233. class VerificationError(Exception):
  234. pass
  235. class VerifyMode(ProcessMode):
  236. def __init__(self):
  237. self._blockDigester = None
  238. self._recordedBlockDigest = None
  239. self._payloadDigester = None
  240. self._brokenPayloadDigester = None
  241. self._recordedPayloadDigest = None
  242. self._printedBrokenPayloadWarning = False
  243. self._verificationFailed = False
  244. def parse_digest(self, digest):
  245. if not digest.startswith(b'sha1:'):
  246. print('Warning: don\'t understand hash format: {!r}'.format(digest), file = sys.stderr)
  247. return None
  248. if len(digest) == 37 and digest.rstrip(b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') == b'sha1:': # 5 for 'sha1:' + 32 for base-32 hash
  249. return Base32Digest(base64.b32decode(digest[5:]))
  250. if len(digest) == 45 and digest.rstrip(b'0123456789abcdef') == b'sha1:':
  251. return HexDigest(bytes.fromhex(digest[5:].decode('ascii')))
  252. return None
  253. def process_event(self, event):
  254. if type(event) is NewFile:
  255. self._printedBrokenPayloadWarning = False
  256. self._verificationFailed = False
  257. elif type(event) is BeginOfRecord:
  258. if any(x[0] == b'WARC-Block-Digest' for x in event.warcHeaders):
  259. self._blockDigester = hashlib.sha1()
  260. self._recordedBlockDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Block-Digest'))
  261. else:
  262. self._blockDigester = None
  263. self._recordedBlockDigest = None
  264. if any(x[0] == b'WARC-Payload-Digest' for x in event.warcHeaders):
  265. self._payloadDigester = hashlib.sha1()
  266. self._brokenPayloadDigester = hashlib.sha1()
  267. self._recordedPayloadDigest = self.parse_digest(next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Payload-Digest'))
  268. else:
  269. self._payloadDigester = None
  270. self._brokenPayloadDigester = None
  271. self._recordedPayloadDigest = None
  272. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID')
  273. self._recordType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  274. elif type(event) is WARCBlockChunk:
  275. if self._blockDigester:
  276. self._blockDigester.update(event.data)
  277. elif type(event) is HTTPBodyChunk:
  278. if self._payloadDigester:
  279. self._payloadDigester.update(event.data)
  280. elif type(event) is RawHTTPBodyChunk:
  281. if self._brokenPayloadDigester:
  282. self._brokenPayloadDigester.update(event.data)
  283. elif type(event) is WARCParsingIssueEvent:
  284. self._verificationFailed = True
  285. elif type(event) is EndOfRecord:
  286. if self._blockDigester and self._recordedBlockDigest:
  287. if not self._recordedBlockDigest.equals(self._blockDigester.digest()):
  288. print('Block digest mismatch for record {}: recorded {} v calculated {}'.format(self._recordID, self._recordedBlockDigest.format(), self._recordedBlockDigest.format(self._blockDigester.digest())), file = sys.stderr)
  289. self._verificationFailed = True
  290. if self._payloadDigester and self._recordType in (b'request', b'response'): #TODO: Support revisit
  291. if not self._recordedPayloadDigest.equals(self._payloadDigester.digest()):
  292. if self._recordedPayloadDigest.equals(self._brokenPayloadDigester.digest()):
  293. if not self._printedBrokenPayloadWarning:
  294. print('Warning: WARC uses incorrect payload digests without stripping the transfer encoding', file = sys.stderr)
  295. self._printedBrokenPayloadWarning = True
  296. else:
  297. print('Payload digest mismatch for record {}: recorded {} vs. calculated {} (calculated broken {})'.format(self._recordID, self._recordedPayloadDigest.format(), self._recordedPayloadDigest.format(self._payloadDigester.digest()), self._recordedPayloadDigest.format(self._brokenPayloadDigester.digest())), file = sys.stderr)
  298. self._verificationFailed = True
  299. elif type(event) is EndOfFile and self._verificationFailed:
  300. raise VerificationError('one or more errors encountered while verifying {}'.format(event.filename))
  301. class DumpResponsesMode(ProcessMode):
  302. @classmethod
  303. def split_args(cls, args):
  304. if args[0] == '-m' or args[0] == '--meta':
  305. return (True,), args[1:]
  306. return (False,), args
  307. def __init__(self, withMeta):
  308. self._printEOR = False
  309. self._isResponse = False
  310. self._withMeta = withMeta
  311. if withMeta:
  312. self._recordID = None
  313. self._targetURI = None
  314. self._buffer = b''
  315. def _write(self, data):
  316. if not self._withMeta:
  317. sys.stdout.buffer.write(data)
  318. return
  319. buf = self._buffer + data
  320. lines = buf.split(b'\n')
  321. self._buffer = lines.pop() # Since there's an explicit `_write(b'\r\n')` at the end of the record, this implicitly resets the buffer as well
  322. for line in lines:
  323. sys.stdout.buffer.write(':'.join((self._filename, '-1', self._recordID, '<' + self._targetURI + '>', '')).encode('utf-8'))
  324. sys.stdout.buffer.write(line)
  325. sys.stdout.buffer.write(b'\n')
  326. def process_event(self, event):
  327. if type(event) is NewFile:
  328. self._filename = event.filename
  329. if ':' in self._filename:
  330. self._filename = '<' + self._filename + '>'
  331. elif type(event) is BeginOfRecord:
  332. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  333. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  334. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  335. self._printEOR = False
  336. if self._withMeta:
  337. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  338. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  339. self._targetURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  340. self._buffer = b''
  341. elif type(event) is HTTPBodyChunk:
  342. if self._isResponse:
  343. self._printEOR = True
  344. self._write(event.data)
  345. elif type(event) is EndOfRecord:
  346. if self._printEOR:
  347. self._write(b'\r\n')
  348. class COLOURS:
  349. RESET = b'\x1b[0m'
  350. GREEN = b'\x1b[0;32m'
  351. LIGHTGREEN = b'\x1b[1;32m'
  352. PURPLE = b'\x1b[0;35m'
  353. LIGHTPURPLE = b'\x1b[1;35m'
  354. RED = b'\x1b[0;31m'
  355. INVERTED = b'\x1b[7m'
  356. class ColourMode(ProcessMode):
  357. def __init__(self):
  358. self._hadHttpStatusLine = False
  359. def _replace_esc(self, data):
  360. return data.replace(b'\x1b', COLOURS.INVERTED + b'ESC' + COLOURS.RESET)
  361. def _print_line(self, line, colour, withLF = True, colourOnlyBeforeColon = False):
  362. if colourOnlyBeforeColon:
  363. if b':' in line:
  364. offset = line.index(b':')
  365. else:
  366. offset = 0
  367. else:
  368. offset = len(line)
  369. if offset > 0:
  370. sys.stdout.buffer.write(colour)
  371. sys.stdout.buffer.write(self._replace_esc(line[:offset]))
  372. sys.stdout.buffer.write(COLOURS.RESET)
  373. sys.stdout.buffer.write(line[offset:])
  374. if withLF:
  375. sys.stdout.buffer.write(b'\n')
  376. def _print_data(self, data, colour, colourOnlyBeforeColon):
  377. later = False
  378. for line in data.split(b'\r\n'):
  379. if later:
  380. sys.stdout.buffer.write(b'\n')
  381. self._print_line(line, colour, withLF = False, colourOnlyBeforeColon = colourOnlyBeforeColon)
  382. later = True
  383. def process_event(self, event):
  384. if type(event) is BeginOfRecord:
  385. firstNewline = event.rawData.index(b'\r\n')
  386. self._print_line(event.rawData[:firstNewline], COLOURS.LIGHTGREEN)
  387. self._print_data(event.rawData[firstNewline + 2:], COLOURS.GREEN, True)
  388. sys.stdout.buffer.write(b'\n\n') # separator between header and block
  389. self._hadHttpStatusLine = False
  390. elif type(event) is WARCBlockChunk:
  391. if event.isHttpHeader is True:
  392. if not self._hadHttpStatusLine:
  393. firstNewline = event.data.index(b'\r\n')
  394. self._print_line(event.data[:firstNewline], COLOURS.LIGHTPURPLE)
  395. offset = firstNewline + 2
  396. self._hadHttpStatusLine = True
  397. else:
  398. offset = 0
  399. self._print_data(event.data[offset:], COLOURS.PURPLE, True)
  400. elif event.isHttpHeader is False:
  401. self._print_data(event.data, COLOURS.RED, False)
  402. elif event.isHttpHeader is None:
  403. sys.stdout.buffer.write(self._replace_esc(event.data))
  404. elif type(event) is EndOfRecord:
  405. sys.stdout.buffer.write(b'\n\n')
  406. class ScrapeMode(ProcessMode):
  407. @classmethod
  408. def split_args(cls, args):
  409. if args[0] == '-u' or args[0] == '--urls':
  410. return (True,), args[1:]
  411. return (False,), args
  412. def __init__(self, urlsOnly):
  413. self._urlsOnly = urlsOnly
  414. assert wpull is not None, 'Scrape mode requires wpull and lxml'
  415. htmlParser = wpull.document.htmlparse.lxml_.HTMLParser()
  416. elementWalker = wpull.scraper.html.ElementWalker()
  417. scrapers = []
  418. scrapers.append(wpull.scraper.html.HTMLScraper(htmlParser, elementWalker))
  419. scrapers.append(wpull.scraper.css.CSSScraper())
  420. elementWalker.css_scraper = scrapers[-1]
  421. scrapers.append(wpull.scraper.javascript.JavaScriptScraper())
  422. elementWalker.javascript_scraper = scrapers[-1]
  423. scrapers.append(wpull.scraper.sitemap.SitemapScraper(htmlParser))
  424. self._scraper = wpull.scraper.base.DemuxDocumentScraper(scrapers)
  425. self._isResponse = None
  426. self._body = None
  427. self._recordURI = None
  428. self._statusCode = None
  429. self._statusReason = None
  430. if not self._urlsOnly:
  431. self._filename = None
  432. self._recordID = None
  433. def process_event(self, event):
  434. if type(event) is NewFile and not self._urlsOnly:
  435. self._filename = event.filename
  436. elif type(event) is BeginOfRecord:
  437. warcContentType = next(x[1] for x in event.warcHeaders if x[0] == b'Content-Type')
  438. warcType = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Type')
  439. self._isResponse = warcContentType in (b'application/http;msgtype=response', b'application/http; msgtype=response') and warcType == b'response'
  440. if self._isResponse:
  441. self._body = wpull.body.Body(file = tempfile.SpooledTemporaryFile(max_size = 10485760)) # Up to 10 MiB in memory
  442. self._printEOR = False
  443. if not self._urlsOnly:
  444. # Both of these are URIs, and per RFC 3986, those can only contain ASCII characters.
  445. self._recordID = next(x[1] for x in event.warcHeaders if x[0] == b'WARC-Record-ID').decode('ascii')
  446. self._recordURI = next((x[1] for x in event.warcHeaders if x[0] == b'WARC-Target-URI'), b'').decode('ascii')
  447. elif type(event) is HTTPHeaders and self._isResponse:
  448. assert len(event.headers[0]) == 1 and event.headers[0][0].startswith(b'HTTP/'), 'malformed HTTP response'
  449. _, statusCode, reason = event.headers[0][0].decode('ascii').split(' ', 2)
  450. self._statusCode = int(statusCode)
  451. self._statusReason = reason
  452. elif type(event) is HTTPBodyChunk and self._isResponse:
  453. self._body.write(event.data)
  454. elif type(event) is EndOfRecord and self._isResponse:
  455. request = wpull_protocol_http_request.Request(self._recordURI)
  456. response = wpull_protocol_http_request.Response(self._statusCode, self._statusReason)
  457. response.body = self._body
  458. response.body.seek(0)
  459. for scraper, scrapeResult in self._scraper.scrape_info(request, response).items():
  460. if not scrapeResult:
  461. continue
  462. for linkContext in scrapeResult.link_contexts:
  463. if self._urlsOnly:
  464. print(linkContext.link)
  465. continue
  466. o = {
  467. 'filename': self._filename,
  468. 'recordOffset': None,
  469. 'recordID': self._recordID,
  470. 'recordURI': self._recordURI,
  471. 'linkType': linkContext.link_type.value if isinstance(linkContext.link_type, enum.Enum) else linkContext.link_type,
  472. 'inline': bool(linkContext.inline), # Needs manual casting; https://github.com/ArchiveTeam/wpull/issues/458
  473. 'linked': bool(linkContext.linked),
  474. 'url': linkContext.link,
  475. }
  476. print(json.dumps(o))
  477. def main():
  478. processorMap = {'verify': VerifyMode, 'dump-responses': DumpResponsesMode, 'colour': ColourMode, 'scrape': ScrapeMode}
  479. assert len(sys.argv) - 1 >= 2
  480. mode = sys.argv[1]
  481. assert mode in processorMap
  482. processorArgs, files = processorMap[mode].split_args(sys.argv[2:])
  483. assert files
  484. processor = processorMap[mode](*processorArgs)
  485. try:
  486. for f in files:
  487. if f.endswith('.warc.gz') or f.endswith('.warc.zst'):
  488. print(f'Warning: warc-tiny does not support decompressing WARCs like {f}. Please use zcat/zstdcat/zstdwarccat and pipe the decompressed stream into warc-tiny instead.', file = sys.stderr)
  489. print('Info: processing {}'.format(f), file = sys.stderr)
  490. processor.process_event(NewFile(f))
  491. if f == '-':
  492. f = sys.stdin.buffer
  493. for event in iter_warc(f):
  494. processor.process_event(event)
  495. processor.process_event(EndOfFile(f))
  496. except BrokenPipeError:
  497. return
  498. if __name__ == '__main__':
  499. main()