本文整理汇总了Python中util.safehasattr函数的典型用法代码示例。如果您正苦于以下问题:Python safehasattr函数的具体用法?Python safehasattr怎么用?Python safehasattr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了safehasattr函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: subrelpath
def subrelpath(sub):
"""return path to this subrepo as seen from outermost repo"""
if util.safehasattr(sub, '_relpath'):
return sub._relpath
if not util.safehasattr(sub, '_repo'):
return sub._path
return reporelpath(sub._repo)
开发者ID:agbiotec,项目名称:galaxy-tools-vcr,代码行数:7,代码来源:subrepo.py
示例2: json
def json(obj):
if obj is None or obj is False or obj is True:
return {None: 'null', False: 'false', True: 'true'}[obj]
elif isinstance(obj, int) or isinstance(obj, float):
return str(obj)
elif isinstance(obj, str):
u = unicode(obj, encoding.encoding, 'replace')
return '"%s"' % jsonescape(u)
elif isinstance(obj, unicode):
return '"%s"' % jsonescape(obj)
elif util.safehasattr(obj, 'keys'):
out = []
for k, v in sorted(obj.iteritems()):
s = '%s: %s' % (json(k), json(v))
out.append(s)
return '{' + ', '.join(out) + '}'
elif util.safehasattr(obj, '__iter__'):
out = []
for i in obj:
out.append(json(i))
return '[' + ', '.join(out) + ']'
elif util.safehasattr(obj, '__call__'):
return json(obj())
else:
raise TypeError('cannot encode type %s' % obj.__class__.__name__)
开发者ID:RayFerr000,项目名称:PLTL,代码行数:25,代码来源:templatefilters.py
示例3: makefileobj
def makefileobj(repo, pat, node=None, desc=None, total=None,
seqno=None, revwidth=None, mode='wb', pathname=None):
writable = mode not in ('r', 'rb')
if not pat or pat == '-':
fp = writable and repo.ui.fout or repo.ui.fin
if util.safehasattr(fp, 'fileno'):
return os.fdopen(os.dup(fp.fileno()), mode)
else:
# if this fp can't be duped properly, return
# a dummy object that can be closed
class wrappedfileobj(object):
noop = lambda x: None
def __init__(self, f):
self.f = f
def __getattr__(self, attr):
if attr == 'close':
return self.noop
else:
return getattr(self.f, attr)
return wrappedfileobj(fp)
if util.safehasattr(pat, 'write') and writable:
return pat
if util.safehasattr(pat, 'read') and 'r' in mode:
return pat
return open(makefilename(repo, pat, node, desc, total, seqno, revwidth,
pathname),
mode)
开发者ID:mortonfox,项目名称:cr48,代码行数:30,代码来源:cmdutil.py
示例4: moduleversion
def moduleversion(module):
'''return version information from given module as a string'''
if (util.safehasattr(module, 'getversion')
and callable(module.getversion)):
version = module.getversion()
elif util.safehasattr(module, '__version__'):
version = module.__version__
else:
version = ''
if isinstance(version, (list, tuple)):
version = '.'.join(str(o) for o in version)
return version
开发者ID:gorcz,项目名称:mercurial,代码行数:12,代码来源:extensions.py
示例5: remoteui
def remoteui(src, opts):
"build a remote ui from ui or repo and opts"
if util.safehasattr(src, "baseui"): # looks like a repository
dst = src.baseui.copy() # drop repo-specific config
src = src.ui # copy target options from repo
else: # assume it's a global ui object
dst = src.copy() # keep all global options
# copy ssh-specific options
for o in "ssh", "remotecmd":
v = opts.get(o) or src.config("ui", o)
if v:
dst.setconfig("ui", o, v, "copied")
# copy bundle-specific options
r = src.config("bundle", "mainreporoot")
if r:
dst.setconfig("bundle", "mainreporoot", r, "copied")
# copy selected local settings to the remote ui
for sect in ("auth", "hostfingerprints", "http_proxy"):
for key, val in src.configitems(sect):
dst.setconfig(sect, key, val, "copied")
v = src.config("web", "cacerts")
if v:
dst.setconfig("web", "cacerts", util.expandpath(v), "copied")
return dst
开发者ID:areshero,项目名称:ThirdWorldApp,代码行数:28,代码来源:hg.py
示例6: reporelpath
def reporelpath(repo):
"""return path to this (sub)repo as seen from outermost repo"""
parent = repo
while util.safehasattr(parent, '_subparent'):
parent = parent._subparent
p = parent.root.rstrip(os.sep)
return repo.root[len(p) + 1:]
开发者ID:agbiotec,项目名称:galaxy-tools-vcr,代码行数:7,代码来源:subrepo.py
示例7: unbundle
def unbundle(repo, proto, heads):
their_heads = decodelist(heads)
try:
proto.redirect()
exchange.check_heads(repo, their_heads, 'preparing changes')
# write bundle data to temporary file because it can be big
fd, tempname = tempfile.mkstemp(prefix='hg-unbundle-')
fp = os.fdopen(fd, 'wb+')
r = 0
try:
proto.getfile(fp)
fp.seek(0)
gen = exchange.readbundle(repo.ui, fp, None)
r = exchange.unbundle(repo, gen, their_heads, 'serve',
proto._client())
if util.safehasattr(r, 'addpart'):
# The return looks streameable, we are in the bundle2 case and
# should return a stream.
return streamres(r.getchunks())
return pushres(r)
finally:
fp.close()
os.unlink(tempname)
except bundle2.UnknownPartError, exc:
bundler = bundle2.bundle20(repo.ui)
part = bundle2.bundlepart('B2X:ERROR:UNKNOWNPART',
[('parttype', str(exc))])
bundler.addpart(part)
return streamres(bundler.getchunks())
开发者ID:leetaizhu,项目名称:Odoo_ENV_MAC_OS,代码行数:33,代码来源:wireproto.py
示例8: runsymbol
def runsymbol(context, mapping, key):
v = mapping.get(key)
if v is None:
v = context._defaults.get(key, '')
if util.safehasattr(v, '__call__'):
return v(**mapping)
return v
开发者ID:agbiotec,项目名称:galaxy-tools-vcr,代码行数:7,代码来源:templater.py
示例9: helptopic
def helptopic(name):
for names, header, doc in helptable:
if name in names:
break
else:
raise error.UnknownCommand(name)
rst = [minirst.section(header)]
# description
if not doc:
rst.append(" %s\n" % _("(no help text available)"))
if util.safehasattr(doc, '__call__'):
rst += [" %s\n" % l for l in doc().splitlines()]
if not ui.verbose:
omitted = (_('use "hg help -v %s" to show more complete help') %
name)
indicateomitted(rst, omitted)
try:
cmdutil.findcmd(name, commands.table)
rst.append(_('\nuse "hg help -c %s" to see help for '
'the %s command\n') % (name, name))
except error.UnknownCommand:
pass
return rst
开发者ID:leetaizhu,项目名称:Odoo_ENV_MAC_OS,代码行数:27,代码来源:help.py
示例10: wrapcommand
def wrapcommand(table, command, wrapper):
'''Wrap the command named `command' in table
Replace command in the command table with wrapper. The wrapped command will
be inserted into the command table specified by the table argument.
The wrapper will be called like
wrapper(orig, *args, **kwargs)
where orig is the original (wrapped) function, and *args, **kwargs
are the arguments passed to it.
'''
assert util.safehasattr(wrapper, '__call__')
aliases, entry = cmdutil.findcmd(command, table)
for alias, e in table.iteritems():
if e is entry:
key = alias
break
origfn = entry[0]
def wrap(*args, **kwargs):
return util.checksignature(wrapper)(
util.checksignature(origfn), *args, **kwargs)
wrap.__doc__ = getattr(origfn, '__doc__')
wrap.__module__ = getattr(origfn, '__module__')
newentry = list(entry)
newentry[0] = wrap
table[key] = tuple(newentry)
return entry
开发者ID:32bitfloat,项目名称:intellij-community,代码行数:32,代码来源:extensions.py
示例11: unbundle
def unbundle(repo, proto, heads):
their_heads = decodelist(heads)
try:
proto.redirect()
exchange.check_heads(repo, their_heads, "preparing changes")
# write bundle data to temporary file because it can be big
fd, tempname = tempfile.mkstemp(prefix="hg-unbundle-")
fp = os.fdopen(fd, "wb+")
r = 0
try:
proto.getfile(fp)
fp.seek(0)
gen = exchange.readbundle(repo.ui, fp, None)
r = exchange.unbundle(repo, gen, their_heads, "serve", proto._client())
if util.safehasattr(r, "addpart"):
# The return looks streameable, we are in the bundle2 case and
# should return a stream.
return streamres(r.getchunks())
return pushres(r)
finally:
fp.close()
os.unlink(tempname)
except error.BundleValueError, exc:
bundler = bundle2.bundle20(repo.ui)
errpart = bundler.newpart("B2X:ERROR:UNSUPPORTEDCONTENT")
if exc.parttype is not None:
errpart.addparam("parttype", exc.parttype)
if exc.params:
errpart.addparam("params", "\0".join(exc.params))
return streamres(bundler.getchunks())
开发者ID:ZanderZhang,项目名称:Andriod-Learning,代码行数:34,代码来源:wireproto.py
示例12: remoteui
def remoteui(src, opts):
'build a remote ui from ui or repo and opts'
if util.safehasattr(src, 'baseui'): # looks like a repository
dst = src.baseui.copy() # drop repo-specific config
src = src.ui # copy target options from repo
else: # assume it's a global ui object
dst = src.copy() # keep all global options
# copy ssh-specific options
for o in 'ssh', 'remotecmd':
v = opts.get(o) or src.config('ui', o)
if v:
dst.setconfig("ui", o, v)
# copy bundle-specific options
r = src.config('bundle', 'mainreporoot')
if r:
dst.setconfig('bundle', 'mainreporoot', r)
# copy selected local settings to the remote ui
for sect in ('auth', 'hostfingerprints', 'http_proxy'):
for key, val in src.configitems(sect):
dst.setconfig(sect, key, val)
v = src.config('web', 'cacerts')
if v:
dst.setconfig('web', 'cacerts', util.expandpath(v))
return dst
开发者ID:sandeepprasanna,项目名称:ODOO,代码行数:28,代码来源:hg.py
示例13: stringify
def stringify(thing):
""":stringify: Any type. Turns the value into text by converting values into
text and concatenating them.
"""
if util.safehasattr(thing, '__iter__') and not isinstance(thing, str):
return "".join([stringify(t) for t in thing if t is not None])
return str(thing)
开发者ID:chuchiperriman,项目名称:hg-stable,代码行数:7,代码来源:templatefilters.py
示例14: pushkey
def pushkey(repo, proto, namespace, key, old, new):
# compatibility with pre-1.8 clients which were accidentally
# sending raw binary nodes rather than utf-8-encoded hex
if len(new) == 20 and new.encode('string-escape') != new:
# looks like it could be a binary node
try:
new.decode('utf-8')
new = encoding.tolocal(new) # but cleanly decodes as UTF-8
except UnicodeDecodeError:
pass # binary, leave unmodified
else:
new = encoding.tolocal(new) # normal path
if util.safehasattr(proto, 'restore'):
proto.redirect()
try:
r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
encoding.tolocal(old), new) or False
except util.Abort:
r = False
output = proto.restore()
return '%s\n%s' % (int(r), output)
r = repo.pushkey(encoding.tolocal(namespace), encoding.tolocal(key),
encoding.tolocal(old), new)
return '%s\n' % int(r)
开发者ID:chuchiperriman,项目名称:hg-stable,代码行数:30,代码来源:wireproto.py
示例15: unbundle
def unbundle(repo, cg, heads, source, url):
"""Apply a bundle to a repo.
this function makes sure the repo is locked during the application and have
mechanism to check that no push race occurred between the creation of the
bundle and its application.
If the push was raced as PushRaced exception is raised."""
r = 0
# need a transaction when processing a bundle2 stream
tr = None
lock = repo.lock()
try:
check_heads(repo, heads, 'uploading changes')
# push can proceed
if util.safehasattr(cg, 'params'):
try:
tr = repo.transaction('unbundle')
tr.hookargs['source'] = source
tr.hookargs['url'] = url
tr.hookargs['bundle2-exp'] = '1'
r = bundle2.processbundle(repo, cg, lambda: tr).reply
cl = repo.unfiltered().changelog
p = cl.writepending() and repo.root or ""
repo.hook('b2x-pretransactionclose', throw=True, pending=p,
**tr.hookargs)
tr.close()
hookargs = dict(tr.hookargs)
def runhooks():
repo.hook('b2x-transactionclose', **hookargs)
repo._afterlock(runhooks)
except Exception, exc:
exc.duringunbundle2 = True
raise
else:
开发者ID:ZanderZhang,项目名称:Andriod-Learning,代码行数:35,代码来源:exchange.py
示例16: unbundle
def unbundle(self, cg, heads, source):
'''Send cg (a readable file-like object representing the
changegroup to push, typically a chunkbuffer object) to the
remote server as a bundle.
When pushing a bundle10 stream, return an integer indicating the
result of the push (see localrepository.addchangegroup()).
When pushing a bundle20 stream, return a bundle20 stream.'''
if heads != ['force'] and self.capable('unbundlehash'):
heads = encodelist(['hashed',
util.sha1(''.join(sorted(heads))).digest()])
else:
heads = encodelist(heads)
if util.safehasattr(cg, 'deltaheader'):
# this a bundle10, do the old style call sequence
ret, output = self._callpush("unbundle", cg, heads=heads)
if ret == "":
raise error.ResponseError(
_('push failed:'), output)
try:
ret = int(ret)
except ValueError:
raise error.ResponseError(
_('push failed (unexpected response):'), ret)
for l in output.splitlines(True):
self.ui.status(_('remote: '), l)
else:
# bundle2 push. Send a stream, fetch a stream.
stream = self._calltwowaystream('unbundle', cg, heads=heads)
ret = bundle2.unbundle20(self.ui, stream)
return ret
开发者ID:areshero,项目名称:ThirdWorldApp,代码行数:35,代码来源:wireproto.py
示例17: _checkshellalias
def _checkshellalias(lui, ui, args):
norepo = commands.norepo
options = {}
try:
args = fancyopts.fancyopts(args, commands.globalopts, options)
except fancyopts.getopt.GetoptError:
return
if not args:
return
cmdtable = commands.table.copy()
addaliases(lui, cmdtable)
cmd = args[0]
try:
aliases, entry = cmdutil.findcmd(cmd, cmdtable, lui.config("ui", "strict"))
except (error.AmbiguousCommand, error.UnknownCommand):
commands.norepo = norepo
return
cmd = aliases[0]
fn = entry[0]
if cmd and util.safehasattr(fn, 'shell'):
d = lambda: fn(ui, *args[1:])
return lambda: runcommand(lui, None, cmd, args[:1], ui, options, d, [], {})
commands.norepo = norepo
开发者ID:mortonfox,项目名称:cr48,代码行数:30,代码来源:dispatch.py
示例18: copies
def copies(self, c2):
if not util.safehasattr(self, "_copycache"):
self._copycache = {}
sc2 = str(c2)
if sc2 not in self._copycache:
self._copycache[sc2] = copies.pathcopies(c2)
return self._copycache[sc2]
开发者ID:32bitfloat,项目名称:intellij-community,代码行数:7,代码来源:context.py
示例19: _exthook
def _exthook(ui, repo, name, cmd, args, throw):
ui.note(_("running hook %s: %s\n") % (name, cmd))
starttime = time.time()
env = {}
for k, v in args.iteritems():
if util.safehasattr(v, '__call__'):
v = v()
if isinstance(v, dict):
# make the dictionary element order stable across Python
# implementations
v = ('{' +
', '.join('%r: %r' % i for i in sorted(v.iteritems())) +
'}')
env['HG_' + k.upper()] = v
if repo:
cwd = repo.root
else:
cwd = os.getcwd()
if 'HG_URL' in env and env['HG_URL'].startswith('remote:http'):
r = util.system(cmd, environ=env, cwd=cwd, out=ui)
else:
r = util.system(cmd, environ=env, cwd=cwd, out=ui.fout)
duration = time.time() - starttime
ui.log('exthook', 'exthook-%s: %s finished in %0.2f seconds\n',
name, cmd, duration)
if r:
desc, r = util.explainexit(r)
if throw:
raise util.Abort(_('%s hook %s') % (name, desc))
ui.warn(_('warning: %s hook %s\n') % (name, desc))
return r
开发者ID:32bitfloat,项目名称:intellij-community,代码行数:34,代码来源:hook.py
示例20: _flatten
def _flatten(thing):
'''yield a single stream from a possibly nested set of iterators'''
if isinstance(thing, str):
yield thing
elif not util.safehasattr(thing, '__iter__'):
if thing is not None:
yield str(thing)
else:
for i in thing:
if isinstance(i, str):
yield i
elif not util.safehasattr(i, '__iter__'):
if i is not None:
yield str(i)
elif i is not None:
for j in _flatten(i):
yield j
开发者ID:RayFerr000,项目名称:PLTL,代码行数:17,代码来源:templater.py
注:本文中的util.safehasattr函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论