summaryrefslogtreecommitdiffstats
path: root/patches/replicant_prepare_patch.py
blob: c1f52e776029c74dee116ca703c628c3fd67c193 (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
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
#!/bin/env python
# Copyright (C) 2020 Denis 'GNUtoo' Carikli <GNUtoo@cyberdimension.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

import os, sys
import re

import configparser
import sh

# Settings
cover_mail_template = """Hi,

In addition to the {patch} that will follow in a response to
this mail, here's an URL to the see the {patch} in a web interface:
{web_url}

And here's how to get {it} in a git repository:
git clone {clone_repo}
cd {repo_name}
git show {commit}

{signature}
"""

def usage(progname):
    print('Usage:\n\t{} [-C <directory>] <git_revision> [nr_patches] <patches_serie_revision>'.format(
        progname))
    print('Options:')
    print('\t-C <directory>\t\tRun as if it was started in the given git directory')
    sys.exit(1)

def get_config():
    # This should implement the XDG Base Directory Specification which is
    # available here:
    # https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

    config_file = None

    xdg_config_home = ''
    try:
        xdg_config_home = os.environ['XDG_CONFIG_HOME']
    except KeyError:
        pass

    if xdg_config_home == '':
        try:
            xdg_config_home = os.environ['HOME'] + os.sep + '.config'
        except KeyError:
            # This follow strictly the specification
            xdg_config_home = os.sep + '.config'

    xdg_config_dirs = ''
    try:
        xdg_config_dirs = os.environ['XDG_CONFIG_DIRS']
    except KeyError:
        pass
    if xdg_config_dirs == '':
        xdg_config_dirs = os.sep + 'etc' + os.sep + 'xdg'

    for base in [xdg_config_home] + xdg_config_dirs.split(os.pathsep):
        config_path = base + os.sep + 'replicant' + os.sep \
            + 'replicant_prepare_patch.conf'
        if not os.path.isfile(config_path):
            continue
        try:
            # Silently skip the file in case of issues as per the specification
            config_file = open(config_path, 'r')
        except:
            pass

        if config_file:
            break

    if config_file is None:
        return None

    config = configparser.ConfigParser()
    config.read_file(config_file)
    return config

class GitRepo(object):
    def __init__(self, config, directory):
        self.config = config
        self.directory = None

        if directory:
            self.directory = re.sub('/+$', '', directory)
            self.git = sh.git.bake("-C", self.directory)
        else:
            self.git = sh.git.bake()

    def get_repo_url(self):
        output = self.git('remote', 'get-url', self.config['local']['git_remote'])
        return output

    def get_repo_name(self):
        output = self.git('remote', 'get-url', config['local']['git_remote'])
        output = os.path.basename(str(output))
        output = re.sub(os.linesep, '', output)
        output = re.sub('\.git', '', output)

        return output

    # We want to generate a prefix to have the project name in it.
    # Examples:
    # - [libsamsung-ipc][PATCH] Fix IPC_SEC_LOCK_INFOMATION typo
    # - [device_samsung_i9300][PATCH] Add scripts to disable the modem
    # The revision is handled separately with git format-patch's -v<num> switch
    def get_subject_prefix(self):
        repo_name = self.get_repo_name()

        # Try to autodetect the project name:
        # external_libsamsung-ipc -> libsamsung-ipc
        # device_samsung_i9300 -> device_samsung_i9300
        dirs = repo_name.split('_')

        project_name = None
        if dirs[0] == "external":
            project_name = dirs[-1]
        elif dirs[0] == "hardware" and dirs[1] == "replicant":
            project_name = dirs[-1]
        elif dirs[0] == "device":
            project_name =repo_name
        else:
            project_name =repo_name

        if project_name == None:
            return None

        return '{project}] [PATCH'.format(project=project_name)

    def generate_patches(self, git_revision, nr_patches, patches_revision):
        subject_prefix = self.get_subject_prefix()

        git_arguments = ['format-patch', git_revision, '-{}'.format(nr_patches)]

        if subject_prefix != None:
            git_arguments.append('--subject-prefix={}'.format(subject_prefix))

        if patches_revision != None:
            git_arguments.append('-v{}'.format(patches_revision))

        patches = self.git(*git_arguments).split(os.linesep)
        patches.remove('')

        if self.directory:
            results = []
            for patch in patches:
                results.append(self.directory + os.sep + patch)
            return results
        else:
            return patches

    def generate_cover_mail_text(self, commit, nr_patches, repo):
        cgit_url = 'https://git.replicant.us'

        web_url = '{base}/contrib/{user}/{repo}/commit/?id={commit}'.format(
            base=cgit_url, user=self.config['project']['username'], repo=repo,
            commit=commit)

        clone_repo = '{base}/{user}/{repo}'.format(
            base=cgit_url, user=self.config['project']['username'], repo=repo)

        signature = self.config['local']['mail_signature']

        patch = 'patch'
        it = 'it'
        if nr_patches > 1:
            patch = 'patches'
            it = 'them'

        return cover_mail_template.format(patch=patch,
                                          it=it,
                                          web_url=web_url,
                                          clone_repo=clone_repo,
                                          commit=commit,
                                          repo_name=repo,
                                          signature=signature)

    def generate_git_send_email_command(self, git_revision, patches):
        command = ['send-email',
                   '--compose',
                   '--to={}'.format(self.config['project']['mailing_list'])]

        command += patches

        return command

    def get_git_revision(self, git_revision):
        output = self.git('--no-pager', 'log', '--oneline', git_revision, '-1',
                          '--format=%H')
        revision = re.sub(os.linesep, '', str(output))

        return revision

if __name__ == '__main__':
    nr_patches = 1
    patches_revision = None
    directory = None

    if len(sys.argv) not in [2, 3, 4, 5, 6]:
        usage(sys.argv[0])

    if sys.argv[1] == '-C':
        sys.argv.pop(1)
        directory =  sys.argv.pop(1)

    if len (sys.argv) >= 3:
        nr_patches = int(sys.argv[2])

    if len (sys.argv) >= 4:
        patches_revision = int(sys.argv[3])

    config = get_config()

    if config == None:
        print('Failed to find a configuration file')
        sys.exit(1)

    repo = GitRepo(config, directory)
    git_revision = repo.get_git_revision(sys.argv[1])

    patches = repo.generate_patches(git_revision, nr_patches, patches_revision)

    print('patches:')
    print('--------')
    for patch in patches:
        print(patch)

    print()
    print('git command:')
    print('------------')
    print('git ' + ' '.join(
        repo.generate_git_send_email_command(git_revision, patches)))

    print()
    print('Cover mail:')
    print('-----------')
    print(repo.generate_cover_mail_text(git_revision, nr_patches,
                                        repo.get_repo_name()))