File: helpers.py

package info (click to toggle)
offlineimap3 0.0~git20210225.1e7ef9e%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 1,328 kB
  • sloc: python: 7,974; sh: 548; makefile: 81
file content (328 lines) | stat: -rw-r--r-- 8,661 bytes parent folder | download | duplicates (3)
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
"""

Put into Public Domain, by Nicolas Sebrecht.

Helpers for maintenance scripts.

"""

from os import chdir, makedirs, system, getcwd
from os.path import expanduser
import shlex
from subprocess import check_output, check_call, CalledProcessError

import yaml


FS_ENCODING = 'UTF-8'
ENCODING = 'UTF-8'

MAILING_LIST = 'offlineimap-project@lists.alioth.debian.org'
CACHEDIR = '.git/offlineimap-release'
EDITOR = 'vim'
MAILALIASES_FILE = expanduser('~/.mutt/mail_aliases')
TESTERS_FILE = "{}/testers.yml".format(CACHEDIR)
ME = "Nicolas Sebrecht <nicolas.s-dev@laposte.net>"


def run(cmd):
    return check_output(cmd, timeout=5).rstrip()

def goTo(path):
    try:
        chdir(path)
        return True
    except FileNotFoundError:
        print(("Could not find the '{}' directory in '{}'...".format(
            path, getcwd())
        ))
    return False


class Author():
    def __init__(self, name, count, email):
        self.name = name
        self.count = count
        self.email = email

    def getName(self):
        return self.name

    def getCount(self):
        return self.count

    def getEmail(self):
        return self.email


class Git():
    @staticmethod
    def getShortlog(ref):
        shortlog = ""

        cmd = shlex.split("git shortlog --no-merges -n v{}..".format(ref))
        output = run(cmd).decode(ENCODING)

        for line in output.split("\n"):
            if len(line) > 0:
                if line[0] != " ":
                    line = "  {}\n".format(line)
                else:
                    line = "     {}\n".format(line.lstrip())
            else:
                line = "\n"

            shortlog += line

        return shortlog

    @staticmethod
    def add(files):
        cmd = shlex.split("git add -- {}".format(files))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def commit(msg):
        cmd = shlex.split("git commit -s -m '{}'".format(msg))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def tag(version):
        cmd = shlex.split("git tag -a 'v{}' -m 'v{}'".format(version, version))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def stash(msg):
        cmd = shlex.split("git stash create '{}'".format(msg))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def mergeFF(ref):
        cmd = shlex.split("git merge --ff '{}'".format(ref))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def getDiffstat(ref):
        cmd = shlex.split("git diff --stat v{}..".format(ref))
        return run(cmd).decode(ENCODING)

    @staticmethod
    def isClean():
        try:
            check_call(shlex.split("git diff --quiet"))
            check_call(shlex.split("git diff --cached --quiet"))
        except CalledProcessError:
            return False
        return True

    @staticmethod
    def buildMessageId():
        cmd = shlex.split(
            "git log HEAD~1.. --oneline --pretty='%H.%t.upcoming.%ce'")
        return run(cmd).decode(ENCODING)

    @staticmethod
    def resetKeep(ref):
        return run(shlex.split("git reset --keep {}".format(ref)))

    @staticmethod
    def getRef(ref):
        return run(shlex.split("git rev-parse {}".format(ref))).rstrip()

    @staticmethod
    def rmTag(tag):
        return run(shlex.split("git tag -d {}".format(tag)))

    @staticmethod
    def checkout(ref, create=False):
        if create:
            create = "-b"
        else:
            create = ""

        cmd = shlex.split("git checkout {} {}".format(create, ref))
        run(cmd)
        head = shlex.split("git rev-parse HEAD")
        revparseRef = shlex.split("git rev-parse {}".format(ref))
        if run(head) != run(revparseRef):
            raise Exception("checkout to '{}' did not work".format(ref))

    @staticmethod
    def makeCacheDir():
        try:
            makedirs(CACHEDIR)
        except FileExistsError:
            pass

    @staticmethod
    def getLocalUser():
        cmd = shlex.split("git config --get user.name")
        name = run(cmd).decode(ENCODING)
        cmd = shlex.split("git config --get user.email")
        email = run(cmd).decode(ENCODING)
        return name, email

    @staticmethod
    def buildDate():
        cmd = shlex.split("git log HEAD~1.. --oneline --pretty='%cD'")
        return run(cmd).decode(ENCODING)

    @staticmethod
    def getAuthorsList(sinceRef):
        authors = []

        cmd = shlex.split("git shortlog --no-merges -sne v{}..".format(sinceRef))
        output = run(cmd).decode(ENCODING)

        for line in output.split("\n"):
            count, full = line.strip().split("\t")
            full = full.split(' ')
            name = ' '.join(full[:-1])
            email = full[-1]

            authors.append(Author(name, count, email))

        return authors

    @staticmethod
    def getCommitsList(sinceRef):
        cmd = shlex.split(
            "git log --no-merges --format='- %h %s. [%aN]' v{}..".format(sinceRef)
        )
        return run(cmd).decode(ENCODING)

    @staticmethod
    def chdirToRepositoryTopLevel():
        cmd = shlex.split("git rev-parse --show-toplevel")
        topLevel = run(cmd)

        chdir(topLevel)


