rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
if not props['status'] or props['status'] == unread_id:
if (not props.has_key('status') or props['status'] == unread_id):
def handle_message(self, message): ''' message - a Message instance
self.arguments = {}
self.arguments = arguments
def __init__(self, instance, db, arguments={}): self.instance = instance self.db = db self.arguments = {}
def field(self, size=30, default=None): ''' Render a form edit field for the property If not editable, just display the value via plain(). ''' self.view_check()
def field(self, size=30, default=None, format=_marker): '''Render a form edit field for the property If not editable, just display the value via plain(). The format string is a standard python strftime format string. ''' self.view_check() if not self.is_edit_ok(): if format is self._marker: return self.plain() else: return self.pretty(format)
def field(self, size=30, default=None): ''' Render a form edit field for the property
value = raw_value
if format is self._marker: value = raw_value else: value = date.Date(raw_value).pretty(format)
def field(self, size=30, default=None): ''' Render a form edit field for the property
value = cgi.escape(str(raw_value.local(tz))) if self.is_edit_ok(): value = '"'.join(value.split('"')) return self.input(name=self._formname,value=value,size=size) return self.plain()
value = raw_value.local(tz) if format is not self._marker: value = value.pretty(format) value = cgi.escape(str(value), True) return self.input(name=self._formname, value=value, size=size)
def field(self, size=30, default=None): ''' Render a form edit field for the property
_marker = []
def reldate(self, pretty=1): ''' Render the interval between the date and now.
if format is not self._marker:
if not self._value: return '' elif format is not self._marker:
def pretty(self, format=_marker): ''' Render the date in a pretty format (eg. month names, spaces).
week = 60*60*24*7
def clean_sessions(self): """Age sessions, remove when they haven't been used for a week.
if (hasattr(self.client, 'FILTER_POSITION') and
if (show_display_form and hasattr(self.client, 'FILTER_POSITION') and
def render(self, filterspec={}, filter=[], columns=[], sort=[], group=[], show_display_form=1, nodeids=None, show_customization=1): self.filterspec = filterspec
all_filters, all_columns, show_display_form, show_customization)
all_filters, all_columns, show_customization)
def render(self, filterspec={}, filter=[], columns=[], sort=[], group=[], show_display_form=1, nodeids=None, show_customization=1): self.filterspec = filterspec
all_columns, show_display_form, show_customization):
all_columns, show_customization):
def filter_section(self, template, filter, columns, group, all_filters, all_columns, show_display_form, show_customization):
w('<tr class="location-bar">')
def filter_section(self, template, filter, columns, group, all_filters, all_columns, show_display_form, show_customization):
if show_display_form: w('<th align="left" colspan=%s>' '<input style="height : 1em; width : 1em; font-size: 12pt" type="submit" name="action" value="%s">&nbsp;View ' 'customisation...</th></tr>\n'%(len(names)+1, action)) if show_customization: w('<tr class="location-bar"><th>&nbsp;</th>') for name in names: w('<th>%s</th>'%name.capitalize()) w('</tr>\n') if all_filters: w('<tr><th width="1%" align=right class="location-bar">' 'Filters</th>\n') for name in names: if name not in all_filters: w('<td>&nbsp;</td>') continue if name in filter: checked=' checked' else: checked='' w('<td align=middle>\n') w(' <input type="checkbox" name=":filter" value="%s" ' '%s></td>\n'%(name, checked)) w('</tr>\n') if all_columns: w('<tr><th width="1%" align=right class="location-bar">' 'Columns</th>\n') for name in names: if name not in all_columns: w('<td>&nbsp;</td>') continue if name in columns: checked=' checked' else: checked='' w('<td align=middle>\n') w(' <input type="checkbox" name=":columns" value="%s"' '%s></td>\n'%(name, checked)) w('</tr>\n') w('<tr><th width="1%" align=right class="location-bar">' 'Grouping</th>\n') for name in names: prop = self.properties[name] if name not in all_columns: w('<td>&nbsp;</td>') continue if name in group: checked=' checked' else: checked='' w('<td align=middle>\n') w(' <input type="checkbox" name=":group" value="%s"' '%s></td>\n'%(name, checked)) w('</tr>\n') w('<tr class="location-bar"><td width="1%">&nbsp;</td>') w('<td colspan="%s">'%len(names)) w('<input type="submit" name="action" value="Redisplay"></td>') w('</tr>\n')
w('<th align="left" colspan=%s>' '<input style="height : 1em; width : 1em; font-size: 12pt" type="submit" name="action" value="%s">&nbsp;View ' 'customisation...</th></tr>\n'%(len(names)+1, action)) if not show_customization:
def filter_section(self, template, filter, columns, group, all_filters, all_columns, show_display_form, show_customization):
self.db.getjournal('b', bid)
def test_removeClass(self): self.init_ml() aid = self.db.a.create(name='apple') bid = self.db.b.create(name='bear', fooz=[aid]) self.db.commit(); self.db.close()
self.handle()
return self.handle()
def execute(self): """Execute the action specified by this object.""" self.permission() self.handle()
request = templating.HTMLRequest(self)
request = templating.HTMLRequest(self.client)
def handle(self): ''' Export the specified search query as CSV. ''' # figure the request request = templating.HTMLRequest(self) filterspec = request.filterspec sort = request.sort group = request.group columns = request.columns klass = self.db.getclass(request.classname)
h = self.additional_headers
h = self.client.additional_headers
def handle(self): ''' Export the specified search query as CSV. ''' # figure the request request = templating.HTMLRequest(self) filterspec = request.filterspec sort = request.sort group = request.group columns = request.columns klass = self.db.getclass(request.classname)
self.header() writer = rcsv.writer(self.request.wfile)
self.client.header() writer = rcsv.writer(self.client.request.wfile)
def handle(self): ''' Export the specified search query as CSV. ''' # figure the request request = templating.HTMLRequest(self) filterspec = request.filterspec sort = request.sort group = request.group columns = request.columns klass = self.db.getclass(request.classname)
lab = lab + ' (%s)'%', '.join(m)
lab = lab + ' (%s)'%', '.join(map(str, m))
def do_menu(self, property, size=None, height=None, showid=0, additional=[]): ''' For a Link/Multilink property, display a menu of the available choices
import urlparse path = urlparse.urlparse( self.absolute_url() )[2] path_components = path.split( '/' )
url = urlparse.urlparse( self.absolute_url() ) path_components = url[2].split( '/' )
def _opendb(self): '''Open the roundup instance database for a transaction. ''' instance = roundup.instance.open(self.instance_home) request = RequestWrapper(self.REQUEST['RESPONSE']) env = self.REQUEST.environ
del path_components , path
def _opendb(self): '''Open the roundup instance database for a transaction. ''' instance = roundup.instance.open(self.instance_home) request = RequestWrapper(self.REQUEST['RESPONSE']) env = self.REQUEST.environ
sendto = [sendto[0][1]] m = ['Subject: Well, it seemed to work', '', 'hi, mum!']
return
def handle_Message(self, message): '''Handle an RFC822 Message
'roundup.scripts'
'roundup.scripts',
def main(): # build list of scripts from their implementation modules roundup_scripts = map(scriptname, glob('roundup/scripts/[!_]*.py')) # template munching packagelist = [ 'roundup', 'roundup.cgi', 'roundup.cgi.PageTemplates', 'roundup.cgi.TAL', 'roundup.cgi.ZTUtils', 'roundup.backends', 'roundup.scripts' ] installdatafiles = [ ('share/roundup/cgi-bin', ['cgi-bin/roundup.cgi']), ] # install man pages on POSIX platforms if os.name == 'posix': installdatafiles.append(('man/man1', ['doc/roundup-admin.1', 'doc/roundup-mailgw.1', 'doc/roundup-server.1'])) # add the templates to the data files lists from roundup.init import listTemplates templates = [t['path'] for t in listTemplates('templates').values()] for tdir in templates: # scan for data files for idir in '. detectors extensions html'.split(): idir = os.path.join(tdir, idir) tfiles = [] for f in os.listdir(idir): if f.startswith('.'): continue ifile = os.path.join(idir, f) if os.path.isfile(ifile): tfiles.append(ifile) installdatafiles.append( (os.path.join('share', 'roundup', idir), tfiles) ) # add message files for (_dist_file, _mo_file) in list_message_files(): installdatafiles.append((os.path.dirname(_mo_file), [os.path.join("build", _mo_file)])) # perform the setup action from roundup import __version__ setup( name = "roundup", version = __version__, description = "A simple-to-use and -install issue-tracking system" " with command-line, web and e-mail interfaces. Highly" " customisable.", long_description =
content = traceback.format_exc()
content = '\n'.join(traceback.format_exception(*sys.exc_info()))
def exception_message(self): '''Send a message to the admins with information about the latest traceback. ''' subject = '%s: %s'%(self.config.TRACKER_NAME, sys.exc_info()[1]) to = [self.config.ADMIN_EMAIL] content = traceback.format_exc() self.standard_message(to, subject, content)
user = raw_input(_('User: '))
user = raw_input('User: ')
def do_pop(self, server, user='', password='', apop=0): '''Read a series of messages from the specified POP server. ''' import getpass, poplib, socket try: if not user: user = raw_input(_('User: ')) if not password: password = getpass.getpass() except (KeyboardInterrupt, EOFError): # Ctrl C or D maybe also Ctrl Z under Windows. print "\nAborted by user." return 1
if s1 == s2:
l1=s1.strip().split('\n') l2=[x for x in s2.strip().split('\n') if not x.startswith('Date: ')] if l1 == l2:
def compareStrings(self, s2, s1): '''Note the reversal of s2 and s1 - difflib.SequenceMatcher wants the first to be the "original" but in the calls in this file, the second arg is the original. Ho hum. ''' if s1 == s2: return
if sys.version_info[0:2] == (2,1): if s1+'\n' == s2: return if sys.version_info[0:2] == (2,2): if s1 == s2+'\n': return l1=s1.split('\n') l2=s2.split('\n')
def compareStrings(self, s2, s1): '''Note the reversal of s2 and s1 - difflib.SequenceMatcher wants the first to be the "original" but in the calls in this file, the second arg is the original. Ho hum. ''' if s1 == s2: return
if (hasattr(self.client, 'FILTER_POSITION') and self.client.FILTER_POSITION in ('top and bottom', 'top')): w('<form>\n') self.filter_section(filter_template, filter, columns, group, all_filters, all_columns, show_display_form, show_customization) w('</form>\n') if sort: w('<input type="hidden" name=":sort" value="%s">'%','.join(sort))
def render(self, filterspec={}, filter=[], columns=[], sort=[], group=[], show_display_form=1, nodeids=None, show_customization=1): self.filterspec = filterspec
if hasattr(value, 'type'):
if hasattr(value, 'type') and value.type:
propdef = all_propdef[cn]
self.error_message.append(_('Error: ') + str(message))
self.error_message.append(_('Parse Error: ') + str(message))
def editItemAction(self): ''' Perform an edit of an item in the database.
self.error_message.append(_('Error: ') + str(message))
self.error_message.append(_('Apply Error: ') + str(message))
def editItemAction(self): ''' Perform an edit of an item in the database.
if cl.hasnode(nodeid):
if nodeid in ('x', 'X') or not cl.hasnode(nodeid): exists = 0 else:
def editCSVAction(self): ''' Performs an edit of all of a class' items in one go.
else: exists = 0
def editCSVAction(self): ''' Performs an edit of all of a class' items in one go.
self.debug = os.environ.get('SENDMAILDEBUG', '')
self.debug = os.environ.get('SENDMAILDEBUG', '') \ or config["MAIL_DEBUG"]
def __init__(self, config): self.config = config
use_tls = getattr(config, 'MAILHOST_TLS', 'no') if use_tls == 'yes': keyfile = getattr(config, 'MAILHOST_TLS_KEYFILE', '') if keyfile: certfile = getattr(config, 'MAILHOST_TLS_CERTFILE', '') if certfile: args = (keyfile, certfile) else: args = (keyfile, ) else: args = () self.starttls(*args)
if config["MAIL_TLS"]: self.starttls(config["MAIL_TLS_KEYFILE"], config["MAIL_TLS_CERFILE"])
def __init__(self, config): smtplib.SMTP.__init__(self, config.MAILHOST)
mailuser = getattr(config, 'MAILUSER', None)
mailuser = config["MAIL_USERNAME"]
def __init__(self, config): smtplib.SMTP.__init__(self, config.MAILHOST)
self.login(*config.MAILUSER)
self.login(mailuser, config["MAIL_PASSWORD"])
def __init__(self, config): smtplib.SMTP.__init__(self, config.MAILHOST)
node = node.copy() node['creation'] = node['activity'] = date.Date() node['creator'] = self.curuserid
if not node.has_key('creator'): node = node.copy() node['creation'] = node['activity'] = date.Date() node['creator'] = self.curuserid
def addnode(self, classname, nodeid, node): ''' Add the specified node to its class's db. ''' if __debug__: print >>hyperdb.DEBUG, 'addnode', (self, classname, nodeid, node) # gadfly requires values for all non-multilink columns cl = self.classes[classname] cols, mls = self.determine_columns(cl.properties.items())
if not self.db.security.hasPermission('Edit', userid):
if not self.db.security.hasPermission('Edit', userid, cn):
def shownode(self, message=None, num_re=re.compile('^\d+$')): ''' display an item ''' cn = self.classname cl = self.db.classes[cn] if self.form.has_key(':multilink'): link = self.form[':multilink'].value designator, linkprop = link.split(':') xtra = ' for <a href="%s">%s</a>' % (designator, designator) else: xtra = ''
self.session = binascii.b2a_base64(repr(random.random())).strip()
sessions = self.db.getSessionManager() s = '%s%s'%(time.time(), random.random()) print s self.session = binascii.b2a_base64(s).strip() while sessions.exists(self.session): s = '%s%s'%(time.time(), random.random()) self.session = binascii.b2a_base64(s).strip()
def set_cookie(self, user): """Set up a session cookie for the user.
sessions = self.db.getSessionManager()
def set_cookie(self, user): """Set up a session cookie for the user.
''' Return HTMLProperty for all props
''' Return HTMLProperty for all of this class' properties.
def properties(self): ''' Return HTMLProperty for all props ''' l = [] for name, prop in self._props.items(): for klass, htmlklass in propclasses: if isinstance(prop, hyperdb.Multilink): value = [] else: value = None if isinstance(prop, klass): l.append(htmlklass(self._client, '', prop, name, value)) return l
Hase useful attributes:
Has useful attributes:
def hasPermission(self, role, classname=_marker): ''' Determine if the user has the Role.
s.append('- index of '+self.classname)
if self.template == 'item': s.append('- new %s'%self.classname) elif self.template == 'index': s.append('- %s index'%self.classname) else: s.append('- %s %s'%(self.classname, self.template))
def description(self): ''' Return a description of the request - handle for the page title. ''' s = [self.client.db.config.TRACKER_NAME] if self.classname: if self.client.nodeid: s.append('- %s%s'%(self.classname, self.client.nodeid)) else: s.append('- index of '+self.classname) else: s.append('- home') return ' '.join(s)
'%(python)s -c "from %(package)s.scripts.%(module)s import run; run()" %%$\n'
'if NOT "%%_4ver%%" == "" %(python)s -c "from %(package)s.scripts.%(module)s import run; run()" %%$\n' 'if "%%_4ver%%" == "" %(python)s -c "from %(package)s.scripts.%(module)s import run; run()" %%*\n'
def copy_scripts(self): """ Create each script listed in 'self.scripts' """ if not self.package_name: raise Exception("You have to inherit build_scripts_create and" " provide a package name") to_module = string.maketrans('-/', '_.')
writer.addheader('Form', self.ISSUE_TRACKER_EMAIL)
writer.addheader('From', self.ISSUE_TRACKER_EMAIL)
def sendmessage(self, nodeid, msgid): """Send a message to the members of an issue's nosy list.
prop_test = self.cl.getprops()[property]
dummy = self.cl.getprops()[property]
def do_plain(self, property, escape=0): ''' display a String property directly;
s = _('Plain: bad propclass "%(propclass)s"')%locals()
value = _('Plain: bad propclass "%(propclass)s"')%locals()
def do_plain(self, property, escape=0): ''' display a String property directly;
arg_s = str(arg)
arg_s = str(args)
def do_history(self, direction='descending'): ''' list the history of the item
except KeyError, message:
except KeyError:
def do_history(self, direction='descending'): ''' list the history of the item
return replace.go(m.group('text'))
return replace.go(text)
def __call__(self, m, filter=None, columns=None, sort=None, group=None): if m.group('name'): if m.group('name') in self.props: text = m.group('text') replace = IndexTemplateReplace(self.globals, {}, self.props) return replace.go(m.group('text')) else: return '' if m.group('display'): command = m.group('command') return eval(command, self.globals, self.locals) print '*** unhandled match', m.groupdict()
print '*** unhandled match', m.groupdict()
return '*** unhandled match: %s'%str(m.groupdict())
def __call__(self, m, filter=None, columns=None, sort=None, group=None): if m.group('name'): if m.group('name') in self.props: text = m.group('text') replace = IndexTemplateReplace(self.globals, {}, self.props) return replace.go(m.group('text')) else: return '' if m.group('display'): command = m.group('command') return eval(command, self.globals, self.locals) print '*** unhandled match', m.groupdict()
TemplateFunctions.__init__(self)
def __init__(self, client, templates, classname): self.client = client self.instance = client.instance self.templates = templates self.classname = classname
prop = self.properties[name]
def filter_section(self, template, filter, columns, group, all_filters, all_columns, show_customization):
print '*** unhandled match', m.groupdict()
return '*** unhandled match: %s'%str(m.groupdict())
def __call__(self, m, filter=None, columns=None, sort=None, group=None): if m.group('name'): if self.nodeid and self.cl.get(self.nodeid, m.group('name')): replace = ItemTemplateReplace(self.globals, {}, self.cl, self.nodeid) return replace.go(m.group('text')) else: return '' if m.group('display'): command = m.group('command') return eval(command, self.globals, self.locals) print '*** unhandled match', m.groupdict()
try: self._ = self.gettext = client.gettext self.ngettext = client.ngettext except AttributeError: _translator = templating.translationService self._ = self.gettext = _translator.gettext self.ngettext = _translator.ngettext
def __init__(self, client): self.client = client self.db = client.db self.form = client.form self.classname = client.classname self.nodeid = client.nodeid
raise FormError, \ 'link "%s" value "%s" not a designator'%(key, entry)
raise FormError, self._('link "%(key)s" ' 'value "%(value)s" not a designator') % locals()
propdef = all_propdef[cn]
raise FormError, '%s %s is not a link or '\ 'multilink property'%(cn, propname)
raise FormError, self._('%(class)s %(property)s ' 'is not a link or multilink property') % { 'class':cn, 'property':propname}
propdef = all_propdef[cn]
raise FormError, 'You have submitted a %s action for'\ ' the property "%s" which doesn\'t exist'%(mlaction, propname)
raise FormError, self._('You have submitted a %(action)s ' 'action for the property "%(property)s" ' 'which doesn\'t exist') % { 'action': mlaction, 'property':propname}
propdef = all_propdef[cn]
raise FormError, 'You have submitted more than one value'\ ' for the %s property'%propname
raise FormError, self._('You have submitted more than one ' 'value for the %s property') % propname
propdef = all_propdef[cn]
raise FormError, 'Password and confirmation text do '\ 'not match'
raise FormError, self._('Password and confirmation text ' 'do not match')
propdef = all_propdef[cn]
raise FormError, _('property "%(propname)s": ' '"%(value)s" not currently in list')%{
raise FormError, self._('property ' '"%(propname)s": "%(value)s" ' 'not currently in list') % {
propdef = all_propdef[cn]
if len(required) > 1: p = 'properties' else: p = 'property' s.append('Required %s %s %s not supplied'%(thing[0], p, ', '.join(required)))
s.append(self.ngettext( 'Required %(class)s property %(property)s not supplied', 'Required %(class)s properties %(property)s not supplied', len(required) ) % {'class': thing[0], 'property': ', '.join(required)})
propdef = all_propdef[cn]
raise FormError, _('File is empty')
raise FormError, self._('File is empty')
propdef = all_propdef[cn]
self.second, x, x, x = spec self.offset = offset
self.second, x, x, x = time.gmtime(ts)
def __init__(self, spec='.', offset=0): """Construct a date given a specification and a time zone offset.
y,m,d,H,M,S,x,x,x = time.gmtime(time.time()) ts = calendar.timegm((y,m,d,H+offset,M,S,0,0,0))
y,m,d,H,M,S,x,x,x = time.gmtime() if info['m'] is not None and info['d'] is not None: m = int(info['m']) d = int(info['d']) if info['y'] is not None: y = int(info['y']) H = M = S = 0 if info['H'] is not None and info['M'] is not None: H = int(info['H']) - offset M = int(info['M']) S = 0 if info['S'] is not None: S = int(info['S']) ts = calendar.timegm((y,m,d,H,M,S,0,0,0))
def set(self, spec, offset=0, date_re=re.compile(r''' (((?P<y>\d\d\d\d)-)?((?P<m>\d\d)-(?P<d>\d\d))?)? # yyyy-mm-dd (?P<n>\.)? # . (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss (?P<o>.+)? # offset ''', re.VERBOSE)): ''' set the date to the value in spec ''' m = date_re.match(spec) if not m: raise ValueError, 'Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]] [offset]' info = m.groupdict()
if info['m'] is not None and info['d'] is not None: self.month = int(info['m']) self.day = int(info['d']) if info['y'] is not None: self.year = int(info['y']) self.hour = self.minute = self.second = 0 if info['H'] is not None and info['M'] is not None: self.hour = int(info['H']) self.minute = int(info['M']) if info['S'] is not None: self.second = int(info['S'])
def set(self, spec, offset=0, date_re=re.compile(r''' (((?P<y>\d\d\d\d)-)?((?P<m>\d\d)-(?P<d>\d\d))?)? # yyyy-mm-dd (?P<n>\.)? # . (((?P<H>\d?\d):(?P<M>\d\d))?(:(?P<S>\d\d))?)? # hh:mm:ss (?P<o>.+)? # offset ''', re.VERBOSE)): ''' set the date to the value in spec ''' m = date_re.match(spec) if not m: raise ValueError, 'Not a date spec: [[yyyy-]mm-dd].[[h]h:mm[:ss]] [offset]' info = m.groupdict()
valuu must contain a quote character, it must be backslash-quoted or inside
value must contain a quote character, it must be backslash-quoted or inside
def help_all(self): print _('''
Roch\'e Compaan (2 tokens: Roch'e Compaan)
Roch\\'e Compaan (2 tokens: Roch'e Compaan)
def help_all(self): print _('''
\\ (1 token: \) \n\r\t (1 token: a newline, carriage-return and tab)
\\\\ (1 token: \\) \\n\\r\\t (1 token: a newline, carriage-return and tab)
def help_all(self): print _('''
key, entry, self.properties[key].classname)
k, entry, self.properties[k].classname)
def filter(self, filterspec, sort, group, num_re = re.compile('^\d+$')): ''' Return a list of the ids of the active nodes in this class that match the 'filter' spec, sorted by the group spec and then the sort spec ''' cn = self.classname
if not fuzzy and str:
if not fuzzy and str and not str.startswith('\0'):
def add(id, str, fuzzy): "Add a non-fuzzy translation to the dictionary." global MESSAGES if not fuzzy and str: MESSAGES[id] = str
if len(msgstr) > 0: msgstr += '\0'
def make(filename, outfile): ID = 1 STR = 2 # Compute .mo name from .po name and arguments if filename.endswith('.po'): infile = filename else: infile = filename + '.po' if outfile is None: outfile = os.path.splitext(infile)[0] + '.mo' try: lines = open(infile).readlines() except IOError, msg: print >> sys.stderr, msg sys.exit(1) section = None fuzzy = 0 # Parse the catalog lno = 0 for l in lines: lno += 1 # If we get a comment line after a msgstr, this is a new entry if l[0] == '#' and section == STR: add(msgid, msgstr, fuzzy) section = None fuzzy = 0 # Record a fuzzy mark if l[:2] == '#,' and (l.find('fuzzy') >= 0): fuzzy = 1 # Skip comments if l[0] == '#': continue # Start of msgid_plural section, separate from singular form with \0 if l.startswith('msgid_plural'): msgid += '\0' l = l[12:] # Now we are in a msgid section, output previous section elif l.startswith('msgid'): if section == STR: add(msgid, msgstr, fuzzy) section = ID l = l[5:] msgid = msgstr = '' # Now we are in a msgstr section elif l.startswith('msgstr'): section = STR l = l[6:] # Check for plural forms if l.startswith('['): # Ignore the index - must come in sequence l = l[l.index(']') + 1:] # Separate plural forms with \0 if len(msgstr) > 0: msgstr += '\0' # Skip empty lines l = l.strip() if not l: continue # XXX: Does this always follow Python escape semantics? l = eval(l) if section == ID: msgid += l elif section == STR: msgstr += l else: print >> sys.stderr, 'Syntax error on %s:%d' % (infile, lno), \ 'before:' print >> sys.stderr, l sys.exit(1) # Add last entry if section == STR: add(msgid, msgstr, fuzzy) # Compute output output = generate() try: open(outfile,"wb").write(output) except IOError,msg: print >> sys.stderr, msg
def create_check(self): ''' Raise the Unauthorised exception if the user's not permitted to create items of this class. ''' if not self.is_create_ok(): raise Unauthorised("create", self._classname, translator=self._client.translator)
def create_check(self): ''' Raise the Unauthorised exception if the user's not permitted to create items of this class. ''' if not self.is_create_ok(): raise Unauthorised("create", self._classname, translator=self._client.translator)
return self.is_create_ok()
return self.is_edit_ok()
def is_view_ok(self): ''' Is the user allowed to View the current class? ''' if self._db.security.hasPermission('View', self._client.userid, self._classname): return 1 return self.is_create_ok()
return self.is_view_ok() and not self.is_create_ok()
return self.is_view_ok() and not self.is_edit_ok()
def is_only_view_ok(self): ''' Is the user only allowed to View (ie. not Create) the current class? ''' return self.is_view_ok() and not self.is_create_ok()
interval = now - okts.get(sessid, '__time')
interval = now - otks.get(sessid, '__time')
def clean_sessions(self): ''' Age sessions, remove when they haven't been used for a week. Do it only once an hour.
otk.destroy(sessid)
otks.destroy(sessid)
def clean_sessions(self): ''' Age sessions, remove when they haven't been used for a week. Do it only once an hour.
try: smtp = smtplib.SMTP(self.db.config.MAILHOST) smtp.sendmail(self.db.config.ADMIN_EMAIL, [to], message.getvalue()) except socket.error, value: self.error_message.append("Error: couldn't send email: " "mailhost %s"%value) return 0 except smtplib.SMTPException, value: self.error_message.append("Error: couldn't send email: %s"%value)
if SENDMAILDEBUG: open(SENDMAILDEBUG, 'a').write('FROM: %s\nTO: %s\n%s\n'%( self.db.config.ADMIN_EMAIL, ', '.join(to),message.getvalue())) else: try: smtp = smtplib.SMTP(self.db.config.MAILHOST) smtp.sendmail(self.db.config.ADMIN_EMAIL, [to], message.getvalue()) except socket.error, value: self.error_message.append("Error: couldn't send email: " "mailhost %s"%value) return 0 except smtplib.SMTPException, msg: self.error_message.append("Error: couldn't send email: %s"%msg)
def sendEmail(self, to, subject, content): # send email to the user's email address message = StringIO.StringIO() writer = MimeWriter.MimeWriter(message) tracker_name = self.db.config.TRACKER_NAME writer.addheader('Subject', encode_header(subject)) writer.addheader('To', to) writer.addheader('From', roundupdb.straddr((tracker_name, self.db.config.ADMIN_EMAIL))) writer.addheader('Date', time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime())) # add a uniquely Roundup header to help filtering writer.addheader('X-Roundup-Name', tracker_name) # avoid email loops writer.addheader('X-Roundup-Loop', 'hello') writer.addheader('Content-Transfer-Encoding', 'quoted-printable') body = writer.startbody('text/plain; charset=utf-8')
self.db.addnode(self.classname, newid, d)
def import_list(self, propnames, proplist): ''' Import a node - all information including "id" is present and should not be sanity checked. Triggers are not triggered. The journal should be initialised using the "creator" and "created" information.
from roundup.backends import anydbm
backend = backends.get_backend('anydbm')
def setUp(self): from roundup.backends import anydbm # remove previous test, ignore errors if os.path.exists(config.DATABASE): shutil.rmtree(config.DATABASE) os.makedirs(config.DATABASE + '/files') self.db = anydbm.Database(config, 'admin') setupSchema(self.db, 1, anydbm)
self.db = anydbm.Database(config, 'admin') setupSchema(self.db, 1, anydbm)
self.db = backend.Database(config, 'admin') setupSchema(self.db, 1, backend)
def setUp(self): from roundup.backends import anydbm # remove previous test, ignore errors if os.path.exists(config.DATABASE): shutil.rmtree(config.DATABASE) os.makedirs(config.DATABASE + '/files') self.db = anydbm.Database(config, 'admin') setupSchema(self.db, 1, anydbm)
else: propvalues[key] = None
def create_inner(self, **propvalues): ''' Called by create, in-between the audit and react calls. ''' if propvalues.has_key('id'): raise KeyError, '"id" is reserved'
self.db.indexer.add_text((self.classname, newid, 'content'), content, mime_type)
def create(self, **propvalues): ''' Snarf the "content" propvalue and store in a file ''' # we need to fire the auditors now, or the content property won't # be in propvalues for the auditors to play with self.fireAuditors('create', None, propvalues)
self.assertEqual(self.dex.find(['world']), {2: 'testing2', 1: 'testing1'}) self.assertEqual(self.dex.find(['blah']), {2: 'testing2'}) self.assertEqual(self.dex.find(['blah', 'hello']), {})
self.assertEqual(self.dex.find(['world']), ['testing1', 'testing2']) self.assertEqual(self.dex.find(['blah']), ['testing2']) self.assertEqual(self.dex.find(['blah', 'hello']), [])
def test_basics(self): self.dex.add_text('testing1', 'a the hello world') self.assertEqual(self.dex.words, {'HELLO': {1: 1}, 'WORLD': {1: 1}}) self.dex.add_text('testing2', 'blah blah the world') self.assertEqual(self.dex.words, {'BLAH': {2: 2}, 'HELLO': {1: 1}, 'WORLD': {2: 1, 1: 1}}) self.assertEqual(self.dex.find(['world']), {2: 'testing2', 1: 'testing1'}) self.assertEqual(self.dex.find(['blah']), {2: 'testing2'}) self.assertEqual(self.dex.find(['blah', 'hello']), {}) self.dex.save_index()
''' Age sessions, remove when they haven't been used for a week.
"""Age sessions, remove when they haven't been used for a week.
def clean_sessions(self): ''' Age sessions, remove when they haven't been used for a week. Do it only once an hour.
Do it only once an hour. Note: also cleans One Time Keys, and other "session" based stuff. '''
Do it only once an hour. Note: also cleans One Time Keys, and other "session" based stuff. """
def clean_sessions(self): ''' Age sessions, remove when they haven't been used for a week. Do it only once an hour.
''' Determine who the user is
'''Determine who the user is.
def determine_user(self): ''' Determine who the user is ''' # open the database as admin self.opendb('admin')
''' Determine the context of this page from the URL:
""" Determine the context of this page from the URL:
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')): ''' Determine the context of this page from the URL:
'''
"""
def determine_context(self, dre=re.compile(r'([^\d]+)(\d+)')): ''' Determine the context of this page from the URL:
''' Performs an edit of all of a class' items in one go.
""" Performs an edit of all of a class' items in one go.
def editCSVAction(self): ''' Performs an edit of all of a class' items in one go.
'''
"""
def editCSVAction(self): ''' Performs an edit of all of a class' items in one go.
''' Item properties and their values are edited with html FORM
""" Item properties and their values are edited with html FORM
def parsePropsFromForm(self, num_re=re.compile('^\d+$')): ''' Item properties and their values are edited with html FORM variables and their values. You can:
'''
"""
def parsePropsFromForm(self, num_re=re.compile('^\d+$')): ''' Item properties and their values are edited with html FORM variables and their values. You can:
try: import win32serviceutil except: RoundupService = None else: import win32service import win32event from win32event import * from win32file import * SvcShutdown = "ServiceShutdown" class RoundupService(win32serviceutil.ServiceFramework, BaseHTTPServer.HTTPServer): ''' A Roundup standalone server for Win32 by Ewout Prangsma ''' _svc_name_ = "Roundup Bug Tracker" _svc_display_name_ = "Roundup Bug Tracker" address = ('', 8888) def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) BaseHTTPServer.HTTPServer.__init__(self, self.address, RoundupRequestHandler) self.hevSvcStop = win32event.CreateEvent(None, 0, 0, None) self.hevConn = win32event.CreateEvent(None, 0, 0, None) import servicemanager self.servicemanager = servicemanager def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hevSvcStop) def SvcDoRun(self): try: self.serve_forever() except SvcShutdown: pass def get_request(self): WSAEventSelect(self.socket, self.hevConn, FD_ACCEPT) while 1: try: rv = self.socket.accept() except socket.error, why: if why[0] != WSAEWOULDBLOCK: raise rc = WaitForMultipleObjects((self.hevSvcStop, self.hevConn), 0, INFINITE) if rc == WAIT_OBJECT_0: raise SvcShutdown else: WSAEventSelect(rv[0], self.hevConn, 0) rv[0].setblocking(1) break return rv
def address_string(self): if self.LOG_IPADDRESS: return self.client_address[0] else: host, port = self.client_address return socket.getfqdn(host)
address = (hostname, port)
def run(): ''' Script entry point - handle args and figure out what to to. ''' # time out after a minute if we can import socket if hasattr(socket, 'setdefaulttimeout'): socket.setdefaulttimeout(60) hostname = '' port = 8080 pidfile = None logfile = None try: # handle the command-line args try: optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:d:l:hN') except getopt.GetoptError, e: usage(str(e)) user = ROUNDUP_USER for (opt, arg) in optlist: if opt == '-n': hostname = arg elif opt == '-p': port = int(arg) elif opt == '-u': user = arg elif opt == '-d': pidfile = abspath(arg) elif opt == '-l': logfile = abspath(arg) elif opt == '-h': usage() elif opt == '-N': RoundupRequestHandler.LOG_IPADDRESS = 0 if pidfile and not logfile: raise ValueError, _("logfile *must* be specified if pidfile is") if hasattr(os, 'getuid'): # if root, setuid to the running user if not os.getuid() and user is not None: try: import pwd except ImportError: raise ValueError, _("Can't change users - no pwd module") try: uid = pwd.getpwnam(user)[2] except KeyError: raise ValueError, _("User %(user)s doesn't exist")%locals() os.setuid(uid) elif os.getuid() and user is not None: print _('WARNING: ignoring "-u" argument, not root') # People can remove this check if they're really determined if not os.getuid() and user is None: raise ValueError, _("Can't run as root!") # handle tracker specs if args: d = {} for arg in args: try: name, home = arg.split('=') except ValueError: raise ValueError, _("Instances must be name=home") d[name] = home RoundupRequestHandler.TRACKER_HOMES = d except SystemExit: raise except: exc_type, exc_value = sys.exc_info()[:2] usage('%s: %s'%(exc_type, exc_value)) # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] address = (hostname, port) # fork? if pidfile: if RoundupService: # don't do any other stuff RoundupService.address = address return win32serviceutil.HandleCommandLine(RoundupService) elif not hasattr(os, 'fork'): print "Sorry, you can't run the server as a daemon on this" \ 'Operating System' sys.exit(0) else: daemonize(pidfile) # redirect stdout/stderr to our logfile if logfile: # appending, unbuffered sys.stdout = sys.stderr = open(logfile, 'a', 0) httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler) print _('Roundup server started on %(address)s')%locals() try: httpd.serve_forever() except KeyboardInterrupt: print 'Keyboard Interrupt: exiting'
if RoundupService: RoundupService.address = address return win32serviceutil.HandleCommandLine(RoundupService) elif not hasattr(os, 'fork'):
if not hasattr(os, 'fork'):
def run(): ''' Script entry point - handle args and figure out what to to. ''' # time out after a minute if we can import socket if hasattr(socket, 'setdefaulttimeout'): socket.setdefaulttimeout(60) hostname = '' port = 8080 pidfile = None logfile = None try: # handle the command-line args try: optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:d:l:hN') except getopt.GetoptError, e: usage(str(e)) user = ROUNDUP_USER for (opt, arg) in optlist: if opt == '-n': hostname = arg elif opt == '-p': port = int(arg) elif opt == '-u': user = arg elif opt == '-d': pidfile = abspath(arg) elif opt == '-l': logfile = abspath(arg) elif opt == '-h': usage() elif opt == '-N': RoundupRequestHandler.LOG_IPADDRESS = 0 if pidfile and not logfile: raise ValueError, _("logfile *must* be specified if pidfile is") if hasattr(os, 'getuid'): # if root, setuid to the running user if not os.getuid() and user is not None: try: import pwd except ImportError: raise ValueError, _("Can't change users - no pwd module") try: uid = pwd.getpwnam(user)[2] except KeyError: raise ValueError, _("User %(user)s doesn't exist")%locals() os.setuid(uid) elif os.getuid() and user is not None: print _('WARNING: ignoring "-u" argument, not root') # People can remove this check if they're really determined if not os.getuid() and user is None: raise ValueError, _("Can't run as root!") # handle tracker specs if args: d = {} for arg in args: try: name, home = arg.split('=') except ValueError: raise ValueError, _("Instances must be name=home") d[name] = home RoundupRequestHandler.TRACKER_HOMES = d except SystemExit: raise except: exc_type, exc_value = sys.exc_info()[:2] usage('%s: %s'%(exc_type, exc_value)) # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] address = (hostname, port) # fork? if pidfile: if RoundupService: # don't do any other stuff RoundupService.address = address return win32serviceutil.HandleCommandLine(RoundupService) elif not hasattr(os, 'fork'): print "Sorry, you can't run the server as a daemon on this" \ 'Operating System' sys.exit(0) else: daemonize(pidfile) # redirect stdout/stderr to our logfile if logfile: # appending, unbuffered sys.stdout = sys.stderr = open(logfile, 'a', 0) httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler) print _('Roundup server started on %(address)s')%locals() try: httpd.serve_forever() except KeyboardInterrupt: print 'Keyboard Interrupt: exiting'
httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler)
def run(): ''' Script entry point - handle args and figure out what to to. ''' # time out after a minute if we can import socket if hasattr(socket, 'setdefaulttimeout'): socket.setdefaulttimeout(60) hostname = '' port = 8080 pidfile = None logfile = None try: # handle the command-line args try: optlist, args = getopt.getopt(sys.argv[1:], 'n:p:u:d:l:hN') except getopt.GetoptError, e: usage(str(e)) user = ROUNDUP_USER for (opt, arg) in optlist: if opt == '-n': hostname = arg elif opt == '-p': port = int(arg) elif opt == '-u': user = arg elif opt == '-d': pidfile = abspath(arg) elif opt == '-l': logfile = abspath(arg) elif opt == '-h': usage() elif opt == '-N': RoundupRequestHandler.LOG_IPADDRESS = 0 if pidfile and not logfile: raise ValueError, _("logfile *must* be specified if pidfile is") if hasattr(os, 'getuid'): # if root, setuid to the running user if not os.getuid() and user is not None: try: import pwd except ImportError: raise ValueError, _("Can't change users - no pwd module") try: uid = pwd.getpwnam(user)[2] except KeyError: raise ValueError, _("User %(user)s doesn't exist")%locals() os.setuid(uid) elif os.getuid() and user is not None: print _('WARNING: ignoring "-u" argument, not root') # People can remove this check if they're really determined if not os.getuid() and user is None: raise ValueError, _("Can't run as root!") # handle tracker specs if args: d = {} for arg in args: try: name, home = arg.split('=') except ValueError: raise ValueError, _("Instances must be name=home") d[name] = home RoundupRequestHandler.TRACKER_HOMES = d except SystemExit: raise except: exc_type, exc_value = sys.exc_info()[:2] usage('%s: %s'%(exc_type, exc_value)) # we don't want the cgi module interpreting the command-line args ;) sys.argv = sys.argv[:1] address = (hostname, port) # fork? if pidfile: if RoundupService: # don't do any other stuff RoundupService.address = address return win32serviceutil.HandleCommandLine(RoundupService) elif not hasattr(os, 'fork'): print "Sorry, you can't run the server as a daemon on this" \ 'Operating System' sys.exit(0) else: daemonize(pidfile) # redirect stdout/stderr to our logfile if logfile: # appending, unbuffered sys.stdout = sys.stderr = open(logfile, 'a', 0) httpd = BaseHTTPServer.HTTPServer(address, RoundupRequestHandler) print _('Roundup server started on %(address)s')%locals() try: httpd.serve_forever() except KeyboardInterrupt: print 'Keyboard Interrupt: exiting'
init.initialise(self.dirname, 'sekrit') self.instance = instance.open(self.dirname)
self.instance = tracker = instance.open(self.dirname) if tracker.exists(): tracker.nuke() tracker.init(password.Password('sekrit'))
def setUp(self): self.dirname = '_test_cgi_form' try: shutil.rmtree(self.dirname) except OSError, error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise # create the instance init.install(self.dirname, 'templates/classic') init.write_select_db(self.dirname, 'anydbm') init.initialise(self.dirname, 'sekrit') # check we can load the package self.instance = instance.open(self.dirname) # and open the database self.db = self.instance.open('admin') self.db.user.create(username='Chef', address='[email protected]', realname='Bork, Chef', roles='User') self.db.user.create(username='mary', address='mary@test', roles='User', realname='Contrary, Mary')
test = self.instance.dbinit.Class(self.db, "test",
test = self.instance.get_backend().Class(self.db, "test",
def setUp(self): self.dirname = '_test_cgi_form' try: shutil.rmtree(self.dirname) except OSError, error: if error.errno not in (errno.ENOENT, errno.ESRCH): raise # create the instance init.install(self.dirname, 'templates/classic') init.write_select_db(self.dirname, 'anydbm') init.initialise(self.dirname, 'sekrit') # check we can load the package self.instance = instance.open(self.dirname) # and open the database self.db = self.instance.open('admin') self.db.user.create(username='Chef', address='[email protected]', realname='Bork, Chef', roles='User') self.db.user.create(username='mary', address='mary@test', roles='User', realname='Contrary, Mary')