rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
replacements.append((templateR, ''))
|
replacements.append((templateRegex, ''))
|
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapitalize: old = '[' + self.old[0].upper() + self.old[0].lower() + ']' + self.old[1:] else: old = self.old old = re.sub('[_ ]', '[_ ]', old) templateR=re.compile(r'\{\{([mM][sS][gG]:)?' + old + '(?P<parameters>\|[^}]+|)}}') replacements = [] if self.remove: replacements.append((templateR, '')) elif self.resolve: replacements.append((templateR, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateR, '{{' + self.new + '\g<parameters>}}')) replaceBot = replace.ReplaceRobot(self.generator, replacements) replaceBot.run()
|
replacements.append((templateR, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateR, '{{' + self.new + '\g<parameters>}}'))
|
replacements.append((templateRegex, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateRegex, '{{' + self.new + '\g<parameters>}}'))
|
def run(self): # regular expression to find the original template. # {{msg:vfd}} does the same thing as {{msg:Vfd}}, so both will be found. # The new syntax, {{vfd}}, will also be found. # The group 'parameters' will either match the parameters, or an # empty string if there are none. if not wikipedia.getSite().nocapitalize: old = '[' + self.old[0].upper() + self.old[0].lower() + ']' + self.old[1:] else: old = self.old old = re.sub('[_ ]', '[_ ]', old) templateR=re.compile(r'\{\{([mM][sS][gG]:)?' + old + '(?P<parameters>\|[^}]+|)}}') replacements = [] if self.remove: replacements.append((templateR, '')) elif self.resolve: replacements.append((templateR, '{{subst:' + self.old + '\g<parameters>}}')) else: replacements.append((templateR, '{{' + self.new + '\g<parameters>}}')) replaceBot = replace.ReplaceRobot(self.generator, replacements) replaceBot.run()
|
gen = XmlTemplatePageGenerator(oldTemplate, xmlfilename)
|
gen = XmlDumpTemplatePageGenerator(oldTemplate, xmlfilename)
|
def main(): template_names = [] resolve = False remove = False # If xmlfilename is None, references will be loaded from the live wiki. xmlfilename = None new = None # read command line parameters for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, 'template') if arg: if arg == '-remove': remove = True elif arg.startswith('-xml'): if len(arg) == 4: xmlfilename = wikipedia.input(u'Please enter the XML dump\'s filename: ') else: xmlfilename = arg[5:] else: template_names.append(arg) if len(template_names) == 0 or len(template_names) > 2: wikipedia.showHelp('template') sys.exit() old = template_names[0] if len(template_names) == 2: new = template_names[1] mysite = wikipedia.getSite() ns = mysite.template_namespace() oldTemplate = wikipedia.Page(mysite, ns + ':' + old) if xmlfilename: gen = XmlTemplatePageGenerator(oldTemplate, xmlfilename) else: gen = pagegenerators.ReferringPageGenerator(oldTemplate, onlyTemplateInclusion = True) preloadingGen = pagegenerators.PreloadingGenerator(gen) bot = TemplateRobot(preloadingGen, old, new, remove) bot.run()
|
pass
|
print "NOTE: %s does not exist"% pl.asasciilink() except wikipedia.SubpageError: print "NOTE: %s subpage does not exist"% pl.asasciilink()
|
def workDone(self, counter): """This is called by a worker to tell us that the promised work was completed as far as possible. The only argument is an instance of a counter class, that has methods minus() and plus() to keep counts of the total work todo.""" # Loop over all the pages that should have been taken care of for pl in self.pending: # Mark the page as done self.done[pl] = pl.code() # Register this fact at the todo-counter. counter.minus(pl.code()) # Now check whether any interwiki links should be added to the # todo list. if unequal.bigger(pl, self.inpl): print "NOTE: %s is bigger than %s, not following references" % (pl, self.inpl) else: try: iw = pl.interwiki() except wikipedia.IsRedirectPage,arg: pl3 = wikipedia.PageLink(pl.code(),arg.args[0]) print "NOTE: %s is redirect to %s"% (pl.asasciilink(), pl3.asasciilink()) self.conditionalAdd(pl3, counter) except wikipedia.NoPage: pass else: for pl2 in iw: self.conditionalAdd(pl2, counter) # These pages are no longer 'in progress' del self.pending # Check whether we need hints and the user offered to give them if len(self.done) == 1 and len(self.todo) == 0 and globalvar.untranslated: if globalvar.bell: sys.stdout.write('\07') print "%s does not have any interwiki links"%self.inpl.asasciilink() newhint = raw_input("Hint:") if newhint: arr = {} titletranslate.translate(pl, arr, same = False, hints = [newhint]) for pl in arr.iterkeys(): self.todo[pl] = pl.code()
|
if code == wikipedia.mylang and self.done[pl] is not None:
|
if code == wikipedia.mylang and pl.exists() and not pl.isRedirectPage():
|
def finish(self): """Round up the subject, making any necessary changes. This method should be called exactly once after the todo list has gone empty.""" if self.inpl.isRedirectPage(): return if not self.isDone(): raise "Bugcheck: finish called before done" print "======Post-processing %s======"%(self.inpl.asasciilink()) # Assemble list of accepted interwiki links new = {} for pl in self.done.keys(): code = pl.code() if code == wikipedia.mylang and self.done[pl] is not None: if pl != self.inpl: self.problem('Someone refers to %s with us' % pl.asasciilink()) elif pl.exists() and not pl.isRedirectPage(): if new.has_key(code) and new[code] != pl: self.problem("'%s' as well as '%s'" % (new[code].asasciilink(), pl.asasciilink())) if globalvar.autonomous: return while 1: if globalvar.bell: sys.stdout.write('\07') answer = raw_input("Use (f)ormer or (l)atter or (n)either or (g)ive up?") if answer.startswith('f'): break elif answer.startswith('l'): new[pl.code()] = pl break elif answer.startswith('n'): new[pl.code()] = None break elif answer.startswith('g'): # Give up return elif code in ('zh-tw','zh-cn') and new.has_key('zh') and new['zh'] is not None: print "NOTE: Ignoring %s, using %s"%(new['zh'].asasciilink(),pl.asasciilink()) new['zh'] = None # Remove the global zh link new[code] = pl # Add the more precise one elif code == 'zh' and ( (new.has_key('zh-tw') and new['zh-tw'] is not None) or (new.has_key('zh-cn') and new['zh-cn'] is not None)): print "NOTE: Ignoring %s"%(pl.asasciilink()) pass # do not add global zh if there is a specific zh-tw or zh-cn elif code not in new: new[code] = pl
|
self.add(self.generator.next())
|
pl=self.generator.next() while pl in globalvar.skip: pl=self.generator.next() self.add(pl)
|
def generateMore(self, number): """Generate more subjects. This is called internally when the list of subjects becomes to small, but only if there is a generator""" fs = self.firstSubject() if fs: print "NOTE: The first unfinished subject is:", fs.pl().asasciilink() print "NOTE: Number of pages queued is %d, trying to add %d more."%( len(self.subjects), number) for i in range(number): try: self.add(self.generator.next()) except StopIteration: self.generator = None break
|
except KeyboardInterrupt: print "Process was interrupted." print "The first unfinished subject is:",sa.firstSubject().pl().asasciilink()
|
except: sa.dump('interwiki.dump')
|
def compareLanguages(old, new): removing = [] adding = [] modifying = [] for code in old.keys(): if code not in new.keys(): removing.append(code) elif old[code] != new[code]: modifying.append(code) for code2 in new.keys(): if code2 not in old.keys(): adding.append(code2) s = "" if adding: s = s + " %s:" % (msg[msglang][0]) + ",".join(adding) if removing: s = s + " %s:" % (msg[msglang][1]) + ",".join(removing) if modifying: s = s + " %s:" % (msg[msglang][2]) + ",".join(modifying) return s,removing
|
'_default': [u'Memory Alpha', self.namespaces[4]['_default']],
|
'_default': u'Memory Alpha',
|
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'Memory Alpha talk', self.namespaces[5]['_default']], 'de': u'Memory Alpha Diskussion', 'nl': u'Overleg Memory Alpha', 'sv': u'Memory Alphadiskussion', } # A few selected big languages for things that we do not want to loop over # all languages. This is only needed by the titletranslate.py module, so # if you carefully avoid the options, you could get away without these # for another wiki family. self.languages_by_size = ['en', 'de', 'nl', 'sv']
|
'_default': [u'Memory Alpha talk', self.namespaces[5]['_default']],
|
'_default': u'Memory Alpha talk',
|
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'Memory Alpha talk', self.namespaces[5]['_default']], 'de': u'Memory Alpha Diskussion', 'nl': u'Overleg Memory Alpha', 'sv': u'Memory Alphadiskussion', } # A few selected big languages for things that we do not want to loop over # all languages. This is only needed by the titletranslate.py module, so # if you carefully avoid the options, you could get away without these # for another wiki family. self.languages_by_size = ['en', 'de', 'nl', 'sv']
|
self.languages_by_size = ['en', 'de', 'nl', 'sv']
|
self.languages_by_size = ['en', 'de', 'es', 'nl', 'sv', 'fr', 'eo', 'pl'] alphabetic = ['de', 'en', 'es', 'eo', 'fr', 'nl', 'pl', 'sv']
|
def __init__(self): family.Family.__init__(self) self.name = 'memoryalpha' self.langs = { 'de': None, 'en': None, 'nl': None, 'sv': None, } # Most namespaces are inherited from family.Family. self.namespaces[4] = { '_default': [u'Memory Alpha', self.namespaces[4]['_default']], } self.namespaces[5] = { '_default': [u'Memory Alpha talk', self.namespaces[5]['_default']], 'de': u'Memory Alpha Diskussion', 'nl': u'Overleg Memory Alpha', 'sv': u'Memory Alphadiskussion', } # A few selected big languages for things that we do not want to loop over # all languages. This is only needed by the titletranslate.py module, so # if you carefully avoid the options, you could get away without these # for another wiki family. self.languages_by_size = ['en', 'de', 'nl', 'sv']
|
def __init__(self, title, url):
|
def __init__(self, title, url, history):
|
def __init__(self, title, url): threading.Thread.__init__(self) self.title = title self.url = url
|
self.history = history
|
def __init__(self, title, url): threading.Thread.__init__(self) self.title = title self.url = url
|
|
if not ok:
|
if ok: self.history.linkAlive(self.url) pass else:
|
def run(self): linkChecker = LinkChecker(self.url) ok, message = linkChecker.check() if not ok: wikipedia.output('*[[%s]] links to %s - %s' % (self.title, self.url, message))
|
self.history.linkDead(self.url, message, self.title) class History: ''' Stores previously found dead links. The URLs are dict's keys, and values are lists of tuples where each tuple represents one time the URL was found dead. Tuples have the form (title, date, error) where title is the wiki page where the URL was found, date is an instance of time, and error is a string with error code and message. We assume that the first element in the list represents the first time we found this dead link, and the last element represents the last time. Example: dict = { 'http://www.example.org/page': [ ('WikiPageTitle', DATE, '404: File not found'), ('WikiPageName2', DATE, '404: File not found'), ] ''' def __init__(self): site = wikipedia.getSite() self.datfilename = 'deadlinks/deadlinks-%s-%s.dat' % (site.family.name, site.lang) try: datfile = open(self.datfilename, 'r') self.dict = pickle.load(datfile) datfile.close() except (IOError, EOFError): self.dict = {} def log(self, url, error, containingPage): site = wikipedia.getSite() wikipedia.output(u"** Logging page for deletion.") txtfilename = 'deadlinks/delete-%s-%s.txt' % (site.family.name, site.lang) txtfile = codecs.open(txtfilename, 'a', 'utf-8') txtfile.write("* %s\n" % url) for (title, date, error) in self.dict[url]: txtfile.write("** In [[%s]] on %s, %s\n" % (title, time.ctime(date), error)) txtfile.close() def linkDead(self, url, error, containingPage): now = time.time() if self.dict.has_key(url): timeSinceFirstFound = now - self.dict[url][0][1] timeSinceLastFound= now - self.dict[url][-1][1] if timeSinceLastFound > 60 * 60: self.dict[url].append((containingPage, now, error)) if timeSinceFirstFound > 60 * 60 * 24 * 7: self.log(url, error, containingPage) else: self.dict[url] = [(containingPage, now, error)] def linkAlive(self, url): if self.dict.has_key(url): del self.dict[url] def save(self): datfile = open(self.datfilename, 'w') self.dict = pickle.dump(self.dict, datfile) datfile.close()
|
def run(self): linkChecker = LinkChecker(self.url) ok, message = linkChecker.check() if not ok: wikipedia.output('*[[%s]] links to %s - %s' % (self.title, self.url, message))
|
|
self.history = History()
|
def __init__(self, generator, start ='!'): self.generator = generator self.start = start
|
|
for (title, text) in self.generator.generate(): self.checkLinksIn(title, text)
|
try: for (title, text) in self.generator.generate(): self.checkLinksIn(title, text) except: if threading.activeCount() > 1: wikipedia.output(u"Waiting for remaining %i threads to finish, please wait..." % threading.activeCount()) time.sleep(5) if threading.activeCount() > 1: wikipedia.output(u"Killing remaining %i threads..." % threading.activeCount())
|
def run(self): for (title, text) in self.generator.generate(): self.checkLinksIn(title, text)
|
while threading.activeCount() >= 10:
|
while threading.activeCount() >= 50:
|
def checkLinksIn(self, title, text): #wikipedia.output(title) linkR = re.compile(r'http://[^ \]\r\n]+') urls = linkR.findall(text) for url in urls: # Don't start more than 10 threads at once. Each thread will check # one page, then die. # TODO: Make number of threads a config variable. while threading.activeCount() >= 10: # wait 100 ms time.sleep(0.1) thread = LinkCheckThread(title, url) thread.start()
|
thread = LinkCheckThread(title, url)
|
thread = LinkCheckThread(title, url, self.history) thread.setDaemon(True)
|
def checkLinksIn(self, title, text): #wikipedia.output(title) linkR = re.compile(r'http://[^ \]\r\n]+') urls = linkR.findall(text) for url in urls: # Don't start more than 10 threads at once. Each thread will check # one page, then die. # TODO: Make number of threads a config variable. while threading.activeCount() >= 10: # wait 100 ms time.sleep(0.1) thread = LinkCheckThread(title, url) thread.start()
|
bot.run()
|
try: bot.run() finally: bot.history.save()
|
def main(): start = '!' sqlfilename = None for arg in sys.argv[1:]: arg = wikipedia.argHandler(arg, logname = 'weblinkchecker.log') if arg: if arg.startswith('-sql'): if len(arg) == 4: sqlfilename = wikipedia.input(u'Please enter the SQL dump\'s filename: ') else: sqlfilename = arg[5:] source = sqlfilename elif arg.startswith('-start:'): start = arg[7:] else: print 'Unknown argument: %s' % arg if sqlfilename: gen = SqlPageGenerator(sqlfilename) else: gen = AllpagesPageGenerator(start) bot = WeblinkCheckerRobot(gen) bot.run()
|
print name
|
def getPage(code, name): """Get the contents of page 'name' from the 'code' language wikipedia""" host = langs[code] if host[-4:]=='.com': # Old algorithm name = re.sub('_', ' ', name) n=[] for x in name.split(): n.append(x.capitalize()) name='_'.join(n) print name else: name = re.sub(' ', '_', name) if not '%' in name: # It should not have been done yet if name!=urllib.quote(name): print "DBG> quoting",name name = urllib.quote(name) if host[-4:] == '.org': # New software address = '/w/wiki.phtml?title='+name+'&action=edit' elif host[-4:]=='.com': # Old software address = '/wiki.cgi?action=edit&id='+name if debug: print host,address text,charset = getUrl(host,address) if debug: print "Raw:",len(text),type(text),text.count('x') if charset is None: print "WARNING: No character set found" else: # Store character set for later reference if charsets.has_key(code): assert charsets[code]==charset charsets[code]=charset if debug>1: print repr(text) m = re.search('value="(\d+)" name=\'wpEdittime\'',text) if m: edittime[code,space2underline(name)]=m.group(1) else: m = re.search('value="(\d+)" name="wpEdittime"',text) if m: edittime[code,name]=m.group(1) else: edittime[code,name]=0 try: i1 = re.search('<textarea[^>]*>',text).end() except AttributeError: print "No text area.",host,address raise NoPage() i2 = re.search('</textarea>',text).start() if i2-i1 < 2: # new software raise NoPage() if debug: print text[i1:i2] if text[i1:i2] == 'Describe the new page here.\n': # old software raise NoPage() Rredirect=re.compile(r'\#redirect:? *\[\[(.*?)\]\]',re.I) m=Rredirect.match(text[i1:i2]) if m: raise IsRedirectPage(m.group(1)) assert edittime[code,name]!=0 or host[-4:]=='.com', "No edittime on non-empty page?! %s:%s\n%s"%(code,name,text) x=text[i1:i2] x=unescape(x) if charset=='utf-8': # Make it to a unicode string encode_func, decode_func, stream_reader, stream_writer = codecs.lookup('utf-8') x,l=decode_func(x) # Convert the unicode characters to &# references, and make it ascii. x=str(UnicodeToHtml(x)) return x
|
|
sys.stdout.write(result)
|
sys.stdout.write(result.encode(config.console_encoding, 'replace'))
|
def printColorizedInUnix(self, text, colors): result = "" lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: # add an ANSI escape character result += unixColors[colors[i]] # append one text character result += text[i] lastColor = colors[i] if lastColor != None: # reset the color to default at the end result += unixColors[None] sys.stdout.write(result)
|
sys.stdout.write(text[i])
|
sys.stdout.write(text[i].encode(config.console_encoding, 'replace'))
|
def printColorizedInWindows(self, text, colors): """ This only works in Python 2.5 or higher. """ try: import ctypes std_out_handle = ctypes.windll.kernel32.GetStdHandle(-11) lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: #sys.stdout.flush() if colors[i] == None: ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, 8) else: ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, colors[i]) # print one text character. sys.stdout.write(text[i]) lastColor = colors[i] if lastColor != None: # reset the color to default at the end ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, 8) except ImportError: # ctypes is only available since Python 2.5, and we won't # try to colorize without it. sys.stdout.write(text)
|
sys.stdout.write(text)
|
sys.stdout.write(text.encode(config.console_encoding, 'replace'))
|
def printColorizedInWindows(self, text, colors): """ This only works in Python 2.5 or higher. """ try: import ctypes std_out_handle = ctypes.windll.kernel32.GetStdHandle(-11) lastColor = None for i in range(0, len(colors)): if colors[i] != lastColor: #sys.stdout.flush() if colors[i] == None: ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, 8) else: ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, colors[i]) # print one text character. sys.stdout.write(text[i]) lastColor = colors[i] if lastColor != None: # reset the color to default at the end ctypes.windll.kernel32.SetConsoleTextAttribute(std_out_handle, 8) except ImportError: # ctypes is only available since Python 2.5, and we won't # try to colorize without it. sys.stdout.write(text)
|
sys.stdout.write(text)
|
sys.stdout.write(text.encode(config.console_encoding, 'replace'))
|
def printColorized(self, text, colors): if colors and config.colorized_output: if sys.platform == 'win32': self.printColorizedInWindows(text, colors) else: self.printColorizedInUnix(text, colors) else: sys.stdout.write(text)
|
encodedText = text.encode(config.console_encoding, 'replace')
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
|
colors = colors or [None for char in encodedText] transliteratedTextList = []
|
codecedText = text.encode(config.console_encoding, 'replace').decode(config.console_encoding) colors = colors or [None for char in text] transliteratedText = ''
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
for i in xrange(len(encodedText)):
|
for i in xrange(len(codecedText)):
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
if encodedText[i] == '?' and text[i] != '?':
|
if codecedText[i] == '?' and text[i] != u'?':
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
transliteratedTextList += [char for char in transliterated]
|
transliteratedText += transliterated
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
transliteratedTextList.append('?')
|
transliteratedText += '?'
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
transliteratedTextList.append(encodedText[i]) encodedText = "".join(transliteratedTextList)
|
transliteratedText += codecedText[i] text = transliteratedText
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
encodedText += '\n'
|
text += u'\n'
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
self.printColorized(encodedText, colors)
|
self.printColorized(text, colors)
|
def output(self, text, colors = None, newline = True): """ If a character can't be displayed in the encoding used by the user's terminal, it will be replaced with a question mark or by a transliteration.
|
print "ERROR: ignoring link to obsolete language %s:%s"%( code, repr(t))
|
output(u"ERROR: ignoring link to obsolete language %s:%s" % (code, repr(t)))
|
def getLanguageLinks(text,incode=None): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}. Do not call this routine directly, use PageLink objects instead""" result = {} for code in family.langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: if m.group(1): t=m.group(1) if '|' in t: t=t[:t.index('|')] if incode == 'eo': t=t.replace('xx','x') if code in family.obsolete: print "ERROR: ignoring link to obsolete language %s:%s"%( code, repr(t)) elif not t: print "ERROR: ignoring impossible link to %s:%s"%(code,m.group(1)) else: result[code] = t else: print "ERROR: empty link to %s:"%(code) if incode in ['zh','zh-cn','zh-tw']: m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7b80\\]\\]', text) if m: #print "DBG> found link to traditional Chinese", repr(m.group(0)) result['zh-cn'] = m.group(1) m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7c21\\]\\]', text) if m: #print "DBG> found link to traditional Chinese", repr(m.group(0)) result['zh-cn'] = m.group(1) m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7e41\\]\\]', text) if m: #print "DBG> found link to simplified Chinese", repr(m.group(0)) result['zh-tw'] = m.group(1) return result
|
print "ERROR: ignoring impossible link to %s:%s"%(code,m.group(1))
|
output(u"ERROR: ignoring impossible link to %s:%s" % (code, m.group(1)))
|
def getLanguageLinks(text,incode=None): """Returns a dictionary of other language links mentioned in the text in the form {code:pagename}. Do not call this routine directly, use PageLink objects instead""" result = {} for code in family.langs: m=re.search(r'\[\['+code+':([^\]]*)\]\]', text) if m: if m.group(1): t=m.group(1) if '|' in t: t=t[:t.index('|')] if incode == 'eo': t=t.replace('xx','x') if code in family.obsolete: print "ERROR: ignoring link to obsolete language %s:%s"%( code, repr(t)) elif not t: print "ERROR: ignoring impossible link to %s:%s"%(code,m.group(1)) else: result[code] = t else: print "ERROR: empty link to %s:"%(code) if incode in ['zh','zh-cn','zh-tw']: m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7b80\\]\\]', text) if m: #print "DBG> found link to traditional Chinese", repr(m.group(0)) result['zh-cn'] = m.group(1) m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7c21\\]\\]', text) if m: #print "DBG> found link to traditional Chinese", repr(m.group(0)) result['zh-cn'] = m.group(1) m=re.search(u'\\[\\[([^\\]\\|]*)\\|\u7e41\\]\\]', text) if m: #print "DBG> found link to simplified Chinese", repr(m.group(0)) result['zh-tw'] = m.group(1) return result
|
print dictionary
|
def get(key, lang = None): if lang == None: lang = wikipedia.mylang try: # find out how old our saved dump is (in seconds) file_age = time.time() - os.path.getmtime('mediawiki-messages/mediawiki-messages-%s.dat' % lang) # if it's older than 1 month, reload it if file_age > 30 * 24 * 60 * 60: print 'Current MediaWiki message dump is one month old, reloading' refresh_messages(lang) except OSError: # no saved dumped exists yet refresh_messages(lang) # TODO: It's quite inefficient to reload the file every time this function # is used. Maybe we can save its content the first time the function is # called. f = open('mediawiki-messages/mediawiki-messages-%s.dat' % lang, 'r') dictionary = pickle.load(f) f.close() key = key[0].lower() + key[1:] print dictionary if dictionary.has_key(key): return dictionary[key] else: # TODO: Throw exception instead? print 'ERROR: MediaWiki Key %s not found' % key
|
|
'minnan' : lambda v: dh_noConv( v, u'%d nî' ),
|
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalToDigits) # Convert return dh_noConv( tmp, u'%d' ) else: raise ValueError("string contains regular digits")
|
|
'nb' : dh_simpleInt,
|
def dh_knYearConverter( value ): if type(value) is int: # Encode an integer value into a textual form. return unicode(value).translate(_knDigitsToLocal) else: # First make sure there are no real digits in the string tmp = value.translate(_knDigitsToLocal) # Test if tmp == value: tmp = value.translate(_knLocalToDigits) # Convert return dh_noConv( tmp, u'%d' ) else: raise ValueError("string contains regular digits")
|
|
catlib.change_category(subcategory, self.cat.title(), None)
|
catlib.change_category(subcategory, self.cat, None)
|
def run(self): articles = self.cat.articles(recurse = 0) if len(articles) == 0: wikipedia.output(u'There are no articles in category %s' % self.cat.title()) else: for article in articles: catlib.change_category(article, self.cat, None) # Also removes the category tag from subcategories' pages subcategories = self.cat.subcategories(recurse = 0) if len(subcategories) == 0: wikipedia.output(u'There are no subcategories in category %s' % self.cat.title()) else: for subcategory in subcategories: catlib.change_category(subcategory, self.cat.title(), None) if self.cat.exists() and self.cat.isEmpty(): reason = wikipedia.translate(wikipedia.getSite(), self.deletion_reason_remove) if batchMode == True: self.cat.delete(reason, False) else: self.cat.delete(reason, True)
|
print interwiki_links
|
def replaceCategoryLinks(oldtext, new, code = None): """Replace the category links given in the wikitext given in oldtext by the new links given in new. 'new' should be a list of category pagelink objects. """ if code is None: code = mylang # first remove interwiki links and add them later, so that # interwiki tags appear below category tags if both are set # to appear at the bottom of the article if not code in config.categories_last: interwiki_links = getLanguageLinks(oldtext) print interwiki_links oldtext = removeLanguageLinks(oldtext) s = categoryFormat(new) s2 = removeCategoryLinks(oldtext, code) if s: if mylang in config.category_attop: newtext = s + config.category_text_separator + s2 else: newtext = s2 + config.category_text_separator + s else: newtext = s2 # now re-add interwiki links if not code in config.categories_last: newtext = replaceLanguageLinks(newtext, interwiki_links) return newtext
|
|
wikipedia.setAction(editSummary)
|
wikipedia.setAction(self.editSummary)
|
def __init__(self, generator, old, new = None, remove = False, customSummary = False, editSummary = '', acceptAll = False): """ Arguments: * generator - A page generator. * old - The title of the old template (without namespace) * new - The title of the new template (without namespace), or None if you want to substitute the template with its text. * remove - True if the template should be removed. """ self.generator = generator self.old = old self.new = new self.remove = remove
|
print status, reason
|
def fix_double_redirects(self): mysite = wikipedia.getSite() for redir_name in self.generator.retrieve_double_redirects(): print '' redir = wikipedia.Page(mysite, redir_name) try: target = redir.getRedirectTarget() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % redir.title()) except wikipedia.NoPage: wikipedia.output(u'%s doesn\'t exist.' % redir.title()) else: try: second_redir = wikipedia.Page(mysite, target) second_target = second_redir.getRedirectTarget() except wikipedia.IsNotRedirectPage: wikipedia.output(u'%s is not a redirect.' % second_redir.title()) except wikipedia.NoPage: wikipedia.output(u'%s doesn\'t exist.' % second_redir.title()) else: txt = redir.get(get_redirect=True).replace('[['+target,'[['+second_target) try: status, reason, data = redir.put(txt) except wikipedia.LockedPage: wikipedia.output(u'%s is locked.' % redir.title()) print status, reason
|
|
'fr': 'Lien_AdQ',
|
'fr': 'lien AdQ',
|
def LINKS(site,name, ignore=[]): p=wikipedia.Page(site, name) links=p.linkedPages() for n in links[:]: if n.titleWithoutNamespace() in ignore: links.remove(n) links.sort() return links
|
pl = wikipedia.PageLink(mysite,title)
|
pl = wikipedia.PageLink(mysite,wikipedia.UnicodeToAsciiHtml(title)) print pl.linkname()
|
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding!"%title else: pl.put(page, comment = commenttext, minorEdit = False) except AttributeError: print "No title found - skipping a page." findpage(t[location.end()+1:]) return
|
if arg.startswith("-stop:"):
|
elif arg.startswith("-stop:"):
|
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding!"%title else: pl.put(page, comment = commenttext, minorEdit = False) except AttributeError: print "No title found - skipping a page." findpage(t[location.end()+1:]) return
|
if arg.startswith("-file:"):
|
elif arg.startswith("-file:"):
|
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding!"%title else: pl.put(page, comment = commenttext, minorEdit = False) except AttributeError: print "No title found - skipping a page." findpage(t[location.end()+1:]) return
|
if arg=="-include":
|
elif arg=="-include":
|
def findpage(t): try: location = re.search(starttext+"([^\Z]*?)"+endtext,t) if include: page = location.group() else: page = location.group(1) except AttributeError: return try: title = re.search("'''(.*?)'''",page).group(1) pl = wikipedia.PageLink(mysite,title) if pl.exists(): print "Page %s already exists, not adding!"%title else: pl.put(page, comment = commenttext, minorEdit = False) except AttributeError: print "No title found - skipping a page." findpage(t[location.end()+1:]) return
|
try: addr = self.addr%special[self.code]
|
addr = self.addr%special[self.code]
|
def getData(self): import httplib try: addr = self.addr%special[self.code] pagenames = u'\r\n'.join([x.hashfreeLinkname() for x in self.pages]) pagenames = forCode(pagenames, self.code) data = urlencode(( ('action', 'submit'), ('pages', pagenames), ('curonly', 'True'), )) #print repr(data) headers = {"Content-type": "application/x-www-form-urlencoded", "User-agent": "RobHooftWikiRobot/1.0"} # Slow ourselves down get_throttle(requestsize = len(self.pages)) # Now make the actual request to the server conn = httplib.HTTPConnection(langs[self.code]) conn.request("POST", addr, data, headers) response = conn.getresponse() data = response.read() conn.close() return data
|
continue i2 = re.search('</textarea>', text).start()
|
continue
|
def getEditPage(self, get_redirect=False, throttle = True, sysop = False): """ Get the contents of the Page via the edit page. Do not use this directly, use get() instead. Arguments: get_redirect - Get the contents, even if it is a redirect page This routine returns a unicode string containing the wiki text. """ isWatched = False editRestriction = None output(u'Getting page %s' % self.aslink()) path = self.site().edit_address(self.urlname()) # Make sure Brion doesn't get angry by waiting if the last time a page # was retrieved was not long enough ago. if throttle: get_throttle() # Try to retrieve the page until it was successfully loaded (just in case # the server is down or overloaded) # wait for retry_idle_time minutes (growing!) between retries. retry_idle_time = 1 while True: starttime = time.time() try: text = self.site().getUrl(path, sysop = sysop) except AttributeError: # We assume that the server is down. Wait some time, then try again. print "WARNING: Could not load %s%s. Maybe the server is down. Retrying in %i minutes..." % (self.site().hostname(), path, retry_idle_time) time.sleep(retry_idle_time * 60) # Next time wait longer, but not longer than half an hour retry_idle_time *= 2 if retry_idle_time > 30: retry_idle_time = 30 continue # Extract the actual text from the textedit field try: i1 = re.search('<textarea[^>]*>', text).end() except AttributeError: # find out if the username or IP has been blocked if text.find(mediawiki_messages.get('blockedtitle', self.site())) != -1: raise UserBlocked(self.site(), self.title()) else: # We assume that the server is down. Wait some time, then try again. print "WARNING: No text area found on %s%s. Maybe the server is down. Retrying in %i minutes..." % (self.site().hostname(), path, retry_idle_time) time.sleep(retry_idle_time * 60) # Next time wait longer, but not longer than half an hour retry_idle_time *= 2 if retry_idle_time > 30: retry_idle_time = 30 continue i2 = re.search('</textarea>', text).start() # We now know that there is a textarea. # Look for the edit token Rwatch = re.compile(r"\<input type='hidden' value=\"(.*?)\" name=\"wpEditToken\"") tokenloc = Rwatch.search(text) if tokenloc: self.site().putToken(tokenloc.group(1), sysop = sysop) elif not self.site().getToken(getalways = False): self.site().putToken('', sysop = sysop) # Find out if page actually exists. Only existing pages have a # version history tab. RversionTab = re.compile(r'<li id="ca-history"><a href=".*title=.*&action=history">.*</a></li>') matchVersionTab = RversionTab.search(text) if not matchVersionTab: raise NoPage(self.site(), self.title()) # Look if the page is on our watchlist R = re.compile(r"\<input tabindex='[\d]+' type='checkbox' name='wpWatchthis' checked='checked'") matchWatching = R.search(text) if matchWatching: isWatched = True # Get timestamps m = re.search('value="(\d+)" name=["\']wpEdittime["\']', text) if m: self._editTime = m.group(1) else: self._editTime = "0" m = re.search('value="(\d+)" name=["\']wpStarttime["\']', text) if m: self._startTime = m.group(1) else: self._startTime = "0" # Now process the contents of the textarea m = self.site().redirectRegex().match(text[i1:i2]) if self._editTime == "0": output(u"DBG> page may be locked?!") editRestriction = 'sysop' if m: if get_redirect: self._redirarg = m.group(1) else: output(u"DBG> %s is redirect to %s" % (self.title(), m.group(1))) raise IsRedirectPage(m.group(1)) x = text[i1:i2] x = unescape(x) while x and x[-1] in '\n ': x = x[:-1] return x, isWatched, editRestriction
|
print repr(fn)
|
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = file.read() if contents.find("The requested URL was not found on this server.") != -1: print "Couldn't download the image." return file.close() # Isolate the pure name if '/' in fn: fn = fn.split('/')[-1] if '\\' in fn: fn = fn.split('\\')[-1] # convert ISO 8859-1 to Unicode, or parse UTF-8. If source_wiki is None, # the filename is already in Unicode. if source_wiki != None: try: fn = unicode(fn, wikipedia.code2encoding(source_wiki)) except TypeError: print 'Type error in lib_images.py. This should not happen. Please report this problem.' pass if not keep: print "The filename on wikipedia will default to:", fn newfn = wikipedia.input(u'Better name:') if newfn != '': fn = newfn # Wikipedia doesn't allow spaces in the file name. # Replace them here to avoid an extra confirmation form fn = fn.replace(' ', '_') # Convert the filename (currently Unicode) to the encoding used on the # target wiki fn = fn.encode(wikipedia.myencoding()) print repr(fn) # A proper description for the submission. if description=='': description = wikipedia.input(u'Give a description for the image:') else: print ("The suggested description is:") print print wikipedia.output(description) print print ("Enter return to use this description, enter a text to add something") print ("at the end, or enter = followed by a text to replace the description.") newtext = wikipedia.input(u'Enter return, text or =text : ') if newtext=='': pass elif newtext[0]=='=': description=newtext[1:] else: description=description+' '+newtext # try to encode the description to the encoding used by the home Wikipedia. # if that's not possible (e.g. because there are non-Latin-1 characters and # the home Wikipedia uses Latin-1), convert all non-ASCII characters to # HTML entities. try: description = description.encode(wikipedia.myencoding()) except UnicodeEncodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) except UnicodeDecodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) # don't upload if we're in debug mode if not debug: returned_html = post_multipart(wikipedia.family.hostname(wikipedia.mylang), wikipedia.family.upload_address(wikipedia.mylang), (('wpUploadDescription', description), ('wpUploadAffirm', '1'), ('wpIgnoreWarning', '1'), ('wpUpload','upload bestand')), (('wpUploadFile',fn,contents),) ) # do we know how the "success!" HTML page should look like? success_msg = mediawiki_messages.get('successfulupload') success_msgR = re.compile(re.escape(success_msg)) if success_msgR.search(returned_html): print "Upload successful." else: # dump the HTML page print returned_html + "\n\n" answer = raw_input(u"Upload of " + fn + " failed. Above you see the HTML page which was returned by MediaWiki. Try again? [y|N]") if answer in ["y", "Y"]: return get_image(original_url, source_wiki, original_description, debug) else: return return fn
|
|
if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year))
|
if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and value > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and value > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,value))
|
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if given as -hint:xy or -hint:xy:, assume that there should # be a page in language xy with the same title as the page # we're currently working on newname = pl.title() try: number = int(codes) codes = site.family.languages_by_size[:number] except ValueError: if codes == 'all': codes = site.family.languages_by_size elif codes == 'cyril': codes = site.family.cyrilliclangs else: codes = codes.split(',') for newcode in codes: if newcode in site.languages(): if newcode != site.language(): x = wikipedia.Page(site.getSite(code=newcode), newname) if x not in arr: arr[x] = None else: wikipedia.output(u"Ignoring unknown language code %s"%newcode) # Autotranslate dates into all other languages, the rest will come from existing interwiki links. if auto: # search inside all dictionaries for this link dictName, value = date.getAutoFormat( pl.site().language(), pl.title() ) if dictName: if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year)) for entryLang, entry in date.formats[dictName].iteritems(): if entryLang != pl.site().language(): if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]: pass elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]: pass else: newname = entry(year) x = wikipedia.Page( wikipedia.getSite(code=entryLang, fam=site.family), newname ) if x not in arr: arr[x] = None # add new page
|
if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]:
|
if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and value > date.maxyearBC[entryLang]:
|
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if given as -hint:xy or -hint:xy:, assume that there should # be a page in language xy with the same title as the page # we're currently working on newname = pl.title() try: number = int(codes) codes = site.family.languages_by_size[:number] except ValueError: if codes == 'all': codes = site.family.languages_by_size elif codes == 'cyril': codes = site.family.cyrilliclangs else: codes = codes.split(',') for newcode in codes: if newcode in site.languages(): if newcode != site.language(): x = wikipedia.Page(site.getSite(code=newcode), newname) if x not in arr: arr[x] = None else: wikipedia.output(u"Ignoring unknown language code %s"%newcode) # Autotranslate dates into all other languages, the rest will come from existing interwiki links. if auto: # search inside all dictionaries for this link dictName, value = date.getAutoFormat( pl.site().language(), pl.title() ) if dictName: if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year)) for entryLang, entry in date.formats[dictName].iteritems(): if entryLang != pl.site().language(): if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]: pass elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]: pass else: newname = entry(year) x = wikipedia.Page( wikipedia.getSite(code=entryLang, fam=site.family), newname ) if x not in arr: arr[x] = None # add new page
|
elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]:
|
elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and value > date.maxyearAD[entryLang]:
|
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if given as -hint:xy or -hint:xy:, assume that there should # be a page in language xy with the same title as the page # we're currently working on newname = pl.title() try: number = int(codes) codes = site.family.languages_by_size[:number] except ValueError: if codes == 'all': codes = site.family.languages_by_size elif codes == 'cyril': codes = site.family.cyrilliclangs else: codes = codes.split(',') for newcode in codes: if newcode in site.languages(): if newcode != site.language(): x = wikipedia.Page(site.getSite(code=newcode), newname) if x not in arr: arr[x] = None else: wikipedia.output(u"Ignoring unknown language code %s"%newcode) # Autotranslate dates into all other languages, the rest will come from existing interwiki links. if auto: # search inside all dictionaries for this link dictName, value = date.getAutoFormat( pl.site().language(), pl.title() ) if dictName: if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year)) for entryLang, entry in date.formats[dictName].iteritems(): if entryLang != pl.site().language(): if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]: pass elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]: pass else: newname = entry(year) x = wikipedia.Page( wikipedia.getSite(code=entryLang, fam=site.family), newname ) if x not in arr: arr[x] = None # add new page
|
newname = entry(year)
|
newname = entry(value)
|
def translate(pl, arr, same = False, hints = None, auto = True): site = pl.site() if same: return sametranslate(pl, arr, same) if hints: for h in hints: if h.find(':') == -1: # argument given as -hint:xy where xy is a language code codes = h newname = '' else: codes, newname = h.split(':', 1) if newname == '': # if given as -hint:xy or -hint:xy:, assume that there should # be a page in language xy with the same title as the page # we're currently working on newname = pl.title() try: number = int(codes) codes = site.family.languages_by_size[:number] except ValueError: if codes == 'all': codes = site.family.languages_by_size elif codes == 'cyril': codes = site.family.cyrilliclangs else: codes = codes.split(',') for newcode in codes: if newcode in site.languages(): if newcode != site.language(): x = wikipedia.Page(site.getSite(code=newcode), newname) if x not in arr: arr[x] = None else: wikipedia.output(u"Ignoring unknown language code %s"%newcode) # Autotranslate dates into all other languages, the rest will come from existing interwiki links. if auto: # search inside all dictionaries for this link dictName, value = date.getAutoFormat( pl.site().language(), pl.title() ) if dictName: if not (dictName == 'yearsBC' and date.maxyearBC.has_key(pl.site().language()) and year > date.maxyearBC[pl.site().language()]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(pl.site().language()) and year > date.maxyearAD[pl.site().language()]): wikipedia.output(u'TitleTranslate: %s was recognized as %s with value %d' % (pl.title(),dictName,year)) for entryLang, entry in date.formats[dictName].iteritems(): if entryLang != pl.site().language(): if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and year > date.maxyearBC[entryLang]: pass elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and year > date.maxyearAD[entryLang]: pass else: newname = entry(year) x = wikipedia.Page( wikipedia.getSite(code=entryLang, fam=site.family), newname ) if x not in arr: arr[x] = None # add new page
|
def appendFormatedDates( result, dictName, year ): for code, value in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,value(year)) )
|
def appendFormatedDates( result, dictName, value ): for code, func in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,func(value)) )
|
def appendFormatedDates( result, dictName, year ): for code, value in date.formats[dictName].iteritems(): result.append( u'[[%s:%s]]' % (code,value(year)) )
|
print "The filename on wikipedia will default to:",fn newfn = wikipedia.input(u'Better name : ', encode = wikipedia.myencoding())
|
print "The filename on wikipedia will default to:", fn newfn = wikipedia.input(u'Better name:') if newfn != '': fn = newfn
|
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = file.read() if contents.find("The requested URL was not found on this server.") != -1: print "Couldn't download the image." return file.close() # Isolate the pure name if '/' in fn: fn = fn.split('/')[-1] if '\\' in fn: fn = fn.split('\\')[-1] # convert ISO 8859-1 to Unicode, or parse UTF-8 if source_wiki != None: try: fn = unicode(fn, wikipedia.code2encoding(source_wiki)) except TypeError: pass if not keep: print "The filename on wikipedia will default to:",fn newfn = wikipedia.input(u'Better name : ', encode = wikipedia.myencoding()) # Wikipedia doesn't allow spaces in the file name. # Replace them here to avoid an extra confirmation form fn = fn.replace(' ', '_') # A proper description for the submission. if description=='': description = wikipedia.input(u'Give a description for the image:') else: print ("The suggested description is:") print print wikipedia.output(description) print print ("Enter return to use this description, enter a text to add something") print ("at the end, or enter = followed by a text to replace the description.") newtext = wikipedia.input(u'Enter return, text or =text : ') if newtext=='': pass elif newtext[0]=='=': description=newtext[1:] else: description=description+' '+newtext # try to encode the description to the encoding used by the home Wikipedia. # if that's not possible (e.g. because there are non-Latin-1 characters and # the home Wikipedia uses Latin-1), convert all non-ASCII characters to # HTML entities. try: description = description.encode(wikipedia.myencoding()) except UnicodeEncodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) except UnicodeDecodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) # don't upload if we're in debug mode if not debug: returned_html = post_multipart(wikipedia.family.hostname(wikipedia.mylang), wikipedia.family.upload_address(wikipedia.mylang), (('wpUploadDescription', description), ('wpUploadAffirm', '1'), ('wpIgnoreWarning', '1'), ('wpUpload','upload bestand')), (('wpUploadFile',fn,contents),) ) # do we know how the "success!" HTML page should look like? success_msg = mediawiki_messages.get('successfulupload') success_msgR = re.compile(re.escape(success_msg)) if success_msgR.search(returned_html): print "Upload successful." else: # dump the HTML page print returned_html + "\n\n" answer = raw_input(u"Upload of " + fn + " failed. Above you see the HTML page which was returned by MediaWiki. Try again? [y|N]") if answer in ["y", "Y"]: return get_image(original_url, source_wiki, original_description, debug) else: return return fn
|
fn = fn.encode(wikipedia.myencoding()) print repr(fn)
|
def get_image(original_url, source_wiki, original_description, keep=False, debug=False): # work with a copy of argument variables so we can reuse the # original ones if the upload fails fn = original_url description = original_description # Get file contents uo = wikipedia.MyURLopener() file = uo.open(fn) contents = file.read() if contents.find("The requested URL was not found on this server.") != -1: print "Couldn't download the image." return file.close() # Isolate the pure name if '/' in fn: fn = fn.split('/')[-1] if '\\' in fn: fn = fn.split('\\')[-1] # convert ISO 8859-1 to Unicode, or parse UTF-8 if source_wiki != None: try: fn = unicode(fn, wikipedia.code2encoding(source_wiki)) except TypeError: pass if not keep: print "The filename on wikipedia will default to:",fn newfn = wikipedia.input(u'Better name : ', encode = wikipedia.myencoding()) # Wikipedia doesn't allow spaces in the file name. # Replace them here to avoid an extra confirmation form fn = fn.replace(' ', '_') # A proper description for the submission. if description=='': description = wikipedia.input(u'Give a description for the image:') else: print ("The suggested description is:") print print wikipedia.output(description) print print ("Enter return to use this description, enter a text to add something") print ("at the end, or enter = followed by a text to replace the description.") newtext = wikipedia.input(u'Enter return, text or =text : ') if newtext=='': pass elif newtext[0]=='=': description=newtext[1:] else: description=description+' '+newtext # try to encode the description to the encoding used by the home Wikipedia. # if that's not possible (e.g. because there are non-Latin-1 characters and # the home Wikipedia uses Latin-1), convert all non-ASCII characters to # HTML entities. try: description = description.encode(wikipedia.myencoding()) except UnicodeEncodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) except UnicodeDecodeError: description = wikipedia.UnicodeToAsciiHtml(description).encode(wikipedia.myencoding()) # don't upload if we're in debug mode if not debug: returned_html = post_multipart(wikipedia.family.hostname(wikipedia.mylang), wikipedia.family.upload_address(wikipedia.mylang), (('wpUploadDescription', description), ('wpUploadAffirm', '1'), ('wpIgnoreWarning', '1'), ('wpUpload','upload bestand')), (('wpUploadFile',fn,contents),) ) # do we know how the "success!" HTML page should look like? success_msg = mediawiki_messages.get('successfulupload') success_msgR = re.compile(re.escape(success_msg)) if success_msgR.search(returned_html): print "Upload successful." else: # dump the HTML page print returned_html + "\n\n" answer = raw_input(u"Upload of " + fn + " failed. Above you see the HTML page which was returned by MediaWiki. Try again? [y|N]") if answer in ["y", "Y"]: return get_image(original_url, source_wiki, original_description, debug) else: return return fn
|
|
start=link2url(start,code='nl',incode='nl')
|
start=link2url(start,code='nl')
|
def allnlpages(start='%20%200'): import sys start=link2url(start,code='nl',incode='nl') m=0 while 1: text=getPage('nl','Speciaal:Allpages&printable=yes&from=%s'%start,do_quote=0,do_edit=0) #print text R=re.compile('/wiki/(.*?)" *class=[\'\"]printable') n=0 for hit in R.findall(text): if not ':' in hit: if not hit in ['Hoofdpagina','In_het_nieuws']: n=n+1 yield url2link(hit,code='nl',incode='nl') start=hit+'%20%200' if n<100: break m=m+n sys.stderr.write('AllNLPages: %d done; continuing from "%s";\n'%(m,url2link(start,code='nl')))
|
if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl':
|
if code=='pl':
|
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
|
elif code=='ru':
|
if code=='ru':
|
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
|
return 'iso-8859-1',
|
return code2encoding(code),
|
def code2encodings(code): if code in ['meta','eo','ja','zh','hi','he','hu','ko']: return 'utf-8', elif code=='pl': return 'utf-8','iso-8859-2' elif code=='ru': return 'utf-8','iso-8859-5' return 'iso-8859-1',
|
def link2url(name,code,incode):
|
def link2url(name,code):
|
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicode(name,language=code) else: import urllib name=html2unicode(name,language=code,inlanguage=incode) try: result=str(name.encode(code2encoding(code))) except UnicodeError: try: #print "Trying to encode into latin1" result=str(name.encode('latin1')) #print "Result=",result except UnicodeError: result=str(name.encode('utf-8')) result=space2underline(result) return urllib.quote(result)
|
import urllib name=name[0].upper()+name[1:] name=name.strip()
|
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicode(name,language=code) else: import urllib name=html2unicode(name,language=code,inlanguage=incode) try: result=str(name.encode(code2encoding(code))) except UnicodeError: try: #print "Trying to encode into latin1" result=str(name.encode('latin1')) #print "Result=",result except UnicodeError: result=str(name.encode('utf-8')) result=space2underline(result) return urllib.quote(result)
|
|
import urllib name=html2unicode(name,language=code,inlanguage=incode)
|
name=html2unicode(name,language=code) name=name.strip() name=name[0].upper()+name[1:]
|
def link2url(name,code,incode): """Convert a interwiki link name of a page to the proper name to be used in a URL for that page. code should specify the language for the link, incode the language of the page the link is in.""" import urllib name=name[0].upper()+name[1:] name=name.strip() if '%' in name: name=url2unicode(name,language=code) else: import urllib name=html2unicode(name,language=code,inlanguage=incode) try: result=str(name.encode(code2encoding(code))) except UnicodeError: try: #print "Trying to encode into latin1" result=str(name.encode('latin1')) #print "Result=",result except UnicodeError: result=str(name.encode('utf-8')) result=space2underline(result) return urllib.quote(result)
|
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed. If you set forceInterwiki to True, the link will have the format of an interwiki link even if it points to the home wiki. Note that the family is never included. """ if self.sortKey: titleWithSortKey = '%s|%s' % (self.title(), self.sortKey) else:
|
def aslink(self): """ A string representation in the form of a link. This method is different from Page.aslink() as the link will never have the form of an an interwiki link. """ if self.sortKey: titleWithSortKey = '%s|%s' % (self.title(), self.sortKey) else:
|
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed.
|
if forceInterwiki or self.site() != wikipedia.getSite(): return '[[%s:%s]]' % (self.site().lang, titleWithSortKey) else: return '[[%s]]' % titleWithSortKey
|
return '[[%s]]' % titleWithSortKey
|
def aslink(self, forceInterwiki = False): """ A string representation in the form of a link. The link will be an interwiki link if needed.
|
except IOError: self.rebuild() else:
|
def __init__(self, rebuild = False, filename = 'category.dump'): if rebuild: self.rebuild() else: try: f = open(filename, 'r') except IOError: # Apparently the file category.dump does not exist self.rebuild() else: databases = pickle.load(f) f.close() # keys are categories, values are 2-tuples with lists as entries. self.catContentDB = databases['catContentDB'] # like the above, but for supercategories self.superclassDB = databases['superclassDB'] del databases
|
|
wikipedia.get_throttle.setDelay(5)
|
wikipedia.get_throttle.setDelay(1)
|
def __init__(self, catTitle, catDB): self.catTitle = catTitle self.catDB = catDB
|
catDB = CategoryDatabase()
|
def run(self): """ Prints the multi-line string generated by treeview or saves it to a file. Parameters: * catTitle - the title of the category which will be the tree's root * maxDepth - the limit beyond which no subcategories will be listed """ cat = catlib.CatLink(wikipedia.getSite(), self.catTitle) tree = self.treeview(cat) if filename: wikipedia.output(u'Saving results in %s' % filename) import codecs f = codecs.open(filename, 'a', 'utf-8') f.write(tree) f.close() else: wikipedia.output(tree)
|
|
cat_title = wikipedia.input(u'Which category do you want to tidy up?') tidy_category(catTitle)
|
catTitle = wikipedia.input(u'Which category do you want to tidy up?')
|
def run(self): """ Prints the multi-line string generated by treeview or saves it to a file. Parameters: * catTitle - the title of the category which will be the tree's root * maxDepth - the limit beyond which no subcategories will be listed """ cat = catlib.CatLink(wikipedia.getSite(), self.catTitle) tree = self.treeview(cat) if filename: wikipedia.output(u'Saving results in %s' % filename) import codecs f = codecs.open(filename, 'a', 'utf-8') f.write(tree) f.close() else: wikipedia.output(tree)
|
return "[[user:%s" % username.lower() in text.lower()
|
return "[[user:%s" % self.username.lower() in text.lower()
|
def botAllowed(self): """ Checks whether the bot is listed on Wikipedia:Bots to comply with the policy on the English Wikipedia. """ if self.site == wikipedia.getSite('en', 'wikipedia'): pl = wikipedia.Page(self.site, "Wikipedia:Bots") text = pl.get() return "[[user:%s" % username.lower() in text.lower() else: # No bot policies on other return True
|
wikipedia.output(u'Your username is not listed on [[Wikipedia:Bots]]. Please make sure you are allowed to use the robot before actually using it!')
|
wikipedia.output(u'*** Your username is not listed on [[Wikipedia:Bots]].\n*** Please make sure you are allowed to use the robot before actually using it!')
|
def login(self): if not self.password: # As we don't want the password to appear on the screen, we use getpass(). self.password = getpass.getpass('Password for user %s on %s: ' % (self.username, self.site)) # Convert the password from the encoding your shell uses to the one your wiki # uses, via Unicode. This is the same as wikipedia.input() does with the # username, but input() uses raw_input() instead of getpass(). self.password = unicode(self.password, config.console_encoding) self.password = self.password.encode(wikipedia.myencoding()) wikipedia.output(u"Logging in to %s as %s" % (self.site, self.username)) # Ensure bot policy on the English Wikipedia if not self.botAllowed(): wikipedia.output(u'Your username is not listed on [[Wikipedia:Bots]]. Please make sure you are allowed to use the robot before actually using it!') cookiedata = self.getCookie() if cookiedata: self.storecookiedata(cookiedata) wikipedia.output(u"Should be logged in now") else: wikipedia.output(u"Login failed. Wrong password?")
|
cnt = cnt + 9
|
cnt = cnt + 11
|
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 cnt = cnt + 1 elif operand != '': if opName[0] == 'b' and opName != 'bit': print >> f, ' CPU_OP_RD_L,' if opName in ['bpl', 'bvc', 'bne', 'bcc']: print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' if opName in ['bpl', 'bmi']: print >> f, ' CPU_OP_TEST_N,' elif opName in ['bvc', 'bvs']: print >> f, ' CPU_OP_TEST_V,' elif opName in ['bne', 'beq']: print >> f, ' CPU_OP_TEST_Z,' elif opName in ['bcc', 'bcs']: print >> f, ' CPU_OP_TEST_C,' print >> f, ' CPU_OP_BRANCH,' print >> f, ' CPU_OP_JMP_RELATIVE,' cnt = cnt + 5 elif opName[0] != 'j': if operand == 'nn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 2 elif operand == 'nn,x' or operand == 'nn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nn,y' or operand == 'nn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_Y_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' cnt = cnt + 2 elif operand == 'nnnn,x' or operand == 'nnnn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'sta']: print >> f, ' CPU_OP_ADDR_X_SLOW,' else: print >> f, ' CPU_OP_ADDR_X,' cnt = cnt + 3 elif operand == 'nnnn,y' or operand == 'nnnn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'sta']: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 3 elif operand == '(nn),y' or operand == '(nn), y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' if opName in ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'sta']: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 7 elif operand == '(nn,x)' or operand == '(nn, x)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' cnt = cnt + 8 else: print ' *** invalid addressing mode' raise SystemExit(-1) if opName[:2] != 'st' and opName != 'sax': print >> f, ' CPU_OP_LD_TMP_MEM,' cnt = cnt + 1 if opName == 'nop': pass elif opName[:2] == 'ld': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 elif opName[:2] == 'st': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName in ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 3 elif opName == 'lax': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_LD_X_TMP,' cnt = cnt + 3 elif opName == 'sax': print >> f, ' CPU_OP_SAX,' print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 elif opName == 'jmp' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 3 elif opName == 'jmp' and operand == '(nnnn)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 7 elif opName == 'jsr' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 6 else: print ' *** invalid instruction' raise SystemExit(-1) else: if opName == 'brk': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_BRK,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 10 elif opName == 'int': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_INTERRUPT,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName == 'rst': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName[:2] == 'se' or opName[:2] == 'cl': if opName[:2] == 'cl': print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' print >> f, ' CPU_OP_SET_%s,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName[:2] == 'in' or opName[:2] == 'de': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_%sC,' % opName[:2].upper() print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName[0] == 't': if opName[1] != 's': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[1].upper() else: print >> f, ' CPU_OP_LD_TMP_SP,' if opName[2] != 's': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_LD_SP_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName in ['asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName == 'rts': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' print >> f, ' CPU_OP_RD_TMP,' cnt = cnt + 5 elif opName == 'rti': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' cnt = cnt + 6 elif opName == 'pha': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'php': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_SR,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'pla': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' cnt = cnt + 5 elif opName == 'plp': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' cnt = cnt + 4 elif opName == 'nop': print >> f, ' CPU_OP_WAIT,' cnt = cnt + 1 elif opName == '???': print >> f, ' CPU_OP_INVALID_OPCODE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12 else: print ' *** invalid instruction' raise SystemExit(-1) while cnt < 16: if not (opNum == 0x0101 and cnt == 15): print >> f, ' CPU_OP_RD_OPCODE,' else: print >> f, ' CPU_OP_RD_OPCODE' cnt = cnt + 1
|
print >> f, ' CPU_OP_LD_MEM_TMP,'
|
print >> f, ' CPU_OP_LD_MEM_TMP_NODEBUG,'
|
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 cnt = cnt + 1 elif operand != '': if opName[0] == 'b' and opName != 'bit': print >> f, ' CPU_OP_RD_L,' if opName in ['bpl', 'bvc', 'bne', 'bcc']: print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' if opName in ['bpl', 'bmi']: print >> f, ' CPU_OP_TEST_N,' elif opName in ['bvc', 'bvs']: print >> f, ' CPU_OP_TEST_V,' elif opName in ['bne', 'beq']: print >> f, ' CPU_OP_TEST_Z,' elif opName in ['bcc', 'bcs']: print >> f, ' CPU_OP_TEST_C,' print >> f, ' CPU_OP_BRANCH,' print >> f, ' CPU_OP_JMP_RELATIVE,' cnt = cnt + 5 elif opName[0] != 'j': if operand == 'nn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 2 elif operand == 'nn,x' or operand == 'nn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nn,y' or operand == 'nn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_Y_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' cnt = cnt + 2 elif operand == 'nnnn,x' or operand == 'nnnn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_X_SLOW,' else: print >> f, ' CPU_OP_ADDR_X,' cnt = cnt + 3 elif operand == 'nnnn,y' or operand == 'nnnn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 3 elif operand == '(nn),y' or operand == '(nn), y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 7 elif operand == '(nn,x)' or operand == '(nn, x)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' cnt = cnt + 8 else: print ' *** invalid addressing mode' raise SystemExit(-1) if opName[:2] != 'st' and opName != 'sax': print >> f, ' CPU_OP_LD_TMP_MEM,' cnt = cnt + 1 if opName == 'nop': pass elif opName[:2] == 'ld': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 elif opName == 'lax': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_LD_X_TMP,' cnt = cnt + 3 elif opName[:2] == 'st': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName == 'sax': print >> f, ' CPU_OP_SAX,' print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName in writeInstructions: print >> f, ' CPU_OP_LD_MEM_TMP,' if opName == 'slo': print >> f, ' CPU_OP_ASL,' print >> f, ' CPU_OP_ORA,' cnt = cnt + 2 elif opName == 'rla': print >> f, ' CPU_OP_ROL,' print >> f, ' CPU_OP_AND,' cnt = cnt + 2 elif opName == 'sre': print >> f, ' CPU_OP_LSR,' print >> f, ' CPU_OP_EOR,' cnt = cnt + 2 elif opName == 'rra': print >> f, ' CPU_OP_ROR,' print >> f, ' CPU_OP_ADC,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 elif opName == 'jmp' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 3 elif opName == 'jmp' and operand == '(nnnn)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 7 elif opName == 'jsr' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 6 else: print ' *** invalid instruction' raise SystemExit(-1) else: if opName == 'brk': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_BRK,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 10 elif opName == 'int': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_INTERRUPT,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 11 elif opName == 'rst': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName[:2] == 'se' or opName[:2] == 'cl': if opName[:2] == 'cl': print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' print >> f, ' CPU_OP_SET_%s,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName[:2] == 'in' or opName[:2] == 'de': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_%sC,' % opName[:2].upper() print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName[0] == 't': if opName[1] != 's': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[1].upper() else: print >> f, ' CPU_OP_LD_TMP_SP,' if opName[2] != 's': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_LD_SP_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName in ['asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName == 'rts': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' print >> f, ' CPU_OP_RD_TMP,' cnt = cnt + 5 elif opName == 'rti': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' cnt = cnt + 6 elif opName == 'pha': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'php': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_SR,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'pla': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' cnt = cnt + 5 elif opName == 'plp': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' cnt = cnt + 4 elif opName == 'nop': print >> f, ' CPU_OP_WAIT,' cnt = cnt + 1 elif opName == '???': print >> f, ' CPU_OP_INVALID_OPCODE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12 else: print ' *** invalid instruction' raise SystemExit(-1) while cnt < 16: if not (opNum == 0x0101 and cnt == 15): print >> f, ' CPU_OP_RD_OPCODE,' else: print >> f, ' CPU_OP_RD_OPCODE' cnt = cnt + 1
|
print >> f, ' CPU_OP_RD_TMP,'
|
print >> f, ' CPU_OP_RD_TMP_NODEBUG,'
|
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 cnt = cnt + 1 elif operand != '': if opName[0] == 'b' and opName != 'bit': print >> f, ' CPU_OP_RD_L,' if opName in ['bpl', 'bvc', 'bne', 'bcc']: print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' if opName in ['bpl', 'bmi']: print >> f, ' CPU_OP_TEST_N,' elif opName in ['bvc', 'bvs']: print >> f, ' CPU_OP_TEST_V,' elif opName in ['bne', 'beq']: print >> f, ' CPU_OP_TEST_Z,' elif opName in ['bcc', 'bcs']: print >> f, ' CPU_OP_TEST_C,' print >> f, ' CPU_OP_BRANCH,' print >> f, ' CPU_OP_JMP_RELATIVE,' cnt = cnt + 5 elif opName[0] != 'j': if operand == 'nn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 2 elif operand == 'nn,x' or operand == 'nn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nn,y' or operand == 'nn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_Y_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' cnt = cnt + 2 elif operand == 'nnnn,x' or operand == 'nnnn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_X_SLOW,' else: print >> f, ' CPU_OP_ADDR_X,' cnt = cnt + 3 elif operand == 'nnnn,y' or operand == 'nnnn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 3 elif operand == '(nn),y' or operand == '(nn), y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 7 elif operand == '(nn,x)' or operand == '(nn, x)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' cnt = cnt + 8 else: print ' *** invalid addressing mode' raise SystemExit(-1) if opName[:2] != 'st' and opName != 'sax': print >> f, ' CPU_OP_LD_TMP_MEM,' cnt = cnt + 1 if opName == 'nop': pass elif opName[:2] == 'ld': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 elif opName == 'lax': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_LD_X_TMP,' cnt = cnt + 3 elif opName[:2] == 'st': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName == 'sax': print >> f, ' CPU_OP_SAX,' print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName in writeInstructions: print >> f, ' CPU_OP_LD_MEM_TMP,' if opName == 'slo': print >> f, ' CPU_OP_ASL,' print >> f, ' CPU_OP_ORA,' cnt = cnt + 2 elif opName == 'rla': print >> f, ' CPU_OP_ROL,' print >> f, ' CPU_OP_AND,' cnt = cnt + 2 elif opName == 'sre': print >> f, ' CPU_OP_LSR,' print >> f, ' CPU_OP_EOR,' cnt = cnt + 2 elif opName == 'rra': print >> f, ' CPU_OP_ROR,' print >> f, ' CPU_OP_ADC,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 elif opName == 'jmp' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 3 elif opName == 'jmp' and operand == '(nnnn)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 7 elif opName == 'jsr' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 6 else: print ' *** invalid instruction' raise SystemExit(-1) else: if opName == 'brk': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_BRK,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 10 elif opName == 'int': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_INTERRUPT,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 11 elif opName == 'rst': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName[:2] == 'se' or opName[:2] == 'cl': if opName[:2] == 'cl': print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' print >> f, ' CPU_OP_SET_%s,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName[:2] == 'in' or opName[:2] == 'de': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_%sC,' % opName[:2].upper() print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName[0] == 't': if opName[1] != 's': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[1].upper() else: print >> f, ' CPU_OP_LD_TMP_SP,' if opName[2] != 's': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_LD_SP_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName in ['asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName == 'rts': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' print >> f, ' CPU_OP_RD_TMP,' cnt = cnt + 5 elif opName == 'rti': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' cnt = cnt + 6 elif opName == 'pha': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'php': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_SR,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'pla': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' cnt = cnt + 5 elif opName == 'plp': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' cnt = cnt + 4 elif opName == 'nop': print >> f, ' CPU_OP_WAIT,' cnt = cnt + 1 elif opName == '???': print >> f, ' CPU_OP_INVALID_OPCODE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12 else: print ' *** invalid instruction' raise SystemExit(-1) while cnt < 16: if not (opNum == 0x0101 and cnt == 15): print >> f, ' CPU_OP_RD_OPCODE,' else: print >> f, ' CPU_OP_RD_OPCODE' cnt = cnt + 1
|
print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12
|
cnt = cnt + 1
|
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 cnt = cnt + 1 elif operand != '': if opName[0] == 'b' and opName != 'bit': print >> f, ' CPU_OP_RD_L,' if opName in ['bpl', 'bvc', 'bne', 'bcc']: print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' if opName in ['bpl', 'bmi']: print >> f, ' CPU_OP_TEST_N,' elif opName in ['bvc', 'bvs']: print >> f, ' CPU_OP_TEST_V,' elif opName in ['bne', 'beq']: print >> f, ' CPU_OP_TEST_Z,' elif opName in ['bcc', 'bcs']: print >> f, ' CPU_OP_TEST_C,' print >> f, ' CPU_OP_BRANCH,' print >> f, ' CPU_OP_JMP_RELATIVE,' cnt = cnt + 5 elif opName[0] != 'j': if operand == 'nn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 2 elif operand == 'nn,x' or operand == 'nn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nn,y' or operand == 'nn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_Y_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' cnt = cnt + 2 elif operand == 'nnnn,x' or operand == 'nnnn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_X_SLOW,' else: print >> f, ' CPU_OP_ADDR_X,' cnt = cnt + 3 elif operand == 'nnnn,y' or operand == 'nnnn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 3 elif operand == '(nn),y' or operand == '(nn), y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 7 elif operand == '(nn,x)' or operand == '(nn, x)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' cnt = cnt + 8 else: print ' *** invalid addressing mode' raise SystemExit(-1) if opName[:2] != 'st' and opName != 'sax': print >> f, ' CPU_OP_LD_TMP_MEM,' cnt = cnt + 1 if opName == 'nop': pass elif opName[:2] == 'ld': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 elif opName == 'lax': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_LD_X_TMP,' cnt = cnt + 3 elif opName[:2] == 'st': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName == 'sax': print >> f, ' CPU_OP_SAX,' print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName in writeInstructions: print >> f, ' CPU_OP_LD_MEM_TMP,' if opName == 'slo': print >> f, ' CPU_OP_ASL,' print >> f, ' CPU_OP_ORA,' cnt = cnt + 2 elif opName == 'rla': print >> f, ' CPU_OP_ROL,' print >> f, ' CPU_OP_AND,' cnt = cnt + 2 elif opName == 'sre': print >> f, ' CPU_OP_LSR,' print >> f, ' CPU_OP_EOR,' cnt = cnt + 2 elif opName == 'rra': print >> f, ' CPU_OP_ROR,' print >> f, ' CPU_OP_ADC,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 elif opName == 'jmp' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 3 elif opName == 'jmp' and operand == '(nnnn)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 7 elif opName == 'jsr' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 6 else: print ' *** invalid instruction' raise SystemExit(-1) else: if opName == 'brk': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_BRK,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 10 elif opName == 'int': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_INTERRUPT,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 11 elif opName == 'rst': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName[:2] == 'se' or opName[:2] == 'cl': if opName[:2] == 'cl': print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' print >> f, ' CPU_OP_SET_%s,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName[:2] == 'in' or opName[:2] == 'de': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_%sC,' % opName[:2].upper() print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName[0] == 't': if opName[1] != 's': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[1].upper() else: print >> f, ' CPU_OP_LD_TMP_SP,' if opName[2] != 's': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_LD_SP_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName in ['asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName == 'rts': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' print >> f, ' CPU_OP_RD_TMP,' cnt = cnt + 5 elif opName == 'rti': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' cnt = cnt + 6 elif opName == 'pha': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'php': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_SR,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'pla': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' cnt = cnt + 5 elif opName == 'plp': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' cnt = cnt + 4 elif opName == 'nop': print >> f, ' CPU_OP_WAIT,' cnt = cnt + 1 elif opName == '???': print >> f, ' CPU_OP_INVALID_OPCODE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12 else: print ' *** invalid instruction' raise SystemExit(-1) while cnt < 16: if not (opNum == 0x0101 and cnt == 15): print >> f, ' CPU_OP_RD_OPCODE,' else: print >> f, ' CPU_OP_RD_OPCODE' cnt = cnt + 1
|
generateOpcode(f, 0xF2, '???')
|
generateOpcode(f, 0xF2, 'SYS')
|
def generateOpcode(f, opNum, opName_): print >> f, ' // 0x%02X: %s' % (opNum, opName_) cnt = 0 opName = opName_[:3].lower() if opName_.__len__() > 3: operand = opName_[4:].lower() else: operand = '' writeInstructions = ['inc', 'dec', 'asl', 'lsr', 'rol', 'ror', 'rla', 'rra', 'slo', 'sre', 'sta'] if operand == '#nn': print >> f, ' CPU_OP_RD_TMP,' if opName == 'nop': pass elif opName[:2] != 'ld': print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 cnt = cnt + 1 elif operand != '': if opName[0] == 'b' and opName != 'bit': print >> f, ' CPU_OP_RD_L,' if opName in ['bpl', 'bvc', 'bne', 'bcc']: print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' if opName in ['bpl', 'bmi']: print >> f, ' CPU_OP_TEST_N,' elif opName in ['bvc', 'bvs']: print >> f, ' CPU_OP_TEST_V,' elif opName in ['bne', 'beq']: print >> f, ' CPU_OP_TEST_Z,' elif opName in ['bcc', 'bcs']: print >> f, ' CPU_OP_TEST_C,' print >> f, ' CPU_OP_BRANCH,' print >> f, ' CPU_OP_JMP_RELATIVE,' cnt = cnt + 5 elif opName[0] != 'j': if operand == 'nn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 2 elif operand == 'nn,x' or operand == 'nn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nn,y' or operand == 'nn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_Y_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' cnt = cnt + 4 elif operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' cnt = cnt + 2 elif operand == 'nnnn,x' or operand == 'nnnn, x': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_X_SLOW,' else: print >> f, ' CPU_OP_ADDR_X,' cnt = cnt + 3 elif operand == 'nnnn,y' or operand == 'nnnn, y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 3 elif operand == '(nn),y' or operand == '(nn), y': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' if opName in writeInstructions: print >> f, ' CPU_OP_ADDR_Y_SLOW,' else: print >> f, ' CPU_OP_ADDR_Y,' cnt = cnt + 7 elif operand == '(nn,x)' or operand == '(nn, x)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_ADDR_X_SLOW,' print >> f, ' CPU_OP_ADDR_ZEROPAGE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' cnt = cnt + 8 else: print ' *** invalid addressing mode' raise SystemExit(-1) if opName[:2] != 'st' and opName != 'sax': print >> f, ' CPU_OP_LD_TMP_MEM,' cnt = cnt + 1 if opName == 'nop': pass elif opName[:2] == 'ld': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 2 elif opName == 'lax': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_LD_X_TMP,' cnt = cnt + 3 elif opName[:2] == 'st': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName == 'sax': print >> f, ' CPU_OP_SAX,' print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 elif opName in writeInstructions: print >> f, ' CPU_OP_LD_MEM_TMP,' if opName == 'slo': print >> f, ' CPU_OP_ASL,' print >> f, ' CPU_OP_ORA,' cnt = cnt + 2 elif opName == 'rla': print >> f, ' CPU_OP_ROL,' print >> f, ' CPU_OP_AND,' cnt = cnt + 2 elif opName == 'sre': print >> f, ' CPU_OP_LSR,' print >> f, ' CPU_OP_EOR,' cnt = cnt + 2 elif opName == 'rra': print >> f, ' CPU_OP_ROR,' print >> f, ' CPU_OP_ADC,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 print >> f, ' CPU_OP_LD_MEM_TMP,' cnt = cnt + 2 else: print >> f, ' CPU_OP_%s,' % opName.upper() cnt = cnt + 1 elif opName == 'jmp' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 3 elif opName == 'jmp' and operand == '(nnnn)': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 7 elif opName == 'jsr' and operand == 'nnnn': print >> f, ' CPU_OP_RD_L,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RD_H,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 6 else: print ' *** invalid instruction' raise SystemExit(-1) else: if opName == 'brk': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_BRK,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 10 elif opName == 'int': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_INTERRUPT,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 11 elif opName == 'rst': print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 9 elif opName[:2] == 'se' or opName[:2] == 'cl': if opName[:2] == 'cl': print >> f, ' CPU_OP_LD_TMP_00,' else: print >> f, ' CPU_OP_LD_TMP_FF,' print >> f, ' CPU_OP_SET_%s,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName[:2] == 'in' or opName[:2] == 'de': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[2].upper() print >> f, ' CPU_OP_%sC,' % opName[:2].upper() print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName[0] == 't': if opName[1] != 's': print >> f, ' CPU_OP_LD_TMP_%s,' % opName[1].upper() else: print >> f, ' CPU_OP_LD_TMP_SP,' if opName[2] != 's': print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_%s_TMP,' % opName[2].upper() cnt = cnt + 1 else: print >> f, ' CPU_OP_LD_SP_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 3 elif opName in ['asl', 'lsr', 'rol', 'ror']: print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_%s,' % opName.upper() print >> f, ' CPU_OP_LD_A_TMP,' print >> f, ' CPU_OP_WAIT,' cnt = cnt + 4 elif opName == 'rts': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' print >> f, ' CPU_OP_RD_TMP,' cnt = cnt + 5 elif opName == 'rti': print >> f, ' CPU_OP_RD_TMP,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' print >> f, ' CPU_OP_POP_PCL,' print >> f, ' CPU_OP_POP_PCH,' cnt = cnt + 6 elif opName == 'pha': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_A,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'php': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_LD_TMP_SR,' print >> f, ' CPU_OP_PUSH_TMP,' cnt = cnt + 3 elif opName == 'pla': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_SET_NZ,' print >> f, ' CPU_OP_LD_A_TMP,' cnt = cnt + 5 elif opName == 'plp': print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_WAIT,' print >> f, ' CPU_OP_POP_TMP,' print >> f, ' CPU_OP_LD_SR_TMP,' cnt = cnt + 4 elif opName == 'nop': print >> f, ' CPU_OP_WAIT,' cnt = cnt + 1 elif opName == '???': print >> f, ' CPU_OP_INVALID_OPCODE,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_LD_MEM_TMP,' print >> f, ' CPU_OP_PUSH_PCH,' print >> f, ' CPU_OP_PUSH_PCL,' print >> f, ' CPU_OP_RESET,' print >> f, ' CPU_OP_PUSH_TMP,' print >> f, ' CPU_OP_LD_TMP_MEM,' print >> f, ' CPU_OP_INC_L,' print >> f, ' CPU_OP_LD_H_MEM,' print >> f, ' CPU_OP_LD_L_TMP,' print >> f, ' CPU_OP_LD_PC_HL,' cnt = cnt + 12 else: print ' *** invalid instruction' raise SystemExit(-1) while cnt < 16: if not (opNum == 0x0101 and cnt == 15): print >> f, ' CPU_OP_RD_OPCODE,' else: print >> f, ' CPU_OP_RD_OPCODE' cnt = cnt + 1
|
progress (_ ("Assembling raw font to `%s'... ") % outname) system ('t1asm --pfa mftrace.t1asm %s' % outname + '.raw')
|
rawname = outname + '.raw' progress (_ ("Assembling raw font to `%s'... ") % rawname) system ('t1asm --pfa mftrace.t1asm %s' % rawname)
|
/.notdef { 0 0 hsbw endchar } |-
|
generate_cmds += 'Generate("%s");' % (filename + '.' + f)
|
generate_cmds += 'Generate("%s");' % (fontname + '.' + f)
|
def make_outputs (fontname, formats): """ run pfaedit to convert to other formats """ ff_command = get_fontforge_command () if not ff_command: shutil.copy2 (fontname + '.pfa.raw', fontname + '.pfa') return 0 # not used? if round_to_int : round_cmd = 'RoundToInt();\n' generate_cmds = '' for f in formats: generate_cmds += 'Generate("%s");' % (filename + '.' + f) simplify_cmd = '' if simplify_p: simplify_cmd ='''SelectAll ();
|
(filename + '.pfa.raw'), tfmfile))
|
(fontname+ '.pfa.raw'), tfmfile))
|
def make_outputs (fontname, formats): """ run pfaedit to convert to other formats """ ff_command = get_fontforge_command () if not ff_command: shutil.copy2 (fontname + '.pfa.raw', fontname + '.pfa') return 0 # not used? if round_to_int : round_cmd = 'RoundToInt();\n' generate_cmds = '' for f in formats: generate_cmds += 'Generate("%s");' % (filename + '.' + f) simplify_cmd = '' if simplify_p: simplify_cmd ='''SelectAll ();
|
('', '', 'keep-all', _ ("Really keep all output (implies --keep)")),
|
def strip_extension (f, ext): (p, e) = os.path.splitext (f) if e == ext: e = '' return p + e
|
|
command = "gf2pbm -n %d -o %s %s" % (char_number, outname, filename)
|
command = "%s/gf2pbm -n %d -o %s %s" % (exec_prefix, char_number, outname, filename)
|
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'. Return FALSE if the glyph is not valid. """ command = "gf2pbm -n %d -o %s %s" % (char_number, outname, filename) status = system (command, ignore_error = 1) return (status == 0)
|
str = popen ('gf2pbm -n %d -s %s' % (c, name)).read ()
|
str = popen ('%s/gf2pbm -n %d -s %s' % (exec_prefix, c, name)).read ()
|
def read_gf_dims (name, c): str = popen ('gf2pbm -n %d -s %s' % (c, name)).read () m = re.search ('size: ([0-9]+)+x([0-9]+), offset: \(([0-9-]+),([0-9-]+)\)', str) return tuple (map (string.atoi, m.groups ()))
|
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification):
|
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification, fontinfo):
|
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification): t1os = [] font_bbox = (10000, 10000, -10000, -10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_file, 'char.pbm', a) if not valid: continue (w, h, xo, yo) = read_gf_dims (gf_file, a) if not verbose_p: sys.stderr.write ('[%d' % a) sys.stderr.flush () # this wants the id, not the filename. success = trace_one ("char.pbm", '%s-%d' % (gf_fontname, a)) if not success: sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write (']') sys.stderr.flush () metric_width = metric.get_char (a).width tw = int (round (metric_width / metric.design_size * 1000)) (bbox, t1o) = path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '': continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a], t1o)) progress ('\n') to_type1 (t1os, font_bbox, fontname, encoding, magnification)
|
to_type1 (t1os, font_bbox, fontname, encoding, magnification)
|
to_type1 (t1os, font_bbox, fontname, encoding, magnification, fontinfo )
|
def trace_font (fontname, gf_file, metric, glyphs, encoding, magnification): t1os = [] font_bbox = (10000, 10000, -10000, -10000) progress (_ ("Tracing bitmaps... ")) eps_lines = [] # for single glyph testing. # glyphs = [] for a in glyphs: valid = metric.has_char (a) if not valid: continue valid = make_pbm (gf_file, 'char.pbm', a) if not valid: continue (w, h, xo, yo) = read_gf_dims (gf_file, a) if not verbose_p: sys.stderr.write ('[%d' % a) sys.stderr.flush () # this wants the id, not the filename. success = trace_one ("char.pbm", '%s-%d' % (gf_fontname, a)) if not success: sys.stderr.write ("(skipping character)]") sys.stderr.flush () continue if not verbose_p: sys.stderr.write (']') sys.stderr.flush () metric_width = metric.get_char (a).width tw = int (round (metric_width / metric.design_size * 1000)) (bbox, t1o) = path_to_type1_ops ("char.eps", (h, w, xo, yo), tw) if t1o == '': continue font_bbox = update_bbox_with_bbox (font_bbox, bbox) t1os.append ('/%s %s ' % (encoding[a], t1o)) progress ('\n') to_type1 (t1os, font_bbox, fontname, encoding, magnification)
|
def to_type1 (outlines, bbox, fontname, encoding, magnification):
|
def to_type1 (outlines, bbox, fontname, encoding, magnification, fontinfo):
|
def to_type1 (outlines, bbox, fontname, encoding, magnification): """ Fill in the header template for the font, append charstrings, and shove result through t1asm """ template = r"""%%!PS-AdobeFont-1.0: %(FontName)s %(VVV)s.%(WWW)s
|
'FontName': '%s' % fontinfo['FontName'],
|
/.notdef { 0 0 hsbw endchar } |-
|
|
'FullName': fontinfo['FullName'], 'FamilyName': fontinfo['FamilyName'], 'Weight': fontinfo['Weight'], 'ItalicAngle': fontinfo['ItalicAngle'], 'isFixedPitch': 'false',
|
/.notdef { 0 0 hsbw endchar } |-
|
|
fontinfo = {} def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo. This should be tailored for each metafont font set. """ fontinfo = {"FontName": filename}
|
def derive_font_name (family, fullname): fullname = re.sub (family, '', fullname) fullname = re.sub ('Oldstyle Figures', 'OsF', fullname) fullname = re.sub ('Small Caps', 'SC', fullname) fullname = re.sub ('[Mm]edium', '', fullname) fullname = re.sub ('[^A-Za-z0-9]', '', fullname) return '%s-%s' % (family, fullname) def cm_guess_font_info (filename, fontinfo):
|
def abs_path (path, dir): # Python's ABSPATH means ABSDIR dir = os.path.abspath (dir) return string.join (map (lambda x: abs_dir (x, dir), string.split (path, os.pathsep)), os.pathsep)
|
design_size = m.group (1) prefixes = [("cmtt", "Computer Modern Typewriter Text"), ("cmvtt", "Computer Modern Variable Width Typewriter Text"), ("cmss", "Computer Modern Sans Serif"), ("cm", "Computer Modern")]
|
design_size = string.atoi (m.group (1)) fontinfo['DesignSize'] = design_size prefixes = [("cmtt", "CMTypewriter"), ("cmvtt", "CMVariableWidthTypewriter"), ("cmss", "CMSans"), ("cm", "CM")]
|
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
|
("csc", "Small caps"),
|
("csc", "Small Caps"),
|
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
|
prefixes = [("bx", "Bold Extended"), ("b", "Bold"), ("dc", "Demi Bold Condensed"),
|
prefixes = [("b", "Bold"),
|
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
|
weight = 'medium'
|
weight = 'Regular'
|
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
|
fontinfo['FullName'] = '%s %s %s designed at %spt' \ % (family, shape, weight, design_size)
|
full = '%s %s %s %s %dpt' \ % (family, shape, weight, stretch, design_size) full = re.sub (" +", ' ', full) fontinfo['FullName'] = full fontinfo['FontName'] = derive_font_name (family, full) return fontinfo def ec_guess_font_info (filename, fontinfo): design_size = 12 m = re.search ("([0-9]+)$", filename) if m: design_size = string.atoi (m.group (1)) fontinfo['DesignSize'] = design_size prefixes = [("ecss", "EuropeanCMSans"), ("ectt", "EuropeanCMTypewriter"), ("ec", "EuropeanCM")] family = '' for (k, v) in prefixes: if re.search (k, filename): if k == 'ectt': fontinfo['isFixedPitch'] = 'true' family = v filename = re.sub (k, '', filename) break prefixes = [("r", "Roman"), ("mi", "Math italic"), ("u", "Unslanted italic"), ("sl", "Oblique"), ("cc", "Small caps"), ("ex", "Math extension"), ("ti", "Italic"), ("i", "Italic")] shape = '' for (k, v) in prefixes: if re.search (k, filename): shape = v filename = re.sub (k, '', filename) prefixes = [("b", "Bold"), ("d", "Demi bold")] weight = 'Regular' for (k, v) in prefixes: if re.search (k, filename): weight = v filename = re.sub (k, '', filename) prefixes = [("c", "Condensed"), ("x", "Extended")] stretch = '' for (k, v) in prefixes: if re.search (k, filename): stretch = v filename = re.sub (k, '', filename) fontinfo['ItalicAngle'] = 0 if re.search ('[Ii]talic', shape) or re.search ('[Oo]blique', shape): a = -14 if re.search ("Sans", family): a = -12 fontinfo ["ItalicAngle"] = a fontinfo['Weight'] = weight fontinfo['FamilyName'] = family full = '%s %s %s %s %dpt' \ % (family, shape, weight, stretch, design_size) full = re.sub (" +", ' ', full) fontinfo['FontName'] = derive_font_name (family, full) fontinfo['FullName'] = full
|
def cm_guess_font_info (filename): """this function fills in sensible values for fontinfo.
|
'Weight': 'regular',
|
'Weight': 'Regular',
|
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
|
fi.update (cm_guess_font_info (filename)) return fi if read_afm_p:
|
fi.update (cm_guess_font_info (filename, fi)) elif re.search ("^ec", filename): fi.update (ec_guess_font_info (filename, fi)) elif read_afm_p:
|
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
|
magnification)
|
magnification, fontinfo)
|
def guess_fontinfo (filename): fi = { 'FontName': filename, 'FamilyName': filename, 'Weight': 'regular', 'ItalicAngle': 0, 'FullName': filename, } if re.search ('^cm', filename): fi.update (cm_guess_font_info (filename)) return fi if read_afm_p: global afmfile if not afmfile: afmfile = find_file (filename + '.afm') if afmfile: afmfile = os.path.abspath (afmfile) afm_struct = afm.read_afm_file (afmfile) fi.update (afm_struct.__dict__) return fi
|
if os.path.abspath (x) != x:
|
if x and os.path.abspath (x) != x:
|
def abs_dir (x, dir): if os.path.abspath (x) != x: return os.path.join (dir, x) return x
|
""" Extract bitmap from the PK file using `gf2pbm'
|
""" Extract bitmap from the PK file FILENAME (absolute) using `gf2pbm'.
|
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file using `gf2pbm' Return FALSE if the glyph is not valid. """ status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1) return (status == 0)
|
status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1)
|
command = "gf2pbm -n %d -o %s %s" %(char_number, outname, filename) status = system (command, ignore_error = 1)
|
def make_pbm (filename, outname, char_number): """ Extract bitmap from the PK file using `gf2pbm' Return FALSE if the glyph is not valid. """ status = system ("gf2pbm -n %d -o %s %s" %(char_number, outname, filename), ignore_error = 1) return (status == 0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.