rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
args[x] = argv.value
|
args[x] = argv.value.replace('\r','')
|
def real_main(): import sync import Href import perm import auth from util import redirect path_info = os.getenv('PATH_INFO') remote_addr = os.getenv('REMOTE_ADDR') remote_user = os.getenv('REMOTE_USER') http_cookie = os.getenv('HTTP_COOKIE') http_referer = os.getenv('HTTP_REFERER') cgi_location = os.getenv('SCRIPT_NAME') database = open_database() config = database.load_config() Href.initialize(cgi_location) # Authenticate the user cookie = Cookie.SimpleCookie(http_cookie) if cookie.has_key('trac_auth'): auth_cookie = cookie['trac_auth'].value else: auth_cookie = None authenticator = auth.Authenticator(database, auth_cookie, remote_addr) if path_info == '/logout': authenticator.logout() redirect (http_referer or Href.href.wiki()) elif remote_user and authenticator.authname == 'anonymous': auth_cookie = authenticator.login(remote_user, remote_addr) # send the cookie to the browser as a http header cookie = Cookie.SimpleCookie() cookie['trac_auth'] = auth_cookie cookie['trac_auth']['path'] = cgi_location print cookie.output() if path_info == '/login': redirect (http_referer or Href.href.wiki()) # Parse arguments args = parse_args(path_info) _args = cgi.FieldStorage() for x in _args.keys(): argv = _args[x] if type(argv) == list: argv = argv[0] args[x] = argv.value # Load the selected module mode = args.get('mode', 'wiki') module_name, constructor_name, need_svn = modules[mode] module = __import__(module_name, globals(), locals(), []) constructor = getattr(module, constructor_name) module = constructor(config, args) module._name = mode module.db = database module.authname = authenticator.authname module.remote_addr = remote_addr module.cgi_location = cgi_location module.perm = perm.PermissionCache(database, authenticator.authname) module.perm.add_to_hdf(module.cgi.hdf) # Only open the subversion repository for the modules that really # need it. This saves us some precious time. if need_svn: from svn import util, repos, core core.apr_initialize() pool = core.svn_pool_create(None) repos_dir = config['general']['repository_dir'] # Remove any trailing slash or else subversion might abort if not os.path.split(repos_dir)[1]: repos_dir = os.path.split(repos_dir)[0] rep = repos.svn_repos_open(repos_dir, pool) fs_ptr = repos.svn_repos_fs(rep) module.repos = rep module.fs_ptr = fs_ptr sync.sync(database, rep, fs_ptr, pool) else: pool = None # Let the wiki module build a dictionary of all page names import Wiki Wiki.populate_page_dict(database) module.pool = pool module.run() if pool: core.svn_pool_destroy(pool) core.apr_terminate()
|
self.assertEqual((3, 0), diff2._get_change_extent('xxx', 'xxx')) self.assertEqual((0, 0), diff2._get_change_extent('', 'xxx')) self.assertEqual((0, 0), diff2._get_change_extent('xxx', '')) self.assertEqual((0, 0), diff2._get_change_extent('xxx', 'yyy')) self.assertEqual((1, -1), diff2._get_change_extent('xxx', 'xyx')) self.assertEqual((1, -1), diff2._get_change_extent('xxx', 'xyyyx')) self.assertEqual((1, 0), diff2._get_change_extent('xy', 'xzz')) self.assertEqual((1, -1), diff2._get_change_extent('xyx', 'xzzx')) self.assertEqual((1, -1), diff2._get_change_extent('xzzx', 'xyx'))
|
self.assertEqual((3, 0), Diff._get_change_extent('xxx', 'xxx')) self.assertEqual((0, 0), Diff._get_change_extent('', 'xxx')) self.assertEqual((0, 0), Diff._get_change_extent('xxx', '')) self.assertEqual((0, 0), Diff._get_change_extent('xxx', 'yyy')) self.assertEqual((1, -1), Diff._get_change_extent('xxx', 'xyx')) self.assertEqual((1, -1), Diff._get_change_extent('xxx', 'xyyyx')) self.assertEqual((1, 0), Diff._get_change_extent('xy', 'xzz')) self.assertEqual((1, -1), Diff._get_change_extent('xyx', 'xzzx')) self.assertEqual((1, -1), Diff._get_change_extent('xzzx', 'xyx'))
|
def test_get_change_extent(self): self.assertEqual((3, 0), diff2._get_change_extent('xxx', 'xxx')) self.assertEqual((0, 0), diff2._get_change_extent('', 'xxx')) self.assertEqual((0, 0), diff2._get_change_extent('xxx', '')) self.assertEqual((0, 0), diff2._get_change_extent('xxx', 'yyy')) self.assertEqual((1, -1), diff2._get_change_extent('xxx', 'xyx')) self.assertEqual((1, -1), diff2._get_change_extent('xxx', 'xyyyx')) self.assertEqual((1, 0), diff2._get_change_extent('xy', 'xzz')) self.assertEqual((1, -1), diff2._get_change_extent('xyx', 'xzzx')) self.assertEqual((1, -1), diff2._get_change_extent('xzzx', 'xyx'))
|
opcodes = diff2._get_opcodes(['A', 'B'], ['A', 'B', ''],
|
opcodes = Diff._get_opcodes(['A', 'B'], ['A', 'B', ''],
|
def test_insert_blank_line(self): opcodes = diff2._get_opcodes(['A', 'B'], ['A', 'B', ''], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('insert', 2, 2, 2, 3), opcodes.next())
|
opcodes = diff2._get_opcodes(['A'], ['A', 'B', ''],
|
opcodes = Diff._get_opcodes(['A'], ['A', 'B', ''],
|
def test_insert_blank_line(self): opcodes = diff2._get_opcodes(['A', 'B'], ['A', 'B', ''], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('insert', 2, 2, 2, 3), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B', ''], ['A', 'B'],
|
opcodes = Diff._get_opcodes(['A', 'B', ''], ['A', 'B'],
|
def test_delete_blank_line(self): opcodes = diff2._get_opcodes(['A', 'B', ''], ['A', 'B'], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('delete', 2, 3, 2, 2), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B', ''], ['A'],
|
opcodes = Diff._get_opcodes(['A', 'B', ''], ['A'],
|
def test_delete_blank_line(self): opcodes = diff2._get_opcodes(['A', 'B', ''], ['A', 'B'], ignore_blank_lines=0) self.assertEqual(('equal', 0, 2, 0, 2), opcodes.next()) self.assertEqual(('delete', 2, 3, 2, 2), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B b'],
|
opcodes = Diff._get_opcodes(['A', 'B b'], ['A', 'B b'],
|
def test_space_changes(self): opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B b'], ignore_space_changes=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B B'],
|
opcodes = Diff._get_opcodes(['A', 'B b'], ['A', 'B B'],
|
def test_case_changes(self): opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B B'],
|
opcodes = Diff._get_opcodes(['A', 'B b'], ['A', 'B B'],
|
def test_space_and_case_changes(self): opcodes = diff2._get_opcodes(['A', 'B b'], ['A', 'B B'], ignore_case=0, ignore_space_changes=0) self.assertEqual(('equal', 0, 1, 0, 1), opcodes.next()) self.assertEqual(('replace', 1, 2, 1, 2), opcodes.next())
|
opcodes = diff2._get_opcodes(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
|
opcodes = Diff._get_opcodes(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
|
def test_grouped_opcodes_context1(self): opcodes = diff2._get_opcodes(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['A', 'B', 'C', 'd', 'e', 'f', 'G', 'H']) groups = diff2._group_opcodes(opcodes, n=1) group = groups.next() self.assertEqual(('equal', 2, 3, 2, 3), group[0]) self.assertEqual(('replace', 3, 6, 3, 6), group[1]) self.assertEqual(('equal', 6, 8, 6, 8), group[2])
|
groups = diff2._group_opcodes(opcodes, n=1)
|
groups = Diff._group_opcodes(opcodes, n=1)
|
def test_grouped_opcodes_context1(self): opcodes = diff2._get_opcodes(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'], ['A', 'B', 'C', 'd', 'e', 'f', 'G', 'H']) groups = diff2._group_opcodes(opcodes, n=1) group = groups.next() self.assertEqual(('equal', 2, 3, 2, 3), group[0]) self.assertEqual(('replace', 3, 6, 3, 6), group[1]) self.assertEqual(('equal', 6, 8, 6, 8), group[2])
|
import textwrap return '\n'.join(textwrap.wrap(t, replace_whitespace=0, width=cols, break_long_words=0,
|
import textwrap t = t.replace('\r\n', '\n').replace('\r', '\n') wrapper = textwrap.TextWrapper(cols, replace_whitespace=0, break_long_words=0,
|
def wrap(t, cols=75, initial_indent='', subsequent_indent=''): try: import textwrap return '\n'.join(textwrap.wrap(t, replace_whitespace=0, width=cols, break_long_words=0, initial_indent=initial_indent, subsequent_indent=subsequent_indent)) except ImportError: return t
|
subsequent_indent=subsequent_indent))
|
subsequent_indent=subsequent_indent) wrappedLines = [] for line in t.split('\n'): wrappedLines += wrapper.wrap(line.rstrip()) return '\n'.join(wrappedLines)
|
def wrap(t, cols=75, initial_indent='', subsequent_indent=''): try: import textwrap return '\n'.join(textwrap.wrap(t, replace_whitespace=0, width=cols, break_long_words=0, initial_indent=initial_indent, subsequent_indent=subsequent_indent)) except ImportError: return t
|
self.COLS)
|
self.COLS, initial_indent=' ', subsequent_indent=' ')
|
def notify(self, tktid, newticket=1, modtime=0):
|
subsequent_indent=' ').strip()
|
subsequent_indent=' ')
|
def notify(self, tktid, newticket=1, modtime=0):
|
self._pages = None
|
self._index = None self._last_index_update = 0
|
def __init__(self): self._pages = None
|
def _load_pages(self): self._pages = {} db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT DISTINCT name FROM wiki") for (name,) in cursor: self._pages[name] = True
|
def _update_index(self): now = time.time() if now > self._last_index_update + WikiSystem.INDEX_UPDATE_INTERVAL: self.log.debug('Updating wiki page index') db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT DISTINCT name FROM wiki") self._index = {} for (name,) in cursor: self._index[name] = True self._last_index_update = now
|
def _load_pages(self): self._pages = {} db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT DISTINCT name FROM wiki") for (name,) in cursor: self._pages[name] = True
|
if self._pages is None: self._load_pages() for page in self._pages.keys():
|
self._update_index() for page in self._index.keys():
|
def get_pages(self, prefix=None): if self._pages is None: self._load_pages() for page in self._pages.keys(): if not prefix or page.startswith(prefix): yield page
|
if self._pages is None: self._load_pages() return pagename in self._pages.keys()
|
self._update_index() return pagename in self._index.keys()
|
def has_page(self, pagename): if self._pages is None: self._load_pages() return pagename in self._pages.keys()
|
yield (r"!?(^|(?<=[^A-Za-z]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+(?:
|
yield (r"!?(^|(?<=[^A-Za-z]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+(?: lambda x, y, z: self._format_link(x, 'wiki', y, y))
|
def get_wiki_syntax(self): yield (r"!?(^|(?<=[^A-Za-z]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+(?:#[A-Za-z0-9]+)?(?=\Z|\s|[.,;:!?\)}\]])", lambda x, y, z: self._format_link(x, 'wiki', y, y))
|
hdf.setValue(p + '.descr', wiki_to_oneliner(file['description'], hdf, self,self.get_db_cnx))
|
hdf.setValue(p + '.descr', wiki_to_oneliner(file['description'], hdf, self,self.get_db_cnx() ))
|
def get_attachments_hdf(self, cnx, type, id, hdf, prefix): from Wiki import wiki_to_oneliner files = self.get_attachments(cnx, type, id) idx = 0 for file in files: p = '%s.%d' % (prefix, idx) hdf.setValue(p + '.name', file['filename']) hdf.setValue(p + '.descr', wiki_to_oneliner(file['description'], hdf, self,self.get_db_cnx)) hdf.setValue(p + '.author', util.escape(file['author'])) hdf.setValue(p + '.ipnr', file['ipnr']) hdf.setValue(p + '.size', util.pretty_size(file['size'])) hdf.setValue(p + '.time', time.strftime('%c', time.localtime(file['time']))) hdf.setValue(p + '.href', self.href.attachment(type, id, file['filename'])) idx += 1
|
self.req.hdf.setValue('title', self.path)
|
def display(self): self.env.log.debug("Displaying file: %s mime-type: %s" % (self.filename, self.mime_type)) # We don't have to guess if the charset is specified in the # svn:mime-type property ctpos = self.mime_type.find('charset=') if ctpos >= 0: charset = self.mime_type[ctpos + 8:] self.env.log.debug("Charset %s selected" % charset) else: charset = self.env.get_config('trac', 'default_charset', 'iso-8859-15') data = util.to_utf8(self.read_func(self.DISP_MAX_FILE_SIZE), charset)
|
|
def _history(self, path, start, end, limit=None):
|
def _history(self, path, start, end, limit=None, pool=None):
|
def _history(self, path, start, end, limit=None): scoped_path = posixpath.join(self.scope[1:], path) return _get_history(scoped_path, self.authz, self.fs_ptr, self.pool, start, end, limit)
|
return _get_history(scoped_path, self.authz, self.fs_ptr, self.pool, start, end, limit)
|
return _get_history(scoped_path, self.authz, self.fs_ptr, pool or self.pool, start, end, limit) def _previous_rev(self, rev, path='', pool=None): if rev > 1: try: for _, prev in self._history(path, 0, rev-1, limit=1, pool=pool): return prev except (SystemError, core.SubversionException): pass return None
|
def _history(self, path, start, end, limit=None): scoped_path = posixpath.join(self.scope[1:], path) return _get_history(scoped_path, self.authz, self.fs_ptr, self.pool, start, end, limit)
|
if rev > 1: try: for _, prev in self._history(path, 0, rev-1, limit=1): return prev except (SystemError, core.SubversionException): pass return None
|
return self._previous_rev(rev, path)
|
def previous_rev(self, rev, path=''): rev = self.normalize_rev(rev) if rev > 1: # don't use oldest here, as it's too expensive try: for _, prev in self._history(path, 0, rev-1, limit=1): return prev except (SystemError, # "null arg to internal routine" in 1.2.x core.SubversionException): # in 1.3.x pass return None
|
rev = self.previous_rev(r)
|
rev = self._previous_rev(r, pool=subpool)
|
def get_path_history(self, path, rev=None, limit=None): path = self.normalize_path(path) rev = self.normalize_rev(rev) expect_deletion = False subpool = Pool(self.pool) while rev: subpool.clear() if self.has_node(path, rev, subpool): if expect_deletion: # it was missing, now it's there again: # rev+1 must be a delete yield path, rev+1, Changeset.DELETE newer = None # 'newer' is the previously seen history tuple older = None # 'older' is the currently examined history tuple for p, r in _get_history(self.scope + path, self.authz, self.fs_ptr, subpool, 0, rev, limit): older = (_path_within_scope(self.scope, p), r, Changeset.ADD) rev = self.previous_rev(r) if newer: if older[0] == path: # still on the path: 'newer' was an edit yield newer[0], newer[1], Changeset.EDIT else: # the path changed: 'newer' was a copy rev = self.previous_rev(newer[1]) # restart before the copy op yield newer[0], newer[1], Changeset.COPY older = (older[0], older[1], 'unknown') break newer = older if older: # either a real ADD or the source of a COPY yield older else: expect_deletion = True rev = self.previous_rev(rev)
|
rev = self.previous_rev(newer[1])
|
rev = self._previous_rev(newer[1], pool=subpool)
|
def get_path_history(self, path, rev=None, limit=None): path = self.normalize_path(path) rev = self.normalize_rev(rev) expect_deletion = False subpool = Pool(self.pool) while rev: subpool.clear() if self.has_node(path, rev, subpool): if expect_deletion: # it was missing, now it's there again: # rev+1 must be a delete yield path, rev+1, Changeset.DELETE newer = None # 'newer' is the previously seen history tuple older = None # 'older' is the currently examined history tuple for p, r in _get_history(self.scope + path, self.authz, self.fs_ptr, subpool, 0, rev, limit): older = (_path_within_scope(self.scope, p), r, Changeset.ADD) rev = self.previous_rev(r) if newer: if older[0] == path: # still on the path: 'newer' was an edit yield newer[0], newer[1], Changeset.EDIT else: # the path changed: 'newer' was a copy rev = self.previous_rev(newer[1]) # restart before the copy op yield newer[0], newer[1], Changeset.COPY older = (older[0], older[1], 'unknown') break newer = older if older: # either a real ADD or the source of a COPY yield older else: expect_deletion = True rev = self.previous_rev(rev)
|
rev = self.previous_rev(rev)
|
rev = self._previous_rev(rev, pool=subpool)
|
def get_path_history(self, path, rev=None, limit=None): path = self.normalize_path(path) rev = self.normalize_rev(rev) expect_deletion = False subpool = Pool(self.pool) while rev: subpool.clear() if self.has_node(path, rev, subpool): if expect_deletion: # it was missing, now it's there again: # rev+1 must be a delete yield path, rev+1, Changeset.DELETE newer = None # 'newer' is the previously seen history tuple older = None # 'older' is the currently examined history tuple for p, r in _get_history(self.scope + path, self.authz, self.fs_ptr, subpool, 0, rev, limit): older = (_path_within_scope(self.scope, p), r, Changeset.ADD) rev = self.previous_rev(r) if newer: if older[0] == path: # still on the path: 'newer' was an edit yield newer[0], newer[1], Changeset.EDIT else: # the path changed: 'newer' was a copy rev = self.previous_rev(newer[1]) # restart before the copy op yield newer[0], newer[1], Changeset.COPY older = (older[0], older[1], 'unknown') break newer = older if older: # either a real ADD or the source of a COPY yield older else: expect_deletion = True rev = self.previous_rev(rev)
|
options = field['options']
|
options = field['options'][:]
|
def process_request(self, req): req.perm.assert_permission('TICKET_CREATE')
|
pobj.close() if sys.platform[:3] != "win" and sys.platform != "os2emx": os.waitpid(-1, 0)
|
def print_diff (self, old_path, new_path, pool): options = ['-u'] options.append('-L') options.append("%s\t(revision %d)" % (old_path, self.rev-1)) options.append('-L') options.append("%s\t(revision %d)" % (new_path, self.rev))
|
|
txt += '\n'
|
txt += CRLF
|
def format_props(self): tkt = self.ticket fields = [f for f in tkt.fields if f['type'] != 'textarea' and f['name'] not in ('summary', 'cc')] t = self.modtime or tkt.time_changed width = [0, 0, 0, 0] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if fval.find('\n') > -1: continue idx = 2 * (i % 2) if len(f) > width[idx]: width[idx] = len(f) if len(fval) > width[idx + 1]: width[idx + 1] = len(fval) format = ('%%%is: %%-%is | ' % (width[0], width[1]), ' %%%is: %%-%is%s' % (width[2], width[3], CRLF)) i = 1 l = (width[0] + width[1] + 5) sep = l*'-' + '+' + (self.COLS-l)*'-' txt = sep + CRLF big = [] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if '\n' in str(fval): big.append((f.capitalize(), fval)) else: txt += format[i % 2] % (f.capitalize(), fval) if not i % 2: txt += '\n' if big: txt += sep for k,v in big: txt += '\n%s:\n%s\n\n' % (k,v) txt += sep return txt
|
for k,v in big: txt += '\n%s:\n%s\n\n' % (k,v)
|
for name, value in big: txt += CRLF.join(['', name + ':', value, '', '')]
|
def format_props(self): tkt = self.ticket fields = [f for f in tkt.fields if f['type'] != 'textarea' and f['name'] not in ('summary', 'cc')] t = self.modtime or tkt.time_changed width = [0, 0, 0, 0] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if fval.find('\n') > -1: continue idx = 2 * (i % 2) if len(f) > width[idx]: width[idx] = len(f) if len(fval) > width[idx + 1]: width[idx + 1] = len(fval) format = ('%%%is: %%-%is | ' % (width[0], width[1]), ' %%%is: %%-%is%s' % (width[2], width[3], CRLF)) i = 1 l = (width[0] + width[1] + 5) sep = l*'-' + '+' + (self.COLS-l)*'-' txt = sep + CRLF big = [] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if '\n' in str(fval): big.append((f.capitalize(), fval)) else: txt += format[i % 2] % (f.capitalize(), fval) if not i % 2: txt += '\n' if big: txt += sep for k,v in big: txt += '\n%s:\n%s\n\n' % (k,v) txt += sep return txt
|
lambda x: _mark_weakpool_invalid(weakself));
|
lambda x: \ _mark_weakpool_invalid(weakself));
|
def _mark_valid(self): """Mark pool as valid""" if self._parent_pool: # Refer to self using a weakreference so that we don't # create a reference cycle weakself = weakref.ref(self)
|
raise TracError, "%s does not appear to be a Subversion repository." % (path, )
|
raise TracError, \ "%s does not appear to be a Subversion repository." % (path, )
|
def __init__(self, path, authz, log): Repository.__init__(self, authz, log)
|
self.log.debug("Opening subversion file-system at %s with scope %s" % (self.path, self.scope))
|
self.log.debug("Opening subversion file-system at %s with scope %s" \ % (self.path, self.scope))
|
def __init__(self, path, authz, log): Repository.__init__(self, authz, log)
|
cursor.execute("SELECT rev FROM revision ORDER BY -LENGTH(rev), rev DESC LIMIT 1")
|
cursor.execute("SELECT rev FROM revision " "ORDER BY -LENGTH(rev), rev DESC LIMIT 1")
|
def get_youngest_rev_in_cache(self, db): """ Get the latest stored revision by sorting the revision strings numerically """ cursor = db.cursor() cursor.execute("SELECT rev FROM revision ORDER BY -LENGTH(rev), rev DESC LIMIT 1") row = cursor.fetchone() return row and row[0] or None
|
change = newer[0] == older[0] and Changeset.EDIT or Changeset.COPY
|
change = newer[0] == older[0] and Changeset.EDIT or \ Changeset.COPY
|
def get_history(self,limit=None): newer = None # 'newer' is the previously seen history tuple older = None # 'older' is the currently examined history tuple pool = Pool(self.pool) for path, rev in _get_history(self.scoped_path, self.authz, self.fs_ptr, pool, 0, self._requested_rev, limit): if rev > 0 and path.startswith(self.scope): older = (path[len(self.scope):], rev, Changeset.ADD) if newer: change = newer[0] == older[0] and Changeset.EDIT or Changeset.COPY newer = (newer[0], newer[1], change) yield newer newer = older if newer: yield newer
|
np = NaivePopen(cmdline, content.encode('utf-8'), capturestderr=1)
|
content = content_to_unicode(self.env, content, mimetype) content = content.encode('utf-8') np = NaivePopen(cmdline, content, capturestderr=1)
|
def render(self, req, mimetype, content, filename=None, rev=None): cmdline = self.config.get('mimeviewer', 'php_path') # -n to ignore php.ini so we're using default colors cmdline += ' -sn' self.env.log.debug("PHP command line: %s" % cmdline)
|
projects.sort(lambda x, y: cmp(x['name'], y['name']))
|
projects.sort(lambda x, y: cmp(x['name'].lower(), y['name'].lower()))
|
def send_project_index(req, options, env_paths=None): from trac.web.clearsilver import HDFWrapper if 'TRAC_ENV_INDEX_TEMPLATE' in options: tmpl_path, template = os.path.split(options['TRAC_ENV_INDEX_TEMPLATE']) from trac.config import default_dir req.hdf = HDFWrapper(loadpaths=[default_dir('templates'), tmpl_path]) tmpl_vars = {} if 'TRAC_TEMPLATE_VARS' in options: for pair in options['TRAC_TEMPLATE_VARS'].split(','): key, val = pair.split('=') req.hdf[key] = val else: req.hdf = HDFWrapper() template = req.hdf.parse('''<html>
|
self.old_name = name
|
def __init__(self, env, perm_=None, name=None, db=None): self.env = env self.old_name = name self.perm = perm_ if name: self._fetch(name, db) else: self.name = None self.due = 0 self.completed = 0 self.description = ''
|
|
else: self.name = None self.due = 0 self.completed = 0
|
self.old_name = name else: self.name = self.old_name = None self.due = self.completed = 0
|
def __init__(self, env, perm_=None, name=None, db=None): self.env = env self.old_name = name self.perm = perm_ if name: self._fetch(name, db) else: self.name = None self.due = 0 self.completed = 0 self.description = ''
|
if milestone.exists: req.redirect(self.env.href.milestone(milestone.name)) else: req.redirect(self.env.href.roadmap())
|
req.redirect(self.env.href.milestone(milestone.name))
|
def _do_save(self, req, db, milestone): if req.args.has_key('save'): if not 'name' in req.args.keys(): raise TracError('You must provide a name for the milestone.', 'Required Field Missing') milestone.name = req.args.get('name')
|
width = self.logo_width > -1 or None height = self.logo_height > -1 or None
|
width = self.logo_width > -1 and self.logo_width height = self.logo_height > -1 and self.logo_height
|
def populate_hdf(self, req, handler): """Add chrome-related data to the HDF."""
|
r"(?P<heading>^\s*(?P<hdepth>=+)\s.*\s(?P=hdepth)\s*$)",
|
r"(?P<heading>^\s*(?P<hdepth>=+)\s.*\s(?P=hdepth)\s*" r"(?P<hanchor>
|
def process(self, req, text, in_paragraph=False): if self.error: text = system_message(Markup('Error: Failed to load processor ' '<code>%s</code>', self.name), self.error) else: text = self.processor(req, text) if in_paragraph: content_for_span = None interrupt_paragraph = False if isinstance(text, Element): tagname = text.tagname.lower() if tagname == 'div': class_ = text.attr.get('class_', '') if class_ and 'code' in class_: content_for_span = text.children else: interrupt_paragraph = True elif tagname == 'table': interrupt_paragraph = True else: match = re.match(self._code_block_re, text) if match: if match.group(1) and 'code' in match.group(1): content_for_span = match.group(2) else: interrupt_paragraph = True elif text.startswith('<table'): interrupt_paragraph = True if content_for_span: text = html.SPAN(class_='code-block')[content_for_span] elif interrupt_paragraph: text = "</p>%s<p>" % to_unicode(text) return text
|
_anchor_re = re.compile('[^\w/-:]+', re.UNICODE)
|
_anchor_re = re.compile('[^\w:.-]+', re.UNICODE)
|
def process(self, req, text, in_paragraph=False): if self.error: text = system_message(Markup('Error: Failed to load processor ' '<code>%s</code>', self.name), self.error) else: text = self.processor(req, text) if in_paragraph: content_for_span = None interrupt_paragraph = False if isinstance(text, Element): tagname = text.tagname.lower() if tagname == 'div': class_ = text.attr.get('class_', '') if class_ and 'code' in class_: content_for_span = text.children else: interrupt_paragraph = True elif tagname == 'table': interrupt_paragraph = True else: match = re.match(self._code_block_re, text) if match: if match.group(1) and 'code' in match.group(1): content_for_span = match.group(2) else: interrupt_paragraph = True elif text.startswith('<table'): interrupt_paragraph = True if content_for_span: text = html.SPAN(class_='code-block')[content_for_span] elif interrupt_paragraph: text = "</p>%s<p>" % to_unicode(text) return text
|
heading = match[depth+1:-depth-1] text = wiki_to_oneliner(heading, self.env, self.db, False, self._absurls) sans_markup = text.plaintext(keeplinebreaks=False) anchor = self._anchor_re.sub('', sans_markup) if not anchor or not anchor[0].isalpha(): anchor = 'a' + anchor
|
anchor = fullmatch.group('hanchor') or '' heading = match[depth+1:-depth-1-len(anchor)] heading = wiki_to_oneliner(heading, self.env, self.db, False, self._absurls) if anchor: anchor = anchor[1:] else: sans_markup = heading.plaintext(keeplinebreaks=False) anchor = self._anchor_re.sub('', sans_markup) if not anchor or anchor[0].isdigit() or anchor[0] in '.-': anchor = 'a' + anchor
|
def _heading_formatter(self, match, fullmatch): match = match.strip() self.close_table() self.close_paragraph() self.close_indentation() self.close_list() self.close_def_list()
|
self.out.write('<h%d id="%s">%s</h%d>' % (depth, anchor, text, depth))
|
self.out.write('<h%d id="%s">%s</h%d>' % (depth, anchor, heading, depth))
|
def _heading_formatter(self, match, fullmatch): match = match.strip() self.close_table() self.close_paragraph() self.close_indentation() self.close_list() self.close_def_list()
|
if not text: return '' elif len(text) < maxlen: shortline = text else: last_cut = i = j = -1 cut = 0 while cut < maxlen and cut > last_cut: last_cut = cut i = text.find('[[BR]]', i+1) j = text.find('\n', j+1) cut = max(i,j) if last_cut > 0: shortline = text[:last_cut]+' ...' else: i = text[:maxlen].rfind(' ') if i == -1: i = maxlen shortline = text[:i]+' ...'
|
if len(text) < maxlen: return text shortline = text[:maxlen] cut = shortline.rfind(' ') + 1 or shortline.rfind('\n') + 1 or maxlen shortline = text[:cut]+' ...'
|
def shorten_line(text, maxlen = 75): if not text: return '' elif len(text) < maxlen: shortline = text else: last_cut = i = j = -1 cut = 0 while cut < maxlen and cut > last_cut: last_cut = cut i = text.find('[[BR]]', i+1) j = text.find('\n', j+1) cut = max(i,j) if last_cut > 0: shortline = text[:last_cut]+' ...' else: i = text[:maxlen].rfind(' ') if i == -1: i = maxlen shortline = text[:i]+' ...' return shortline
|
Options include `TimeLineModule`, `RoadmapModule`, `BrowserModule`, `QueryModule`, `ReportModule` and `NewticketModule` (''since 0.9'').""")
|
Options include `TimelineModule`, `RoadmapModule`, `BrowserModule`, `QueryModule`, `ReportModule` and `TicketModule` (''since 0.9'').""")
|
def populate_hdf(hdf, env, req=None): """Populate the HDF data set with various information, such as common URLs, project information and request-related information. FIXME: do we really have req==None at times? """ from trac import __version__ hdf['trac'] = { 'version': __version__, 'time': format_datetime(), 'time.gmt': http_date() } hdf['project'] = { 'shortname': os.path.basename(env.path), 'name': env.project_name, 'name_encoded': env.project_name, 'descr': env.project_description, 'footer': Markup(env.project_footer), 'url': env.project_url } if req: hdf['trac.href'] = { 'wiki': req.href.wiki(), 'browser': req.href.browser('/'), 'timeline': req.href.timeline(), 'roadmap': req.href.roadmap(), 'milestone': req.href.milestone(None), 'report': req.href.report(), 'query': req.href.query(), 'newticket': req.href.newticket(), 'search': req.href.search(), 'about': req.href.about(), 'about_config': req.href.about('config'), 'login': req.href.login(), 'logout': req.href.logout(), 'settings': req.href.settings(), 'homepage': 'http://trac.edgewall.org/' } hdf['base_url'] = req.base_url hdf['base_host'] = req.base_url[:req.base_url.rfind(req.base_path)] hdf['cgi_location'] = req.base_path hdf['trac.authname'] = req.authname if req.perm: for action in req.perm.permissions(): hdf['trac.acl.' + action] = True for arg in [k for k in req.args.keys() if k]: if isinstance(req.args[arg], (list, tuple)): hdf['args.%s' % arg] = [v for v in req.args[arg]] elif isinstance(req.args[arg], basestring): hdf['args.%s' % arg] = req.args[arg] # others are file uploads
|
import trac.Browser import trac.Changeset
|
import trac.versioncontrol.web_ui.browser import trac.versioncontrol.web_ui.changeset
|
def get_db_cnx(self): return db
|
event = {'kind': kind, 'title': title, 'author': author or 'anonymous', 'href': href,
|
event = {'kind': kind, 'title': title, 'href': escape(href), 'author': escape(author or 'anonymous'),
|
def process_request(self, req): req.perm.assert_permission('TIMELINE_VIEW')
|
event['author.email'] = author elif author in email_map.keys(): event['author.email'] = email_map[author]
|
event['author.email'] = escape(author) elif email_map.has_key(author): event['author.email'] = escape(email_map[author])
|
def process_request(self, req): req.perm.assert_permission('TIMELINE_VIEW')
|
self.in_table = 1
|
def open_table(self): if not self.in_table: self.in_table = 1 self.close_paragraph() self.close_indentation() self.close_list() self.out.write('<table class="wiki">' + os.linesep)
|
|
self.cnx.rollback()
|
def close(self): self.cnx.rollback() self.__pool._return_cnx(self.cnx)
|
|
'HTTP_X_FORWARDED_FOR': 'example.org'}
|
'HTTP_X_FORWARDED_HOST': 'example.org'}
|
def test_base_url_proxy(self): environ = {'SCRIPT_NAME': '/trac', 'SERVER_NAME': 'some_proxy.org', 'HTTP_X_FORWARDED_FOR': 'example.org'} req = CGIRequest(environ) req.base_url = _reconstruct_base_url(req) self.assertEqual('http://example.org/trac', req.base_url)
|
module_name = env.config.get('trac','authz_module_name','')
|
module_name = env.config.get('trac', 'authz_module_name')
|
def SubversionAuthorizer(env, authname): authz_file = env.config.get('trac','authz_file') if not authz_file: return Authorizer() module_name = env.config.get('trac','authz_module_name','') db = env.get_db_cnx() return RealSubversionAuthorizer(db, authname, module_name, authz_file)
|
req.hdf = None
|
def dispatch(self, req): """Find a registered handler that matches the request and let it process it. In addition, this method initializes the HDF data set and adds the web site chrome. """ req.authname = self.authenticate(req) req.perm = PermissionCache(self.env, req.authname)
|
|
returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp)
|
returnvals.append(raw_input('Project Name [%s]> ' % dp).strip() or dp)
|
def get_initenv_args(self): returnvals = [] print 'Creating a new Trac environment at %s' % self.envname print print 'Trac will first ask a few questions about your environment ' print 'in order to initalize and prepare the project database.' print print " Please enter the name of your project." print " This name will be used in page titles and descriptions." print dp = 'My Project' returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp) print print ' Please specify the connection string for the database to use.' print ' By default, a local SQLite database is created in the environment ' print ' directory. It is also possible to use an already existing ' print ' PostgreSQL database (check the Trac documentation for the exact ' print ' connection string syntax).' print ddb = 'sqlite:db/trac.db' prompt = 'Database connection string [%s]> ' % ddb returnvals.append(raw_input(prompt) or ddb) print print ' Please specify the absolute path to the project Subversion repository.' print ' Repository must be local, and trac-admin requires read+write' print ' permission to initialize the Trac database.' print drp = '/var/svn/test' prompt = 'Path to repository [%s]> ' % drp returnvals.append(raw_input(prompt) or drp) print print ' Please enter location of Trac page templates.' print ' Default is the location of the site-wide templates installed with Trac.' print dt = default_dir('templates') prompt = 'Templates directory [%s]> ' % dt returnvals.append(raw_input(prompt) or dt) return returnvals
|
returnvals.append(raw_input(prompt) or ddb)
|
returnvals.append(raw_input(prompt).strip() or ddb)
|
def get_initenv_args(self): returnvals = [] print 'Creating a new Trac environment at %s' % self.envname print print 'Trac will first ask a few questions about your environment ' print 'in order to initalize and prepare the project database.' print print " Please enter the name of your project." print " This name will be used in page titles and descriptions." print dp = 'My Project' returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp) print print ' Please specify the connection string for the database to use.' print ' By default, a local SQLite database is created in the environment ' print ' directory. It is also possible to use an already existing ' print ' PostgreSQL database (check the Trac documentation for the exact ' print ' connection string syntax).' print ddb = 'sqlite:db/trac.db' prompt = 'Database connection string [%s]> ' % ddb returnvals.append(raw_input(prompt) or ddb) print print ' Please specify the absolute path to the project Subversion repository.' print ' Repository must be local, and trac-admin requires read+write' print ' permission to initialize the Trac database.' print drp = '/var/svn/test' prompt = 'Path to repository [%s]> ' % drp returnvals.append(raw_input(prompt) or drp) print print ' Please enter location of Trac page templates.' print ' Default is the location of the site-wide templates installed with Trac.' print dt = default_dir('templates') prompt = 'Templates directory [%s]> ' % dt returnvals.append(raw_input(prompt) or dt) return returnvals
|
returnvals.append(raw_input(prompt) or drp)
|
returnvals.append(raw_input(prompt).strip() or drp)
|
def get_initenv_args(self): returnvals = [] print 'Creating a new Trac environment at %s' % self.envname print print 'Trac will first ask a few questions about your environment ' print 'in order to initalize and prepare the project database.' print print " Please enter the name of your project." print " This name will be used in page titles and descriptions." print dp = 'My Project' returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp) print print ' Please specify the connection string for the database to use.' print ' By default, a local SQLite database is created in the environment ' print ' directory. It is also possible to use an already existing ' print ' PostgreSQL database (check the Trac documentation for the exact ' print ' connection string syntax).' print ddb = 'sqlite:db/trac.db' prompt = 'Database connection string [%s]> ' % ddb returnvals.append(raw_input(prompt) or ddb) print print ' Please specify the absolute path to the project Subversion repository.' print ' Repository must be local, and trac-admin requires read+write' print ' permission to initialize the Trac database.' print drp = '/var/svn/test' prompt = 'Path to repository [%s]> ' % drp returnvals.append(raw_input(prompt) or drp) print print ' Please enter location of Trac page templates.' print ' Default is the location of the site-wide templates installed with Trac.' print dt = default_dir('templates') prompt = 'Templates directory [%s]> ' % dt returnvals.append(raw_input(prompt) or dt) return returnvals
|
returnvals.append(raw_input(prompt) or dt)
|
returnvals.append(raw_input(prompt).strip() or dt)
|
def get_initenv_args(self): returnvals = [] print 'Creating a new Trac environment at %s' % self.envname print print 'Trac will first ask a few questions about your environment ' print 'in order to initalize and prepare the project database.' print print " Please enter the name of your project." print " This name will be used in page titles and descriptions." print dp = 'My Project' returnvals.append(raw_input('Project Name [%s]> ' % dp) or dp) print print ' Please specify the connection string for the database to use.' print ' By default, a local SQLite database is created in the environment ' print ' directory. It is also possible to use an already existing ' print ' PostgreSQL database (check the Trac documentation for the exact ' print ' connection string syntax).' print ddb = 'sqlite:db/trac.db' prompt = 'Database connection string [%s]> ' % ddb returnvals.append(raw_input(prompt) or ddb) print print ' Please specify the absolute path to the project Subversion repository.' print ' Repository must be local, and trac-admin requires read+write' print ' permission to initialize the Trac database.' print drp = '/var/svn/test' prompt = 'Path to repository [%s]> ' % drp returnvals.append(raw_input(prompt) or drp) print print ' Please enter location of Trac page templates.' print ' Default is the location of the site-wide templates installed with Trac.' print dt = default_dir('templates') prompt = 'Templates directory [%s]> ' % dt returnvals.append(raw_input(prompt) or dt) return returnvals
|
if not tkt.has_key(f): continue if '\n' in tkt[f]:
|
if not tkt.has_key(f) or str(tkt[f]).find('\n') > -1:
|
def format_props(self): tkt = self.ticket tkt['id'] = '%s' % tkt['id'] t = self.modtime or tkt['time'] tkt['modified'] = time.strftime('%c', time.localtime(t)) fields = ['id', 'status', 'component', 'modified', 'severity', 'milestone', 'priority', 'version', 'owner', 'reporter'] fields.extend(filter(lambda f: f.startswith('custom_'), self.ticket.keys())) i = 1 width = [0,0,0,0] for f in fields: if not tkt.has_key(f): continue if '\n' in tkt[f]: continue fname = f.startswith('custom_') and f[7:] or f idx = 2*(i % 2) if len(fname) > width[idx]: width[idx] = len(fname) if len(tkt[f]) > width[idx+1]: width[idx+1] = len(tkt[f]) i += 1 format = (' %%%is: %%-%is%s' % (width[0], width[1], CRLF), '%%%is: %%-%is | ' % (width[2], width[3])) i = 1 l = (width[2] + width[3] + 5) sep = l*'-' + '+' + (self.COLS-l)*'-' txt = sep + CRLF big=[] for f in fields: if not tkt.has_key(f): continue fval = tkt[f] fname = f.startswith('custom_') and f[7:] or f if '\n' in fval: big.append((fname.capitalize(), fval)) else: txt += format[i%2] % (fname.capitalize(), fval) i += 1 if i % 2 == 0: txt += '\n' if big: txt += sep for k,v in big: txt += '\n%s:\n%s\n\n' % (k,v) txt += sep return txt
|
rev_specified = 0
|
rev_specified = rev.lower() in ['head', 'latest', 'trunk']
|
def render(self): self.perm.assert_permission (perm.BROWSER_VIEW) rev = self.args.get('rev', None) path = self.args.get('path', '/') order = self.args.get('order', 'name').lower() desc = self.args.has_key('desc') self.authzperm.assert_permission (path) if not rev: rev_specified = 0 rev = svn.fs.youngest_rev(self.fs_ptr, self.pool) else: try: rev = int(rev) rev_specified = 1 except: rev_specified = 0 rev = svn.fs.youngest_rev(self.fs_ptr, self.pool)
|
data = util.to_utf8(f.read())
|
data = util.to_unicode(f.read())
|
def _do_wiki_import(self, filename, title, cursor=None): if not os.path.isfile(filename): raise Exception, '%s is not a file' % filename
|
f.write(text)
|
f.write(text.encode('utf-8'))
|
def _do_wiki_export(self, page, filename=''): data = self.db_query("SELECT text FROM wiki WHERE name=%s " "ORDER BY version DESC LIMIT 1", params=[page]) text = data.next()[0] if not filename: print text else: if os.path.isfile(filename): raise Exception("File '%s' exists" % filename) f = open(filename,'w') f.write(text) f.close()
|
if self.args.has_key('delete'):
|
if not self.args.has_key('cancel'):
|
def delete_report(self, id): self.perm.assert_permission(perm.REPORT_DELETE)
|
cursor = self.db.cursor() title = self.args.get('title', '') sql = self.args.get('sql', '') description = self.args.get('description', '') cursor.execute('UPDATE report SET title=%s, sql=%s, description=%s ' ' WHERE id=%s', title, sql, description, id) self.db.commit()
|
if not self.args.has_key('cancel'): cursor = self.db.cursor() title = self.args.get('title', '') sql = self.args.get('sql', '') description = self.args.get('description', '') cursor.execute('UPDATE report SET title=%s, sql=%s, description=%s ' ' WHERE id=%s', title, sql, description, id) self.db.commit()
|
def commit_changes(self, id): """ saves report changes to the database """ self.perm.assert_permission(perm.REPORT_MODIFY)
|
self.req.hdf.setValue('title', 'Delete {%s} %s (report)' % (id, row['title']))
|
self.req.hdf.setValue('title', 'Delete Report {%s} %s' % (id, row['title']))
|
def render_confirm_delete(self, id): self.perm.assert_permission(perm.REPORT_DELETE) cursor = self.db.cursor()
|
self.req.hdf.setValue('title', 'Create New Report')
|
if action == 'commit': self.req.hdf.setValue('title', 'Edit Report {%d} %s' % (id, row['title'])) else: self.req.hdf.setValue('title', 'Create New Report')
|
def render_report_editor(self, id, action='commit', copy=0): self.perm.assert_permission(perm.REPORT_MODIFY) cursor = self.db.cursor()
|
if not (self.args.has_key('sql') or self.args.has_key('title')):
|
if self.args.has_key('cancel'):
|
def render(self): self.perm.assert_permission(perm.REPORT_VIEW) # did the user ask for any special report? id = int(self.args.get('id', -1)) action = self.args.get('action', 'list')
|
info['browser_href.old'] = self.env.href.browser(base_path, base_rev)
|
info['browser_href.old'] = self.env.href.browser(base_path, rev=base_rev)
|
def render_html(self, req, repos, chgset, diff_options): """HTML version"""
|
(self.id, when, self.id, when, self.id, when))
|
(self.id, when, str(self.id), when, self.id, when))
|
def get_changelog(self, when=0, db=None): """Return the changelog as a list of tuples of the form (time, author, field, oldvalue, newvalue). """ if not db: db = self.env.get_db_cnx() cursor = db.cursor() if when: cursor.execute("SELECT time,author,field,oldvalue,newvalue " "FROM ticket_change WHERE ticket=%s AND time=%s " "UNION " "SELECT time,author,'attachment',null,filename " "FROM attachment WHERE id=%s AND time=%s " "UNION " "SELECT time,author,'comment',null,description " "FROM attachment WHERE id=%s AND time=%s " "ORDER BY time", (self.id, when, self.id, when, self.id, when)) else: cursor.execute("SELECT time,author,field,oldvalue,newvalue " "FROM ticket_change WHERE ticket=%s " "UNION " "SELECT time,author,'attachment',null,filename " "FROM attachment WHERE id=%s " "UNION " "SELECT time,author,'comment',null,description " "FROM attachment WHERE id=%s " "ORDER BY time", (self.id, self.id, self.id)) log = [] for t, author, field, oldvalue, newvalue in cursor: log.append((int(t), author, field, oldvalue or '', newvalue or '')) return log
|
"ORDER BY time", (self.id, self.id, self.id))
|
"ORDER BY time", (self.id, str(self.id), self.id))
|
def get_changelog(self, when=0, db=None): """Return the changelog as a list of tuples of the form (time, author, field, oldvalue, newvalue). """ if not db: db = self.env.get_db_cnx() cursor = db.cursor() if when: cursor.execute("SELECT time,author,field,oldvalue,newvalue " "FROM ticket_change WHERE ticket=%s AND time=%s " "UNION " "SELECT time,author,'attachment',null,filename " "FROM attachment WHERE id=%s AND time=%s " "UNION " "SELECT time,author,'comment',null,description " "FROM attachment WHERE id=%s AND time=%s " "ORDER BY time", (self.id, when, self.id, when, self.id, when)) else: cursor.execute("SELECT time,author,field,oldvalue,newvalue " "FROM ticket_change WHERE ticket=%s " "UNION " "SELECT time,author,'attachment',null,filename " "FROM attachment WHERE id=%s " "UNION " "SELECT time,author,'comment',null,description " "FROM attachment WHERE id=%s " "ORDER BY time", (self.id, self.id, self.id)) log = [] for t, author, field, oldvalue, newvalue in cursor: log.append((int(t), author, field, oldvalue or '', newvalue or '')) return log
|
if env and env.log:
|
if env and env.log != None:
|
def send_pretty_error(e, env, req=None): import util import Href import os.path import traceback import StringIO tb = StringIO.StringIO() traceback.print_exc(file=tb) if not req: req = CGIRequest() req.authname = '' req.init_request() try: if not env: env = open_environment() env.href = Href.Href(req.cgi_location) cnx = env.get_db_cnx() populate_hdf(req.hdf, env, cnx, req) if isinstance(e, util.TracError): req.hdf.setValue('title', e.title or 'Error') req.hdf.setValue('error.title', e.title or 'Error') req.hdf.setValue('error.type', 'TracError') req.hdf.setValue('error.message', e.message) if e.show_traceback: req.hdf.setValue('error.traceback',tb.getvalue()) elif isinstance(e, perm.PermissionError): req.hdf.setValue('title', 'Permission Denied') req.hdf.setValue('error.type', 'permission') req.hdf.setValue('error.action', e.action) req.hdf.setValue('error.message', str(e)) else: req.hdf.setValue('title', 'Oops') req.hdf.setValue('error.type', 'internal') req.hdf.setValue('error.message', str(e)) req.hdf.setValue('error.traceback',tb.getvalue()) req.display('error.cs', response=500) except Exception: req.send_response(500) req.send_header('Content-Type', 'text/plain') req.end_headers() req.write('Oops...\n\nTrac detected an internal error:\n\n') req.write(str(e)) req.write('\n') req.write(tb.getvalue()) if env and env.log: env.log.error(str(e)) env.log.error(tb.getvalue())
|
change.base_path, pool()) change.base_rev = fs.node_created_rev(prev_root,
|
def get_changes(self): pool = Pool(self.pool) root = fs.revision_root(self.fs_ptr, self.rev, pool()) if self.rev > 0: prev_root = fs.revision_root(self.fs_ptr, self.rev - 1, pool()) editor = repos.RevisionChangeCollector(self.fs_ptr, self.rev, pool()) e_ptr, e_baton = delta.make_editor(editor, pool()) repos.svn_repos_replay(root, e_ptr, e_baton, pool())
|
|
if self.args.has_key('updatetickets'): self.env.log.info('Updating milestone field of all tickets ' 'associated with milestone %s' % id) cursor.execute ('UPDATE ticket SET milestone = %s ' 'WHERE milestone = %s', name, id)
|
self.env.log.info('Updating milestone field of all tickets ' 'associated with milestone %s' % id) cursor.execute ('UPDATE ticket SET milestone = %s ' 'WHERE milestone = %s', name, id)
|
def update_milestone(self, id, name, date, descr): self.perm.assert_permission(perm.MILESTONE_MODIFY) cursor = self.db.cursor() self.env.log.debug("Updating milestone '%s'" % id) if self.args.has_key('save'): if self.args.has_key('updatetickets'): self.env.log.info('Updating milestone field of all tickets ' 'associated with milestone %s' % id) cursor.execute ('UPDATE ticket SET milestone = %s ' 'WHERE milestone = %s', name, id) cursor.execute("UPDATE milestone SET name = %s, time = %d, " "descr = %s WHERE name = %s", name, date, descr, id) self.db.commit() self.req.redirect(self.env.href.milestone(name)) else: self.req.redirect(self.env.href.milestone(id))
|
self.add_link('alternate', '?daysback=90&max=50&format=rss',
|
self.add_link('alternate', '?daysback=90&max=50&format=rss',
|
def render (self): self.perm.assert_permission(perm.TIMELINE_VIEW)
|
if req.method == 'POST' and not req.perm.has_permission('TICKET_MODIFY'):
|
if req.method == 'POST' and 'owner' in req.args and \ not req.perm.has_permission('TICKET_MODIFY'):
|
def process_request(self, req): req.perm.assert_permission('TICKET_CREATE')
|
page = urllib.unquote(page) label = urllib.unquote(label)
|
def _format_link(self, formatter, ns, page, label, ignore_missing): anchor = '' if page.find('#') != -1: anchor = page[page.find('#'):] page = page[:page.find('#')] page = urllib.unquote(page) label = urllib.unquote(label)
|
|
yield (r"!?(^|(?<=[^A-Za-z]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+"
|
yield (r"!?(^|(?<=[^A-Za-z/]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+"
|
def get_wiki_syntax(self): yield (r"!?(^|(?<=[^A-Za-z]))[A-Z][a-z]+(?:[A-Z][a-z]*[a-z/])+" "(?:#[A-Za-z0-9]+)?(?=\Z|\s|[.,;:!?\)}\]])", lambda x, y, z: self._format_link(x, 'wiki', y, y))
|
('initenv <projectname> <repospath> <templatepath>',
|
('initenv <projectname> <db> <repospath> <templatepath>',
|
def _do_permission_remove(self, user, action): sql = "DELETE FROM permission" clauses = [] if action != '*': clauses.append("action='%s'" % action) if user != '*': clauses.append("username='%s'" % user) if clauses: sql += " WHERE " + " AND ".join(clauses) self.db_update(sql)
|
code_block_start = re.compile('^<div class="code-block">')
|
code_block_start = re.compile('^<div(?:\s+class="([^"]+)")?>')
|
def process(self, req, text, inline=False): if self.error: return system_message(util.Markup('Error: Failed to load processor ' '<code>%s</code>', self.name), self.error) text = self.processor(req, text) if inline: code_block_start = re.compile('^<div class="code-block">') code_block_end = re.compile('</div>$') text, nr = code_block_start.subn('<span class="code-block">', text, 1 ) if nr: text, nr = code_block_end.subn('</span>', text, 1 ) return text else: return text
|
text, nr = code_block_start.subn('<span class="code-block">', text, 1 ) if nr: text, nr = code_block_end.subn('</span>', text, 1 )
|
match = re.match(code_block_start, text) if match: if match.group(1) and 'code' in match.group(1): text, nr = code_block_start.subn('<span class="code-block">', text, 1 ) if nr: text, nr = code_block_end.subn('</span>', text, 1 ) else: text = "</p>%s<p>" % text
|
def process(self, req, text, inline=False): if self.error: return system_message(util.Markup('Error: Failed to load processor ' '<code>%s</code>', self.name), self.error) text = self.processor(req, text) if inline: code_block_start = re.compile('^<div class="code-block">') code_block_end = re.compile('</div>$') text, nr = code_block_start.subn('<span class="code-block">', text, 1 ) if nr: text, nr = code_block_end.subn('</span>', text, 1 ) return text else: return text
|
return macro.process(self.req, args, 1)
|
return macro.process(self.req, args, True)
|
def _macro_formatter(self, match, fullmatch): name = fullmatch.group('macroname') if name in ['br', 'BR']: return '<br />' args = fullmatch.group('macroargs') try: macro = WikiProcessor(self.env, name) return macro.process(self.req, args, 1) except Exception, e: self.env.log.error('Macro %s(%s) failed' % (name, args), exc_info=True) return system_message('Error: Macro %s(%s) failed' % (name, args), e)
|
text = unicode(text)
|
text = to_unicode(text)
|
def escape(cls, text, quotes=True): """Create a Markup instance from a string and escape special characters it may contain (<, >, & and \"). If the `quotes` parameter is set to `False`, the \" character is left as is. Escaping quotes is generally only required for strings that are to be used in attribute values. """ if isinstance(text, (cls, Element)): return text text = unicode(text) if not text: return cls() text = text.replace('&', '&') \ .replace('<', '<') \ .replace('>', '>') if quotes: text = text.replace('"', '"') return cls(text)
|
return Markup(''.join(self.serialize()))
|
return ''.join(self.serialize())
|
def __str__(self): return Markup(''.join(self.serialize()))
|
txt += CRLF.join(['', name + ':', value, '', '')]
|
txt += CRLF.join(['', name + ':', value, '', ''])
|
def format_props(self): tkt = self.ticket fields = [f for f in tkt.fields if f['type'] != 'textarea' and f['name'] not in ('summary', 'cc')] t = self.modtime or tkt.time_changed width = [0, 0, 0, 0] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if fval.find('\n') > -1: continue idx = 2 * (i % 2) if len(f) > width[idx]: width[idx] = len(f) if len(fval) > width[idx + 1]: width[idx + 1] = len(fval) format = ('%%%is: %%-%is | ' % (width[0], width[1]), ' %%%is: %%-%is%s' % (width[2], width[3], CRLF)) i = 1 l = (width[0] + width[1] + 5) sep = l*'-' + '+' + (self.COLS-l)*'-' txt = sep + CRLF big = [] for i, f in enum([f['name'] for f in fields]): if not tkt.values.has_key(f): continue fval = tkt[f] if '\n' in str(fval): big.append((f.capitalize(), fval)) else: txt += format[i % 2] % (f.capitalize(), fval) if not i % 2: txt += CRLF if big: txt += sep for name, value in big: txt += CRLF.join(['', name + ':', value, '', '')] txt += sep return txt
|
path, targetfile = util.create_unique_file(os.path.join(self.path, filename))
|
def insert(self, filename, fileobj, size, t=None, db=None): if not db: db = self.env.get_db_cnx() handle_ta = True else: handle_ta = False
|
|
start = stop - daysback * 86400
|
start = stop - (daysback + 1) * 86400
|
def render (self): self.perm.assert_permission(perm.TIMELINE_VIEW)
|
diff_style, diff_options = get_diff_options(req) if req.args.has_key('update'): req.redirect(self.env.href.wiki(page.name, version=page.version, action='diff'))
|
def _render_diff(self, req, db, page): req.perm.assert_permission(perm.WIKI_VIEW)
|
|
def __call__(self, *args): self.dummy() def __getattr__(self, name): return self.__dummy def __dummy(self, *args):
|
def __noop(self, *args):
|
def __call__(self, *args): self.dummy()
|
"AND name != '' ORDER BY value", by)
|
"AND IFNULL(name,'') != '' ORDER BY value", by)
|
def get_groups(self, by='component'): cursor = self.db.cursor () groups = [] if by in ['status', 'resolution', 'severity', 'priority']: cursor.execute("SELECT name FROM enum WHERE type = %s " "AND name != '' ORDER BY value", by) elif by in ['component', 'milestone', 'version']: cursor.execute("SELECT name FROM %s " "WHERE name != '' ORDER BY name" % by) elif by == 'owner': cursor.execute("SELECT DISTINCT owner AS name FROM ticket " "ORDER BY owner") elif by not in Ticket.std_fields: fields = get_custom_fields(self.env) field = [f for f in fields if f['name'] == by] if not field: return [] return [o for o in field[0]['options'] if o != ''] while 1: row = cursor.fetchone() if not row: break groups.append(row['name']) return groups
|
"WHERE name != '' ORDER BY name" % by)
|
"WHERE IFNULL(name,'') != '' ORDER BY name" % by)
|
def get_groups(self, by='component'): cursor = self.db.cursor () groups = [] if by in ['status', 'resolution', 'severity', 'priority']: cursor.execute("SELECT name FROM enum WHERE type = %s " "AND name != '' ORDER BY value", by) elif by in ['component', 'milestone', 'version']: cursor.execute("SELECT name FROM %s " "WHERE name != '' ORDER BY name" % by) elif by == 'owner': cursor.execute("SELECT DISTINCT owner AS name FROM ticket " "ORDER BY owner") elif by not in Ticket.std_fields: fields = get_custom_fields(self.env) field = [f for f in fields if f['name'] == by] if not field: return [] return [o for o in field[0]['options'] if o != ''] while 1: row = cursor.fetchone() if not row: break groups.append(row['name']) return groups
|
return [o for o in field[0]['options'] if o != '']
|
return [o for o in field[0]['options'] if o]
|
def get_groups(self, by='component'): cursor = self.db.cursor () groups = [] if by in ['status', 'resolution', 'severity', 'priority']: cursor.execute("SELECT name FROM enum WHERE type = %s " "AND name != '' ORDER BY value", by) elif by in ['component', 'milestone', 'version']: cursor.execute("SELECT name FROM %s " "WHERE name != '' ORDER BY name" % by) elif by == 'owner': cursor.execute("SELECT DISTINCT owner AS name FROM ticket " "ORDER BY owner") elif by not in Ticket.std_fields: fields = get_custom_fields(self.env) field = [f for f in fields if f['name'] == by] if not field: return [] return [o for o in field[0]['options'] if o != ''] while 1: row = cursor.fetchone() if not row: break groups.append(row['name']) return groups
|
groups.append(row['name'])
|
groups.append(row['name'] or '')
|
def get_groups(self, by='component'): cursor = self.db.cursor () groups = [] if by in ['status', 'resolution', 'severity', 'priority']: cursor.execute("SELECT name FROM enum WHERE type = %s " "AND name != '' ORDER BY value", by) elif by in ['component', 'milestone', 'version']: cursor.execute("SELECT name FROM %s " "WHERE name != '' ORDER BY name" % by) elif by == 'owner': cursor.execute("SELECT DISTINCT owner AS name FROM ticket " "ORDER BY owner") elif by not in Ticket.std_fields: fields = get_custom_fields(self.env) field = [f for f in fields if f['name'] == by] if not field: return [] return [o for o in field[0]['options'] if o != ''] while 1: row = cursor.fetchone() if not row: break groups.append(row['name']) return groups
|
tn.notify(ticket, newticket=1)
|
tn.notify(ticket, newticket=True)
|
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError('Tickets must contain a summary.')
|
tn.notify(ticket, newticket=0, modtime=now)
|
tn.notify(ticket, newticket=False, modtime=now)
|
def _do_save(self, req, db, ticket): if req.perm.has_permission(perm.TICKET_CHGPROP): # TICKET_CHGPROP gives permission to edit the ticket if not req.args.get('summary'): raise TracError('Tickets must contain summary.')
|
'mode': mode,
|
def process_request(self, req): req.perm.assert_permission(perm.LOG_VIEW)
|
|
'Interactive Trac adminstration console.\n' \
|
'Interactive Trac administration console.\n' \
|
def run(self): self.interactive = True print 'Welcome to trac-admin %(ver)s\n' \ 'Interactive Trac adminstration console.\n' \ '%(copy)s\n\n' \ "Type: '?' or 'help' for help on commands.\n" % \ {'ver':trac.__version__,'copy':__copyright__} self.cmdloop()
|
return match[1:]
|
return escape(match[1:])
|
def handle_match(self, fullmatch): for itype, match in fullmatch.groupdict().items(): if match and not itype in self.wiki.helper_patterns: # Check for preceding escape character '!' if match[0] == '!': return match[1:] if itype in self.wiki.external_handlers: external_handler = self.wiki.external_handlers[itype] return external_handler(self, match, fullmatch) else: internal_handler = getattr(self, '_%s_formatter' % itype) return internal_handler(match, fullmatch)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.