about summary refs log tree commit diff
path: root/src/main.rs
blob: 3d68b30e613c1597eea5936c0fb99aabe2abe891 (plain) (blame)
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
mod util;

use clap::clap_app;
use failure::{err_msg, format_err, Error};
use isahc::prelude::*;
use serde::Deserialize;
use std::ffi::CString;
use std::ffi::{OsStr, OsString};
use std::io::{self, stderr, stdin, BufRead, BufReader, Read, Write};
use std::mem::MaybeUninit;
use std::os::unix::prelude::*;
use std::path::Path;
use std::process::{exit, Command, ExitStatus, Stdio};
use std::ptr::{null, null_mut};
use libc::{
    posix_spawn_file_actions_adddup2, posix_spawn_file_actions_init, posix_spawnp,
    waitpid
};

use self::util::*;

extern "C" {
    static mut environ: *mut *mut libc::c_char;
}

type Result<T> = std::result::Result<T, Error>;

#[derive(Clone, Debug)]
struct Config<'a> {
    from: &'a OsStr,
    repo_path: &'a Path,
    owner: &'a str,
    repo: &'a str,
    remote_ref: &'a OsStr,
    recipients: &'a [&'a str],
    token: &'a [u8],
    verbose: bool,
}

impl<'a> Config<'a> {
    pub fn from(&self) -> &OsStr {
        self.from
    }

    pub fn repo_path(&self) -> &Path {
        self.repo_path
    }

    pub fn remote_ref(&self) -> &OsStr {
        self.remote_ref
    }

    pub fn owner(&self) -> &str {
        self.owner
    }

    pub fn repo(&self) -> &str {
        self.repo
    }
}

struct Git<S> {
    /// Arguments like `--git-dir` that should be applied to every Git
    /// command, regardless of subcommand.
    global_args: Vec<S>,
}

impl<S: AsRef<OsStr>> Git<S> {
    pub fn new(global_args: Vec<S>) -> Self {
        Self { global_args }
    }

    pub fn git<Sub: AsRef<OsStr>>(&self, subcommand_name: Sub) -> Command {
        let mut command = Command::new("git");
        command.args(&self.global_args).arg(subcommand_name);
        command
    }

    fn git_print_user_info(&self, fd: &dyn AsRawFd, commit: &OsStr) -> Result<()> {
        let mut file_actions = MaybeUninit::uninit();
        let r = unsafe { posix_spawn_file_actions_init(file_actions.as_mut_ptr()) };
        if r != 0 {
            return Err(io::Error::from_raw_os_error(r).into());
        }
        let mut file_actions = unsafe { file_actions.assume_init() };

        let r = unsafe { posix_spawn_file_actions_adddup2(&mut file_actions, fd.as_raw_fd(), 1) };
        if r != 0 {
            return Err(io::Error::from_raw_os_error(r).into());
        }

        let mut range = Vec::with_capacity(40 + 1);
        range.extend_from_slice(commit.as_bytes());
        range.push(0);

        let global_args: Vec<CString> = self
            .global_args
            .iter()
            .map(|arg| {
                CString::new(arg.as_ref().as_bytes()).expect("git global_args contains '\0'")
            })
            .collect();

        let c_global_args: Vec<*const u8> = global_args
            .iter()
            .map(|arg| arg.as_ptr() as *const _)
            .collect();

        let mut argv: Vec<*const u8> = vec![b"git\0" as *const _];
        argv.extend_from_slice(&c_global_args);
        argv.push(b"show\0" as *const _);
        argv.push(b"--no-patch\0" as *const _);
        argv.push(b"--format=Committer: %cn <%ce>\0" as *const _);
        argv.push(range.as_ptr());
        argv.push(null());

        let mut pid = MaybeUninit::uninit();
        let r = unsafe {
            posix_spawnp(
                pid.as_mut_ptr(),
                argv[0] as *mut _,
                &file_actions,
                null_mut(),
                argv.as_mut_ptr() as *const _,
                environ,
            )
        };
        if r != 0 {
            return Err(io::Error::from_raw_os_error(r).into());
        }
        let pid = unsafe { pid.assume_init() };

        let mut wstatus = MaybeUninit::uninit();
        if unsafe { waitpid(pid, wstatus.as_mut_ptr(), 0) } == -1 {
            return Err(io::Error::last_os_error().into());
        }
        let wstatus = unsafe { wstatus.assume_init() };

        if (wstatus & 0x7f) != 0 {
            return Err(err_msg("git show exited abnormally"));
        }

        let status = (wstatus & 0xff00) >> 8;
        if status != 0 {
            return Err(format_err!("git show exited with status {}", status));
        }

        Ok(())
    }
}

