本文整理汇总了Python中tractags.api.TagEngine.get_tagged_names方法的典型用法代码示例。如果您正苦于以下问题:Python TagEngine.get_tagged_names方法的具体用法?Python TagEngine.get_tagged_names怎么用?Python TagEngine.get_tagged_names使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tractags.api.TagEngine
的用法示例。
在下文中一共展示了TagEngine.get_tagged_names方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: render_listtagged
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def render_listtagged(self, req, *tags, **kwargs):
""" List tagged objects. Optionally accepts a list of tags to match
against. The special tag '''. (dot)''' inserts the current Wiki page name.
`[[ListTagged(<tag>, ...)]]`
||'''Argument'''||'''Description'''||
||`tagspace=<tagspace>`||Specify the tagspace the macro should operate on.||
||`tagspaces=(<tagspace>,...)`||Specify a set of tagspaces the macro should operate on.||
||`operation=intersection|union`||The set operation to perform on the discovered objects.||
||`showheadings=true|false`||List objects under the tagspace they occur in.||
"""
if 'tagspace' in kwargs:
tagspaces = [kwargs.get('tagspace', None)]
else:
tagspaces = kwargs.get('tagspaces', '') or \
list(TagEngine(self.env).tagspaces)
showheadings = kwargs.get('showheadings', 'false')
operation = kwargs.get('operation', 'intersection')
if operation not in ('union', 'intersection'):
raise TracError("Invalid tag set operation '%s'" % operation)
engine = TagEngine(self.env)
page_name = req.hdf.get('wiki.page_name')
if page_name:
tags = [tag == '.' and page_name or tag for tag in tags]
taginfo = {}
out = StringIO()
out.write('<ul class="listtagged">')
# Cull empty names
tagged_names = [(tagspace, names) for tagspace, names in
engine.get_tagged_names(tags=tags, tagspaces=tagspaces,
operation=operation, detailed=True).iteritems()
if names]
for tagspace, tagspace_names in sorted(tagged_names):
if showheadings == 'true':
out.write('<lh>%s tags</lh>' % tagspace)
for name, tags in sorted(tagspace_names.iteritems()):
if tagspace == 'wiki' and unicode(name).startswith('tags/'): continue
tags = sorted(tags)
taginfo = self._tag_details(taginfo, tags)
href, link, title = engine.name_details(tagspace, name)
htitle = wiki_to_oneliner(title, self.env)
name_tags = ['<a href="%s" title="%s">%s</a>'
% (taginfo[tag][0], taginfo[tag][1], tag)
for tag in tags]
if not name_tags:
name_tags = ''
else:
name_tags = ' (' + ', '.join(sorted(name_tags)) + ')'
out.write('<li>%s %s%s</li>\n' %
(link, htitle, name_tags))
out.write('</ul>')
return out.getvalue()
示例2: getHacks
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def getHacks(self, req, release, type):
""" Fetch a list of hacks for Trac release, of type. """
from trac.versioncontrol.api import Node
from tractags.api import TagEngine
repo = self.env.get_repository(req.authname)
wikitags = TagEngine(self.env).tagspace.wiki
repo_rev = repo.get_youngest_rev()
releases = wikitags.get_tagged_names([release])
types = wikitags.get_tagged_names([type])
for plugin in releases.intersection(types):
if plugin.startswith("tags/"):
continue
path = "%s/%s" % (plugin.lower(), release)
rev = 0
if repo.has_node(str(path), repo_rev):
node = repo.get_node(path)
rev = node.rev
yield (plugin, rev)
示例3: getDetails
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def getDetails(self, req, hack):
""" Fetch hack details. Returns dict with name, dependencies and
description. """
from tractags.api import TagEngine
wikitags = TagEngine(self.env).tagspace.wiki
tags = wikitags.get_tags(hack)
types = self.getTypes()
hacks = wikitags.get_tagged_names(types)
dependencies = hacks.intersection(tags)
href, htmllink, description = wikitags.name_details(hack)
return {"name": hack, "dependencies": tuple(dependencies), "description": description}
示例4: render_listtagged
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def render_listtagged(self, req, *tags, **kwargs):
""" List tagged objects. Takes a list of tags to match against.
The special tag '.' inserts the current Wiki page name.
Optional keyword arguments are tagspace=wiki,
tagspaces=(wiki, title, ...) and showheadings=true.
By default displays the intersection of objects matching each tag.
By passing operation=union this can be modified to display
the union of objects matching each tag.
"""
if 'tagspace' in kwargs:
tagspaces = [kwargs.get('tagspace', None)]
else:
tagspaces = kwargs.get('tagspaces', '') or \
list(TagEngine(self.env).tagspaces)
showheadings = kwargs.get('showheadings', 'false')
operation = kwargs.get('operation', 'intersection')
if operation not in ('union', 'intersection'):
raise TracError("Invalid tag set operation '%s'" % operation)
engine = TagEngine(self.env)
page_name = req.hdf.get('wiki.page_name')
if page_name:
tags = [tag == '.' and page_name or tag for tag in tags]
taginfo = {}
out = StringIO()
out.write('<ul class="listtagged">')
for tagspace, tagspace_names in sorted(engine.get_tagged_names(tags=tags, tagspaces=tagspaces, operation=operation, detailed=True).iteritems()):
if showheadings == 'true':
out.write('<lh>%s tags</lh>' % tagspace)
for name, tags in sorted(tagspace_names.iteritems()):
if tagspace == 'wiki' and unicode(name).startswith('tags/'): continue
tags = sorted(tags)
taginfo = self._tag_details(taginfo, tags)
href, link, title = engine.name_details(tagspace, name)
htitle = wiki_to_oneliner(title, self.env)
name_tags = ['<a href="%s" title="%s">%s</a>'
% (taginfo[tag][0], taginfo[tag][1], tag)
for tag in tags]
if not name_tags:
name_tags = ''
else:
name_tags = ' (' + ', '.join(sorted(name_tags)) + ')'
out.write('<li>%s %s%s</li>\n' %
(link, htitle, name_tags))
out.write('</ul>')
return out.getvalue()
示例5: getNames
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def getNames(self, req, tagname):
""" Returns all pages with tagname """
engine = TagEngine(self.env)
try:
tagspaces = list()
tagspaces.append(self.tagsystem.tagspace)
tags = list()
tags.append (tagname)
names = engine.get_tagged_names(tags=tags,tagspaces=tagspaces)
self.env.log.debug("getNames found %s for tagname %s"%(names, tagname))
return list(names[self.tagsystem.tagspace])
except Exception, e:
self.env.log.debug('Error in getNames(%s): %s\n' % (tagname, str(e)))
return None
示例6: render_macro
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def render_macro(self, req, name, content):
from StringIO import StringIO
from trac.wiki import wiki_to_html
from trac.wiki.model import WikiPage
from trac.util import Markup
from tractags.api import TagEngine
import re
tagspace = TagEngine(self.env).tagspace.wiki
out = StringIO()
pages = tagspace.get_tagged_names(tags=["type"])
pages = sorted(pages)
out.write('<form style="text-align: right; padding-top: 1em; margin-right: 5em;" method="get">')
out.write('<span style="font-size: xx-small">')
out.write("Show hacks for releases: ")
releases = natsorted(tagspace.get_tagged_names(tags=["release"]))
if "update_th_filter" in req.args:
show_releases = req.args.get("release", ["0.12"])
if isinstance(show_releases, basestring):
show_releases = [show_releases]
req.session["th_release_filter"] = ",".join(show_releases)
else:
show_releases = req.session.get("th_release_filter", "0.12").split(",")
for version in releases:
checked = version in show_releases
out.write(
'<input type="checkbox" name="release" value="%s"%s>%s\n'
% (version, checked and " checked" or "", version)
)
out.write(
'<input name="update_th_filter" type="submit" style="font-size: xx-small; padding: 0; border: solid 1px black" value="Update"/>'
)
out.write("</span>")
out.write("</form>")
for i, pagename in enumerate(pages):
page = WikiPage(self.env, pagename)
if page.text:
topmargin = "0em"
if i < len(pages) - 1:
bottommargin = "0em"
else:
bottommargin = "2em"
out.write(
'<fieldset style="padding: 1em; margin: %s 5em %s 5em; border: 1px solid #999;">\n'
% (topmargin, bottommargin)
)
body = page.text
title = re.search("=+\s([^=]*)=+", body)
if title:
title = title.group(1).strip()
body = re.sub("=+\s([^=]*)=+", "", body, 1)
else:
title = pagename
body = re.sub("\\[\\[TagIt.*", "", body)
out.write(
'<legend style="color: #999;"><a href="%s">%s</a></legend>\n'
% (self.env.href.wiki(pagename), title)
)
body = wiki_to_html(body, self.env, req)
# Dear God, the horror!
for line in body.splitlines():
show = False
for release in show_releases:
self.env.log.debug(release)
if ">%s</a>" % release in line:
show = True
break
if show or not "<li>" in line:
out.write(line)
out.write("</fieldset>\n")
return out.getvalue()
示例7: execute
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def execute(hdf, template, env):
out = StringIO()
errors = []
authname = hdf.getValue("trac.authname", "anonymous")
if not template:
raise TracError("No template page supplied")
if authname == "anonymous":
errors.append('You need to <a href="%s">register</a> then <a href="%s">login</a> in order to create a new hack.' % (hdf.getValue("trac.href.registration", ""), hdf.getValue("trac.href.login", "")))
db = env.get_db_cnx()
cursor = db.cursor()
# Fetch meta-data from tags
META_TAGS = set()
from tractags.api import TagEngine
wikitags = TagEngine(env).tagspace.wiki
for tag in wikitags.get_tagged_names(['metatag']):
META_TAGS.update(wikitags.get_tagged_names([tag]))
TYPES = wikitags.get_tagged_names(['type'])
RELEASES = wikitags.get_tagged_names(['release'])
page_name = hdf.getValue('args.name', '')
if not page_name.lower().endswith(hdf.getValue('args.type', '')):
page_name += hdf.getValue('args.type', '').title()
page_title = hdf.getValue('args.title', '')
page_description = hdf.getValue('args.description', '')
page_example = hdf.getValue('args.example', '')
page_type = hdf.getValue('args.type', 'plugin')
page_tags = get_branch_values(hdf, 'args.tags')
page_releases = get_branch_values(hdf, 'args.releases')
page_preview = hdf.getValue('args.previewhack', '')
page_create = hdf.getValue('args.createhack', '')
def write_tags(out, tags, checked = (), name = "tags", type="checkbox"):
count = 0
for tag in sorted(tags):
if tag.startswith('tags/'):
continue
(linktext,title,desc) = getInfo(db,tag)
link = env.href.wiki(tag)
check = ""
if tag in checked:
check = " checked"
out.write('<input type="%s" name="%s" value="%s"%s/> <a href="%s" title="%s">%s</a> \n' % (type, name, tag, check, link, title, tag))
count += 1
if count % 8 == 0:
out.write("<br/>\n")
return count
# Validation
if page_preview or page_create:
try:
fetch_page(cursor, page_name)
except:
pass
else:
errors.append("Page name %s already exists" % page_name)
if not re.match('^([A-Z][a-z]+){2,}$', page_name): errors.append('Invalid WikiName, only alpha characters are accepted and must be CamelCase')
if not page_name: errors.append("No WikiName provided")
if not page_title: errors.append("No page title provided")
if not page_type: errors.append('No page type selected')
if not page_description: errors.append("No description provided")
if not page_example: errors.append("No example provided")
if not page_releases: errors.append("No releases selected")
if page_create and not errors:
import subprocess
repos_dir = env.config.get('trac', 'repository_dir')
cursor.execute("SELECT name FROM component WHERE name=%s", (page_name,))
row = cursor.fetchone()
if row:
errors.append("Component '%s' already exists" % page_name)
if subprocess.call(["svn", "ls", "%s/%s" % (SVN_LOCAL_PATH, page_name.lower())]) == 0:
errors.append("Repository path '%s' already exists" % page_name.lower())
if not os.access(SVN_PERMISSIONS, os.W_OK):
errors.append("Can't write to Subversion permissions file")
lockfile = open("/var/tmp/newhack.lock", "w")
try:
rv = fcntl.flock(lockfile, fcntl.LOCK_EX | fcntl.LOCK_NB)
if rv:
errors.append('Failed to acquire lock, received error code %i' % rv)
except IOError:
errors.append('A hack is currently being created by another user. Try again later.')
if not errors:
try:
# Insert component
cursor.execute('INSERT INTO component (name, owner) VALUES (%s, %s)', (page_name, authname))
# Create page
page = WikiPage(env, page_name, db = db)
page.text = expand_vars(fetch_page(cursor, template), generate_vars(hdf))
out.write('Created wiki page.<br>\n')
# Creating SVN paths
paths = ['%s/%s' % (SVN_LOCAL_PATH, page_name.lower())]
for release in page_releases:
paths.append("%s/%s/%s" % (SVN_LOCAL_PATH, page_name.lower(), release))
output = os.popen('/usr/bin/op create-hack %s "New hack %s, created by %s" %s 2>&1' % (authname, page_name, authname, ' '.join(paths))).readlines()
if output:
raise Exception("Failed to create Subversion paths:\n%s" % ''.join(output))
out.write("Created SVN layout.<br>\n")
#.........这里部分代码省略.........
示例8: TagApiTestCase
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
class TagApiTestCase(unittest.TestCase):
test_data = (('wiki', 'WikiStart', ('foo', 'bar')),
('wiki', 'SandBox', ('bar', 'war')),
('ticket', 1, ('war', 'death')),
('ticket', 2, ('death', 'destruction')),
('ticket', 3, ('foo', 'bar', 'destruction'))
)
req = Mock(perm=Mock(assert_permission=lambda x: True),
authname='anonymous')
def _populate_tags(self, ts):
for tagspace, target, tags in self.test_data:
tagspace = ts.tagspace(tagspace)
tagspace.add_tags(self.req, target, tags)
yield tagspace, target, tags
def setUp(self):
self.env = EnvironmentStub(default_data=True)
self.env.path = '/'
self.tag_engine = TagEngine(self.env)
self.tag_engine.upgrade_environment(self.env.get_db_cnx())
# Insert some test tickets
from trac.ticket.model import Ticket
for id in (1, 2, 3):
ticket = Ticket(self.env)
ticket['summary'] = 'Test ticket %i' % id
ticket['description'] = 'Test ticket %i description' % id
ticket.insert()
def test_tagspaces(self):
tagspaces = set(self.tag_engine.tagspaces)
self.assertEqual(tagspaces, set(('ticket', 'wiki')))
def test_insert(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts):
found_tags = tagspace.get_tags([target])
self.assertEqual(found_tags, set(tags))
def test_remove(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts):
target_tags = tagspace.get_name_tags(target)
tag = iter(target_tags).next()
tagspace.remove_tags(self.req, target, (tag,))
target_tags.discard(tag)
self.assertEqual(tagspace.get_name_tags(target), target_tags)
def test_remove_all(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts):
tagspace.remove_all_tags(self.req, target)
def test_replace(self):
ts = self.tag_engine.tagspace
test_set = set(('foozle', 'stick'))
for tagspace, target, tags in self._populate_tags(ts):
found_tags = tagspace.get_tags([target])
tagspace.replace_tags(self.req, target, test_set)
self.assertEqual(test_set, tagspace.get_name_tags(target))
def test_add(self):
ts = self.tag_engine.tagspace
test_set = set(('foozle', 'stick'))
for tagspace, target, tags in self._populate_tags(ts):
found_tags = tagspace.get_tags([target])
tagspace.add_tags(self.req, target, test_set)
self.assertEqual(test_set.union(found_tags), tagspace.get_name_tags(target))
def test_walk(self):
engine = self.tag_engine
compare_data = {}
for tagspace, target, tags in self._populate_tags(engine.tagspace):
compare_data.setdefault(tagspace.tagspace, {})[target] = set(tags)
tag_data = {}
for tagspace, name, tags in engine.walk_tagged_names():
tag_data.setdefault(tagspace, {})[name] = tags
self.assertEqual(compare_data, tag_data)
def test_get_tagged_union(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts): pass
self.assertEqual(self.tag_engine.get_tagged_names(tags=('foo', 'bar'), operation='union'),
{'wiki': set([u'WikiStart', u'SandBox']), 'ticket': set([3])})
def test_get_tagged_intersection(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts): pass
self.assertEqual(self.tag_engine.get_tagged_names(tags=('foo', 'bar'), operation='intersection'),
{'wiki': set(['WikiStart']), 'ticket': set([3])})
def test_get_tags_union(self):
ts = self.tag_engine.tagspace
for tagspace, target, tags in self._populate_tags(ts): pass
self.assertEqual(self.tag_engine.get_tags(names=('WikiStart', 1), operation='union'),
set(['death', 'bar', 'war', 'foo']))
def test_get_tags_intersection(self):
ts = self.tag_engine.tagspace
#.........这里部分代码省略.........
示例9: _generate_blog
# 需要导入模块: from tractags.api import TagEngine [as 别名]
# 或者: from tractags.api.TagEngine import get_tagged_names [as 别名]
def _generate_blog(self, req, *args, **kwargs):
"""Extract the blog pages and fill the HDF.
*args is a list of tags to use to limit the blog scope
**kwargs are any aditional keyword arguments that are needed
"""
tallies = {}
tags = TagEngine(self.env).tagspace.wiki
try:
union = kwargs['union']
except KeyError:
union = False
# Formatting
read_post = "[wiki:%s Read Post]"
entries = {}
if not len(args):
tlist = [self.env.config.get('blog', 'default_tag', 'blog')]
else:
tlist = args
if union:
blog = tags.get_tagged_names(tlist, operation='union')
else:
blog = tags.get_tagged_names(tlist, operation='intersection')
macropage = req.args.get('page', None)
poststart, postend, default_times = self._get_time_range(req, **kwargs)
mark_updated = self._choose_value('mark_updated', req, kwargs,
convert=bool_val)
if not mark_updated and (not isinstance(mark_updated, bool)):
mark_updated = bool_val(self.env.config.get('blog', 'mark_updated',
True))
macro_bl = self.env.config.get('blog', 'macro_blacklist', '').split(',')
macro_bl = [name.strip() for name in macro_bl if name.strip()]
macro_bl.append('BlogShow')
# Get the email addresses of all known users and validate the "poster"
# BlogShow optional argument at the same time (avoids looping the user
# list twice).
is_poster = None
limit_poster = self._choose_value('poster', req, kwargs, convert=None)
email_map = {}
for username, name, email in self.env.get_known_users():
if email:
email_map[username] = email
if limit_poster != None:
if username == limit_poster:
is_poster = username
num_posts = self._choose_value('num_posts', req, kwargs, convert=int)
if num_posts and default_times:
poststart = sys.maxint
postend = 0
for blog_entry in blog:
if blog_entry == macropage:
continue
try:
page = WikiPage(self.env, version=1, name=blog_entry)
version, post_time, author, comment, ipnr = page.get_history(
).next()
# if we're limiting by poster, do so now so that the calendar
# only shows the number of entries the specific poster made.
if is_poster != None:
if is_poster != author:
continue
self._add_to_tallies(tallies, post_time, blog_entry)
page = WikiPage(self.env, name=blog_entry)
version, modified, author, comment, ipnr = page.get_history(
).next()
except:
self.log.debug("Error loading wiki page %s" % blog_entry, exc_info=True)
continue
if poststart >= post_time >= postend:
time_format = self.env.config.get('blog', 'date_format') \
or '%x %X'
timeStr = format_datetime(post_time, format=time_format)
fulltext = page.text
# remove comments in blog view:
del_comments = re.compile('==== Comment.*\Z', re.DOTALL)
fulltext = del_comments.sub('', fulltext)
# remove the [[AddComment...]] tag, otherwise it would appeare
# more than one and crew up the blog view:
del_addcomment = re.compile('\[\[AddComment.*\Z', re.DOTALL)
fulltext = del_addcomment.sub('', fulltext)
# limit length of preview:
post_size = self._choose_value('post_size', req, kwargs, int)
if not post_size and (not isinstance(post_size, int)):
post_size = int(self.env.config.get('blog', 'post_size',
1024))
text = self._trim_page(fulltext, blog_entry, post_size)
pagetags = [x for x in tags.get_name_tags(blog_entry) if x not in tlist]
tagtags = []
for i, t in enumerate(pagetags[:3]):
d = { 'link' : t,
'name' : t,
'last' : i == (len(pagetags[:3]) - 1),
}
tagtags.append(d)
continue
#.........这里部分代码省略.........