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
mod app;
mod client;
mod clipboard;
mod config;
mod ctl;
mod encode_term;
mod error;
mod event;
mod key;
mod keymap;
mod package_json;
mod proc;
mod protocol;
mod settings;
mod state;
mod theme;
mod ui_add_proc;
mod ui_confirm_quit;
mod ui_keymap;
mod ui_procs;
mod ui_remove_proc;
mod ui_term;
mod ui_zoom_tip;
mod yaml_val;

use std::{io::Read, path::Path};
use std::error::Error;

use anyhow::{bail, Result};
use app::server_main;
use clap::{arg, command, ArgMatches};
use client::client_main;
use config::{CmdConfig, Config, ConfigContext, ProcConfig, ServerConfig};
use ctl::run_ctl;
use flexi_logger::FileSpec;
use keymap::Keymap;
use package_json::load_npm_procs;
use proc::StopSignal;
use protocol::{CltToSrv, SrvToClt};
use serde_yaml::Value;
use settings::Settings;
use yaml_val::Val;

pub async fn run_mprocs(yaml_path: &str) -> anyhow::Result<()> {
    let config_value = Some((
            read_value(&yaml_path)?,
            ConfigContext { path: yaml_path.into() },
        ));

    let mut settings = Settings::default();

    if let Some((value, _)) = &config_value {
        settings
            .merge_value(Val::new(value)?)
            .map_err(|e| anyhow::Error::msg(format!("[{}] {}", "local config", e)))?;
    }



    let mut keymap = Keymap::new();
    settings.add_to_keymap(&mut keymap).unwrap();


    let mut config = if let Some((v, ctx)) = config_value {
        Config::from_value(&v, &ctx, &settings)?
    } else {
        Config::make_default(&settings)
    };


    run_client_and_server(config, keymap).await
}
pub async fn run_app() -> anyhow::Result<()> {
    let matches = command!()
        .arg(arg!(-c --config [PATH] "Config path [default: mprocs.yaml]"))
        .arg(arg!(-s --server [PATH] "Remote control server address. Example: 127.0.0.1:4050."))
        .arg(arg!(--ctl [YAML] "Send yaml/json encoded command to running mprocs"))
        .arg(arg!(--names [NAMES] "Names for processes provided by cli arguments. Separated by comma."))
        .arg(arg!(--npm "Run scripts from package.json. Scripts are not started by default."))
        .arg(arg!([COMMANDS]... "Commands to run (if omitted, commands from config will be run)"))
        .get_matches();

    let config_value = load_config_value(&matches)
        .map_err(|e| anyhow::Error::msg(format!("[{}] {}", "config", e)))?;

    let mut settings = Settings::default();

    // merge ~/.config/mprocs/mprocs.yaml
    settings.merge_from_xdg().map_err(|e| {
        anyhow::Error::msg(format!("[{}] {}", "global settings", e))
    })?;
    // merge ./mprocs.yaml
    if let Some((value, _)) = &config_value {
        settings
            .merge_value(Val::new(value)?)
            .map_err(|e| anyhow::Error::msg(format!("[{}] {}", "local config", e)))?;
    }

    let mut keymap = Keymap::new();
    settings.add_to_keymap(&mut keymap)?;

    let config = {
        let mut config = if let Some((v, ctx)) = config_value {
            Config::from_value(&v, &ctx, &settings)?
        } else {
            Config::make_default(&settings)
        };

        if let Some(server_addr) = matches.value_of("server") {
            config.server = Some(ServerConfig::from_str(server_addr)?);
        }

        if matches.occurrences_of("ctl") > 0 {
            return run_ctl(matches.value_of("ctl").unwrap(), &config).await;
        }

        if let Some(cmds) = matches.values_of("COMMANDS") {
            let names = matches
                .value_of("names")
                .map_or_else(|| Vec::new(), |arg| arg.split(",").collect::<Vec<_>>());
            let procs = cmds
                .into_iter()
                .enumerate()
                .map(|(i, cmd)| ProcConfig {
                    name: names
                        .get(i)
                        .map_or_else(|| cmd.to_string(), |s| s.to_string()),
                    cmd: CmdConfig::Shell {
                        shell: cmd.to_owned(),
                    },
                    env: None,
                    cwd: None,
                    autostart: true,
                    stop: StopSignal::default(),
                })
                .collect::<Vec<_>>();

            config.procs = procs;
        } else if matches.is_present("npm") {
            let procs = load_npm_procs()?;
            config.procs = procs;
        }

        config
    };

    run_client_and_server(config, keymap).await
}

async fn run_client_and_server(config: Config, keymap: Keymap) -> Result<()> {
    let (clt_tx, srv_rx) = tokio::sync::mpsc::channel::<CltToSrv>(64);
    let (srv_tx, clt_rx) = tokio::sync::mpsc::unbounded_channel::<SrvToClt>();

    let client = tokio::spawn(async { client_main(clt_tx, clt_rx).await });
    let server =
        tokio::spawn(async { server_main(config, keymap, srv_tx, srv_rx).await });

    let r1 = server
        .await
        .unwrap_or_else(|err| Err(anyhow::Error::from(err)));
    let r2 = client
        .await
        .unwrap_or_else(|err| Err(anyhow::Error::from(err)));

    r1.and(r2)
        .map_err(|err| anyhow::Error::msg(err.to_string()))
}

fn load_config_value(
    matches: &ArgMatches,
) -> Result<Option<(Value, ConfigContext)>> {
    if let Some(path) = matches.value_of("config") {
        return Ok(Some((
            read_value(path)?,
            ConfigContext { path: path.into() },
        )));
    }


    {
        let path = "mprocs.yaml";
        if Path::new(path).is_file() {
            return Ok(Some((
                read_value(path)?,
                ConfigContext { path: path.into() },
            )));
        }
    }

    {
        let path = "mprocs.json";
        if Path::new(path).is_file() {
            return Ok(Some((
                read_value(path)?,
                ConfigContext { path: path.into() },
            )));
        }
    }

    Ok(None)
}

fn read_value(path: &str) -> Result<Value> {
    // Open the file in read-only mode with buffer.
    let file = match std::fs::File::open(&path) {
        Ok(file) => file,
        Err(err) => match err.kind() {
            std::io::ErrorKind::NotFound => {
                bail!("Config file '{}' not found.", path);
            }
            _kind => return Err(err.into()),
        },
    };
    let mut reader = std::io::BufReader::new(file);
    let ext = std::path::Path::new(path)
        .extension()
        .map_or_else(|| "".to_string(), |ext| ext.to_string_lossy().to_string());
    let value: Value = match ext.as_str() {
        "yaml" | "yml" => serde_yaml::from_reader(reader)?,
        _ => bail!("Supported config extensions: yaml, yml."),
    };
    Ok(value)
}