1
0
mirror of https://github.com/openSUSE/osc.git synced 2025-01-11 16:36:14 +01:00

checkout_package: Use pathlib.Path

Modify it to use pathlib.Path along with its callers. Some str(path) was
necessary to avoid having a large changeset.

It addresses #1258 and continues the work started in
bac162a712.
This commit is contained in:
Bogdano Arendartchuk 2023-02-08 11:46:16 +01:00
parent 83b1e22e52
commit 1d96c6eb2a
2 changed files with 31 additions and 37 deletions

View File

@ -1024,7 +1024,7 @@ class Osc(cmdln.Cmdln):
filename = "_patchinfo" filename = "_patchinfo"
else: else:
checkout_package(apiurl, project, patchinfo, prj_dir=project_dir) checkout_package(apiurl, project, patchinfo, prj_dir=project_dir)
filename = project_dir + "/" + patchinfo + "/_patchinfo" filename = project_dir / patchinfo / "/_patchinfo"
run_editor(filename) run_editor(filename)
@ -2917,8 +2917,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
raise oscerr.WrongArgs('\'checkout\' not possible (request has no \'submit\' actions)') raise oscerr.WrongArgs('\'checkout\' not possible (request has no \'submit\' actions)')
for action in sr_actions: for action in sr_actions:
checkout_package(apiurl, action.src_project, action.src_package, checkout_package(apiurl, action.src_project, action.src_package,
action.src_rev, expand_link=True, prj_dir=action.src_project) action.src_rev, expand_link=True, prj_dir=Path(action.src_project))
else: else:
state_map = {'reopen': 'new', 'accept': 'accepted', 'decline': 'declined', 'wipe': 'deleted', 'revoke': 'revoked', 'supersede': 'superseded'} state_map = {'reopen': 'new', 'accept': 'accepted', 'decline': 'declined', 'wipe': 'deleted', 'revoke': 'revoked', 'supersede': 'superseded'}
# Change review state only # Change review state only
@ -3759,7 +3758,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
# all packages # all packages
for package in meta_get_packagelist(apiurl, result): for package in meta_get_packagelist(apiurl, result):
try: try:
checkout_package(apiurl, result, package, expand_link=True, prj_dir=result) checkout_package(apiurl, result, package, expand_link=True, prj_dir=Path(result))
except: except:
print('Error while checkout package:\n', package, file=sys.stderr) print('Error while checkout package:\n', package, file=sys.stderr)
@ -3914,7 +3913,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
package = targetpkg or args[1] package = targetpkg or args[1]
if opts.checkout: if opts.checkout:
checkout_package(apiurl, targetprj, package, server_service_files=False, checkout_package(apiurl, targetprj, package, server_service_files=False,
expand_link=True, prj_dir=targetprj) expand_link=True, prj_dir=Path(targetprj))
if conf.config['verbose']: if conf.config['verbose']:
print('Note: You can use "osc delete" or "osc submitpac" when done.\n') print('Note: You can use "osc delete" or "osc submitpac" when done.\n')
else: else:
@ -4687,7 +4686,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
m = re.match(r"obs://([^/]+)/(\S+)/([^/]+)/([A-Fa-f\d]+)\-([^:]*)(:\S+)?", args[0]) m = re.match(r"obs://([^/]+)/(\S+)/([^/]+)/([A-Fa-f\d]+)\-([^:]*)(:\S+)?", args[0])
if m and len(args) == 1: if m and len(args) == 1:
apiurl = "https://" + m.group(1) apiurl = "https://" + m.group(1)
project = project_dir = m.group(2) project = m.group(2)
project_dir = Path(project)
# platform = m.group(3) # platform = m.group(3)
opts.revision = m.group(4) opts.revision = m.group(4)
package = m.group(5) package = m.group(5)
@ -4698,7 +4698,8 @@ Please submit there instead, or use --nodevelproject to force direct submission.
project = package = filename = None project = package = filename = None
apiurl = self.get_api_url() apiurl = self.get_api_url()
try: try:
project = project_dir = self._process_project_name(args[0]) project = self._process_project_name(args[0])
project_dir = Path(project)
package = args[1] package = args[1]
filename = args[2] filename = args[2]
except: except:
@ -4706,7 +4707,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if len(args) == 1 and is_project_dir(Path.cwd()): if len(args) == 1 and is_project_dir(Path.cwd()):
project = store_read_project(Path.cwd()) project = store_read_project(Path.cwd())
project_dir = str(Path.cwd()) project_dir = Path.cwd()
package = args[0] package = args[0]
if opts.deleted and package: if opts.deleted and package:
@ -4743,11 +4744,9 @@ Please submit there instead, or use --nodevelproject to force direct submission.
print_request_list(apiurl, project, package) print_request_list(apiurl, project, package)
elif project: elif project:
prj_dir = opts.output_dir if opts.output_dir else project sep = '/' if not opts.output_dir and conf.config['checkout_no_colon'] else conf.config['project_separator']
if not opts.output_dir and conf.config['checkout_no_colon']: chosen_output = opts.output_dir if opts.output_dir else project
prj_dir = prj_dir.replace(':', '/') prj_dir = Path(chosen_output.replace(':', sep))
else:
prj_dir = prj_dir.replace(':', conf.config['project_separator'])
if os.path.exists(prj_dir): if os.path.exists(prj_dir):
sys.exit('osc: project directory \'%s\' already exists' % prj_dir) sys.exit('osc: project directory \'%s\' already exists' % prj_dir)
@ -4759,7 +4758,7 @@ Please submit there instead, or use --nodevelproject to force direct submission.
if not os.path.isfile('/usr/lib/obs/service/obs_scm_bridge'): if not os.path.isfile('/usr/lib/obs/service/obs_scm_bridge'):
raise oscerr.OscIOError(None, 'Install the obs-scm-bridge package to work on packages managed in scm (git)!') raise oscerr.OscIOError(None, 'Install the obs-scm-bridge package to work on packages managed in scm (git)!')
os.putenv("OSC_VERSION", get_osc_version()) os.putenv("OSC_VERSION", get_osc_version())
run_external(['/usr/lib/obs/service/obs_scm_bridge', '--outdir', prj_dir, '--url', scm_url]) run_external(['/usr/lib/obs/service/obs_scm_bridge', '--outdir', str(prj_dir), '--url', scm_url])
Project.init_project(apiurl, prj_dir, project, conf.config['do_package_tracking'], scm_url=scm_url) Project.init_project(apiurl, prj_dir, project, conf.config['do_package_tracking'], scm_url=scm_url)
print(statfrmt('A', prj_dir)) print(statfrmt('A', prj_dir))

