mirror of
https://github.com/openSUSE/osc.git
synced 2025-01-03 21:36:15 +01:00
Merge pull request #1464 from dirkmueller/flynt
Convert to using f-strings
This commit is contained in:
commit
b5c8fa75ea
@ -114,7 +114,7 @@ class SectionLine(Line):
|
|||||||
raise configparser.Error('value and line are mutually exclusive')
|
raise configparser.Error('value and line are mutually exclusive')
|
||||||
|
|
||||||
if value is not None:
|
if value is not None:
|
||||||
line = '%s%s%s' % (optname, sep, value)
|
line = f'{optname}{sep}{value}'
|
||||||
opt = self._find(optname)
|
opt = self._find(optname)
|
||||||
if opt:
|
if opt:
|
||||||
opt.format(line)
|
opt.format(line)
|
||||||
@ -253,10 +253,10 @@ class OscConfigParser(configparser.ConfigParser):
|
|||||||
#cursect[optname] = "%s\n%s" % (cursect[optname], value)
|
#cursect[optname] = "%s\n%s" % (cursect[optname], value)
|
||||||
#self.set(cursect, optname, "%s\n%s" % (self.get(cursect, optname), value))
|
#self.set(cursect, optname, "%s\n%s" % (self.get(cursect, optname), value))
|
||||||
if cursect == configparser.DEFAULTSECT:
|
if cursect == configparser.DEFAULTSECT:
|
||||||
self._defaults[optname] = "%s\n%s" % (self._defaults[optname], value)
|
self._defaults[optname] = f"{self._defaults[optname]}\n{value}"
|
||||||
else:
|
else:
|
||||||
# use the raw value here (original version uses raw=False)
|
# use the raw value here (original version uses raw=False)
|
||||||
self._sections[cursect]._find(optname).value = '%s\n%s' % (self.get(cursect, optname, raw=True), value)
|
self._sections[cursect]._find(optname).value = f'{self.get(cursect, optname, raw=True)}\n{value}'
|
||||||
# a section header or option header?
|
# a section header or option header?
|
||||||
else:
|
else:
|
||||||
# is it a section header?
|
# is it a section header?
|
||||||
@ -342,7 +342,7 @@ class OscConfigParser(configparser.ConfigParser):
|
|||||||
first = False
|
first = False
|
||||||
else:
|
else:
|
||||||
ret.append('')
|
ret.append('')
|
||||||
ret.append('[%s]' % line.name)
|
ret.append(f'[{line.name}]')
|
||||||
for sline in line._lines:
|
for sline in line._lines:
|
||||||
if sline.name == '__name__':
|
if sline.name == '__name__':
|
||||||
continue
|
continue
|
||||||
|
@ -158,7 +158,7 @@ def run(prg, argv=None):
|
|||||||
print(e, file=sys.stderr)
|
print(e, file=sys.stderr)
|
||||||
return 2
|
return 2
|
||||||
except oscerr.ExtRuntimeError as e:
|
except oscerr.ExtRuntimeError as e:
|
||||||
print(e.file + ':', e.msg, file=sys.stderr)
|
print(f"{e.file}:", e.msg, file=sys.stderr)
|
||||||
except oscerr.ServiceRuntimeError as e:
|
except oscerr.ServiceRuntimeError as e:
|
||||||
print(e.msg, file=sys.stderr)
|
print(e.msg, file=sys.stderr)
|
||||||
except oscerr.WorkingCopyOutdated as e:
|
except oscerr.WorkingCopyOutdated as e:
|
||||||
|
@ -11,7 +11,7 @@ class KeyError(Exception):
|
|||||||
self.key = key
|
self.key = key
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return '' + self.key + ' :' + ' '.join(self.args)
|
return f"{self.key} :{' '.join(self.args)}"
|
||||||
|
|
||||||
|
|
||||||
class Checker:
|
class Checker:
|
||||||
|
@ -241,7 +241,7 @@ class Cmdln:
|
|||||||
self.options, self.args = self.argparser.parse_known_args(argv[1:])
|
self.options, self.args = self.argparser.parse_known_args(argv[1:])
|
||||||
unrecognized = [i for i in self.args if i.startswith("-")]
|
unrecognized = [i for i in self.args if i.startswith("-")]
|
||||||
if unrecognized:
|
if unrecognized:
|
||||||
self.argparser.error(f"unrecognized arguments: " + " ".join(unrecognized))
|
self.argparser.error(f"unrecognized arguments: {' '.join(unrecognized)}")
|
||||||
|
|
||||||
self.post_argparse()
|
self.post_argparse()
|
||||||
|
|
||||||
@ -257,7 +257,7 @@ class Cmdln:
|
|||||||
if arg_names == ["subcmd", "opts"]:
|
if arg_names == ["subcmd", "opts"]:
|
||||||
# positional args specified manually via @cmdln.option
|
# positional args specified manually via @cmdln.option
|
||||||
if self.args:
|
if self.args:
|
||||||
self.argparser.error(f"unrecognized arguments: " + " ".join(self.args))
|
self.argparser.error(f"unrecognized arguments: {' '.join(self.args)}")
|
||||||
cmd(self.options.command, self.options)
|
cmd(self.options.command, self.options)
|
||||||
elif arg_names == ["subcmd", "opts", "args"]:
|
elif arg_names == ["subcmd", "opts", "args"]:
|
||||||
# positional args are the remaining (unrecognized) args
|
# positional args are the remaining (unrecognized) args
|
||||||
|
File diff suppressed because it is too large
Load Diff
26
osc/conf.py
26
osc/conf.py
@ -1383,10 +1383,10 @@ def _model_to_rst(cls, title=None, description=None, sections=None, output_file=
|
|||||||
|
|
||||||
ini_key = extra.get("ini_key", name)
|
ini_key = extra.get("ini_key", name)
|
||||||
|
|
||||||
x = bold(ini_key) + " : " + get_type(name, field)
|
x = f"{bold(ini_key)} : {get_type(name, field)}"
|
||||||
default = get_default(name, field)
|
default = get_default(name, field)
|
||||||
if default:
|
if default:
|
||||||
x += " = " + italic(default)
|
x += f" = {italic(default)}"
|
||||||
result.append(x)
|
result.append(x)
|
||||||
result.append("")
|
result.append("")
|
||||||
desc = extra.get("ini_description", None) or field.description or ""
|
desc = extra.get("ini_description", None) or field.description or ""
|
||||||
@ -1499,13 +1499,13 @@ def parse_apisrv_url(scheme, apisrv):
|
|||||||
elif scheme is not None:
|
elif scheme is not None:
|
||||||
url = scheme + apisrv
|
url = scheme + apisrv
|
||||||
else:
|
else:
|
||||||
url = "https://" + apisrv
|
url = f"https://{apisrv}"
|
||||||
scheme, url, path = urlsplit(url)[0:3]
|
scheme, url, path = urlsplit(url)[0:3]
|
||||||
return scheme, url, path.rstrip('/')
|
return scheme, url, path.rstrip('/')
|
||||||
|
|
||||||
|
|
||||||
def urljoin(scheme, apisrv, path=''):
|
def urljoin(scheme, apisrv, path=''):
|
||||||
return '://'.join([scheme, apisrv]) + path
|
return f"{scheme}://{apisrv}" + path
|
||||||
|
|
||||||
|
|
||||||
def is_known_apiurl(url):
|
def is_known_apiurl(url):
|
||||||
@ -1541,7 +1541,7 @@ def get_apiurl_api_host_options(apiurl):
|
|||||||
apiurl = sanitize_apiurl(apiurl)
|
apiurl = sanitize_apiurl(apiurl)
|
||||||
if is_known_apiurl(apiurl):
|
if is_known_apiurl(apiurl):
|
||||||
return config['api_host_options'][apiurl]
|
return config['api_host_options'][apiurl]
|
||||||
raise oscerr.ConfigMissingApiurl('missing credentials for apiurl: \'%s\'' % apiurl,
|
raise oscerr.ConfigMissingApiurl(f'missing credentials for apiurl: \'{apiurl}\'',
|
||||||
'', apiurl)
|
'', apiurl)
|
||||||
|
|
||||||
|
|
||||||
@ -1602,14 +1602,14 @@ def write_config(fname, cp):
|
|||||||
if e.errno != errno.EEXIST:
|
if e.errno != errno.EEXIST:
|
||||||
raise
|
raise
|
||||||
|
|
||||||
with open(fname + '.new', 'w') as f:
|
with open(f"{fname}.new", 'w') as f:
|
||||||
cp.write(f, comments=True)
|
cp.write(f, comments=True)
|
||||||
try:
|
try:
|
||||||
os.rename(fname + '.new', fname)
|
os.rename(f"{fname}.new", fname)
|
||||||
os.chmod(fname, 0o600)
|
os.chmod(fname, 0o600)
|
||||||
except:
|
except:
|
||||||
if os.path.exists(fname + '.new'):
|
if os.path.exists(f"{fname}.new"):
|
||||||
os.unlink(fname + '.new')
|
os.unlink(f"{fname}.new")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
|
||||||
@ -1642,10 +1642,10 @@ def config_set_option(section, opt, val=None, delete=False, update=True, creds_m
|
|||||||
|
|
||||||
section = sections.get(section.rstrip('/'), section)
|
section = sections.get(section.rstrip('/'), section)
|
||||||
if section not in cp.sections():
|
if section not in cp.sections():
|
||||||
raise oscerr.ConfigError('unknown section \'%s\'' % section, config['conffile'])
|
raise oscerr.ConfigError(f'unknown section \'{section}\'', config['conffile'])
|
||||||
if section == 'general' and opt not in general_opts or \
|
if section == 'general' and opt not in general_opts or \
|
||||||
section != 'general' and opt not in api_host_options:
|
section != 'general' and opt not in api_host_options:
|
||||||
raise oscerr.ConfigError('unknown config option \'%s\'' % opt, config['conffile'])
|
raise oscerr.ConfigError(f'unknown config option \'{opt}\'', config['conffile'])
|
||||||
|
|
||||||
if not val and not delete and opt == 'pass' and creds_mgr_descr is not None:
|
if not val and not delete and opt == 'pass' and creds_mgr_descr is not None:
|
||||||
# change password store
|
# change password store
|
||||||
@ -1758,7 +1758,7 @@ def _get_credentials_manager(url, cp):
|
|||||||
if cp.has_option(url, credentials.AbstractCredentialsManager.config_entry):
|
if cp.has_option(url, credentials.AbstractCredentialsManager.config_entry):
|
||||||
creds_mgr = credentials.create_credentials_manager(url, cp)
|
creds_mgr = credentials.create_credentials_manager(url, cp)
|
||||||
if creds_mgr is None:
|
if creds_mgr is None:
|
||||||
msg = 'Unable to instantiate creds mgr (section: %s)' % url
|
msg = f'Unable to instantiate creds mgr (section: {url})'
|
||||||
conffile = get_configParser.conffile
|
conffile = get_configParser.conffile
|
||||||
raise oscerr.ConfigMissingCredentialsError(msg, conffile, url)
|
raise oscerr.ConfigMissingCredentialsError(msg, conffile, url)
|
||||||
return creds_mgr
|
return creds_mgr
|
||||||
@ -1977,7 +1977,7 @@ def identify_conf():
|
|||||||
return '~/.oscrc'
|
return '~/.oscrc'
|
||||||
|
|
||||||
if os.environ.get('XDG_CONFIG_HOME', '') != '':
|
if os.environ.get('XDG_CONFIG_HOME', '') != '':
|
||||||
conffile = os.environ.get('XDG_CONFIG_HOME') + '/osc/oscrc'
|
conffile = f"{os.environ.get('XDG_CONFIG_HOME')}/osc/oscrc"
|
||||||
else:
|
else:
|
||||||
conffile = '~/.config/osc/oscrc'
|
conffile = '~/.config/osc/oscrc'
|
||||||
|
|
||||||
|
@ -488,7 +488,7 @@ class CookieJarAuthHandler(AuthHandlerBase):
|
|||||||
# doing expensive signature auth in multiple processes.
|
# doing expensive signature auth in multiple processes.
|
||||||
# This usually happens when a user runs multiple osc instances
|
# This usually happens when a user runs multiple osc instances
|
||||||
# from the command-line in parallel.
|
# from the command-line in parallel.
|
||||||
self.cookiejar_lock_path = self.cookiejar_path + ".lock"
|
self.cookiejar_lock_path = f"{self.cookiejar_path}.lock"
|
||||||
self.cookiejar_lock_fd = None
|
self.cookiejar_lock_fd = None
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@ -633,7 +633,7 @@ class SignatureAuthHandler(AuthHandlerBase):
|
|||||||
keyfile = self.guess_keyfile()
|
keyfile = self.guess_keyfile()
|
||||||
else:
|
else:
|
||||||
if '/' not in keyfile:
|
if '/' not in keyfile:
|
||||||
keyfile = '~/.ssh/' + keyfile
|
keyfile = f"~/.ssh/{keyfile}"
|
||||||
keyfile = os.path.expanduser(keyfile)
|
keyfile = os.path.expanduser(keyfile)
|
||||||
|
|
||||||
cmd = [self.ssh_keygen_path, '-Y', 'sign', '-f', keyfile, '-n', namespace, '-q']
|
cmd = [self.ssh_keygen_path, '-Y', 'sign', '-f', keyfile, '-n', namespace, '-q']
|
||||||
@ -668,7 +668,7 @@ class SignatureAuthHandler(AuthHandlerBase):
|
|||||||
auth = self.get_authorization(chal)
|
auth = self.get_authorization(chal)
|
||||||
if not auth:
|
if not auth:
|
||||||
return False
|
return False
|
||||||
auth_val = 'Signature %s' % auth
|
auth_val = f'Signature {auth}'
|
||||||
req.add('Authorization', auth_val)
|
req.add('Authorization', auth_val)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
499
osc/core.py
499
osc/core.py
File diff suppressed because it is too large
Load Diff
@ -211,7 +211,7 @@ class KeyringCredentialsManager(AbstractCredentialsManager):
|
|||||||
def set_password(self, url, user, password):
|
def set_password(self, url, user, password):
|
||||||
self._load_backend()
|
self._load_backend()
|
||||||
keyring.set_password(urlsplit(url)[1], user, password)
|
keyring.set_password(urlsplit(url)[1], user, password)
|
||||||
config_value = self._qualified_name() + ':' + self._backend_cls_name
|
config_value = f"{self._qualified_name()}:{self._backend_cls_name}"
|
||||||
self._cp.set(url, self.config_entry, config_value)
|
self._cp.set(url, self.config_entry, config_value)
|
||||||
|
|
||||||
def delete_password(self, url, user):
|
def delete_password(self, url, user):
|
||||||
@ -317,7 +317,7 @@ def create_credentials_manager(url, cp):
|
|||||||
|
|
||||||
|
|
||||||
def qualified_name(obj):
|
def qualified_name(obj):
|
||||||
return obj.__module__ + '.' + obj.__class__.__name__
|
return f"{obj.__module__}.{obj.__class__.__name__}"
|
||||||
|
|
||||||
|
|
||||||
def has_keyring_support():
|
def has_keyring_support():
|
||||||
|
20
osc/fetch.py
20
osc/fetch.py
@ -45,23 +45,23 @@ class Fetcher:
|
|||||||
self.gr = OscFileGrabber(progress_obj=self.progress_obj)
|
self.gr = OscFileGrabber(progress_obj=self.progress_obj)
|
||||||
|
|
||||||
def __add_cpio(self, pac):
|
def __add_cpio(self, pac):
|
||||||
prpap = '%s/%s/%s/%s' % (pac.project, pac.repository, pac.repoarch, pac.repopackage)
|
prpap = f'{pac.project}/{pac.repository}/{pac.repoarch}/{pac.repopackage}'
|
||||||
self.cpio.setdefault(prpap, {})[pac.repofilename] = pac
|
self.cpio.setdefault(prpap, {})[pac.repofilename] = pac
|
||||||
|
|
||||||
def __download_cpio_archive(self, apiurl, project, repo, arch, package, **pkgs):
|
def __download_cpio_archive(self, apiurl, project, repo, arch, package, **pkgs):
|
||||||
if not pkgs:
|
if not pkgs:
|
||||||
return
|
return
|
||||||
query = ['binary=%s' % quote_plus(i) for i in pkgs]
|
query = [f'binary={quote_plus(i)}' for i in pkgs]
|
||||||
query.append('view=cpio')
|
query.append('view=cpio')
|
||||||
for module in self.modules:
|
for module in self.modules:
|
||||||
query.append('module=' + module)
|
query.append(f"module={module}")
|
||||||
try:
|
try:
|
||||||
url = makeurl(apiurl, ['build', project, repo, arch, package], query=query)
|
url = makeurl(apiurl, ['build', project, repo, arch, package], query=query)
|
||||||
sys.stdout.write("preparing download ...\r")
|
sys.stdout.write("preparing download ...\r")
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
with tempfile.NamedTemporaryFile(prefix='osc_build_cpio') as tmparchive:
|
with tempfile.NamedTemporaryFile(prefix='osc_build_cpio') as tmparchive:
|
||||||
self.gr.urlgrab(url, filename=tmparchive.name,
|
self.gr.urlgrab(url, filename=tmparchive.name,
|
||||||
text='fetching packages for \'%s\'' % project)
|
text=f'fetching packages for \'{project}\'')
|
||||||
archive = cpio.CpioRead(tmparchive.name)
|
archive = cpio.CpioRead(tmparchive.name)
|
||||||
archive.read()
|
archive.read()
|
||||||
for hdr in archive:
|
for hdr in archive:
|
||||||
@ -133,7 +133,7 @@ class Fetcher:
|
|||||||
mg = OscMirrorGroup(self.gr, pac.urllist)
|
mg = OscMirrorGroup(self.gr, pac.urllist)
|
||||||
|
|
||||||
if self.http_debug:
|
if self.http_debug:
|
||||||
print('\nURLs to try for package \'%s\':' % pac, file=sys.stderr)
|
print(f'\nURLs to try for package \'{pac}\':', file=sys.stderr)
|
||||||
print('\n'.join(pac.urllist), file=sys.stderr)
|
print('\n'.join(pac.urllist), file=sys.stderr)
|
||||||
print(file=sys.stderr)
|
print(file=sys.stderr)
|
||||||
|
|
||||||
@ -141,7 +141,7 @@ class Fetcher:
|
|||||||
with tempfile.NamedTemporaryFile(prefix='osc_build',
|
with tempfile.NamedTemporaryFile(prefix='osc_build',
|
||||||
delete=False) as tmpfile:
|
delete=False) as tmpfile:
|
||||||
mg_stat = mg.urlgrab(pac.filename, filename=tmpfile.name,
|
mg_stat = mg.urlgrab(pac.filename, filename=tmpfile.name,
|
||||||
text='%s(%s) %s' % (prefix, pac.project, pac.filename))
|
text=f'{prefix}({pac.project}) {pac.filename}')
|
||||||
if mg_stat:
|
if mg_stat:
|
||||||
self.move_package(tmpfile.name, pac.localdir, pac)
|
self.move_package(tmpfile.name, pac.localdir, pac)
|
||||||
|
|
||||||
@ -198,7 +198,7 @@ class Fetcher:
|
|||||||
if self.download_api_only:
|
if self.download_api_only:
|
||||||
return []
|
return []
|
||||||
urllist = self.urllist
|
urllist = self.urllist
|
||||||
key = '%s/%s' % (pac.project, pac.repository)
|
key = f'{pac.project}/{pac.repository}'
|
||||||
project_repo_url = buildinfo.urls.get(key)
|
project_repo_url = buildinfo.urls.get(key)
|
||||||
if project_repo_url is not None:
|
if project_repo_url is not None:
|
||||||
urllist = [project_repo_url]
|
urllist = [project_repo_url]
|
||||||
@ -290,7 +290,7 @@ class Fetcher:
|
|||||||
|
|
||||||
prjs = list(buildinfo.projects.keys())
|
prjs = list(buildinfo.projects.keys())
|
||||||
for i in prjs:
|
for i in prjs:
|
||||||
dest = "%s/%s" % (self.cachedir, i)
|
dest = f"{self.cachedir}/{i}"
|
||||||
if not os.path.exists(dest):
|
if not os.path.exists(dest):
|
||||||
os.makedirs(dest, mode=0o755)
|
os.makedirs(dest, mode=0o755)
|
||||||
dest += '/_pubkey'
|
dest += '/_pubkey'
|
||||||
@ -322,8 +322,8 @@ class Fetcher:
|
|||||||
|
|
||||||
if try_parent:
|
if try_parent:
|
||||||
if self.http_debug:
|
if self.http_debug:
|
||||||
print("can't fetch key for %s" % (i), file=sys.stderr)
|
print(f"can't fetch key for {i}", file=sys.stderr)
|
||||||
print("url: %s" % url, file=sys.stderr)
|
print(f"url: {url}", file=sys.stderr)
|
||||||
|
|
||||||
if os.path.exists(dest):
|
if os.path.exists(dest):
|
||||||
os.unlink(dest)
|
os.unlink(dest)
|
||||||
|
@ -17,10 +17,10 @@ class PBTextMeter:
|
|||||||
|
|
||||||
def start(self, basename, size=None):
|
def start(self, basename, size=None):
|
||||||
if size is None:
|
if size is None:
|
||||||
widgets = [basename + ': ', pb.AnimatedMarker(), ' ', pb.Timer()]
|
widgets = [f"{basename}: ", pb.AnimatedMarker(), ' ', pb.Timer()]
|
||||||
self.bar = pb.ProgressBar(widgets=widgets, maxval=pb.UnknownLength)
|
self.bar = pb.ProgressBar(widgets=widgets, maxval=pb.UnknownLength)
|
||||||
else:
|
else:
|
||||||
widgets = [basename + ': ', pb.Bar(), ' ', pb.ETA()]
|
widgets = [f"{basename}: ", pb.Bar(), ' ', pb.ETA()]
|
||||||
if size:
|
if size:
|
||||||
# if size is 0, using pb.Percentage will result in
|
# if size is 0, using pb.Percentage will result in
|
||||||
# a ZeroDivisionException
|
# a ZeroDivisionException
|
||||||
|
@ -189,7 +189,7 @@ class OscInvalidRevision(OscValueError):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return "Invalid revision value: {}".format("".join(self.args))
|
return f"Invalid revision value: {''.join(self.args)}"
|
||||||
|
|
||||||
|
|
||||||
class PackageNotInstalled(OscBaseError):
|
class PackageNotInstalled(OscBaseError):
|
||||||
@ -201,7 +201,7 @@ class PackageNotInstalled(OscBaseError):
|
|||||||
super().__init__((pkg,))
|
super().__init__((pkg,))
|
||||||
|
|
||||||
def __str__(self):
|
def __str__(self):
|
||||||
return 'Package %s is required for this operation' % self.args
|
return f'Package {self.args} is required for this operation'
|
||||||
|
|
||||||
|
|
||||||
class SignalInterrupt(Exception):
|
class SignalInterrupt(Exception):
|
||||||
|
@ -137,7 +137,7 @@ class Store:
|
|||||||
if not isinstance(value, str):
|
if not isinstance(value, str):
|
||||||
msg = f"The argument `value` should be str, not {type(value).__name__}"
|
msg = f"The argument `value` should be str, not {type(value).__name__}"
|
||||||
raise TypeError(msg)
|
raise TypeError(msg)
|
||||||
self.write_file(fn, value + "\n", subdir=subdir)
|
self.write_file(fn, f"{value}\n", subdir=subdir)
|
||||||
|
|
||||||
def read_int(self, fn):
|
def read_int(self, fn):
|
||||||
if not self.exists(fn):
|
if not self.exists(fn):
|
||||||
|
Loading…
Reference in New Issue
Block a user