2 # This is part of ypp-sc-tools, a set of third-party tools for assisting
3 # players of Yohoho Puzzle Pirates.
5 # Copyright (C) 2009 Ian Jackson <ijackson@chiark.greenend.org.uk>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 # Yohoho and Puzzle Pirates are probably trademarks of Three Rings and
21 # are used without permission. This program is not endorsed or
22 # sponsored by Three Rings.
25 yoweb-scrape is part of ypp-sc-tools Copyright (C) 2009 Ian Jackson
26 This program comes with ABSOLUTELY NO WARRANTY; this is free software,
27 and you are welcome to redistribute it under certain conditions.
28 For details, read the top of the yoweb-scrape file.
31 #---------- setup ----------
34 signal.signal(signal.SIGINT, signal.SIG_DFL)
48 from optparse import OptionParser
49 from StringIO import StringIO
51 from BeautifulSoup import BeautifulSoup
55 #---------- YPP parameters and arrays ----------
57 puzzles = ('Swordfighting/Bilging/Sailing/Rigging/Navigating'+
58 '/Battle Navigation/Gunning/Carpentry/Rumble/Treasure Haul'+
59 '/Drinking/Spades/Hearts/Treasure Drop/Poker/Distilling'+
60 '/Alchemistry/Shipwrightery/Blacksmithing/Foraging').split('/')
64 ['Sailing','Rigging'],
69 duty_puzzles = ([ 'Navigating', 'Battle Navigation' ] +
73 standingvals = ('Able/Proficient/Distinguished/Respected/Master'+
74 '/Renowned/Grand-Master/Legendary/Ultimate').split('/')
75 standing_limit = len(standingvals)
77 pirate_ref_re = regexp.compile('^/yoweb/pirate\\.wm')
79 max_pirate_namelen = 12
82 #---------- general utilities ----------
86 print >>opts.debug_file, m
90 opts.debug_file.flush()
96 def format_time_interval(ti):
97 if ti < 120: return '%d:%02d' % (ti / 60, ti % 60)
98 if ti < 7200: return '%2dm' % (ti / 60)
99 if ti < 86400: return '%dh' % (ti / 3600)
100 return '%dd' % (ti / 86400)
103 lib = os.getenv("YPPSC_YARRG_SRCBASE")
104 if lib is not None: return lib
106 lib = regexp.sub('/[^/]+$', '', lib)
107 os.environ["YPPSC_YARRG_SRCBASE"] = lib
110 #---------- caching and rate-limiting data fetcher ----------
113 def __init__(self, cachedir):
114 debug('Fetcher init %s' % cachedir)
115 self.cachedir = cachedir
116 try: os.mkdir(cachedir)
117 except (OSError,IOError), oe:
118 if oe.errno != errno.EEXIST: raise
119 self._cache_scan(time.time())
121 def _cache_scan(self, now):
122 # returns list of ages, unsorted
124 debug('Fetcher scan_cache')
125 for leaf in os.listdir(self.cachedir):
126 if not leaf.startswith('#'): continue
127 path = self.cachedir + '/' + leaf
128 try: s = os.stat(path)
129 except (OSError,IOError), oe:
130 if oe.errno != errno.ENOENT: raise
132 age = now - s.st_mtime
133 if age > opts.expire_age:
134 debug('Fetcher expire %d %s' % (age, path))
136 except (OSError,IOError), oe:
137 if oe.errno != errno.ENOENT: raise
142 def need_wait(self, now, imaginary=[]):
143 ages = self._cache_scan(now)
146 debug('Fetcher ages ' + `ages`)
150 if age < min_age and age <= 5:
151 debug('Fetcher morewait min=%d age=%d' %
153 need_wait = max(need_wait, min_age - age)
157 need_wait += random.random() - 0.5
160 def _rate_limit_cache_clean(self, now):
161 need_wait = self.need_wait(now)
163 debug('Fetcher wait %d' % need_wait)
166 def fetch(self, url, max_age):
167 debug('Fetcher fetch %s' % url)
168 cache_corename = urllib.quote_plus(url)
169 cache_item = "%s/#%s#" % (self.cachedir, cache_corename)
170 try: f = file(cache_item, 'r')
171 except (OSError,IOError), oe:
172 if oe.errno != errno.ENOENT: raise
175 max_age = max(opts.min_max_age, min(max_age, opts.expire_age))
177 s = os.fstat(f.fileno())
178 age = now - s.st_mtime
180 debug('Fetcher stale %d < %d'% (max_age, age))
185 debug('Fetcher cached %d > %d' % (max_age, age))
188 debug('Fetcher fetch')
189 self._rate_limit_cache_clean(now)
191 stream = urllib2.urlopen(url)
193 cache_tmp = "%s/#%s~%d#" % (
194 self.cachedir, cache_corename, os.getpid())
195 f = file(cache_tmp, 'w')
198 os.rename(cache_tmp, cache_item)
199 debug('Fetcher stored')
202 class Yoweb(Fetcher):
203 def __init__(self, ocean, cachedir):
204 debug('Yoweb init %s' % cachedir)
206 Fetcher.__init__(self, cachedir)
208 def default_ocean(self, ocean='ice'):
209 if self.ocean is None:
212 def yoweb(self, kind, tail, max_age):
215 url = 'http://%s.puzzlepirates.com/yoweb/%s%s' % (
216 self.ocean, kind, tail)
217 return self.fetch(url, max_age)
219 class Yppedia(Fetcher):
220 def __init__(self, cachedir):
221 debug('Yoweb init %s' % cachedir)
222 self.base = 'http://yppedia.puzzlepirates.com/'
223 self.localhtml = opts.localhtml
224 Fetcher.__init__(self, cachedir)
226 def __call__(self, rhs):
227 if self.localhtml is None:
228 url = self.base + rhs
229 debug('Yppedia retrieving YPP '+url);
230 return self.fetch(url, 3000)
232 return file(opts.localhtml + '/' + rhs, 'r')
234 #---------- logging assistance for troubled screenscrapers ----------
241 def soupm(self, obj, m):
242 self.msg(m + '; in ' + `obj`)
243 def needs_msgs(self, child_souplog):
244 self.msgs += child_souplog.msgs
245 child_souplog.msgs = [ ]
248 str = ''.join(obj.findAll(text=True))
251 class SomethingSoupInfo(SoupLog):
252 def __init__(self, kind, tail, max_age):
253 SoupLog.__init__(self)
254 html = fetcher.yoweb(kind, tail, max_age)
255 self._soup = BeautifulSoup(html,
256 convertEntities=BeautifulSoup.HTML_ENTITIES
259 #---------- scraper for pirate pages ----------
261 class PirateInfo(SomethingSoupInfo):
262 # Public data members:
263 # pi.standings = { 'Treasure Haul': 'Able' ... }
265 # pi.crew = (id, name)
266 # pi.flag = (id, name)
267 # pi.msgs = [ 'message describing problem with scrape' ]
269 def __init__(self, pirate, max_age=300):
270 SomethingSoupInfo.__init__(self,
271 'pirate.wm?target=', pirate, max_age)
273 self._find_standings()
274 self.crew = self._find_crewflag('crew',
275 '^/yoweb/crew/info\\.wm')
276 self.flag = self._find_crewflag('flag',
277 '^/yoweb/flag/info\\.wm')
279 def _find_standings(self):
280 imgs = self._soup.findAll('img',
281 src=regexp.compile('/yoweb/images/stat.*'))
283 u'\\s*\\S*/([-A-Za-z]+)\\s*$|\\s*\\S*/\\S*\\s*\\(ocean\\-wide(?:\\s|\\xa0)+([-A-Za-z]+)\\)\\s*$'
287 for skill in puzzles:
288 standings[skill] = [ ]
293 try: puzzle = img['alt']
294 except KeyError: continue
296 if not puzzle in puzzles:
297 skl.soupm(img, 'unknown puzzle: "%s"' % puzzle)
299 key = img.findParent('td')
301 skl.soupm(img, 'puzzle at root! "%s"' % puzzle)
303 valelem = key.findNextSibling('td')
305 skl.soupm(key, 'puzzle missing sibling "%s"'
308 valstr = soup_text(valelem)
309 match = re.match(valstr)
311 skl.soupm(key, ('puzzle "%s" unparseable'+
312 ' standing "%s"') % (puzzle, valstr))
314 standing = match.group(match.lastindex)
315 standings[puzzle].append(standing)
319 for puzzle in puzzles:
320 sl = standings[puzzle]
322 skl.msg('puzzle "%s" multiple standings %s' %
326 skl.msg('puzzle "%s" no standing found' % puzzle)
329 for i in range(0, standing_limit):
330 if standing == standingvals[i]:
331 self.standings[puzzle] = i
332 if not puzzle in self.standings:
333 skl.msg('puzzle "%s" unknown standing "%s"' %
336 all_standings_ok = True
337 for puzzle in puzzles:
338 if not puzzle in self.standings:
341 def _find_crewflag(self, cf, yoweb_re):
342 things = self._soup.findAll('a', href=regexp.compile(yoweb_re))
344 self.msg('zero or several %s id references found' % cf)
347 id_re = '\\b%sid\\=(\\w+)$' % cf
348 id_haystack = thing['href']
349 match = regexp.compile(id_re).search(id_haystack)
351 self.soupm(thing, ('incomprehensible %s id ref'+
352 ' (%s in %s)') % (cf, id_re, id_haystack))
354 name = soup_text(thing)
355 return (match.group(1), name)
358 return `(self.crew, self.flag, self.standings, self.msgs)`
360 #---------- scraper for crew pages ----------
362 class CrewInfo(SomethingSoupInfo):
363 # Public data members:
364 # ci.crew = [ ('Captain', ['Pirate', ...]),
365 # ('Senior Officer', [...]),
367 # pi.msgs = [ 'message describing problem with scrape' ]
369 def __init__(self, crewid, max_age=300):
370 SomethingSoupInfo.__init__(self,
371 'crew/info.wm?crewid=', crewid, max_age)
374 def _find_crew(self):
376 capts = self._soup.findAll('img',
377 src='/yoweb/images/crew-captain.png')
379 self.msg('crew members: no. of captain images != 1')
382 while not tbl.find('a', href=pirate_ref_re):
383 tbl = tbl.findParent('table')
385 self.msg('crew members: cannot find table')
387 current_rank_crew = None
388 crew_rank_re = regexp.compile('/yoweb/images/crew')
389 for row in tbl.contents:
390 # findAll(recurse=False)
391 if isinstance(row,basestring):
394 is_rank = row.find('img', attrs={'src': crew_rank_re})
396 rank = soup_text(row)
397 current_rank_crew = []
398 self.crew.append((rank, current_rank_crew))
400 for cell in row.findAll('a', href=pirate_ref_re):
401 if current_rank_crew is None:
402 self.soupm(cell, 'crew members: crew'
405 current_rank_crew.append(soup_text(cell))
408 return `(self.crew, self.msgs)`
410 class FlagInfo(SomethingSoupInfo):
411 # Public data members (after init):
415 # relations[n] = (otherflagname, otherflagid, [stringfromyoweb],
416 # thisdeclaring, otherdeclaringmin, otherdeclaringmax)
417 # # where {this,other}declaring{,min,max} are:
418 # # -1 {this,other} is declaring war
419 # # 0 {this,other} is not doing either
420 # # +1 {this,other} is allying
421 # relation_byname[otherflagname] = relations[some_n]
422 # relation_byid[otherflagname] = relations[some_n]
424 # islands[n] = (islandname, islandid)
426 def __init__(self, flagid, max_age=600):
427 SomethingSoupInfo.__init__(self,
428 'flag/info.wm?flagid=', flagid, max_age)
431 def _find_flag(self):
432 font2 = self._soup.find('font',{'size':'+2'})
433 self.name = font2.find('b').contents[0]
436 self.relation_byname = { }
437 self.relation_byid = { }
440 magnate = self._soup.find('img',{'src':
441 '/yoweb/images/repute-MAGNATE.png'})
442 warinfo = (magnate.findParent('table').findParent('tr').
443 findNextSibling('tr').findNext('td',{'align':'left'}))
446 print >>sys.stderr, 'WARNING: '+m
448 def wi_warn(head, waritem):
449 warn('unknown warmap item: %s: %s' %
450 (`head`, ``waritem``))
452 def wihelp_item(waritem, thing):
453 url = waritem.get('href', None)
455 return ('no url for '+thing,None,None)
456 m = regexp.search('\?'+thing+'id=(\d+)$', url)
457 if not m: return ('no '+thing+'id',None,None)
459 tname = waritem.string
461 return (thing+' name not just string',None,None)
462 return (None,tid,tname)
464 def wi_alwar(head, waritem, thisdecl, othermin, othermax):
465 (err,flagid,flagname) = wihelp_item(waritem,'flag')
467 rel = self.relation_byid.get(flagid, None)
468 if rel: return 'flag id twice!'
469 if flagname in self.relation_byname:
470 return 'flag name twice!'
471 rel = (flagname,flagid,head, thisdecl,othermin,othermax)
472 self.relations.append(rel)
473 self.relation_byid[flagid] = rel
474 self.relation_byname[flagid] = rel
476 def wi_isle(head, waritem):
477 (err,isleid,islename) = wihelp_item(waritem,'island')
479 self.islands.append((isleid,islename))
482 'Allied with': (wi_alwar,+1,+1,+1),
483 'Declaring war against': (wi_alwar,-1, 0,+1),
484 'At war with': (wi_alwar,-1,-1,-1),
485 'Trying to form an alliance with': (wi_alwar,+1,-1,0),
486 'Islands controlled by this flag': (wi_isle,),
489 how = (wi_warn, None)
491 for waritem in warinfo.findAll(['font','a']):
492 if waritem is None: break
493 if waritem.name == 'font':
494 colour = waritem.get('color',None)
495 if colour.lstrip('#') != '958A5F':
496 warn('strange colour %s in %s' %
497 (colour,``waritem``))
499 head = waritem.string
501 warn('no head string in '+``waritem``)
503 head = regexp.sub('\\s+', ' ', head).strip()
504 head = head.rstrip(':')
505 how = (head,) + warmap.get(head, (wi_warn,))
507 assert(waritem.name == 'a')
509 debug('WARHOW %s(%s, waritem, *%s)' %
510 (how[1], `how[0]`, `how[2:]`))
511 bad = how[1](how[0], waritem, *how[2:])
513 warn('bad waritem %s: %s: %s' % (`how[0]`,
517 return `(self.name, self.islands, self.relations)`
519 #---------- scraper for ocean info incl. embargoes etc. ----------
521 class IslandBasicInfo():
522 # Public data attributes:
525 # Public data attributes maybe set by caller:
527 def __init__(self, ocean, islename):
531 def q(x): return urllib.quote(x.replace(' ','_'))
532 url_rhs = q(self.name) + '_(' + q(self.ocean) + ')'
533 return yppedia(url_rhs)
535 return `(self.ocean, self.name)`
537 class IslandExtendedInfo(IslandBasicInfo):
538 # Public data attributes (inherited):
541 # Public data attributes (additional):
545 def __init__(self, ocean, islename):
546 IslandBasicInfo.__init__(self, ocean, islename)
548 self.yoweb_url = None
549 self._collect_yoweb()
550 self._collect_flagid()
552 def _collect_yoweb(self):
553 debug('IEI COLLECT YOWEB '+`self.name`)
555 self.yoweb_url = None
557 soup = BeautifulSoup(self.yppedia())
558 content = soup.find('div', attrs = {'id': 'content'})
559 yoweb_re = regexp.compile('^http://\w+\.puzzlepirates\.com/'+
560 'yoweb/island/info\.wm\?islandid=(\d+)$')
561 a = soup.find('a', attrs = { 'href': yoweb_re })
563 debug('IEI COLLECT YOWEB '+`self.name`+' NONE')
566 debug('IEI COLLECT YOWEB '+`self.name`+' GOT '+``a``)
567 self.yoweb_url = a['href']
568 m = yoweb_re.search(self.yoweb_url)
569 self.islandid = m.group(1)
571 def _collect_flagid(self):
575 debug('IEI COLLECT FLAGID '+`self.name`+' URL '+`yo`)
576 if yo is None: return None
577 dataf = fetcher.fetch(yo, 1800)
578 soup = BeautifulSoup(dataf)
579 ruler_re = regexp.compile(
580 '/yoweb/flag/info\.wm\?flagid=(\d+)$')
581 ruler = soup.find('a', attrs = { 'href': ruler_re })
583 debug('IEI COLLECT FLAGID '+`self.name`+' NONE')
585 debug('IEI COLLECT FLAGID '+`self.name`+' GOT '+``ruler``)
586 m = ruler_re.search(ruler['href'])
587 self.flagid = m.group(1)
590 return `(self.ocean, self.islandid, self.name,
591 self.yoweb_url, self.flagid)`
593 class IslandFlagInfo(IslandExtendedInfo):
594 def __init__(self, ocean, islename):
595 IslandExtendedInfo.__init__(self, ocean, islename)
599 def _collect_flag(self):
600 if self.flagid is None: return
601 self.flag = FlagInfo(self.flagid, 1800)
604 return IslandExtendedInfo.__str__(self) + '; ' + str(self.flag)
607 # Public data attributes:
608 # oi.islands[islename] = IslandInfo(...)
609 # oi.arches[archname][islename] = IslandInfo(...)
610 def __init__(self, isleclass=IslandBasicInfo):
611 self.isleclass = isleclass
612 self.ocean = fetcher.ocean.lower().capitalize()
614 cmdl = ['./yppedia-ocean-scraper']
615 if opts.localhtml is not None:
616 cmdl += ['--local-html-dir',opts.localhtml]
618 debug('OceanInfo collect running ' + `cmdl`)
619 oscraper = subprocess.Popen(
621 stdout = subprocess.PIPE,
622 cwd = yppsc_dir()+'/yarrg',
623 shell=False, stderr=None,
625 h = oscraper.stdout.readline()
626 debug('OceanInfo collect h '+`h`)
627 assert(regexp.match('^ocean ', h))
628 arch_re = regexp.compile('^ (\S.*)')
629 island_re = regexp.compile('^ (\S.*)')
635 for l in oscraper.stdout:
636 debug('OceanInfo collect l '+`l`)
638 m = island_re.match(l)
640 assert(archname is not None)
641 islename = m.group(1)
642 isle = self.isleclass(self.ocean, islename)
644 self.islands[islename] = isle
645 self.arches[archname][islename] = isle
649 archname = m.group(1)
650 assert(archname not in self.arches)
651 self.arches[archname] = { }
655 assert(oscraper.returncode == 0)
658 return `(self.islands, self.arches)`
660 #---------- pretty-printer for tables of pirate puzzle standings ----------
662 class StandingsTable:
663 def __init__(self, f, use_puzzles=None, col_width=6, gap_every=5):
664 if use_puzzles is None:
666 use_puzzles=duty_puzzles
669 self._puzzles = use_puzzles
671 self._cw = col_width-1
672 self._gap_every = gap_every
676 def _nl(self): self._o('\n')
678 def _pline(self, lhs, puzstrs, extra):
679 if (self._linecount > 0
680 and self._gap_every is not None
681 and not (self._linecount % self._gap_every)):
683 self._o('%-*s' % (max(max_pirate_namelen+1, 15), lhs))
685 self._o(' %-*.*s' % (self._cw,self._cw, v))
691 def _puzstr(self, pi, puzzle):
692 if not isinstance(puzzle,list): puzzle = [puzzle]
693 try: standing = max([pi.standings[p] for p in puzzle])
694 except KeyError: return '?'
695 if not standing: return ''
698 c1 = standingvals[standing][0]
699 if standing < 3: c1 = c1.lower() # 3 = Master
703 s += '*' * (standing / 2)
704 s += '+' * (standing % 2)
707 def headings(self, lhs='', rhs=None):
708 def puzn_redact(name):
709 if isinstance(name,list):
711 ["%.*s" % (self._cw/2, puzn_redact(n))
714 if spc < 0: return name
715 return name[0:min(4,spc)] + name[spc+1:]
717 self._pline(lhs, map(puzn_redact, self._puzzles), rhs)
719 def literalline(self, line):
723 def pirate_dummy(self, name, standingstring, extra=None):
724 standings = standingstring * len(self._puzzles)
725 self._pline(' '+name, standings, extra)
726 def pirate(self, pi, extra=None):
727 puzstrs = [self._puzstr(pi,puz) for puz in self._puzzles]
728 self._pline(' '+pi.name, puzstrs, extra)
731 #---------- chat log parser ----------
734 # This is essentially a transparent, dumb, data class.
744 # Also used for jobbing applicants:
745 # happens when expires (to "-")
746 # - disembark, leaves crew no
747 # aboard evidence of them being aboard no
748 # applied "has applied for the job" 120s, configurable
749 # ashore "has taken a job" 30min, configurable
750 # declined "declined the job offer" 30s, configurable
751 # invited "has been invited to job" 120s, configurable
753 # pa.jobber None, 'ashore', 'applied', 'invited', 'declined'
754 # pa.expires expiry time time
756 def __init__(pa, pn, v, time, event):
760 pa.last_event = event
761 pa.last_chat_time = None
762 pa.last_chat_chan = None
771 age = now - pa.pi_fetched
772 guide = random.randint(120,240)
775 debug('PirateAboard refresh %d > %d %s' % (
776 age, guide, pa.name))
780 wait = fetcher.need_wait(now, imaginary)
782 debug('PirateAboard fetcher not ready %d' % wait)
784 pa.pi = PirateInfo(pa.name, 600)
788 class ChatLogTracker:
789 # This is quite complex so we make it opaque. Use the
790 # official invokers, accessors etc.
792 def __init__(self, myself_pi, logfn):
793 self._pl = {} # self._pl['Pirate'] =
794 self._vl = {} # self._vl['Vessel']['Pirate'] = PirateAboard
795 # self._vl['Vessel']['#lastinfo']
796 # self._vl['Vessel']['#name']
797 # self._v = self._vl[self._vessel]
799 self._myself = myself_pi
801 self._f = file(logfn)
802 flen = os.fstat(self._f.fileno()).st_size
804 if flen > max_backlog:
805 startpos = flen - max_backlog
806 self._f.seek(startpos)
808 self._progress = [0, flen - self._f.tell()]
809 self._disembark_myself()
810 self._need_redisplay = False
811 self._lastvessel = None
813 def _disembark_myself(self):
816 self.force_redisplay()
818 def force_redisplay(self):
819 self._need_redisplay = True
821 def _vessel_updated(self, v, timestamp):
823 v['#lastinfo'] = timestamp
824 self.force_redisplay()
826 def _onboard_event(self,v,timestamp,pirate,event,jobber=None):
827 pa = self._pl.get(pirate, None)
828 if pa is not None and pa.v is v:
829 pa.last_time = timestamp
830 pa.last_event = event
832 if pa is not None and pa.v is not None:
834 pa = PirateAboard(pirate, v, timestamp, event)
835 self._pl[pirate] = pa
836 if v is not None: v[pirate] = pa
839 if jobber is None: timeout = None
840 else: timeout = getattr(opts, 'timeout_'+jobber)
841 if timeout is None: pa.expires = None
842 else: pa.expires = timestamp + timeout
843 self._vessel_updated(v, timestamp)
846 def _expire_jobbers(self, now):
847 for pa in self._pl.values():
848 if pa.expires is None: continue
849 if pa.expires >= now: continue
851 del self._pl[pa.name]
852 if v is not None: del v[pa.name]
853 self.force_redisplay()
855 def _trash_vessel(self, v):
857 if pn.startswith('#'): continue
861 if v is self._v: self._disembark_myself()
862 self.force_redisplay()
864 def _vessel_stale(self, v, timestamp):
865 return timestamp - v['#lastinfo'] > opts.ship_reboard_clearout
867 def _vessel_check_expire(self, v, timestamp):
868 if not self._vessel_stale(v, timestamp):
870 self._debug_line_disposition(timestamp,'',
871 'stale-reset ' + v['#name'])
872 self._trash_vessel(v)
875 def expire_garbage(self, timestamp):
876 for v in self._vl.values():
877 self._vessel_check_expire(v, timestamp)
879 def _vessel_lookup(self, vn, timestamp, dml=[], create=False):
880 v = self._vl.get(vn, None)
882 v = self._vessel_check_expire(v, timestamp)
889 self._vl[vn] = v = { '#name': vn }
890 self._vessel_updated(v, timestamp)
893 def _find_matching_vessel(self, pattern, timestamp, cmdr,
894 dml=[], create=False):
895 # use when a commander pirate `cmdr' specified a vessel
896 # by name `pattern' (either may be None)
897 # if create is true, will create the vessel
898 # record if an exact name is specified
900 if (pattern is not None and
902 and len(pattern.split(' ')) == 2):
905 return self._vessel_lookup(
906 vn, timestamp, dml=dml, create=create)
909 pattern_check = lambda vn: True
911 re = '(?:.* )?%s$' % pattern.lower().replace('*','.+')
912 pattern_check = regexp.compile(re, regexp.I).match
916 cmdr_pa = self._pl.get(cmdr, None)
917 if cmdr_pa: tries.append((cmdr_pa.v, 'cmdr'))
919 tries.append((self._v, 'here'))
922 for (v, dm) in tries:
923 if v is None: dml.append(dm+'?'); continue
926 if not pattern_check(vn):
934 if pattern is not None and '*' in pattern:
937 for (vn,v) in self._vl.iteritems()
938 if not self._vessel_stale(v, timestamp)
941 #debug('CLT-RE /%s/ wanted (%s) searched (%s)' % (
943 # '/'.join(tried_vns),
944 # '/'.join([vn for (vn,v) in search])))
954 def _debug_line_disposition(self,timestamp,l,m):
955 debug('CLT %13s %-40s %s' % (timestamp,m,l))
957 def _rm_crew_l(self,re,l):
958 m = regexp.match(re,l)
959 if m and m.group(2) == self._myself.crew[1]:
964 def local_command(self, metacmd):
965 # returns None if all went well, or problem message
966 return self._command(self._myself.name, metacmd,
967 "local", time.time(),
968 (lambda m: debug('CMD %s' % metacmd)))
970 def _command(self, cmdr, metacmd, chan, timestamp, d):
971 # returns None if all went well, or problem message
972 metacmd = regexp.sub('\\s+', ' ', metacmd).strip()
974 '/([adj]) (?:([A-Za-z* ]+)\\s*:)?([A-Za-z ]+)$',
976 if not m2: return "unknown syntax or command"
978 (cmd, pattern, targets) = m2.groups()
979 dml = ['cmd', chan, cmd]
981 if cmd == 'a': each = self._onboard_event
982 elif cmd == 'd': each = disembark
983 else: each = lambda *l: self._onboard_event(*l,
984 **{'jobber':'applied'})
986 if cmdr == self._myself.name:
988 how = 'cmd: %s' % cmd
991 how = 'cmd: %s %s' % (cmd,cmdr)
994 if pattern is not None:
995 return "/j command does not take a vessel"
998 v = self._find_matching_vessel(
999 pattern, timestamp, cmdr,
1002 if cmd == 'j' or v is not None:
1003 targets = targets.strip().split(' ')
1004 dml.append(`len(targets)`)
1005 for target in targets:
1006 each(v, timestamp, target.title(), how)
1007 self._vessel_updated(v, timestamp)
1014 def chatline(self,l):
1015 rm = lambda re: regexp.match(re,l)
1016 d = lambda m: self._debug_line_disposition(timestamp,l,m)
1017 rm_crew = lambda re: self._rm_crew_l(re,l)
1020 m = rm('=+ (\\d+)/(\\d+)/(\\d+) =+$')
1022 self._date = [int(x) for x in m.groups()]
1023 self._previous_timestamp = None
1024 return d('date '+`self._date`)
1026 if self._date is None:
1027 return d('date unset')
1029 m = rm('\\[(\d\d):(\d\d):(\d\d)\\] ')
1031 return d('no timestamp')
1034 time_tuple = (self._date +
1035 [int(x) for x in m.groups()] +
1037 timestamp = time.mktime(time_tuple)
1038 if timestamp >= self._previous_timestamp: break
1040 self._debug_line_disposition(timestamp,'',
1041 'new date '+`self._date`)
1043 self._previous_timestamp = timestamp
1045 l = l[l.find(' ')+1:]
1047 def ob_x(pirate,event):
1048 return self._onboard_event(
1049 self._v, timestamp, pirate, event)
1050 def ob1(did): ob_x(m.group(1), did); return d(did)
1051 def oba(did): return ob1('%s %s' % (did, m.group(2)))
1053 def jb(pirate,jobber):
1054 return self._onboard_event(
1055 None, timestamp, pirate,
1056 ("jobber %s" % jobber),
1060 def disembark(v, timestamp, pirate, event):
1061 self._onboard_event(
1062 v, timestamp, pirate, 'leaving '+event)
1064 del self._pl[pirate]
1066 def disembark_me(why):
1067 self._disembark_myself()
1068 return d('disembark-me '+why)
1070 m = rm('Going aboard the (\\S.*\\S)\\.\\.\\.$')
1073 pn = self._myself.name
1075 v = self._vessel_lookup(vn, timestamp, dm, create=True)
1076 self._lastvessel = self._vessel = vn
1078 ob_x(pn, 'we boarded')
1079 self.expire_garbage(timestamp)
1080 return d(' '.join(dm))
1083 return d('no vessel')
1085 m = rm('(\\w+) has come aboard\\.$')
1086 if m: return ob1('boarded');
1088 m = rm('You have ordered (\\w+) to do some (\\S.*\\S)\\.$')
1090 (who,what) = m.groups()
1091 pa = ob_x(who,'ord '+what)
1092 if what == 'Gunning':
1094 return d('duty order')
1096 m = rm('(\\w+) abandoned a (\\S.*\\S) station\\.$')
1097 if m: oba('stopped'); return d("end")
1099 def chat_core(speaker, chan):
1100 try: pa = self._pl[speaker]
1101 except KeyError: return 'mystery'
1102 if pa.v is not None and pa.v is not self._v:
1104 pa.last_chat_time = timestamp
1105 pa.last_chat_chan = chan
1106 self.force_redisplay()
1110 speaker = m.group(1)
1111 dm = chat_core(speaker, chan)
1112 return d('chat %s %s' % (chan, dm))
1114 def chat_metacmd(chan):
1115 (cmdr, metacmd) = m.groups()
1116 whynot = self._command(
1117 cmdr, metacmd, chan, timestamp, d)
1118 if whynot is not None:
1121 chat_core(cmdr, 'cmd '+chan)
1123 m = rm('(\\w+) (?:issued an order|ordered everyone) "')
1124 if m: return ob1('general order');
1126 m = rm('(\\w+) says, "')
1127 if m: return chat('public')
1129 m = rm('(\\w+) tells ye, "')
1130 if m: return chat('private')
1132 m = rm('Ye told (\\w+), "(.*)"$')
1133 if m: return chat_metacmd('private')
1135 m = rm('(\\w+) flag officer chats, "')
1136 if m: return chat('flag officer')
1138 m = rm('(\\w+) officer chats, "(.*)"$')
1139 if m: return chat_metacmd('officer')
1141 m = rm('Ye accepted the offer to job with ')
1142 if m: return disembark_me('jobbing')
1144 m = rm('Ye hop on the ferry and are whisked away ')
1145 if m: return disembark_me('ferry')
1147 m = rm('Whisking away to yer home on the magical winds')
1148 if m: return disembark_me('home')
1150 m = rm('Game over\\. Winners: ([A-Za-z, ]+)\\.$')
1152 pl = m.group(1).split(', ')
1153 if not self._myself.name in pl:
1154 return d('lost melee')
1156 if ' ' in pn: continue
1157 ob_x(pn,'won melee')
1158 return d('won melee')
1160 m = rm('(\\w+) is eliminated\\!')
1161 if m: return ob1('eliminated in fray');
1163 m = rm('(\\w+) has driven \w+ from the ship\\!')
1164 if m: return ob1('boarder repelled');
1166 m = rm('\w+ has bested (\\w+), and turns'+
1167 ' to the rest of the ship\\.')
1168 if m: return ob1('boarder unrepelled');
1170 pirate = rm_crew("(\\w+) has taken a job with '(.*)'\\.")
1171 if pirate: return jb(pirate, 'ashore')
1173 pirate = rm_crew("(\\w+) has left '(.*)'\\.")
1175 disembark(self._v, timestamp, pirate, 'left crew')
1176 return d('left crew')
1178 m = rm('(\w+) has applied for the posted job\.')
1179 if m: return jb(m.group(1), 'applied')
1181 pirate= rm_crew("(\\w+) has been invited to job for '(.*)'\\.")
1182 if pirate: return jb(pirate, 'invited')
1184 pirate = rm_crew("(\\w+) declined the job offer for '(.*)'\\.")
1185 if pirate: return jb(pirate, 'declined')
1187 m = rm('(\\w+) has left the vessel\.')
1190 disembark(self._v, timestamp, pirate, 'disembarked')
1191 return d('disembarked')
1193 return d('not-matched')
1195 def _str_pa(self, pn, pa):
1196 assert self._pl[pn] == pa
1197 s = ' '*20 + "%s %-*s %13s %-30s %13s %-20s %13s" % (
1198 (' ','G')[pa.gunner],
1199 max_pirate_namelen, pn,
1200 pa.last_time, pa.last_event,
1201 pa.last_chat_time, pa.last_chat_chan,
1203 if pa.expires is not None:
1204 s += " %-5d" % (pa.expires - pa.last_time)
1208 def _str_vessel(self, vn, v):
1209 s = ' vessel %s\n' % vn
1210 s += ' '*20 + "%-*s %13s\n" % (
1211 max_pirate_namelen, '#lastinfo',
1213 assert v['#name'] == vn
1214 for pn in sorted(v.keys()):
1215 if pn.startswith('#'): continue
1218 s += self._str_pa(pn,pa)
1222 s = '''<ChatLogTracker
1225 ''' % (self._myself.name, self._vessel)
1226 assert ((self._v is None and self._vessel is None) or
1227 (self._v is self._vl[self._vessel]))
1228 if self._vessel is not None:
1229 s += self._str_vessel(self._vessel, self._v)
1230 for vn in sorted(self._vl.keys()):
1231 if vn == self._vessel: continue
1232 s += self._str_vessel(vn, self._vl[vn])
1236 if pa.v is not None:
1237 assert pa.v[p] is pa
1238 assert pa.v in self._vl.values()
1240 s += self._str_pa(pa.name, pa)
1244 def catchup(self, progress=None):
1246 more = self._f.readline()
1249 self._progress[0] += len(more)
1250 if progress: progress.progress(*self._progress)
1253 if self._lbuf.endswith('\n'):
1254 self.chatline(self._lbuf.rstrip())
1257 debug(self.__str__())
1258 self._expire_jobbers(time.time())
1260 if progress: progress.caughtup()
1263 rv = self._need_redisplay
1264 self._need_redisplay = False
1267 # returns our pirate name
1268 return self._myself.name
1269 def vesselname(self):
1270 # returns the vessel name we're aboard or None
1272 def lastvesselname(self):
1273 # returns the last vessel name we were aboard or None
1274 return self._lastvessel
1275 def aboard(self, vesselname=True):
1276 # returns a list of PirateAboard the vessel
1277 # sorted by pirate name
1278 # you can pass this None and you'll get []
1279 # or True for the current vessel (which is the default)
1280 # the returned value is a fresh list of persistent
1281 # PirateAboard objects
1282 if vesselname is True: v = self._v
1283 else: v = self._vl.get(vesselname.title())
1284 if v is None: return []
1286 for pn in sorted(v.keys())
1287 if not pn.startswith('#') ]
1289 # returns a the jobbers' PirateAboards,
1290 # sorted by jobber class and reverse of expiry time
1292 for pa in self._pl.values()
1293 if pa.jobber is not None
1296 return (pa.jobber, -pa.expires)
1297 l.sort(key = compar_key)
1300 #---------- implementations of actual operation modes ----------
1302 def do_pirate(pirates, bu):
1304 for pirate in pirates:
1305 info = PirateInfo(pirate)
1306 print '%s: %s,' % (`pirate`, info)
1309 def prep_crew_of(args, bu, max_age=300):
1310 if len(args) != 1: bu('crew-of takes one pirate name')
1311 pi = PirateInfo(args[0], max_age)
1312 if pi.crew is None: return None
1313 return CrewInfo(pi.crew[0], max_age)
1315 def do_crew_of(args, bu):
1316 ci = prep_crew_of(args, bu)
1319 def do_flag_of(args, bu):
1320 if len(args) != 1: bu('flag-of takes one pirate name')
1322 pi = PirateInfo(args[0], max_age)
1323 if pi.flag is None: fi = None
1324 else: fi = FlagInfo(pi.flag[0], max_age)
1327 def do_standings_crew_of(args, bu):
1328 ci = prep_crew_of(args, bu, 60)
1329 tab = StandingsTable(sys.stdout)
1331 for (rank, members) in ci.crew:
1332 if not members: continue
1334 tab.literalline('%s:' % rank)
1336 pi = PirateInfo(p, random.randint(900,1800))
1339 def do_ocean(args, bu):
1340 if (len(args)): bu('ocean takes no further arguments')
1341 fetcher.default_ocean()
1342 oi = OceanInfo(IslandFlagInfo)
1344 for islename in sorted(oi.islands.keys()):
1345 isle = oi.islands[islename]
1348 #----- modes which use the chat log parser are quite complex -----
1350 class ProgressPrintPercentage:
1351 def __init__(self, f=sys.stdout):
1353 def progress_string(self,done,total):
1354 return "scan chat logs %3d%%\r" % ((done*100) / total)
1355 def progress(self,*a):
1356 self._f.write(self.progress_string(*a))
1358 def show_init(self, pirate, ocean):
1359 print >>self._f, 'Starting up, %s on the %s ocean' % (
1362 self._f.write(' \r')
1365 def prep_chat_log(args, bu,
1366 progress=ProgressPrintPercentage(),
1367 max_myself_age=3600):
1368 if len(args) != 1: bu('this action takes only chat log filename')
1370 logfn_re = '(?:.*/)?([A-Z][a-z]+)_([a-z]+)_'
1371 match = regexp.match(logfn_re, logfn)
1372 if not match: bu('chat log filename is not in expected format')
1373 (pirate, ocean) = match.groups()
1374 fetcher.default_ocean(ocean)
1376 progress.show_init(pirate, fetcher.ocean)
1377 myself = PirateInfo(pirate,max_myself_age)
1378 track = ChatLogTracker(myself, logfn)
1381 track.catchup(progress)
1384 track.force_redisplay()
1386 return (myself, track)
1388 def do_track_chat_log(args, bu):
1389 (myself, track) = prep_chat_log(args, bu)
1394 sleep(0.5 + 0.5 * random.random())
1396 #----- ship management aid -----
1398 class Display_dumb(ProgressPrintPercentage):
1400 ProgressPrintPercentage.__init__(self)
1403 def realstart(self):
1406 class Display_overwrite(ProgressPrintPercentage):
1408 ProgressPrintPercentage.__init__(self)
1410 null = file('/dev/null','w')
1411 curses.setupterm(fd=null.fileno())
1413 self._clear = curses.tigetstr('clear')
1415 self._debug('missing clear!')
1416 self.show = Display_dumb.show
1419 self._t = {'el':'', 'ed':''}
1420 if not self._init_sophisticated():
1421 for k in self._t.keys(): self._t[k] = ''
1422 self._t['ho'] = self._clear
1424 def _debug(self,m): debug('display overwrite: '+m)
1426 def _init_sophisticated(self):
1427 for k in self._t.keys():
1428 s = curses.tigetstr(k)
1430 self._t['ho'] = curses.tigetstr('ho')
1431 if not self._t['ho']:
1432 cup = curses.tigetstr('cup')
1433 self._t['ho'] = curses.tparm(cup,0,0)
1434 missing = [k for k in self._t.keys() if not self._t[k]]
1436 self.debug('missing '+(' '.join(missing)))
1441 w = sys.stdout.write
1442 def wti(k): w(self._t[k])
1446 for l in s.rstrip().split('\n'):
1455 def realstart(self):
1456 sys.stdout.write(self._clear)
1460 def do_ship_aid(args, bu):
1461 if opts.ship_duty is None: opts.ship_duty = True
1463 displayer = globals()['Display_'+opts.display]()
1465 (myself, track) = prep_chat_log(args, bu, progress=displayer)
1467 displayer.realstart()
1469 if os.isatty(0): kr_create = KeystrokeReader
1470 else: kr_create = DummyKeystrokeReader
1473 kreader = kr_create(0, 10)
1474 ship_aid_core(myself, track, displayer, kreader)
1479 class KeyBasedSorter:
1480 def compar_key_pa(self, pa):
1481 pi = pa.pirate_info()
1482 if pi is None: return None
1483 return self.compar_key(pi)
1484 def lsort_pa(self, l):
1485 l.sort(key = self.compar_key_pa)
1487 class NameSorter(KeyBasedSorter):
1488 def compar_key(self, pi): return pi.name
1489 def desc(self): return 'name'
1491 class SkillSorter(NameSorter):
1492 def __init__(self, relevant):
1493 self._want = frozenset(relevant.split('/'))
1495 for p in core_duty_puzzles:
1496 if isinstance(p,basestring): self._avoid.add(p)
1497 else: self._avoid |= set(p)
1498 self._avoid -= self._want
1499 self._desc = '%s' % relevant
1501 def desc(self): return self._desc
1503 def compar_key(self, pi):
1505 pi.standings.get(puz,-1)
1506 for puz in self._want
1509 -pi.standings.get(puz,standing_limit)
1510 for puz in self._avoid
1513 def negate(x): return -x
1514 debug('compar_key %s bw=%s ba=%s' % (pi.name, `best_want`,
1516 return (-best_want, map(negate, best_avoid), pi.name)
1518 def ship_aid_core(myself, track, displayer, kreader):
1521 vn = track.vesselname()
1522 if vn: return (vn, " on board the %s" % vn)
1523 vn = track.lastvesselname()
1524 if vn: return (vn, " ashore from the %s" % vn)
1525 return (None, " not on a vessel")
1528 if t is None: return ' ' * 22
1529 return " %-4s %-16s" % (format_time_interval(now - t),e)
1531 displayer.show(track.myname() + find_vessel()[1] + '...')
1544 (vn, vs) = find_vessel()
1547 if cliexec is not None:
1549 elif clierr is not None:
1550 s += 'Error: '+clierr
1551 elif clicmd is not None:
1554 s = track.myname() + vs
1555 s += " at %s" % time.strftime("%Y-%m-%d %H:%M:%S")
1560 tbl = StandingsTable(tbl_s)
1562 aboard = track.aboard(vn)
1563 sort.lsort_pa(aboard)
1565 jobbers = track.jobbers()
1567 if track.vesselname(): howmany = 'aboard: %2d' % len(aboard)
1570 tbl.headings(howmany, ' sorted by '+sort.desc())
1574 for pa in aboard + jobbers:
1575 if pa.jobber != last_jobber:
1576 last_jobber = pa.jobber
1578 tbl.literalline('jobbers '+last_jobber)
1580 pi = pa.pirate_info()
1583 if pa.gunner: xs += 'G '
1585 xs += timeevent(pa.last_time, pa.last_event)
1586 xs += timeevent(pa.last_chat_time, pa.last_chat_chan)
1589 tbl.pirate_dummy(pa.name, rotate_nya[0], xs)
1593 s += tbl_s.getvalue()
1597 if cliexec is not None:
1598 clierr = track.local_command("/"+cliexec.strip())
1604 rotate_nya = rotate_nya[1:3] + rotate_nya[0]
1607 if clierr is not None:
1611 if clicmd is not None:
1612 if k == '\r' or k == '\n':
1615 elif k == '\e' and clicmd != "":
1619 elif k == '\b' or k == '\177':
1620 clicmd = clicmd[ 0 : len(clicmd)-1 ]
1626 elif k == 'g': sort = SkillSorter('Gunning')
1627 elif k == 'c': sort = SkillSorter('Carpentry')
1628 elif k == 's': sort = SkillSorter('Sailing/Rigging')
1629 elif k == 'b': sort = SkillSorter('Bilging')
1630 elif k == 'n': sort = SkillSorter('Navigating')
1631 elif k == 'd': sort = SkillSorter('Battle Navigation')
1632 elif k == 't': sort = SkillSorter('Treasure Haul')
1633 elif k == 'a': sort = NameSorter()
1634 elif k == '/': clicmdbase = ""; clicmd = clicmdbase
1635 elif k == '+': clicmdbase = "a "; clicmd = clicmdbase
1636 else: pass # unknown key command
1638 #---------- individual keystroke input ----------
1640 class DummyKeystrokeReader:
1641 def __init__(self,fd,timeout_dummy): pass
1642 def stop(self): pass
1643 def getch(self): sleep(1); return None
1644 def info(self): return ' [noninteractive]'
1646 class KeystrokeReader(DummyKeystrokeReader):
1647 def __init__(self, fd, timeout_decisec=0):
1649 self._saved = termios.tcgetattr(fd)
1650 a = termios.tcgetattr(fd)
1651 a[3] &= ~(termios.ECHO | termios.ECHONL |
1652 termios.ICANON | termios.IEXTEN)
1653 a[6][termios.VMIN] = 0
1654 a[6][termios.VTIME] = timeout_decisec
1655 termios.tcsetattr(fd, termios.TCSANOW, a)
1657 termios.tcsetattr(self._fd, termios.TCSANOW, self._saved)
1660 byte = os.read(self._fd, 1)
1661 if not len(byte): return None
1666 #---------- main program ----------
1669 global opts, fetcher, yppedia
1672 '''usage: .../yoweb-scrape [OPTION...] ACTION [ARGS...]
1674 yoweb-scrape [--ocean OCEAN ...] pirate PIRATE
1675 yoweb-scrape [--ocean OCEAN ...] crew-of PIRATE
1676 yoweb-scrape [--ocean OCEAN ...] standings-crew-of PIRATE
1677 yoweb-scrape [--ocean OCEAN ...] track-chat-log CHAT-LOG
1678 yoweb-scrape [options] ship-aid CHAT-LOG (must be .../PIRATE_OCEAN_chat-log*)
1680 display modes (for --display) apply to ship-aid:
1681 --display=dumb just print new information, scrolling the screen
1682 --display=overwrite use cursor motion, selective clear, etc. to redraw at top''')
1684 ao('-O','--ocean',dest='ocean', metavar='OCEAN', default=None,
1685 help='select ocean OCEAN')
1686 ao('--cache-dir', dest='cache_dir', metavar='DIR',
1687 default='~/.yoweb-scrape-cache',
1688 help='cache yoweb pages in DIR')
1689 ao('-D','--debug', action='count', dest='debug', default=0,
1690 help='enable debugging output')
1691 ao('--debug-fd', type='int', dest='debug_fd',
1692 help='write any debugging output to specified fd')
1693 ao('-q','--quiet', action='store_true', dest='quiet',
1694 help='suppress warning output')
1695 ao('--display', action='store', dest='display',
1696 type='choice', choices=['dumb','overwrite'],
1697 help='how to display ship aid')
1698 ao('--local-ypp-dir', action='store', dest='localhtml',
1699 help='get yppedia pages from local directory LOCALHTML'+
1700 ' instead of via HTTP')
1702 ao_jt = lambda wh, t: ao(
1703 '--timeout-sa-'+wh, action='store', dest='timeout_'+wh,
1704 default=t, help=('set timeout for expiring %s jobbers' % wh))
1705 ao_jt('applied', 120)
1706 ao_jt('invited', 120)
1707 ao_jt('declined', 30)
1708 ao_jt('ashore', 1800)
1710 ao('--ship-duty', action='store_true', dest='ship_duty',
1711 help='show ship duty station puzzles')
1712 ao('--all-puzzles', action='store_false', dest='ship_duty',
1713 help='show all puzzles, not just ship duty stations')
1715 ao('--min-cache-reuse', type='int', dest='min_max_age',
1716 metavar='SECONDS', default=60,
1717 help='always reuse cache yoweb data if no older than this')
1719 (opts,args) = pa.parse_args()
1723 print >>sys.stderr, copyright_info
1724 pa.error('need a mode argument')
1726 if opts.debug_fd is not None:
1727 opts.debug_file = os.fdopen(opts.debug_fd, 'w')
1729 opts.debug_file = sys.stdout
1732 mode_fn_name = 'do_' + mode.replace('_','#').replace('-','_')
1733 try: mode_fn = globals()[mode_fn_name]
1734 except KeyError: pa.error('unknown mode "%s"' % mode)
1737 opts.expire_age = max(3600, opts.min_max_age)
1739 opts.ship_reboard_clearout = 3600
1741 if opts.cache_dir.startswith('~/'):
1742 opts.cache_dir = os.getenv('HOME') + opts.cache_dir[1:]
1744 if opts.display is None:
1745 if ((opts.debug > 0 and opts.debug_fd is None)
1746 or not os.isatty(sys.stdout.fileno())):
1747 opts.display = 'dumb'
1749 opts.display = 'overwrite'
1751 fetcher = Yoweb(opts.ocean, opts.cache_dir)
1752 yppedia = Yppedia(opts.cache_dir)
1754 mode_fn(args[1:], pa.error)