use graphql_client::GraphQLQuery;

type GitObjectID = String;

#[derive(GraphQLQuery)]
#[graphql(
    schema_path = "vendor/github_schema.graphql",
    query_path = "src/commit_pr.graphql",
    response_derives = "Debug"
)]
struct CommitPRQuery;

#[derive(Debug, Deserialize)]
struct GitHubGraphQLResponse<D> {
    data: D,
}

use commit_pr_query::{CommitPrQueryRepositoryObjectOn, ResponseData};

// TODO: lifetime?
struct Client {
    endpoint: &'static str,
    token: Vec<u8>,
}

use serde::Serialize;

impl Client {
    fn new(token: Vec<u8>) -> Self {
        Self {
            endpoint: "https://api.github.com/graphql",
            token,
        }
    }

    fn request<T: Serialize + ?Sized>(&self, query: &T) -> Result<ResponseData> {
        let mut authorization = b"bearer ".to_vec();
        authorization.extend_from_slice(&self.token);

        let response: GitHubGraphQLResponse<ResponseData> = Request::post(self.endpoint)
            .header("User-Agent", "alyssais")
            .header("Authorization", authorization.as_slice())
            .body(serde_json::to_vec(query)?)?
            .send()?
            .json()?;

        Ok(response.data)
    }
}

struct Run<'a> {
    config: &'a Config<'a>,
    client: Option<Client>,
    git: Git<&'a OsStr>,
}

impl<'a> Run<'a> {
    pub fn new(config: &'a Config) -> Self {
        Self {
            config,
            client: None,
            git: Git::new(vec![
                OsStr::new("--no-pager"),
                OsStr::new("-C"),
                config.repo_path().as_os_str(),
            ]),
        }
    }

    fn git<Sub: AsRef<OsStr>>(&self, subcommand_name: Sub) -> Command {
        self.git.git(subcommand_name)
    }

    fn refspec(&self) -> OsString {
        "FETCH_HEAD".into()
    }

    fn repo_url(&self) -> String {
        format!(
            "https://github.com/{}/{}",
            self.config.owner(),
            self.config.repo()
        )
    }

    fn commit_url(&self, commit: &str) -> String {
        format!("{}/commit/{}", self.repo_url(), commit)
    }

    fn head(&self) -> Result<OsString> {
        let mut out = self
            .git("rev-parse")
            .arg(self.refspec())
            .stderr(Stdio::inherit())
            .output()?
            .stdout;
        out.pop(); // Remove trailing newline
        Ok(OsString::from_vec(out))
    }

    fn cursor_ref(&self) -> OsString {
        let mut cursor_ref: OsString = "pushmail/cursor/github.com/".into();
        cursor_ref.push(self.config.owner());
        cursor_ref.push("/");
        cursor_ref.push(self.config.repo());
        cursor_ref.push("/");
        cursor_ref.push(self.config.remote_ref());
        cursor_ref
    }

    fn update_cursor(&self, commit: &str, force: bool) -> Result<()> {
        match self
            .git("branch")
            .args(if force { &["-f"][..] } else { &[][..] })
            .arg("--end-of-options")
            .arg(self.cursor_ref())
            .arg(commit)
            .status()
            .as_ref()
            .map(ExitStatus::success)
        {
            Ok(true) => Ok(()),
            Ok(false) => Err(err_msg("git branch -f failed")),
            Err(e) => Err(format_err!("git branch: {}", e)),
        }
    }

