aboutsummaryrefslogtreecommitdiff
path: root/patchodon.py
blob: 9086666e3d198e52d6c15ecde204670723abf4d8 (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
#!/usr/bin/env python3

import sys, os
import argparse
import requests
import hashlib
import time

# NOTES: html2text: html2text
# the replies are listed by context, should be link-listed to avoid issues,
# should specify next hash to provide some kind of a filter
# visibility public+unlisted, all unlisted, all private, all direct

VERSION = "0.1.0"

DPASTE_URL = "https://dpaste.com" # TODO any good way to parametrize this?

STATUS_LENGTH_LIMIT = 400 # TODO obtain from instance


def trace(x):
    sys.stderr.write(sys.argv[0] + ": " + x + "\n")


def api_token(args):
    if args.debug_api_token:
        return args.debug_api_token
    if args.env_api_token:
        return os.environ["PATCHODON_API_TOKEN"]
    raise ("API token not specified")


def do_post_status(args, body, parent=None, optional=None):
    if len(body) > STATUS_LENGTH_LIMIT:
        raise ("required status body too long")

    if not args.instance_url:
        raise ("mastodon instance not specified")

    token = api_token(args)

    headers = {"Authorization": f"Bearer {token}"}
    st = body + (
        "\n" + optional[0 : (STATUS_LENGTH_LIMIT - len(body) - 1)]
        if optional
        else ""
    )
    data = {"status": st, "visibility": "direct"}  # TODO parametrize direct
    if parent:
        data["in_reply_to_id"] = parent

    r = requests.post(
        args.instance_url + "/api/v1/statuses", data=data, headers=headers
    )

    if r.status_code != 200:
        raise ("mastodon status posting failed ({r.status_code})")

    rj = r.json()
    return (rj["id"], rj["url"])


def do_pastebin_file(file):
    # DPASTE API USE RULES:
    # - user-agent must be set properly
    # - 1 second between requests
    trace(f"pasting {file}...")
    r = requests.post(
        DPASTE_URL + "/api/v2/",
        data={
            "content": open(file, "r").read(),
            "syntax": "diff",
            "title": os.path.basename(file),
            "expiry_days": 1,  # TODO remove after testing
        },
        headers={"User-agent": f"patchodon v{VERSION}"},
    )
    if r.status_code != 201:
        raise (f"dpaste POST failed for `{file}'")
    time.sleep(1.1)
    return r.headers["location"] + ".txt"


def split_off_diff(s):
    return s.split("\ndiff --git ")[0]


def mapl(f, xs):
    return list(map(f, xs))


def mayline(s):
    if s:
        return s + "\n"
    else:
        return ""


def do_post(args):
    files = args.patchfile
    if not files:
        trace("reading patchfile series from stdin")
        files = mapl(lambda x: x.rstrip(chars="\n"), sys.stdin.readlines())
    n_patches = len(files)
    hashes = mapl(
        lambda x: hashlib.sha1(open(x, "r").read().encode()).hexdigest(), files
    )
    short_hashes = mapl(lambda x: x[0:8], hashes)
    full_hash = hashlib.sha1(" ".join(hashes).encode()).hexdigest()
    paste_raw_urls = mapl(do_pastebin_file, files)
    trace("posting the header...")
    parent_post_id, url = do_post_status(
        args,
        f"{mayline(args.recipient)} {mayline(args.subject)}\n"
        f"[patchodon hash {full_hash} / {' '.join(short_hashes)}]",
    )
    for fn, pst, hsh, series in zip(
        files, paste_raw_urls, hashes, range(n_patches)
    ):
        trace(f"posting patch {series+1}/{n_patches}...")
        parent_post_id, _ = do_post_status(
            args,
            f"{mayline(args.recipient)}"
            f"[patchodon {series+1}/{n_patches} {hsh}]\n"
            f"{pst}\n",
            parent=parent_post_id,
            optional=split_off_diff(open(fn, "r").read()),
        )
    print(url)


def do_get(args):
    pass


def main():
    ap = argparse.ArgumentParser(
        prog=sys.argv[0],
        epilog="patchodon.py version " + VERSION + " is a free software.",
        description="Publicly send and receive git patch series via Mastodon.",
    )

    cmds = ap.add_subparsers(required=True, dest="command")

    if "POST command":
        post = cmds.add_parser("post")
        if "API token sources":
            group = post.add_mutually_exclusive_group()
            group.add_argument(
                "--debug-api-token",
                help=(
                    "specify the API token on command line (not very secure,"
                    " good for debugging only)"
                ),
            )
            group.add_argument(
                "-e",
                "--env-api-token",
                action="store_true",
                help="get the API token from environment PATCHODON_API_TOKEN",
            )

        post.add_argument(
            "-i",
            "--instance-url",
            help=(
                "mastodon instance URL to post to, such as"
                " `https://mastodon.example/'"
            ),
        )
        post.add_argument(
            "-r",
            "--recipient",
            default=None,
            help=(
                "user tag to prepend to all posted statuses (required esp. for"
                " direct sending of statuses))"
            ),
        )
        post.add_argument(
            "-s",
            "--subject",
            default=None,
            help=(
                "start text of the initial post (e.g. to @tag someone and name"
                " the project and topic)"
            ),
        )
        post.add_argument(
            "patchfile",
            nargs="*",
            help=(
                "filenames of the patch series; taken from stdin if none are"
                " specified (useful for piping the output of git-format-patch"
                " into patchodon)"
            ),
        )

    if "GET command":
        get = cmds.add_parser("get")
        get.add_argument(
            "patch_url",
            help=(
                "root URL of the status where the patch was posted (the status"
                " should contain the patch hash)"
            ),
        )
        if "output possibilities":
            group = get.add_mutually_exclusive_group()
            group.add_argument(
                "-a",
                "--am",
                help=(
                    "apply the patches immediately with git-am instead of"
                    " storing them in a directory"
                ),
            )
            group.add_argument(
                "-C",
                "--out-dir",
                help=(
                    "output the patches into a given directory (by default, `.'"
                ),
            )
            get.add_argument(
                "--overwrite",
                action="store_true",
                help="overwrite existing patch files instead of renaming",
            )

    ap.add_argument(
        "-c",
        "--config",
        help=(
            "specify a custom config INI file (it can specify a section"
            " [patchodon] with keys instance_url and api_token), defaults to"
            " `$HOME/.patchodon.ini'; specify /dev/null to avoid reading"
            " configs"
        ),
    )
    args = ap.parse_args()

    if args.command == "post":
        do_post(args)
    elif args.command == "get":
        do_get(args)
    else:
        raise ("fatal: args borked")


if __name__ == "__main__":
    main()