Debian Codegraph @

scripts/flatpak-bisect

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import re
4 import argparse
5 import os
6 import gi
7 import json
8 import subprocess
9
10 gi.require_version('Flatpak', '1.0')
11 from gi.repository import Flatpak
12 from gi.repository import GLib
13
14 def get_bisection_data():
15 return {'ref': None, 'good': None, 'bad': None,
16 'refs': None, 'log': None, 'messages': None}
17
18 class Bisector():
19 def load_cache(self):
20 try:
21 os.makedirs(os.path.join(GLib.get_user_cache_dir(), 'flatpak'))
22 except FileExistsError:
23 pass
24
25 self.cache_path = os.path.join(GLib.get_user_cache_dir(),
26 'flatpak', '%s-%s-bisect.status' % (
27 self.name, self.branch))
28 try:
29 with open(self.cache_path, 'rb') as f:
30 self.data = json.load(f)
31 except FileNotFoundError:
32 self.data = None
33
34 def dump_data(self):
35 with open(self.cache_path, 'w') as f:
36 json.dump(self.data, f)
37
38 def setup_flatpak_app(self):
39 self.installation = Flatpak.Installation.new_user()
40 kind = Flatpak.RefKind.APP
41 if self.runtime:
42 kind = Flatpak.RefKind.RUNTIME
43 try:
44 self.cref = self.installation.get_installed_ref(kind, self.name, None, self.branch, None)
45 except GLib.Error as e:
46 print("%s\n\nMake sure %s is installed as a "
47 "user (flatpak install --user) and specify `--runtime`"
48 " if it is a runtime." % (e, self.name))
49 return -1
50 return 0
51
52 def run(self):
53 self.name = self.name[0]
54 self.load_cache()
55 res = self.setup_flatpak_app()
56 if res:
57 return res
58
59 try:
60 func = getattr(self, self.subparser_name)
61 except AttributeError:
62 print('No action called %s' % self.subparser_name)
63
64 return -1
65
66 res = func()
67
68 if self.data:
69 self.dump_data()
70
71 return res
72
73 def set_reference_commits(self, set_name, check_name):
74 if not self.data:
75 print("You need to first start the bisection")
76 return -1
77 ref = self.cref.get_latest_commit()
78
79 if self.data[check_name] == ref:
80 print('Commit %s is already set as %s...' % (
81 ref, check_name))
82 return 1
83
84 if ref not in self.data['refs']:
85 print("%s is not a known commit." % ref)
86 return -1
87
88 print("Setting %s as %s commit" % (ref, set_name))
89 self.data[set_name] = ref
90
91 if self.data[set_name] and self.data[check_name]:
92 x1 = self.data['refs'].index(self.data['good'])
93 x2 = self.data['refs'].index(self.data['bad'])
94
95 refs = self.data['refs'][x1:x2]
96 if not refs:
97 print("=========================="
98 "First bad commit is:\n%s"
99 "==========================" % self.data['message'][self.data['bad']])
100 exit(0)
101 ref = refs[int(len(refs) / 2)]
102 if self.data['good'] == ref:
103 print("\n==========================\n"
104 "First bad commit is:\n\n%s"
105 "==========================" % self.data['messages'][self.data['bad']])
106 exit(0)
107
108 return self.checkout(ref)
109
110 return -1
111
112 def load_refs(self):
113 repodir, refname = self.download_history()
114 history = subprocess.check_output(['ostree', 'log', '--repo', repodir, refname]).decode()
115
116 refs = []
117 messages = {}
118 message = ""
119 _hash = ''
120 for l in history.split('\n'):
121 rehash = re.search(r'(?<=^commit )\w+', l)
122 if rehash:
123 if message:
124 messages[_hash] = message
125 _hash = rehash.group(0)
126 refs.insert(0, _hash)
127 message = ""
128 message += l + '\n'
129
130 if message:
131 messages[_hash] = message
132
133 self.data['refs'] = refs
134 self.data['log'] = history
135 self.data['messages'] = messages
136
137 def good(self):
138 if not self.data['bad']:
139 print("Set the bad commit first")
140 exit(-1)
141 return self.set_reference_commits('good', 'bad')
142
143 def bad(self):
144 return self.set_reference_commits('bad', 'good')
145
146 def start(self):
147 if self.data:
148 print('Bisection already started')
149 return -1
150
151 print("Updating to %s latest commit" % self.name)
152 self.reset(False)
153 self.data = get_bisection_data()
154 self.load_refs()
155
156 def download_history(self):
157 print("Getting history")
158 appidir = os.path.abspath(os.path.join(self.cref.get_deploy_dir(), '..'))
159 dirname = "app"
160 if self.runtime:
161 dirname = "runtime"
162 appidir = appidir.split('/%s/' % dirname)
163 repodir = os.path.join(appidir[0], 'repo')
164 refname = self.cref.get_origin() + ':' + dirname + '/' + self.cref.get_name() + '/' + self.cref.get_arch() + '/' + self.cref.get_branch()
165 # FIXME Getting `error: Exceeded maximum recursion` in ostree if using --depth=-1 (or > 250)
166 subprocess.call(['ostree', 'pull', '--depth=250', '--commit-metadata-only', '--repo', repodir, refname])
167
168 return repodir, refname
169
170 def log(self):
171 if self.data:
172 cmd = ['echo', self.data['log']]
173 else:
174 repodir, refname = self.download_history()
175 cmd = ['ostree', 'log', '--repo', repodir, refname]
176 pager = os.environ.get('PAGER')
177 if pager:
178 stdout = subprocess.PIPE
179 else:
180 stdout = None
181 p = subprocess.Popen(cmd, stdout=stdout)
182 if pager:
183 subprocess.check_call((pager), stdin=p.stdout)
184 p.wait()
185
186 def checkout(self, commit=None):
187 if not commit:
188 commit = self.commit[0]
189 refname = self.cref.get_name() + '/' + self.cref.get_arch() + '/' + self.cref.get_branch()
190 print("Checking out %s" % commit)
191 return subprocess.call(['flatpak', 'update', '--user', refname, '--commit', commit])
192
193 def reset(self, v=True):
194 if not self.data:
195 if v:
196 print("Not bisecting, nothing to reset")
197 return -1
198
199 refname = self.cref.get_name() + '/' + self.cref.get_arch() + '/' + self.cref.get_branch()
200 print("Removing %s" % self.cache_path)
201 os.remove(self.cache_path)
202 self.data = None
203 return subprocess.call(['flatpak', 'update', '--user', refname])
204
205 if __name__ == "__main__":
206 parser = argparse.ArgumentParser()
207 parser.add_argument('name', nargs=1, help='Application/Runtime to bisect')
208 parser.add_argument('-b', '--branch', default='master', help='The branch to bisect')
209 parser.add_argument('-r', '--runtime', action="store_true", help='Bisecting a runtime not an app')
210
211 subparsers = parser.add_subparsers(dest='subparser_name')
212 subparsers.required = True
213 start_parser = subparsers.add_parser('start', help="Start bisection")
214 bad_parser = subparsers.add_parser('bad', help="Set current version as bad")
215 good_parser = subparsers.add_parser('good', help="Set current version as good")
216 log_parser = subparsers.add_parser('log', help="Download and print application commit history")
217
218 checkout_parser = subparsers.add_parser('checkout', help="Checkout defined commit")
219 checkout_parser.add_argument('commit', nargs=1, help='The commit hash to checkout')
220
221 reset_parser = subparsers.add_parser('reset', help="Reset all bisecting data and go back to latest commit")
222
223 bisector = Bisector()
224 options = parser.parse_args(namespace=bisector)
225 bisector.run()