    fn send_email(&self, commit: &str) -> Result<()> {
        eprintln!("Sending mail for {}", commit);

        let mut from = OsString::from("--from=");
        from.push(self.config.from());

        let to: Vec<_> = self
            .config
            .recipients
            .iter()
            .map(|recipient| format!("--to={}", recipient))
            .collect();

        let mut message_id_hdr = OsString::from("--add-header=Message-ID: <");
        message_id_hdr.push(commit);
        message_id_hdr.push("@");
        message_id_hdr.push(hostname());
        message_id_hdr.push(">");

        let mut format_patch = match self
            .git("format-patch")
            .stdout(Stdio::piped())
            .arg("--stdout")
            .arg(message_id_hdr)
            .arg(from)
            .args(to)
            .arg("--end-of-options")
            .arg(format!("{0}~..{0}", commit))
            .spawn()
        {
            Ok(proc) => proc,
            Err(e) => return Err(format_err!("git format-patch: {}", e)),
        };

        let mut sendmail = match Command::new("sendmail")
            .stdin(Stdio::piped())
            .args(self.config.recipients)
            .spawn()
        {
            Ok(proc) => proc,
            Err(e) => return Err(format_err!("sendmail: {}", e)),
        };

        let sendmail_in = sendmail.stdin.as_mut().unwrap();

        let stdout = format_patch.stdout.as_mut().unwrap();
        let patch = BufReader::new(stdout).split(b'\n');

        #[derive(Copy, Clone, Debug, Eq, PartialEq)]
        enum PatchState {
            Header,
            MessageHeader,
            Message,
            Commentary,
            Diff,
        }

        use PatchState::*;

        let mut state = Header;

        for line in patch {
            let line = line?;

            let new_state = match (state, line.as_slice()) {
                (Header, b"") => MessageHeader,
                (MessageHeader, b"") => Message,
                (Message, b"---") => Commentary,
                (Commentary, l) if l.starts_with(b"diff ") => Diff, // TODO: Rust 1.42 slice literal
                _ => state,
            };

            match (state, new_state) {
                (MessageHeader, Message) => {
                    self.git
                        .git_print_user_info(sendmail_in, OsStr::new(commit))?;
                }

                (Commentary, Diff) => {
                    write!(sendmail_in, " {}\n\n", self.commit_url(commit))?;
                }

                _ => {}
            }

            sendmail_in.write_all(&line)?;
            sendmail_in.write_all(b"\n")?;

            state = new_state;
        }

        match format_patch.wait().as_ref().map(ExitStatus::success) {
            Ok(true) => {}
            Ok(false) => return Err(err_msg("git format-patch failed")),
            Err(e) => return Err(format_err!("git format-patch: {}", e)),
        }

        match sendmail.wait().as_ref().map(ExitStatus::success) {
            Ok(true) => {}
            Ok(false) => return Err(err_msg("sendmail failed")),
            Err(e) => return Err(format_err!("sendmail: {}", e)),
        }

        Ok(())
    }

    fn commit_has_pr(&self, oid: String) -> Result<bool> {
        if self.config.verbose {
            eprintln!("Looking for PR for {}.", oid);
        }

        let query = CommitPRQuery::build_query(commit_pr_query::Variables {
            owner: self.config.owner().to_string(),
            repo: self.config.repo().to_string(),
            oid: Some(oid),
        });

        let response = self.client.as_ref().unwrap().request(&query)?;

        fn require<T>(op: &Option<T>) -> Result<&T> {
            op.as_ref().ok_or_else(|| err_msg("missing json path"))
        }

        let repository = require(&response.repository)?;

        let commit = match require(&repository.object)?.on {
            CommitPrQueryRepositoryObjectOn::Commit(ref c) => c,
            _ => return Err(err_msg("returned object is not a commit")),
        };

        let pull_requests = require(&commit.associated_pull_requests)?;
        let nodes = require(&pull_requests.nodes)?;

        for node in nodes {
            let node = require(node)?;
            let base_repository = require(&node.base_repository)?;

            if base_repository.owner.login == self.config.owner() {
                if self.config.verbose {
                    eprintln!("Found PR for {}.", query.variables.oid.unwrap());
                }
                return Ok(true);
            }
        }

        if self.config.verbose {
            eprintln!("No PR for {}.", query.variables.oid.unwrap());
        }

        Ok(false)
    }

