aboutsummaryrefslogtreecommitdiffstats
path: root/scripts/obs/lib/osc.py
blob: 6a1d42b013aa43f78418ff9723db18b2ca7c2402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright 2022 sysmocom - s.f.m.c. GmbH <info@sysmocom.de>

import glob
import os
import shlex
import shutil
import lib
import lib.config

apiurl = None


def check_proj():
    proj = lib.args.obs_project
    if ":" in proj:
        return

    print(f"ERROR: this doesn't look like a valid OBS project: {proj}")
    exit(1)


def check_oscrc():
    configdir = os.environ.get("XDG_CONFIG_HOME", "~/.config")
    paths = ["~/.oscrc", f"{configdir}/osc/oscrc"]
    for path in paths:
        if os.path.exists(os.path.expanduser(path)):
            return

    print("ERROR: oscrc does not exist, please create one as explained in the"
          " README.")
    exit(1)


def set_apiurl(url):
    global apiurl
    apiurl = url


def run_osc(cmd, *args, **kwargs):
    global apiurl

    # For some osc commands like 'osc add *' it makes sense to use a flat
    # string and shell=True, hence support both list and string in this wrapper
    if isinstance(cmd, str):
        if apiurl:
            cmd = f"osc -A {shlex.quote(apiurl)} {cmd}"
        else:
            cmd = f"osc {cmd}"
    else:
        if apiurl:
            cmd = ["osc", "-A", apiurl] + cmd
        else:
            cmd = ["osc"] + cmd

    return lib.run_cmd(cmd, *args, **kwargs)


def get_remote_pkgs():
    proj = lib.args.obs_project
    print(f"OBS: getting packages in {proj}")
    ret = run_osc(["list", proj])
    return ret.output.rstrip().split("\n")


def get_package_version(package, feed):
    proj = lib.args.obs_project
    print(f"{package}: getting OBS version")
    ret = run_osc(["list", proj, os.path.basename(package)])

    # Empty OBS package
    if ret.output == '\n':
        return "0"

    # Extract the version from the file list
    for line in ret.output.split('\n'):
        line = line.rstrip()

        if feed == "master" and package != "osmocom-master":
            # Use commit_*.txt
            if line.startswith("commit_") and line.endswith(".txt"):
                return line.split("_")[1].split(".")[0]
        else:
            # Use *.dsc
            if line.endswith(".dsc"):
                return line.split("_")[-1][:-4]

    lib.exit_error_cmd(ret, "failed to find package version on OBS by"
                       " extracting the version from the file list")


def create_package(package):
    proj = lib.args.obs_project
    print(f"{package}: creating new OBS package")

    # cut off repository prefix like in "python/osmo-python-tests"
    package = os.path.basename(package)

    path_meta = f"{lib.config.path_temp}/_meta"
    path_meta_obs = f"source/{proj}/{package}/_meta"

    with open(path_meta, "w") as f:
        f.write(f'<package name="{package}" project="{proj}">\n')
        f.write(f'<title>{package}</title>\n')
        f.write('<description></description>\n')
        f.write('</package>\n')

    run_osc(["api", "-X", "PUT", "-T", path_meta, path_meta_obs])

    os.unlink(path_meta)


def remove_temp_osc():
    lib.run_cmd(["rm", "-rf", f"{lib.config.path_temp}/osc"])


def update_package(package, version):
    proj = lib.args.obs_project
    print(f"{package}: updating OBS package")

    # cut off repository prefix like in "python/osmo-python-tests"
    package = os.path.basename(package)

    path_output = lib.get_output_path(package)
    path_temp_osc = f"{lib.config.path_temp}/osc"
    path_temp_osc_pkg = f"{path_temp_osc}/{proj}/{package}"

    remove_temp_osc()
    os.makedirs(path_temp_osc)

    run_osc(["checkout", proj, package], cwd=path_temp_osc)

    if glob.glob(f"{path_temp_osc_pkg}/*"):
        run_osc("del *", shell=True, cwd=path_temp_osc_pkg)

    lib.run_cmd(f"mv * {shlex.quote(path_temp_osc_pkg)}", shell=True,
                cwd=path_output)

    run_osc("add *", shell=True, cwd=path_temp_osc_pkg)
    run_osc(["commit", "-m", f"upgrade to {version}"], cwd=path_temp_osc_pkg)

    remove_temp_osc()