Skip to content

Commit

Permalink
ref(runner): simplify api
Browse files Browse the repository at this point in the history
  • Loading branch information
kkharji committed May 22, 2022
1 parent d6e9ffb commit 0313b76
Show file tree
Hide file tree
Showing 20 changed files with 291 additions and 240 deletions.
1 change: 1 addition & 0 deletions lua/xbase/types.lua
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@

---@class Device
---@field info DeviceInfo
---@field platform Platform

---@class DeviceInfo
---@field availabilityError string?,
Expand Down
6 changes: 3 additions & 3 deletions lua/xbase/util.lua
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ local get_runners = function(platform)
local devices = {}

if platform then
for _, device in ipairs(vim.g.xbase.devices) do
if device.info.runtime_identifier:match(platform) then
for _, device in pairs(vim.g.xbase.devices) do
if platform == device.platform then
table.insert(devices, {
name = device.info.name,
udid = device.info.udid,
platform = platform,
is_on = device.info.state ~= "Shutdown",
})
end
end
end

return devices
end

Expand Down
8 changes: 6 additions & 2 deletions src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,12 +258,16 @@ pub async fn ensure_server_support<'a>(
.pipe(|msg| state.clients.echo_err(&root, &name, msg))
.await;

for (pid, client) in state.clients.iter() {
for (pid, nvim) in state.clients.iter() {
if pid::exists(pid, || {}) {
let mut logger = client.new_logger(format!("Compile:{name}"), &None);
let mut logger = nvim.logger();

logger.set_title(format!("Compile:{name}"));
logger.set_running().await.ok();

logger.open_win().await.ok();
logger.log(err.to_string()).await.ok();

logger.set_status_end(false, true).await.ok();
}
}
Expand Down
12 changes: 9 additions & 3 deletions src/daemon/requests/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::fmt::Debug;
#[cfg(feature = "daemon")]
use {
crate::constants::DAEMON_STATE,
crate::util::serde::value_or_default,
crate::xcode::{append_build_root, build_with_loggger},
};

Expand All @@ -13,7 +14,8 @@ use {
pub struct Build {
pub client: Client,
pub config: BuildConfiguration,
pub direction: Option<BufferDirection>,
#[cfg_attr(feature = "daemon", serde(deserialize_with = "value_or_default"))]
pub direction: BufferDirection,
}

#[cfg(feature = "daemon")]
Expand All @@ -31,7 +33,11 @@ impl Handler for Build {

let args = append_build_root(&root, config.as_args())?;

let ref mut logger = nvim.new_logger(format!("Build:{}", config.target), &direction);
let ref mut logger = nvim.logger();

logger.set_title(format!("Build:{}", config.target));
logger.set_direction(&direction);

let success = build_with_loggger(logger, &root, &args, true, true).await?;

if !success {
Expand Down Expand Up @@ -62,7 +68,7 @@ impl<'a> FromLua<'a> for Build {
Ok(Self {
client: table.get("client")?,
config: table.get("config")?,
direction: table.get("direction").ok(),
direction: table.get("direction").unwrap_or_default(),
})
}
}
81 changes: 36 additions & 45 deletions src/daemon/requests/run.rs
Original file line number Diff line number Diff line change
@@ -1,67 +1,62 @@
use {
super::*,
crate::nvim::BufferDirection,
crate::types::{BuildConfiguration, Platform},
super::*, crate::nvim::BufferDirection, crate::store::DeviceLookup,
crate::types::BuildConfiguration,
};

#[derive(Debug, Serialize, Deserialize)]
pub struct DeviceLookup {
name: String,
udid: String,
platform: Platform,
}

/// Run a project.
#[derive(Debug, Serialize, Deserialize)]
pub struct Run {
pub client: Client,
pub config: BuildConfiguration,
pub device: Option<DeviceLookup>,
pub direction: Option<BufferDirection>,
}

#[cfg(feature = "daemon")]
use {
crate::constants::DAEMON_STATE,
crate::runner::Runner,
crate::types::Platform,
crate::util::serde::value_or_default,
crate::xcode::{append_build_root, build_with_loggger},
crate::Error,
xcodebuild::runner::build_settings,
};

/// Run a project.
#[derive(Debug, Serialize, Deserialize)]
pub struct Run {
pub client: Client,
pub config: BuildConfiguration,
#[cfg_attr(feature = "daemon", serde(deserialize_with = "value_or_default"))]
pub device: DeviceLookup,
#[cfg_attr(feature = "daemon", serde(deserialize_with = "value_or_default"))]
pub direction: BufferDirection,
}

#[cfg(feature = "daemon")]
#[async_trait::async_trait]
impl Handler for Run {
async fn handle(self) -> Result<()> {
let Client { pid, root, .. } = &self.client;
tracing::info!("{:#?}", self);

tracing::info!("⚙️ Running command: {}", self.config.to_string());

let state = DAEMON_STATE.clone().lock_owned().await;
let direction = self.direction.clone();
let platform = if let Some(ref d) = self.device {
tracing::info!("{:#?}", d.platform);
Some(d.platform.clone())
} else {
None
};
let device = state.devices.from_lookup(self.device);
tracing::info!("{:#?}", device);

let nvim = state.clients.get(&pid)?;
let args = {
let mut args = self.config.as_args();
if let Some(ref platform) = platform {
args.extend(platform.sdk_simulator_args())
if let Some(ref device) = device {
args.extend(device.special_build_args())
}
append_build_root(&root, args)?
};

let ref mut logger = nvim.new_logger(format!("Run:{}", self.config.target), &direction);
let ref mut logger = nvim.logger();

logger.set_title(format!("Run:{}", self.config.target));
logger.set_direction(&self.direction);

let settings = build_settings(&root, &args).await?;
let platform = match platform {
Some(v) => v,
None => Platform::from_display(&settings.platform_display_name)?,
};
let platform = device
.as_ref()
.map(|d| d.platform.clone())
.unwrap_or_else(|| Platform::from_display(&settings.platform_display_name).unwrap());

let success = build_with_loggger(logger, &root, &args, true, true).await?;
if !success {
Expand All @@ -81,8 +76,8 @@ impl Handler for Run {
client: self.client,
state,
args,
udid: self.device.map(|d| d.udid),
direction,
udid: device.map(|d| d.udid.clone()),
direction: self.direction,
}
.run(settings)
.await?;
Expand All @@ -101,8 +96,8 @@ impl<'a> Requester<'a, Run> for Run {

impl ToString for Run {
fn to_string(&self) -> String {
if let Some(ref device) = self.device {
format!("run [{}] with {}", device.name, self.config.to_string())
if let Some(ref name) = self.device.name {
format!("run [{}] with {}", name, self.config.to_string())
} else {
format!("run with {}", self.config.to_string())
}
Expand All @@ -122,19 +117,15 @@ impl<'a> FromLua<'a> for Run {
Ok(Self {
client: table.get("client")?,
config: table.get("config")?,
direction: table.get("direction").ok(),
direction: table.get("direction").unwrap_or_default(),
device: device
.map(|d| {
let name = d.get("name").ok()?;
let udid = d.get("udid").ok()?;
let platform = d.get("platform").ok()?;
Some(DeviceLookup {
name,
udid,
platform,
})
Some(DeviceLookup { name, udid })
})
.flatten(),
.flatten()
.unwrap_or_default(),
})
}
}
14 changes: 1 addition & 13 deletions src/nvim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use serde::{Deserialize, Serialize};

#[cfg(feature = "daemon")]
use {
crate::{types::Client, util::fmt, Result},
crate::{types::Client, Result},
nvim_rs::{compat::tokio::Compat, create::tokio::new_path as connect, rpc::handler::Dummy},
};

Expand Down Expand Up @@ -57,18 +57,6 @@ impl NvimClient {
self.exec_lua(update_state_script, vec![]).await?;
Ok(())
}

pub fn new_logger<'a>(
&'a self,
title: String,
direction: &'a Option<BufferDirection>,
) -> Logger<'a> {
Logger::new(self, fmt::as_section(title), direction.clone())
}

pub fn new_unamed_logger<'a>(&'a self) -> Logger<'a> {
Logger::new(self, "".into(), None)
}
}

#[cfg(feature = "daemon")]
Expand Down
36 changes: 2 additions & 34 deletions src/nvim/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
#[cfg(feature = "daemon")]
use super::NvimClient;
#[cfg(feature = "daemon")]
use crate::Result;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, strum::EnumString, Serialize, Deserialize)]
#[derive(Default, Clone, Debug, strum::EnumString, Serialize, Deserialize)]
#[strum(ascii_case_insensitive)]
pub enum BufferDirection {
#[default]
Default,
Vertical,
Horizontal,
Expand All @@ -24,35 +21,6 @@ impl BufferDirection {
BufferDirection::TabEdit => format!("tabe {bufnr}"),
}
}

pub async fn get_window_direction(
nvim: &NvimClient,
direction: Option<BufferDirection>,
bufnr: i64,
) -> Result<String> {
use std::str::FromStr;
use tap::Pipe;

if let Some(direction) = direction {
return Ok(direction.to_nvim_command(bufnr));
};

match "return require'xbase.config'.values.default_log_buffer_direction"
.pipe(|str| nvim.exec_lua(str, vec![]))
.await?
.as_str()
.ok_or_else(|| anyhow::anyhow!("Unable to covnert value to string"))?
.pipe(Self::from_str)
.map(|d| d.to_nvim_command(bufnr))
{
Ok(open_command) => open_command,
Err(e) => {
tracing::error!("Unable to convert value to string {e}");
Self::Horizontal.to_nvim_command(bufnr)
}
}
.pipe(Ok)
}
}

#[cfg(feature = "lua")]
Expand Down
Loading

0 comments on commit 0313b76

Please sign in to comment.