    fn run(&mut self) -> Result<()> {
        self.git("fetch")
            .arg(self.repo_url())
            .arg(self.config.remote_ref())
            .status()?;

        let start = self.cursor_ref();
        let end = self.head()?;

        let mut range = start;
        range.push("..");
        range.push(end);

        if self.config.verbose {
            eprintln!("Checking {}", range.to_string_lossy());
        }

        let mut log = match self
            .git("log")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .arg("--reverse")
            .arg("--first-parent")
            .arg("--format=%H")
            .arg("--end-of-options")
            .arg(range)
            .spawn()
        {
            Ok(proc) => proc,
            Err(e) => return Err(format_err!("git log: {}", e)),
        };

        let log_out = log.stdout.as_mut().expect("git log stdout missing");
        let commits = BufReader::new(log_out).split(b'\n');

        self.client = Some(Client::new(self.config.token.to_vec()));

        for commit in commits {
            // The commit_has_pr() calls could be parallelized, but at the time of writing Rayon
            // doesn't support turning a non-indexed parallel iterator into a sequential one, and
            // messages need to be sent out sequentially.

            let commit = String::from_utf8(commit?)?;
            let has_pr = self.commit_has_pr(commit.clone())?;

            self.update_cursor(&commit, true)?;

            if has_pr {
                continue;
            }

            self.send_email(&commit)?;
        }

        match log.wait().as_ref().map(ExitStatus::success) {
            Ok(true) => {}
            Err(e) => return Err(format_err!("git log: {}", e)),

            Ok(false) => {
                // If it failed due to the ref not existing, this is the first time we're running.
                // So all we need to do is create that ref and exit, and then next run we'll start
                // from there.p
                let mut arg = self.cursor_ref().to_os_string();
                arg.push("^{commit}");
                if !self
                    .git("rev-parse")
                    .arg("--verify")
                    .arg("-q")
                    .arg(arg)
                    .status()?
                    .success()
                {
                    self.update_cursor("FETCH_HEAD", false)?;
                    eprintln!("Set FETCH_HEAD as the starting point.  Any direct pushes from this point on will");
                    eprintln!("generate mail in subsequent pushmail runs.");
                    return Ok(());
                }

                // Even if stderr is missing, it's probably more appropriate to fail because of the
                // failed command at this point.
                if let Some(mut log_stderr) = log.stderr {
                    let _ = copy_stream(&mut log_stderr, &mut stderr()); // Already crashing.
                }

                return Err(err_msg("git log failed"));
            }
        }

        Ok(())
    }
}

fn main() {
    let matches = clap_app!(pushmail =>
        (version: "0.1.0")
        (author: "Alyssa Ross <hi@alyssa.is>")
        (about: "Send notification emails when a GitHub repository is pushed to directly.")
        (@arg from: -f --from +takes_value "Value for mail From header")
        (@arg ref: -r --ref +takes_value "Remote git ref to monitor")
        (@arg verbose: -v --verbose "Log more")
        (@arg path: +required "Path to local checkout of watched repository")
        (@arg repo: +required "GitHub repository to monitor (owner/repo)")
        (@arg recipient: +required "Recipient for notification messages")
    )
    .get_matches();

    // Safe because we have ownership of this file descriptor.
    let mut token = Vec::with_capacity(41);
    stdin().read_to_end(&mut token).unwrap();
    if token.last() == Some(&b'\n') {
        token.pop();
    }

    let mut full_repo = matches.value_of("repo").unwrap().splitn(2, '/');
    let owner = full_repo.next().expect("missing repo owner");
    let repo = full_repo.next().expect("missing repo name");

    let config = Config {
        from: matches.value_of_os("from").unwrap(), // TODO: allow omission
        repo_path: Path::new(matches.value_of_os("path").unwrap()),
        owner,
        repo,
        remote_ref: matches
            .value_of_os("ref")
            .unwrap_or_else(|| OsStr::new("HEAD")),
        recipients: &[matches.value_of("recipient").unwrap()],
        token: &token,
        verbose: matches.is_present("verbose"),
    };

    if let Err(error) = Run::new(&config).run() {
        eprintln!("{}", error);
        exit(1);
    }
}