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
use std::{
    error::Error,
    io,
    path::PathBuf,
    process::Stdio,
    sync::Arc,
};

use clap::{
    Args,
    Parser,
    Subcommand,
};
use hyper::service::make_service_fn;
use ngrok::prelude::*;
use watchexec::{
    action::{
        Action,
        Outcome,
    },
    command::Command,
    config::{
        InitConfig,
        RuntimeConfig,
    },
    error::CriticalError,
    handler::PrintDebug,
    signal::source::MainSignal,
    Watchexec,
};

#[derive(Parser, Debug)]
struct Cargo {
    #[command(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, Subcommand)]
enum Cmd {
    DocNgrok(DocNgrok),
}

#[derive(Debug, Args)]
struct DocNgrok {
    #[arg(short)]
    package: Option<String>,

    #[arg(long, short)]
    domain: Option<String>,

    #[arg(long, short)]
    watch: bool,

    #[arg(last = true)]
    doc_args: Vec<String>,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let Cmd::DocNgrok(args) = Cargo::parse().cmd;

    std::process::Command::new("cargo")
        .arg("doc")
        .args(args.doc_args.iter())
        .stderr(Stdio::inherit())
        .stdout(Stdio::inherit())
        .spawn()?
        .wait()?;

    let meta = cargo_metadata::MetadataCommand::new().exec()?;

    let default_package = args
        .package
        .or(meta.root_package().map(|p| p.name.clone()))
        .ok_or("No default package found. You must provide one with -p")?;
    let root_dir = meta.workspace_root;
    let target_dir = meta.target_directory;
    let doc_dir = target_dir.join("doc");

    let sess = ngrok::Session::builder()
        .authtoken_from_env()
        .connect()
        .await?;

    let mut tunnel_cfg = sess.http_endpoint();
    if let Some(domain) = args.domain {
        tunnel_cfg.domain(domain);
    }

    let tunnel = tunnel_cfg.listen().await?;

    println!(
        "serving docs on: {}/{}/",
        tunnel.url(),
        default_package.replace('-', "_")
    );

    let srv = hyper::server::Server::builder(tunnel).serve(make_service_fn(move |_| {
        let stat = hyper_staticfile::Static::new(&doc_dir);
        async move { Result::<_, String>::Ok(stat) }
    }));

    if args.watch {
        let we = make_watcher(args.doc_args, root_dir, target_dir)?;
        tokio::spawn(srv);

        we.main().await??;
    } else {
        srv.await?;
    }

    Ok(())
}

fn make_watcher(
    args: Vec<String>,
    root_dir: impl Into<PathBuf>,
    target_dir: impl Into<PathBuf>,
) -> Result<Arc<Watchexec>, CriticalError> {
    let target_dir = target_dir.into();
    let root_dir = root_dir.into();
    let mut init = InitConfig::default();
    init.on_error(PrintDebug(std::io::stderr()));

    let mut runtime = RuntimeConfig::default();
    runtime.pathset([root_dir]);
    runtime.command(Command::Exec {
        prog: "cargo".into(),
        args: [String::from("doc")].into_iter().chain(args).collect(),
    });
    runtime.on_action({
        move |action: Action| {
            let target_dir = target_dir.clone();
            async move {
                let sigs = action
                    .events
                    .iter()
                    .flat_map(|event| event.signals())
                    .collect::<Vec<_>>();
                if sigs.iter().any(|sig| sig == &MainSignal::Interrupt) {
                    action.outcome(Outcome::Exit);
                } else if action
                    .events
                    .iter()
                    .any(|e| e.paths().any(|(p, _)| !p.starts_with(&target_dir)))
                {
                    action.outcome(Outcome::if_running(
                        Outcome::both(Outcome::Stop, Outcome::Start),
                        Outcome::Start,
                    ));
                }

                Result::<_, io::Error>::Ok(())
            }
        }
    });
    Watchexec::new(init, runtime)
}