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
//! Functions to interact with Mercurial command server.

use std::io;
use std::path::Path;
use std::process::Stdio;
use tokio::process::Command;

use crate::codec::ChannelMessage;
use crate::connection::{Connection, PipeConnection};
use crate::message::{self, ServerSpec};
use crate::protocol::Protocol;
use crate::runcommand::{self, UiHandler};

/// Command-server client holding active connection.
#[derive(Debug)]
pub struct Client<C> {
    proto: Protocol<C>,
    spec: ServerSpec,
}

impl<C> Client<C> {
    fn new(proto: Protocol<C>, spec: ServerSpec) -> Self {
        Self { proto, spec }
    }

    /// Server capabilities, encoding, etc.
    pub fn server_spec(&self) -> &ServerSpec {
        &self.spec
    }

    /// Mutably borrows the underlying protocol.
    ///
    /// This is a low-level interface to implement new command handler.
    pub fn borrow_protocol_mut(&mut self) -> &mut Protocol<C> {
        &mut self.proto
    }
}

impl<C> Client<C>
where
    C: Connection,
{
    /// Runs the Mercurial command specified in bytes.
    ///
    /// # Panics
    ///
    /// Panics if argument contains `\0` character.
    pub async fn run_command(
        &mut self,
        handler: &mut impl UiHandler,
        args: impl IntoIterator<Item = impl AsRef<[u8]>>,
    ) -> io::Result<i32> {
        runcommand::run_command(
            self.borrow_protocol_mut(),
            handler,
            message::pack_args(args),
        )
        .await
    }
}

/// Command-server client which spawns new server process and interacts via pipe.
pub type PipeClient = Client<PipeConnection>;

impl PipeClient {
    /// Spawns a server process at the specified directory with the default configuration.
    pub async fn spawn_at(dir: impl AsRef<Path>) -> io::Result<Self> {
        let mut command = Command::new("hg");
        command
            .args(&[
                "serve",
                "--cmdserver",
                "pipe",
                "--config",
                "ui.interactive=True",
            ])
            .current_dir(dir)
            .env("HGPLAIN", "1");
        PipeClient::spawn_with(&mut command).await
    }

    /// Spawns a server process by the given process builder.
    pub async fn spawn_with(command: &mut Command) -> io::Result<Self> {
        let child = command
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .spawn()?;
        let mut proto = Protocol::new(PipeConnection::new(child));
        let spec = read_hello(&mut proto).await?;
        Ok(Self::new(proto, spec))
    }

    // TODO: shuts down the process cleanly?
}

#[cfg(unix)]
pub use self::unix::UnixClient;

#[cfg(unix)]
mod unix {
    use std::ffi::OsStr;
    use std::os::unix::io::{AsRawFd, RawFd};
    use tokio::net::UnixStream;

    use super::*;
    use crate::connection::UnixConnection;

    impl<C> Client<C>
    where
        C: Connection,
    {
        /// Runs the Mercurial command specified in platform string.
        pub async fn run_command_os(
            &mut self,
            handler: &mut impl UiHandler,
            args: impl IntoIterator<Item = impl AsRef<OsStr>>,
        ) -> io::Result<i32> {
            runcommand::run_command(
                self.borrow_protocol_mut(),
                handler,
                message::pack_args_os(args),
            )
            .await
        }
    }

    impl<C> AsRawFd for Client<C>
    where
        C: AsRawFd,
    {
        fn as_raw_fd(&self) -> RawFd {
            self.proto.as_raw_fd()
        }
    }

    /// Command-server client which interacts via Unix domain socket.
    pub type UnixClient = Client<UnixConnection>;

    impl UnixClient {
        /// Connects to a command server listening at the specified socket path.
        pub async fn connect(path: impl AsRef<Path>) -> io::Result<Self> {
            let stream = UnixStream::connect(path).await?;
            let mut proto = Protocol::new(UnixConnection::new(stream));
            let spec = read_hello(&mut proto).await?;
            Ok(Self::new(proto, spec))
        }
    }
}

async fn read_hello(proto: &mut Protocol<impl Connection>) -> io::Result<ServerSpec> {
    match proto.fetch_response().await? {
        ChannelMessage::Data(b'o', data) => message::parse_hello(data),
        _ => Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "no hello message received",
        )),
    }
}