rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
'?version=%s&format=txt' % version, 'Plain Text', 'text/plain') else: self.add_link('alternate', '?format=txt', 'Plain Text', 'text/plain')
|
'?version=%s&format=txt' % version, 'Plain Text', 'text/plain')
|
def _render_view(self, req, pagename): self.perm.assert_permission(perm.WIKI_VIEW)
|
size = upload.file.len
|
upload.file.seek(0, 2) size = upload.file.tell() upload.file.seek(0)
|
def _do_save(self, req, attachment): perm_map = {'ticket': 'TICKET_APPEND', 'wiki': 'WIKI_MODIFY'} req.perm.require(perm_map[attachment.parent_type])
|
safe_name = milestone.name.replace('/', '%2F') req.redirect(req.href.milestone(safe_name))
|
req.redirect(req.href.milestone(milestone.name))
|
def process_request(self, req): milestone_id = req.args.get('id') if not milestone_id: req.redirect(req.href.roadmap())
|
safe_name = milestone.name.replace('/', '%2F') req.redirect(req.href.milestone(safe_name))
|
req.redirect(req.href.milestone(milestone.name))
|
def _do_save(self, req, db, milestone): if milestone.exists: req.perm.require('MILESTONE_MODIFY') else: req.perm.require('MILESTONE_CREATE')
|
path = env.config.get(section, 'path')
|
path = env.config.get(section, 'path') or None
|
def load_components(env): configured_components = [] # Load configured modules for section in env.config.sections(): for name,value in env.config.options(section): if name == 'module': configured_components.append(value) path = env.config.get(section, 'path') env.log.debug('Loading component module %s from %s' % (name, path or 'default path')) try: load_component(name, path, globals(), locals()) except ImportError, e: env.log.error('Component module %s not found (%s)' % (value, e)) # Load default components from trac.db_default import default_components for module in default_components: if not module in configured_components: load_component(module)
|
% (name, path or 'default path'))
|
% (value, path or 'default path')) if path: path = [path]
|
def load_components(env): configured_components = [] # Load configured modules for section in env.config.sections(): for name,value in env.config.options(section): if name == 'module': configured_components.append(value) path = env.config.get(section, 'path') env.log.debug('Loading component module %s from %s' % (name, path or 'default path')) try: load_component(name, path, globals(), locals()) except ImportError, e: env.log.error('Component module %s not found (%s)' % (value, e)) # Load default components from trac.db_default import default_components for module in default_components: if not module in configured_components: load_component(module)
|
load_component(name, path, globals(), locals())
|
load_component(value, path)
|
def load_components(env): configured_components = [] # Load configured modules for section in env.config.sections(): for name,value in env.config.options(section): if name == 'module': configured_components.append(value) path = env.config.get(section, 'path') env.log.debug('Loading component module %s from %s' % (name, path or 'default path')) try: load_component(name, path, globals(), locals()) except ImportError, e: env.log.error('Component module %s not found (%s)' % (value, e)) # Load default components from trac.db_default import default_components for module in default_components: if not module in configured_components: load_component(module)
|
def load_component(name, path=None, globals=None, locals=None):
|
def load_component(name, path=None):
|
def load_component(name, path=None, globals=None, locals=None): if '.' in name: i = name.find('.') head, tail = name[:i], name[i + 1:] else: head, tail = name, '' module = _load_module(head, head, None, path) if not module: raise ImportError, 'No module named ' + head while tail: i = tail.find('.') if i < 0: i = len(tail) head, tail = tail[:i], tail[i + 1:] module_name = '%s.%s' % (module.__name__, head) module = _load_module(head, module_name, module, path) if not module: raise ImportError, 'No module named ' + module_name
|
self.cgi.hdf.setValue('changeset.author', changeset_info['author'])
|
author = changeset_info['author'] or 'None' self.cgi.hdf.setValue('changeset.author', author)
|
def render (self): perm.assert_permission (perm.CHANGESET_VIEW) if self.args.has_key('rev'): self.rev = int(self.args['rev']) else: self.rev = fs.youngest_rev(self.fs_ptr, self.pool)
|
assert 'chrome.logo' not in req.hdf
|
assert 'chrome.logo.src' not in req.hdf
|
def test_logo(self): env = EnvironmentStub() req = Mock(hdf=HDFWrapper(), cgi_location='/trac.cgi', path_info='')
|
if not milestone_id: req.redirect(req.href.roadmap()) req.perm.require('MILESTONE_VIEW')
|
def process_request(self, req): milestone_id = req.args.get('id') if not milestone_id: req.redirect(req.href.roadmap())
|
|
shutil.copytree(self.__env.path, dest, symlinks=1)
|
db_str = self.__env.config.get('trac', 'database') prefix, db_path = db_str.split(':', 1) if prefix == 'sqlite': db_path = os.path.normpath(db_path) skip = ['%s-journal' % os.path.join(self.__env.path, db_path)] else: skip = [] copytree(self.__env.path, dest, symlinks=1, skip=skip)
|
def do_hotcopy(self, line): arg = self.arg_tokenize(line) if arg[0]: dest = arg[0] else: self.do_help('hotcopy') return
|
custom_fields = self.get_custom_fields() for field in custom_fields:
|
for field in self.get_custom_fields(): if field['name'] in [f['name'] for f in fields]: self.log.warning('Duplicate field name "%s" (ignoring)', field['name']) continue if not re.match('^[a-zA-Z][a-zA-Z0-9_]+$', field['name']): self.log.warning('Invalid name for custom field: "%s" ' '(ignoring)', field['name']) continue
|
def get_ticket_fields(self): """Returns the list of fields available for tickets.""" from trac.ticket import model
|
return fields + custom_fields
|
fields.append(field) return fields
|
def get_ticket_fields(self): """Returns the list of fields available for tickets.""" from trac.ticket import model
|
def __init__(self, pool, cnx):
|
def __init__(self, pool, cnx, tid):
|
def __init__(self, pool, cnx): ConnectionWrapper.__init__(self, cnx) self._pool = pool
|
self._pool._return_cnx(self.cnx)
|
self._pool._return_cnx(self.cnx, self._tid)
|
def close(self): if self.cnx: self._pool._return_cnx(self.cnx) self.cnx = None
|
self._active[tid][0] += 1 return PooledConnection(self, self._active[tid][1])
|
num, cnx = self._active.get(tid) if num == 0: cnx.rollback() self._active[tid][0] = num + 1 return PooledConnection(self, cnx, tid)
|
def get_cnx(self, timeout=None): start = time.time() self._available.acquire() try: tid = threading._get_ident() if tid in self._active: self._active[tid][0] += 1 return PooledConnection(self, self._active[tid][1]) while True: if self._dormant: cnx = self._dormant.pop() try: cnx.cursor() # check whether the connection is stale break except Exception: cnx.close() elif self._maxsize and self._cursize < self._maxsize: cnx = self._connector.get_connection(**self._kwargs) self._cursize += 1 break else: if timeout: self._available.wait(timeout) if (time.time() - start) >= timeout: raise TimeoutError, 'Unable to get database ' \ 'connection within %d seconds' \ % timeout else: self._available.wait() self._active[tid] = [1, cnx] return PooledConnection(self, cnx) finally: self._available.release()
|
return PooledConnection(self, cnx)
|
return PooledConnection(self, cnx, tid)
|
def get_cnx(self, timeout=None): start = time.time() self._available.acquire() try: tid = threading._get_ident() if tid in self._active: self._active[tid][0] += 1 return PooledConnection(self, self._active[tid][1]) while True: if self._dormant: cnx = self._dormant.pop() try: cnx.cursor() # check whether the connection is stale break except Exception: cnx.close() elif self._maxsize and self._cursize < self._maxsize: cnx = self._connector.get_connection(**self._kwargs) self._cursize += 1 break else: if timeout: self._available.wait(timeout) if (time.time() - start) >= timeout: raise TimeoutError, 'Unable to get database ' \ 'connection within %d seconds' \ % timeout else: self._available.wait() self._active[tid] = [1, cnx] return PooledConnection(self, cnx) finally: self._available.release()
|
def _return_cnx(self, cnx):
|
def _return_cnx(self, cnx, tid):
|
def _return_cnx(self, cnx): self._available.acquire() try: tid = threading._get_ident() if tid in self._active: num, cnx_ = self._active.get(tid) assert cnx is cnx_ if num > 1: self._active[tid][0] = num - 1 else: self._cleanup(tid) finally: self._available.release()
|
tid = threading._get_ident()
|
def _return_cnx(self, cnx): self._available.acquire() try: tid = threading._get_ident() if tid in self._active: num, cnx_ = self._active.get(tid) assert cnx is cnx_ if num > 1: self._active[tid][0] = num - 1 else: self._cleanup(tid) finally: self._available.release()
|
|
if cnx not in self._dormant: cnx.rollback() if cnx.poolable:
|
if cnx not in self._dormant: if cnx.poolable: cnx.rollback()
|
def _cleanup(self, tid): # Note: self._available *must* be acquired if tid in self._active: cnx = self._active.pop(tid)[1] if cnx not in self._dormant: cnx.rollback() if cnx.poolable: self._dormant.append(cnx) else: cnx.close() self._cursize -= 1 self._available.notify()
|
else:
|
elif tid == threading._get_ident(): cnx.rollback()
|
def _cleanup(self, tid): # Note: self._available *must* be acquired if tid in self._active: cnx = self._active.pop(tid)[1] if cnx not in self._dormant: cnx.rollback() if cnx.poolable: self._dormant.append(cnx) else: cnx.close() self._cursize -= 1 self._available.notify()
|
html = processor.process(req.hdf, text)
|
html = processor.process(req, text)
|
def code_formatter(language, text): processor = WikiProcessor(self.env, language) html = processor.process(req.hdf, text) raw = nodes.raw('', html, format='html') return raw
|
print>>sys.stderr, '[%d] wait for connection...' % tid
|
def get_cnx(self, timeout=None): start = time.time() self._available.acquire() try: tid = threading._get_ident() if tid in self._active: self._active[tid][0] += 1 return PooledConnection(self, self._active[tid][1]) while True: if self._dormant: cnx = self._dormant.pop() try: cnx.cursor() # check whether the connection is stale break except Exception: cnx.close() elif self._maxsize and self._cursize < self._maxsize: cnx = self._connector.get_connection(**self._kwargs) self._cursize += 1 break else: if timeout: self._available.wait(timeout) if (time.time() - start) >= timeout: raise TimeoutError, 'Unable to get database ' \ 'connection within %d seconds' \ % timeout else: print>>sys.stderr, '[%d] wait for connection...' % tid self._available.wait() self._active[tid] = [1, cnx] return PooledConnection(self, cnx) finally: self._available.release()
|
|
rev = None
|
def _format_link(self, formatter, ns, path, label): rev = None match = img_re.search(path) if formatter.flavor != 'oneliner' and match: return '<img src="%s" alt="%s" />' % \ (formatter.href.file(path, format='raw'), label) match = rev_re.search(path) if match: path = match.group(1) rev = match.group(2) label = urllib.unquote(label) path = urllib.unquote(path) if rev: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label) else: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path), label)
|
|
match = rev_re.search(path) if match: path = match.group(1) rev = match.group(2)
|
path, rev = _get_path_rev(path)
|
def _format_link(self, formatter, ns, path, label): rev = None match = img_re.search(path) if formatter.flavor != 'oneliner' and match: return '<img src="%s" alt="%s" />' % \ (formatter.href.file(path, format='raw'), label) match = rev_re.search(path) if match: path = match.group(1) rev = match.group(2) label = urllib.unquote(label) path = urllib.unquote(path) if rev: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label) else: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path), label)
|
path = urllib.unquote(path) if rev: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label) else: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path), label)
|
return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label)
|
def _format_link(self, formatter, ns, path, label): rev = None match = img_re.search(path) if formatter.flavor != 'oneliner' and match: return '<img src="%s" alt="%s" />' % \ (formatter.href.file(path, format='raw'), label) match = rev_re.search(path) if match: path = match.group(1) rev = match.group(2) label = urllib.unquote(label) path = urllib.unquote(path) if rev: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label) else: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path), label)
|
implements(INavigationContributor, IPermissionRequestor, IRequestHandler)
|
implements(INavigationContributor, IPermissionRequestor, IRequestHandler, IWikiSyntaxProvider)
|
def _format_link(self, formatter, ns, path, label): rev = None match = img_re.search(path) if formatter.flavor != 'oneliner' and match: return '<img src="%s" alt="%s" />' % \ (formatter.href.file(path, format='raw'), label) match = rev_re.search(path) if match: path = match.group(1) rev = match.group(2) label = urllib.unquote(label) path = urllib.unquote(path) if rev: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path, rev=rev), label) else: return '<a class="source" href="%s">%s</a>' \ % (formatter.href.browser(path), label)
|
params = {'rev': rev, 'mode': mode, 'limit': limit}
|
link_rev = rev if rev == str(repos.youngest_rev): link_rev = None params = {'rev': link_rev, 'mode': mode, 'limit': limit}
|
def make_log_href(path, **args): params = {'rev': rev, 'mode': mode, 'limit': limit} params.update(args) if verbose: params['verbose'] = verbose return self.env.href.log(path, **params)
|
cs['shortlog'] = util.escape(cs['shortlog'])
|
cs['shortlog'] = util.escape(cs['shortlog'].replace('\n', ' '))
|
def make_log_href(path, **args): params = {'rev': rev, 'mode': mode, 'limit': limit} params.update(args) if verbose: params['verbose'] = verbose return self.env.href.log(path, **params)
|
return cls.__module__.find('.tests.') == -1
|
return cls.__module__.startswith('trac.') and \ cls.__module__.find('.tests.') == -1
|
def is_component_enabled(self, cls): return cls.__module__.find('.tests.') == -1
|
perm_map = {'tickets': perm.TICKET_VIEW, 'changeset': perm.CHANGESET_VIEW,
|
perm_map = {'ticket': perm.TICKET_VIEW, 'changeset': perm.CHANGESET_VIEW,
|
def get_info(self, req, start, stop, maxrows, filters=AVAILABLE_FILTERS): perm_map = {'tickets': perm.TICKET_VIEW, 'changeset': perm.CHANGESET_VIEW, 'wiki': perm.WIKI_VIEW, 'milestone': perm.MILESTONE_VIEW} filters = list(filters) # copy list so we can make modifications for k,v in perm_map.items(): if k in filters and not self.perm.has_permission(v): filters.remove(k) if not filters: return []
|
"""Return the types of version control systems that are supported by this connector, and their relative priorities. Highest number is highest priority.
|
"""Return the types of version control systems that are supported. Yields `(repotype, priority)` pairs, where `repotype` is used to match against the configured `[trac] repository_type` value in TracIni. If multiple provider match a given type, the `priority` is used to choose between them (highest number is highest priority).
|
def get_supported_types(): """Return the types of version control systems that are supported by this connector, and their relative priorities. Highest number is highest priority. """
|
"""Return the Repository object for the given repository type and directory.
|
"""Return a Repository instance for the given repository type and dir.
|
def get_repository(repos_type, repos_dir, authname): """Return the Repository object for the given repository type and directory. """
|
raise TracError, 'Unsupported version control system "%s"' \ % self.repository_type
|
raise TracError('Unsupported version control system "%s"' % self.repository_type)
|
def get_repository(self, authname): if not self._connector: candidates = [] for connector in self.connectors: for repos_type_, prio in connector.get_supported_types(): if self.repository_type != repos_type_: continue heappush(candidates, (-prio, connector)) if not candidates: raise TracError, 'Unsupported version control system "%s"' \ % self.repository_type self._connector = heappop(candidates)[1] return self._connector.get_repository(self.repository_type, self.repository_dir, authname)
|
""" Retrieve a Node (directory or file) from the repository at the given path. If the rev parameter is specified, the version of the node at that revision is returned, otherwise the latest version of the node is returned.
|
"""Retrieve a Node from the repository at the given path. A Node represents a directory or a file at a given revision in the repository. If the `rev` parameter is specified, the Node corresponding to that revision is returned, otherwise the Node corresponding to the youngest revision is returned.
|
def get_node(self, path, rev=None): """ Retrieve a Node (directory or file) from the repository at the given path. If the rev parameter is specified, the version of the node at that revision is returned, otherwise the latest version of the node is returned. """ raise NotImplementedError
|
""" Return True if rev1 is older than rev2, i.e. if rev1 comes before rev2 in the revision sequence.
|
"""Provides a total order over revisions. Return `True` if `rev1` is older than `rev2`, i.e. if `rev1` comes before `rev2` in the revision sequence.
|
def rev_older_than(self, rev1, rev2): """ Return True if rev1 is older than rev2, i.e. if rev1 comes before rev2 in the revision sequence. """ raise NotImplementedError
|
By default, one assumes that the revisions are sequenced in time.
|
By default, one assumes that the revisions are sequenced in time (... which is ''not'' correct for most VCS, including Subversion).
|
def get_youngest_rev_in_cache(self, db): """ Return the youngest revision currently cached. The way revisions are sequenced is version control specific. By default, one assumes that the revisions are sequenced in time. """ cursor = db.cursor() cursor.execute("SELECT rev FROM revision ORDER BY time DESC LIMIT 1") row = cursor.fetchone() return row and row[0] or None
|
""" Retrieve all the revisions containing this path (no newer than 'rev').
|
"""Retrieve all the revisions containing this path If given, `rev` is used as a starting point (i.e. no revision ''newer'' than `rev` should be returned).
|
def get_path_history(self, path, rev=None, limit=None): """ Retrieve all the revisions containing this path (no newer than 'rev'). The result format should be the same as the one of Node.get_history() """ raise NotImplementedError
|
""" Return a canonical representation of a revision in the repos. 'None' is a valid revision value and represents the youngest revision.
|
"""Return a canonical representation of a revision. It's up to the backend to decide which string values of `rev` (usually provided by the user) should be accepted, and how they should be normalized. Some backends may for instance want to match against known tags or branch names. In addition, if `rev` is `None` or '', the youngest revision should be returned.
|
def normalize_rev(self, rev): """ Return a canonical representation of a revision in the repos. 'None' is a valid revision value and represents the youngest revision. """ return NotImplementedError
|
"""
|
"""Generates changes corresponding to generalized diffs.
|
def get_changes(self, old_path, old_rev, new_path, new_rev, ignore_ancestry=1): """ Generator that yields change tuples (old_node, new_node, kind, change) for each node change between the two arbitrary (path,rev) pairs.
|
assert kind in (Node.DIRECTORY, Node.FILE), "Unknown node kind %s" % kind
|
assert kind in (Node.DIRECTORY, Node.FILE), \ "Unknown node kind %s" % kind
|
def __init__(self, path, rev, kind): assert kind in (Node.DIRECTORY, Node.FILE), "Unknown node kind %s" % kind self.path = unicode(path) self.rev = rev self.kind = kind
|
""" Return a stream for reading the content of the node. This method will return None for directories. The returned object should provide a read([len]) function.
|
"""Return a stream for reading the content of the node. This method will return `None` for directories. The returned object must support a `read([len])` method.
|
def get_content(self): """ Return a stream for reading the content of the node. This method will return None for directories. The returned object should provide a read([len]) function. """ raise NotImplementedError
|
""" Generator that yields the immediate child entries of a directory, in no particular order. If the node is a file, this method returns None.
|
"""Generator that yields the immediate child entries of a directory. The entries are returned in no particular order. If the node is a file, this method returns `None`.
|
def get_entries(self): """ Generator that yields the immediate child entries of a directory, in no particular order. If the node is a file, this method returns None. """ raise NotImplementedError
|
""" Generator that yields (path, rev, chg) tuples, one for each revision in which the node was changed. This generator will follow copies and moves of a node (if the underlying version control system supports that), which will be indicated by the first element of the tuple (i.e. the path) changing.
|
"""Provide backward history for this Node. Generator that yields `(path, rev, chg)` tuples, one for each revision in which the node was changed. This generator will follow copies and moves of a node (if the underlying version control system supports that), which will be indicated by the first element of the tuple (i.e. the path) changing.
|
def get_history(self, limit=None): """ Generator that yields (path, rev, chg) tuples, one for each revision in which the node was changed. This generator will follow copies and moves of a node (if the underlying version control system supports that), which will be indicated by the first element of the tuple (i.e. the path) changing. Starts with an entry for the current revision. """ raise NotImplementedError
|
""" Return the (path, rev, chg) tuple corresponding to the previous revision for that node.
|
"""Return the change event corresponding to the previous revision. This returns a `(path, rev, chg)` tuple.
|
def get_previous(self): """ Return the (path, rev, chg) tuple corresponding to the previous revision for that node. """ skip = True for p in self.get_history(2): if skip: skip = False else: return p
|
""" Returns a dictionary containing the properties (meta-data) of the node.
|
"""Returns the properties (meta-data) of the node, as a dictionary.
|
def get_properties(self): """ Returns a dictionary containing the properties (meta-data) of the node. The set of properties depends on the version control system. """ raise NotImplementedError
|
""" Generator that produces a (path, kind, change, base_path, base_rev) tuple for every change in the changeset, where change can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and kind is one of Node.FILE or Node.DIRECTORY.
|
"""Generator that produces a tuple for every change in the changeset The tuple will contain `(path, kind, change, base_path, base_rev)`, where `change` can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and `kind` is one of Node.FILE or Node.DIRECTORY.
|
def get_changes(self): """ Generator that produces a (path, kind, change, base_path, base_rev) tuple for every change in the changeset, where change can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and kind is one of Node.FILE or Node.DIRECTORY. """ raise NotImplementedError
|
""" Exception raised by an authorizer if the user has insufficient permissions
|
"""Exception raised by an authorizer. This exception is raise if the user has insufficient permissions
|
def get_changes(self): """ Generator that produces a (path, kind, change, base_path, base_rev) tuple for every change in the changeset, where change can be one of Changeset.ADD, Changeset.COPY, Changeset.DELETE, Changeset.EDIT or Changeset.MOVE, and kind is one of Node.FILE or Node.DIRECTORY. """ raise NotImplementedError
|
"""
|
"""Controls the view access to parts of the repository.
|
def __str__(self): return self.action
|
def authz_cb(root, path, pool): return self.authzperm.has_permission(path) and 1 or 0 svn.repos.svn_repos_get_logs(self.repos, [path], 0, rev, 1, authz_cb, self.log_receiver, self.pool)
|
try: def authz_cb(root, path, pool): return self.authzperm.has_permission(path) and 1 or 0 svn.repos.svn_repos_get_logs2(self.repos, [path], 0, rev, 1, 0, authz_cb, self.log_receiver, self.pool) except AttributeError: svn.repos.svn_repos_get_logs(self.repos, [path], 0, rev, 1, 0, self.log_receiver, self.pool)
|
def authz_cb(root, path, pool): return self.authzperm.has_permission(path) and 1 or 0
|
self._render_rss(req, db)
|
self._render_rss(req)
|
def render_report_list(self, req, db, id): """ uses a user specified sql query to extract some information from the database and presents it as a html table. """ actions = {'create': perm.REPORT_CREATE, 'delete': perm.REPORT_DELETE, 'modify': perm.REPORT_MODIFY} for action in [k for k,v in actions.items() if req.perm.has_permission(v)]: req.hdf['report.can_' + action] = True req.hdf['report.href'] = self.env.href.report(id) if id != -1: req.hdf['report.overview_href'] = self.env.href.report()
|
return None
|
def render_report_list(self, req, db, id): """ uses a user specified sql query to extract some information from the database and presents it as a html table. """ actions = {'create': perm.REPORT_CREATE, 'delete': perm.REPORT_DELETE, 'modify': perm.REPORT_MODIFY} for action in [k for k,v in actions.items() if req.perm.has_permission(v)]: req.hdf['report.can_' + action] = True req.hdf['report.href'] = self.env.href.report(id) if id != -1: req.hdf['report.overview_href'] = self.env.href.report()
|
|
name, val = columns[i], row[i]
|
name, field, val = columns[i], fields[i], row[i]
|
def execute(self, req, db=None): if not self.cols: self.get_columns()
|
elif val is None: val = '--'
|
elif field and field['type'] == 'checkbox': try: val = bool(int(val)) except TypeError, ValueError: val = False
|
def execute(self, req, db=None): if not self.cols: self.get_columns()
|
chgset.message,
|
message,
|
def process_request(self, req): """The appropriate mode of operation is inferred from the request parameters:
|
pass
|
message = None
|
def process_request(self, req): """The appropriate mode of operation is inferred from the request parameters:
|
self._render_html(req, repos, chgset, restricted,
|
self._render_html(req, repos, chgset, restricted, message,
|
def process_request(self, req): """The appropriate mode of operation is inferred from the request parameters:
|
def _render_html(self, req, repos, chgset, restricted, diff, diff_options):
|
def _render_html(self, req, repos, chgset, restricted, message, diff, diff_options):
|
def _render_html(self, req, repos, chgset, restricted, diff, diff_options): """HTML version""" req.hdf['changeset'] = { 'chgset': chgset and True, 'restricted': restricted, 'href': { 'new_rev': req.href.changeset(diff.new_rev), 'old_rev': req.href.changeset(diff.old_rev), 'new_path': req.href.browser(diff.new_path, rev=diff.new_rev), 'old_path': req.href.browser(diff.old_path, rev=diff.old_rev) } }
|
message = chgset.message or '--' if self.wiki_format_messages: message = wiki_to_html(message, self.env, req, escape_newlines=True) else: message = html.PRE(message)
|
def _changeset_title(rev): if restricted: return 'Changeset %s for %s' % (rev, path) else: return 'Changeset %s' % rev
|
|
message = wiki_to_html(description, self.env, db,
|
message = wiki_to_html(description, self.env, req, db,
|
def get_timeline_events(self, req, start, stop, filters): if 'milestone' in filters: format = req.args.get('format') db = self.env.get_db_cnx() cursor = db.cursor() cursor.execute("SELECT completed,name,description FROM milestone " "WHERE completed>=%s AND completed<=%s", (start, stop,)) for completed, name, description in cursor: title = Markup('Milestone <em>%s</em> completed', name) if format == 'rss': href = req.abs_href.milestone(name) message = wiki_to_html(description, self.env, db, absurls=True) else: href = req.href.milestone(name) message = wiki_to_oneliner(description, self.env, db, shorten=True) yield 'milestone', href, title, completed, None, message or '--'
|
(r"(?P<macro>!?\[\[(?P<macroname>[\w/+-]+)" r"(\]\]|\((?P<macroargs>.*?)\)\]\]))"),
|
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
|
|
line = 1
|
next_line = 1 line = 0
|
def suite(data=None, setup=None, file=__file__): suite = unittest.TestSuite() if not data: file = os.path.join(os.path.split(file)[0], 'wiki-tests.txt') data = open(file, 'r').read().decode('utf-8') tests = data.split('=' * 30) line = 1 for test in tests: if not test or test == '\n': continue blocks = test.split('-' * 30 + '\n') if len(blocks) != 3: continue input, page, oneliner = blocks tc = WikiTestCase(input, page, file, line) if setup: setup(tc) suite.addTest(tc) if oneliner: tc = OneLinerTestCase(input, oneliner[:-1], file, line) if setup: setup(tc) suite.addTest(tc) line += len(test.split('\n')) return suite
|
line += len(test.split('\n'))
|
def suite(data=None, setup=None, file=__file__): suite = unittest.TestSuite() if not data: file = os.path.join(os.path.split(file)[0], 'wiki-tests.txt') data = open(file, 'r').read().decode('utf-8') tests = data.split('=' * 30) line = 1 for test in tests: if not test or test == '\n': continue blocks = test.split('-' * 30 + '\n') if len(blocks) != 3: continue input, page, oneliner = blocks tc = WikiTestCase(input, page, file, line) if setup: setup(tc) suite.addTest(tc) if oneliner: tc = OneLinerTestCase(input, oneliner[:-1], file, line) if setup: setup(tc) suite.addTest(tc) line += len(test.split('\n')) return suite
|
|
open_tag_re = re.compile(r'<(\w+)\s.*?[^/]?>')
|
open_tag_re = re.compile(r'<(\w+)(\s.*)?[^/]?>')
|
def _html_splitlines(lines): """Tracks open and close tags in lines of HTML text and yields lines that have no tags spanning more than one line.""" open_tag_re = re.compile(r'<(\w+)\s.*?[^/]?>') close_tag_re = re.compile(r'</(\w+)>') open_tags = [] for line in lines: # Reopen tags still open from the previous line for tag in open_tags: line = tag.group(0) + line open_tags = [] # Find all tags opened on this line for tag in open_tag_re.finditer(line): open_tags.append(tag) # Find all tags closed on this line for ctag in close_tag_re.finditer(line): for otag in open_tags: if otag.group(1) == ctag.group(1): open_tags.remove(otag) break # Close all tags still open at the end of line, they'll get reopened at # the beginning of the next line for tag in open_tags: line += '</%s>' % tag.group(1) yield line
|
usage()
|
def _auth_callback(option, opt_str, value, parser, auths, cls): info = value.split(',', 3) if len(info) != 3: raise OptionValueError("Incorrect number of parameters for %s" % option) usage() env_name, filename, realm = info if env_name in auths: print >>sys.stderr, 'Ignoring duplicate authentication option for ' \ 'project: %s' % env_name else: auths[env_name] = cls(filename, realm)
|
|
"ORDER BY version DESC LIMIT 1", params=(title, cursor))
|
"ORDER BY version DESC LIMIT 1", cursor, params=(title,))
|
def _do_wiki_import(self, filename, title, cursor=None): if not os.path.isfile(filename): raise Exception, '%s is not a file' % filename
|
ticket['description'] = wiki_to_oneliner(ticket['description'] or '', self.env, db)
|
ticket['description'] = wiki_to_html(ticket['description'] or '', self.env, req, db)
|
def display_html(self, req, query): req.hdf['title'] = 'Custom Query' add_stylesheet(req, 'report.css')
|
message = wiki_to_html(message or '--', self.env, db)
|
message = wiki_to_html(message or '--', self.env, req, db)
|
def get_timeline_events(self, req, start, stop, filters): if 'ticket' in filters: format = req.args.get('format') sql = []
|
clause.append('%s = \'%s\'' % (constraints[i], vals[j]))
|
clause.append('%s = \'%s\'' % (constraints[i], vals[j].value))
|
def render(self): self.perm.assert_permission(perm.TICKET_VIEW)
|
clause.append('%s = \'%s\'' % (constraints[i], vals))
|
clause.append('%s = \'%s\'' % (constraints[i], vals.value))
|
def render(self): self.perm.assert_permission(perm.TICKET_VIEW)
|
col_width.append(max(len(unicode(d[idx])) for d in data))
|
col_width.append(max([len(unicode(d[idx])) for d in data]))
|
def print_table(data, headers=None, sep=' ', out=None): if out is None: out = sys.stdout charset = getattr(out, 'encoding', 'utf-8') data = list(data) if headers: data.insert(0, headers) elif not data: return num_cols = len(data[0]) # assumes all rows are of equal length col_width = [] for idx in range(num_cols): col_width.append(max(len(unicode(d[idx])) for d in data)) out.write('\n') for ridx, row in enumerate(data): for cidx, cell in enumerate(row): if headers and ridx == 0: sp = ('%%%ds' % len(sep)) % ' ' # No separator in header else: sp = sep if cidx + 1 == num_cols: sp = '' # No separator after last column line = (u'%%-%ds%s' % (col_width[cidx], sp)) % (cell or '') if isinstance(line, unicode): line = line.encode(charset, 'replace') out.write(line) out.write('\n') if ridx == 0 and headers: out.write(''.join(['-' for x in xrange(0, len(sep) * cidx + sum(col_width))])) out.write('\n') out.write('\n')
|
shortlog = wiki_to_oneliner(message, env, db, shorten=True)
|
shortlog = wiki_to_oneliner(message, env, db, shorten=True, absurls=absurls)
|
def get_changes(env, repos, revs, full=None, req=None, format=None): db = env.get_db_cnx() changes = {} for rev in revs: try: changeset = repos.get_changeset(rev) except NoSuchChangeset: changes[rev] = {} continue wiki_format = env.config['changeset'].getbool('wiki_format_messages') message = changeset.message or '--' if wiki_format: shortlog = wiki_to_oneliner(message, env, db, shorten=True) else: shortlog = Markup.escape(shorten_line(message)) if full: if wiki_format: message = wiki_to_html(message, env, req, db, absurls=(format == 'rss'), escape_newlines=True) else: message = html.PRE(message) else: message = shortlog if format == 'rss': if isinstance(shortlog, Markup): shortlog = shortlog.plaintext(keeplinebreaks=False) message = unicode(message) changes[rev] = { 'date_seconds': changeset.date, 'date': format_datetime(changeset.date), 'age': pretty_timedelta(changeset.date), 'author': changeset.author or 'anonymous', 'message': message, 'shortlog': shortlog, } return changes
|
absurls=(format == 'rss'), escape_newlines=True)
|
absurls=absurls, escape_newlines=True)
|
def get_changes(env, repos, revs, full=None, req=None, format=None): db = env.get_db_cnx() changes = {} for rev in revs: try: changeset = repos.get_changeset(rev) except NoSuchChangeset: changes[rev] = {} continue wiki_format = env.config['changeset'].getbool('wiki_format_messages') message = changeset.message or '--' if wiki_format: shortlog = wiki_to_oneliner(message, env, db, shorten=True) else: shortlog = Markup.escape(shorten_line(message)) if full: if wiki_format: message = wiki_to_html(message, env, req, db, absurls=(format == 'rss'), escape_newlines=True) else: message = html.PRE(message) else: message = shortlog if format == 'rss': if isinstance(shortlog, Markup): shortlog = shortlog.plaintext(keeplinebreaks=False) message = unicode(message) changes[rev] = { 'date_seconds': changeset.date, 'date': format_datetime(changeset.date), 'age': pretty_timedelta(changeset.date), 'author': changeset.author or 'anonymous', 'message': message, 'shortlog': shortlog, } return changes
|
query_href = req.href.query(group=query.group, groupdesc=query.groupdesc and 1 or None, verbose=query.verbose and 1 or None, **query.constraints)
|
def display_html(self, context, query): req = context.req db = self.env.get_db_cnx() tickets = query.execute(req, db)
|
|
match = re.match(r'^/attachment/(ticket|wiki)(?:[/:](.*))?$',
|
match = re.match(r'^/(raw-)?attachment/([^/]+)(?:[/:](.*))?$',
|
def match_request(self, req): match = re.match(r'^/attachment/(ticket|wiki)(?:[/:](.*))?$', req.path_info) if match: req.args['type'] = match.group(1) req.args['path'] = match.group(2).replace(':', '/') return True
|
req.args['type'] = match.group(1) req.args['path'] = match.group(2).replace(':', '/')
|
req.args['format'] = match.group(1) and 'raw' or '' req.args['type'] = match.group(2) req.args['path'] = match.group(3).replace(':', '/')
|
def match_request(self, req): match = re.match(r'^/attachment/(ticket|wiki)(?:[/:](.*))?$', req.path_info) if match: req.args['type'] = match.group(1) req.args['path'] = match.group(2).replace(':', '/') return True
|
raw_href = attachment.href(req, format='raw')
|
raw_href = attachment.raw_href(req)
|
def _render_view(self, req, attachment): perm_map = {'ticket': 'TICKET_VIEW', 'wiki': 'WIKI_VIEW'} req.perm.require(perm_map[attachment.parent_type])
|
if formatter.req:
|
if ns.startswith('raw'): href = attachment.raw_href(formatter.req) elif formatter.req:
|
def attachment_link(parent_type, parent_id, filename): href = formatter.href() try: attachment = Attachment(self.env, parent_type, parent_id, filename) if formatter.req: href = attachment.href(formatter.req) + params return html.A(label, class_='attachment', href=href, title='Attachment %s' % attachment.title) except TracError: return None
|
return mime_type[ctpos + 8:]
|
return mimetype[ctpos + 8:]
|
def get_charset(mimetype): """Return the character encoding included in the given content type string, or `None` if `mimetype` is `None` or empty or if no charset information is available. """ if mimetype: ctpos = mimetype.find('charset=') if ctpos >= 0: return mime_type[ctpos + 8:]
|
if i < maxlen: shortline = text[:i]+' ...'
|
if i > -1 and i < maxlen: shortline = text[:i]+' ...'
|
def shorten_line(text, maxlen = 75): if not text: return '' i = text.find('[[BR]]') if i < maxlen: shortline = text[:i]+' ...' elif len(text) < maxlen: shortline = text else: i = text[:maxlen].rfind(' ') if i == -1: i = maxlen shortline = text[:i]+' ...' return shortline
|
'false',
|
'true',
|
def __getattr__(self, str): return self[str]
|
value['date'] = format_date(cell) value['time'] = format_time(cell) value['datetime'] = format_datetime(cell) value['gmt'] = http_date(cell)
|
if cell == 'None': value['date'] = value['time'] = cell value['datetime'] = value['gmt'] = cell else: value['date'] = format_date(cell) value['time'] = format_time(cell) value['datetime'] = format_datetime(cell) value['gmt'] = http_date(cell)
|
def sortkey(row): val = row[colIndex] if isinstance(val, basestring): val = val.lower() return val
|
priority_mapping = {'highest': '1', 'high': '3', 'normal': '5', 'low': '7', 'lowest': '9'}
|
cursor = db.cursor() cursor.execute("SELECT name,value FROM enum WHERE type='priority'") priorities = {} for name, value in cursor: priorities[name] = float(value) def get_priority(ticket): value = priorities.get(ticket['priority']) if value: return int(value * 9 / len(priorities))
|
def render_ics(self, req, db, milestones): req.send_response(200) req.send_header('Content-Type', 'text/calendar;charset=utf-8') req.end_headers()
|
write_prop('URL', req.base_url + '/milestone/' + milestone['name']) if milestone.has_key('description'): write_prop('DESCRIPTION', milestone['description_text'])
|
write_prop('URL', req.base_url + '/milestone/' + milestone['name']) if milestone.has_key('description_source'): write_prop('DESCRIPTION', milestone['description_source'])
|
def write_utctime(name, value, params={}): write_prop(name, strftime('%Y%m%dT%H%M%SZ', value), params)
|
write_prop('PRIORITY', priority_mapping[ticket['priority']])
|
priority = get_priority(ticket) if priority: write_prop('PRIORITY', str(priority))
|
def write_utctime(name, value, params={}): write_prop(name, strftime('%Y%m%dT%H%M%SZ', value), params)
|
href = Href(req.base_path).chrome
|
href = req.href if not filename.startswith('/'): href = href.chrome
|
def add_stylesheet(req, filename, mimetype='text/css'): """Add a link to a style sheet to the HDF data set so that it gets included in the generated HTML page. """ if filename.startswith('common/') and 'htdocs_location' in req.chrome: href = Href(req.chrome['htdocs_location']) filename = filename[7:] else: href = Href(req.base_path).chrome add_link(req, 'stylesheet', href(filename), mimetype=mimetype)
|
href = Href(req.base_path).chrome
|
href = req.href if not filename.startswith('/'): href = href.chrome
|
def add_script(req, filename, mimetype='text/javascript'): """Add a reference to an external javascript file to the template.""" scriptset = req.chrome.setdefault('trac.chrome.scriptset', set()) if filename in scriptset: return False # Already added that script if filename.startswith('common/') and 'htdocs_location' in req.chrome: href = Href(req.chrome['htdocs_location']) path = filename[7:] else: href = Href(req.base_path).chrome path = filename script = {'href': href(path), 'type': mimetype} req.chrome.setdefault('scripts', []).append(script) scriptset.add(filename)
|
target = fullmatch.group('stgt') if target[0] in "'\"": target = target[1:-1]
|
target = self._unquote(fullmatch.group('stgt'))
|
def _shref_formatter(self, match, fullmatch): ns = fullmatch.group('sns') target = fullmatch.group('stgt') if target[0] in "'\"": target = target[1:-1] return self._make_link(ns, target, match, match)
|
target = fullmatch.group('ltgt') if target and target[0] in ("'",'"'): target = target[1:-1]
|
target = self._unquote(fullmatch.group('ltgt'))
|
def _lhref_formatter(self, match, fullmatch): ns = fullmatch.group('lns') target = fullmatch.group('ltgt') if target and target[0] in ("'",'"'): target = target[1:-1] label = fullmatch.group('label') if not label: # e.g. `[http://target]` or `[wiki:target]` if target: if target.startswith('//'): # for `[http://target]` label = ns+':'+target # use `http://target` else: # for `wiki:target` label = target # use only `target` else: # e.g. `[search:]` label = ns if label and label[0] in ("'",'"'): label = label[1:-1] rel = fullmatch.group('rel') if rel: return self._make_relative_link(rel, label or rel) else: return self._make_link(ns, target, match, label)
|
if label and label[0] in ("'",'"'): label = label[1:-1]
|
label = self._unquote(label)
|
def _lhref_formatter(self, match, fullmatch): ns = fullmatch.group('lns') target = fullmatch.group('ltgt') if target and target[0] in ("'",'"'): target = target[1:-1] label = fullmatch.group('label') if not label: # e.g. `[http://target]` or `[wiki:target]` if target: if target.startswith('//'): # for `[http://target]` label = ns+':'+target # use `http://target` else: # for `wiki:target` label = target # use only `target` else: # e.g. `[search:]` label = ns if label and label[0] in ("'",'"'): label = label[1:-1] rel = fullmatch.group('rel') if rel: return self._make_relative_link(rel, label or rel) else: return self._make_link(ns, target, match, label)
|
self.changeno = 0
|
self.changeno = -1
|
def __init__(self, hdf, prefix='changeset.diff'): self.block = [] self.ttype = None self.p_block = [] self.p_type = None self.hdf = hdf self.prefix = prefix self.changeno = 0 self.blockno = 0
|
self.blockno += 1
|
def print_block (self): self.blockno += 1 prefix = '%s.changes.%d.blocks.%d' % (self.prefix, self.changeno, self.blockno) if self.p_type == '-' and self.ttype == '+': self._write_block(prefix, 'mod', old=string.join(self.p_block, '<br />'), new=string.join(self.block, '<br />')) elif self.ttype == '+': self._write_block(prefix, 'add', new=string.join(self.block, '<br />')) elif self.ttype == '-': self._write_block(prefix, 'rem', old=string.join(self.block, '<br />')) elif self.ttype == ' ': self._write_block(prefix, 'unmod', old=string.join(self.block, '<br />'), new=string.join(self.block, '<br />')) self.block = self.p_block = []
|
|
self.print_block()
|
def writeline(self, text): match = header_re.search(text) if match: self.hdf.setValue('%s.name.old' % self.prefix, match.group(1)) self.hdf.setValue('%s.name.new' % self.prefix, match.group(2)) return if text[0:2] in ['++', '--']: return match = line_re.search(text) if match: self.changeno += 1 pfx = '%s.changes.%d.line' % (self.prefix, self.changeno) self.print_block() self.hdf.setValue('%s.old' % pfx, match.group(1)) self.hdf.setValue('%s.new' % pfx, match.group(3)) return ttype = text[0] text = text[1:] text = space_re.sub(' ', text.expandtabs(8)) if ttype == self.ttype: self.block.append(text) else: if ttype == '+' and self.ttype == '-': self.p_block = self.block self.p_type = self.ttype else: self.print_block() self.block = [text] self.ttype = ttype
|
|
def add_file(self, path, parent_baton, copyfrom_path, copyfrom_revision, file_pool): return [None, path, file_pool] def open_file(self, path, parent_baton, base_revision, file_pool): return [path, path, file_pool] def apply_textdelta(self, file_baton, base_checksum): self.print_diff (*file_baton)
|
def add_file(self, path, parent_baton, copyfrom_path, copyfrom_revision, file_pool): return [None, path, file_pool]
|
|
return self.req.headers_out.get(name)
|
return self.req.headers_in.get(name)
|
def get_header(self, name): return self.req.headers_out.get(name)
|
req.redirect(self.env.href.ticket(ticket.id))
|
if req.args.get('attachment'): req.redirect(self.env.href.attachment('ticket', ticket.id, action='new')) else: req.redirect(self.env.href.ticket(ticket.id))
|
def _do_create(self, req, db): if not req.args.get('summary'): raise TracError('Tickets must contain a summary.')
|
tickets = get_tickets_for_milestone(self.env, db, milestone['name'],
|
tickets = get_tickets_for_milestone(self.env, db, milestone_name,
|
def process_request(self, req): req.perm.assert_permission('ROADMAP_VIEW') req.hdf['title'] = 'Roadmap'
|
for k, v in get_query_links(self.env, milestone['name']).items():
|
for k, v in get_query_links(self.env, milestone_name).items():
|
def process_request(self, req): req.perm.assert_permission('ROADMAP_VIEW') req.hdf['title'] = 'Roadmap'
|
rev = req.args.get('rev')
|
rev = req.args.get('rev') or None
|
def process_request(self, req): path = req.args.get('path', '/') rev = req.args.get('rev')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.