1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3# vi: set ft=python :
4"""
5Launchpad Bug Tracker uses launchpadlib to get the Yaru-theme bugs.
6The first time, the full list is saved in a json file.
7The next times, the newly get list of Launchpad yaru-theme bugs are compared with the ones
8stored in the json file to show if any new issue was created since last check.
9"""
10
11import os
12import subprocess
13import logging
14from launchpadlib.launchpad import Launchpad
15
16log = logging.getLogger("lpbugtracker")
17log.setLevel(logging.DEBUG)
18
19HUB = ".github/hub"
20HOME = os.path.expanduser("~")
21CACHEDIR = os.path.join(HOME, ".launchpadlib", "cache")
22
23
24def main():
25    lp_bugs = get_yaru_launchpad_bugs()
26    if len(lp_bugs) == 0:
27        return
28
29    gh_tracked_lp_bugs = get_gh_bugs()
30
31    for id in lp_bugs:
32        tag = "LP#%s" % id
33        if tag not in gh_tracked_lp_bugs:
34            create_issue(id, lp_bugs[id]["title"], lp_bugs[id]["link"])
35
36
37def get_yaru_launchpad_bugs():
38    """Get a list of Yaru bugs from Launchpad"""
39
40    lp = Launchpad.login_anonymously(
41        "Yaru LP bug checker", "production", CACHEDIR, version="devel"
42    )
43
44    ubuntu = lp.distributions["ubuntu"]
45    archive = ubuntu.main_archive
46
47    packages = archive.getPublishedSources(source_name="yaru")
48    package = ubuntu.getSourcePackage(name=packages[0].source_package_name)
49
50    bug_tasks = package.searchTasks()
51    bugs = {}
52
53    for task in bug_tasks:
54        id = str(task.bug.id)
55        title = task.title.split(": ")[1]
56        link = "https://bugs.launchpad.net/ubuntu/+source/yaru-theme/+bug/" + str(id)
57        bugs[id] = {"title": title, "link": link}
58
59    return bugs
60
61
62def get_gh_bugs():
63    """Get the list of the LP bug already tracked in GitHub.
64
65    Launchpad bugs tracked on GitHub have a title like
66
67    "LP#<id> <title>"
68
69    this function returns a list of the "LP#<id>" substring for each bug,
70    open or closed, found on Yaru repository on GitHub.
71    """
72
73    output = subprocess.check_output(
74        [HUB, "issue", "--labels", "Launchpad", "--state", "all"]
75    )
76    return [
77        line.strip().split()[1] for line in output.decode().split("\n") if "LP#" in line
78    ]
79
80
81def create_issue(id, title, weblink):
82    """ Create a new Bug using HUB """
83    print("creating:", id, title, weblink)
84    subprocess.run(
85        [
86            HUB,
87            "issue",
88            "create",
89            "--message",
90            "LP#{} {}".format(id, title),
91            "--message",
92            "Reported first on Launchpad at {}".format(weblink),
93            "-l",
94            "Launchpad",
95        ]
96    )
97
98
99if __name__ == "__main__":
100    main()
101