View File

@ -31,6 +31,7 @@ import time
from functools import cmp_to_key, total_ordering from functools import cmp_to_key, total_ordering
from http.client import IncompleteRead from http.client import IncompleteRead
from io import StringIO from io import StringIO
from pathlib import Path
from typing import Optional, Dict, Union, List, Iterable from typing import Optional, Dict, Union, List, Iterable
from urllib.parse import urlsplit, urlunsplit, urlparse, quote_plus, urlencode, unquote from urllib.parse import urlsplit, urlunsplit, urlparse, quote_plus, urlencode, unquote
from urllib.error import HTTPError from urllib.error import HTTPError
@ -712,7 +713,7 @@ class Project:
`wc_check` : bool `wc_check` : bool
""" """
self.dir = dir self.dir = Path(dir)
self.absdir = os.path.abspath(dir) self.absdir = os.path.abspath(dir)
self.store = Store(dir) self.store = Store(dir)
self.progress_obj = progress_obj self.progress_obj = progress_obj
@ -1181,7 +1182,7 @@ class Project:
@staticmethod @staticmethod
def init_project( def init_project(
apiurl: str, apiurl: str,
dir, dir: Path,
project, project,
package_tracking=True, package_tracking=True,
getPackageList=True, getPackageList=True,
@ -5371,7 +5372,7 @@ def checkout_package(
pathname=None, pathname=None,
prj_obj=None, prj_obj=None,
expand_link=False, expand_link=False,
prj_dir=None, prj_dir: Path=None,
server_service_files=None, server_service_files=None,
service_files=None, service_files=None,
progress_obj=None, progress_obj=None,
@ -5382,20 +5383,19 @@ def checkout_package(
try: try:
# the project we're in might be deleted. # the project we're in might be deleted.
# that'll throw an error then. # that'll throw an error then.
olddir = os.getcwd() olddir = Path.cwd()
except: except FileNotFoundError:
olddir = os.environ.get("PWD") olddir = Path(os.environ.get("PWD"))
if not prj_dir: if not prj_dir:
prj_dir = olddir prj_dir = olddir
elif conf.config['checkout_no_colon']:
prj_dir = prj_dir.replace(':', '/')
else: else:
prj_dir = prj_dir.replace(':', conf.config['project_separator']) sep = "/" if conf.config['checkout_no_colon'] else conf.config['project_separator']
prj_dir = Path(str(prj_dir).replace(':', sep))
root_dots = '.' root_dots = Path('.')
if conf.config['checkout_rooted']: if conf.config['checkout_rooted']:
if prj_dir[:1] == '/': if prj_dir.stem == '/':
if conf.config['verbose']: if conf.config['verbose']:
print("checkout_rooted ignored for %s" % prj_dir) print("checkout_rooted ignored for %s" % prj_dir)
# ?? should we complain if not is_project_dir(prj_dir) ?? # ?? should we complain if not is_project_dir(prj_dir) ??
@ -5409,27 +5409,25 @@ def checkout_package(
# do not easily reveal the fact, that they are part of a project path. # do not easily reveal the fact, that they are part of a project path.
# At least this test should find that the parent of 'home/username/branches' # At least this test should find that the parent of 'home/username/branches'
# is a project (hack alert). Also goto parent in this case. # is a project (hack alert). Also goto parent in this case.
root_dots = "../" root_dots = Path("../")
elif is_project_dir("../.."): elif is_project_dir("../.."):
# testing two levels is better than one. # testing two levels is better than one.
# May happen in case of checkout_no_colon, or # May happen in case of checkout_no_colon, or
# if project roots were previously inconsistent # if project roots were previously inconsistent
root_dots = "../../" root_dots = Path("../../")
if is_project_dir(root_dots): if is_project_dir(root_dots):
oldproj = store_read_project(root_dots) oldproj = store_read_project(root_dots)
if conf.config['checkout_no_colon']: if conf.config['checkout_no_colon']:
n = len(oldproj.split(':')) n = len(oldproj.split(':'))
else: else:
n = 1 n = 1
if root_dots == '.': root_dots = root_dots / ("../" * n)
root_dots = ''
root_dots = root_dots + "../" * n
if root_dots != '.': if str(root_dots) != '.':
if conf.config['verbose']: if conf.config['verbose']:
print("%s is project dir of %s. Root found at %s" % print("%s is project dir of %s. Root found at %s" %
(prj_dir, oldproj, os.path.abspath(root_dots))) (prj_dir, oldproj, os.path.abspath(root_dots)))
prj_dir = root_dots + prj_dir prj_dir = root_dots / prj_dir
if not pathname: if not pathname:
pathname = getTransActPath(os.path.join(prj_dir, package)) pathname = getTransActPath(os.path.join(prj_dir, package))
@ -7951,11 +7949,8 @@ def getTransActPath(pac_dir):
Normally the "dir" attribute of a Package() object will be passed to Normally the "dir" attribute of a Package() object will be passed to
this method. this method.
""" """
if pac_dir != '.': path = str(Path(pac_dir)) # accept str and Path as pac_dir
pathn = os.path.normpath(pac_dir) return '' if path == '.' else path
else:
pathn = ''
return pathn
def get_commit_message_template(pac): def get_commit_message_template(pac):