class OfflineimapInfo():
    def getVersion(self):
        cmd = shlex.split("./offlineimap.py --version")
        return run(cmd).rstrip().decode(FS_ENCODING)

    def editInit(self):
        return system("{} ./offlineimap/__init__.py".format(EDITOR))



class User():
    """Interact with the user."""

    @staticmethod
    def request(msg, prompt='--> '):
        print(msg)
        return eval(input(prompt))

    @staticmethod
    def pause(msg=False):
        return User.request(msg, prompt="Press Enter to continue..")

    @staticmethod
    def yesNo(msg, defaultToYes=False, prompt='--> '):
        endMsg = " [y/N]: No"
        if defaultToYes:
            endMsg = " [Y/n]: Yes"
        msg += endMsg
        answer = User.request(msg, prompt).lower()
        if answer in ['y', 'yes']:
            return True
        if defaultToYes is not False and answer not in ['n', 'no']:
            return True
        return False


class Tester():
    def __init__(self, name, email, feedback):
        self.name = name
        self.email = email
        self.feedback = feedback

    def __str__(self):
        return "{} {}".format(self.name, self.email)

    def getName(self):
        return self.name

    def getEmail(self):
        return self.email

    def getFeedback(self):
        return self.feedback

    def positiveFeedback(self):
        return self.feedback is True

    def setFeedback(self, feedback):
        assert feedback in [True, False, None]
        self.feedback = feedback

    def switchFeedback(self):
        self.feedback = not self.feedback


class Testers():
    def __init__(self):
        self.testers = None
        self._read()

    def _read(self):
        self.testers = []
        with open(TESTERS_FILE, 'r') as fd:
            testers = yaml.load(fd)
            for tester in testers:
                name = tester['name']
                email = tester['email']
                feedback = tester['feedback']
                self.testers.append(Tester(name, email, feedback))
        self.testers.sort(key=lambda x: x.getName().lower())

    @staticmethod
    def listTestersInTeam():
        """Returns a list of emails extracted from my mailaliases file."""

        cmd = shlex.split("grep offlineimap-testers {}".format(MAILALIASES_FILE))
        output = run(cmd).decode(ENCODING)
        emails = output.lstrip("alias offlineimap-testers ").split(', ')
        return emails

    def add(self, name, email, feedback=None):
        self.testers.append(Tester(name, email, feedback))

    def remove(self, tester):
        self.testers.remove(tester)

    def get(self):
        return self.testers

    def getList(self):
        testersList = ""
        for tester in self.testers:
            testersList += "- {}\n".format(tester.getName())
        return testersList

    def getListOk(self):
        testersOk = []
        for tester in self.testers:
            if tester.positiveFeedback():
                testersOk.append(tester)
        return testersOk

    def reset(self):
        for tester in self.testers:
            tester.setFeedback(None)

    def write(self):
        testers = []
        for tester in self.testers:
            testers.append({
                'name': tester.getName(),
                'email': tester.getEmail(),
                'feedback': tester.getFeedback(),
            })
        with open(TESTERS_FILE, 'w') as fd:
            fd.write(yaml.dump(testers))