Skip to content

Commit

Permalink
ref(logger): don't require win to be passed around
Browse files Browse the repository at this point in the history
  • Loading branch information
kkharji committed May 19, 2022
1 parent e0235a7 commit 0cc1e09
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 119 deletions.
6 changes: 3 additions & 3 deletions src/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,9 +253,9 @@ pub async fn ensure_server_support<'a>(
if proc_exists(pid, || {}) {
let mut logger = client.new_logger("Compile Error", name, &None);
logger.set_running().await.ok();
let ref win = Some(logger.open_win().await?);
logger.log(err.to_string(), win).await.ok();
logger.set_status_end(false, true).await.ok();
logger.open_win().await.ok();
logger.log(err.to_string()).await.ok();
logger.set_status_end(false, false).await.ok();
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/daemon/requests/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ impl Handler for Build {
let direction = self.direction.clone();

let args = append_build_root(&root, config.as_args())?;
let (success, _) = nvim
let success = nvim
.new_logger("Build", &config.target, &direction)
.log_build_stream(&root, &args, true, true)
.await?;
Expand Down
4 changes: 0 additions & 4 deletions src/daemon/requests/drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,25 +23,21 @@ impl Handler for Drop {

if state.clients.contains_key(&client.pid) {
tracing::info!("Drop({}: {})", client.pid, client.abbrev_root());

// NOTE: Should only be Some if no more client depend on it
if let Some(project) = state.projects.remove(&client).await? {
// NOTE: Remove project watchers
state.watcher.remove_project_watcher(&client).await;

// NOTE: Remove target watchers associsated with root
state
.watcher
.remove_target_watcher_for_root(&project.root)
.await;
}

// NOTE: Try removing client with given pid
if remove_client {
tracing::debug!("RemoveClient({})", client.pid);
state.clients.remove(&client.pid);
}

// NOTE: Sink state to all client vim.g.xbase.state
state.sync_client_state().await?;
}
Expand Down
35 changes: 18 additions & 17 deletions src/daemon/requests/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use super::*;
use crate::{
nvim::BufferDirection,
types::{BuildConfiguration, Platform},
util::string_as_section,
};

#[cfg(feature = "daemon")]
use {
crate::{constants::DAEMON_STATE, types::SimDevice, xcode::append_build_root, Error},
crate::{
constants::DAEMON_STATE, types::SimDevice, util::string_as_section,
xcode::append_build_root, Error,
},
std::str::FromStr,
tokio_stream::StreamExt,
xcodebuild::runner,
Expand Down Expand Up @@ -63,7 +65,7 @@ impl Handler for Run {
let settings = runner::build_settings(&root, &args).await?;
let platform = platform.unwrap_or(Platform::from_str(&settings.platform_display_name)?);

let (success, ref win) = nvim
let success = nvim
.new_logger("Build", &config.target, &direction)
.log_build_stream(&root, &args, true, true)
.await?;
Expand All @@ -81,6 +83,8 @@ impl Handler for Run {
tracing::debug!("Running binary {program:?}");

logger.log_title().await?;
logger.open_win().await?;

tokio::spawn(async move {
let mut stream = runner::run(program).await?;

Expand All @@ -89,18 +93,16 @@ impl Handler for Run {
while let Some(update) = stream.next().await {
let state = DAEMON_STATE.clone();
let state = state.lock().await;

let nvim = state.clients.get(&pid)?;
let mut logger = nvim.new_logger("Run", &config.target, &direction);
let ref win = Some(logger.open_win().await?);

// NOTE: NSLog get directed to error by default which is odd
match update {
Stdout(msg) => {
logger.log(msg, win).await?;
logger.log(msg).await?;
}
Error(msg) | Stderr(msg) => {
logger.log(format!("[Error] {msg}"), win).await?;
logger.log(format!("[Error] {msg}")).await?;
}
Exit(ref code) => {
let success = code == "0";
Expand All @@ -110,8 +112,8 @@ impl Handler for Run {
format!("Panic {code}")
});

logger.log(msg, win).await?;
logger.set_status_end(success, win.is_none()).await?;
logger.log(msg).await?;
logger.set_status_end(success, true).await?;
}
}
}
Expand All @@ -125,23 +127,22 @@ impl Handler for Run {
tracing::debug!("{app_id}: {:?}", path_to_app);

logger.log_title().await?;

tokio::spawn(async move {
// NOTE: This is required so when neovim exist this should also exit
let state = DAEMON_STATE.clone().lock_owned().await;
let nvim = state.clients.get(&pid)?;
let ref mut logger = nvim.new_logger("Run", &config.target, &direction);
let ref win = Some(logger.open_win().await?);

logger.open_win().await?;
logger.set_running().await?;

device.try_boot(logger, win).await?;
device
.try_install(&path_to_app, &app_id, logger, win)
.await?;
device.try_launch(&app_id, logger, win).await?;
device.try_boot(logger).await?;
device.try_install(&path_to_app, &app_id, logger).await?;
device.try_launch(&app_id, logger).await?;

// TODO: Remove and repalce with app logs
logger.set_status_end(true, win.is_none()).await?;
logger.set_status_end(true, false).await?;

let mut state = DAEMON_STATE.clone().lock_owned().await;
state.devices.insert(device);
Expand All @@ -151,7 +152,7 @@ impl Handler for Run {
}

let msg = format!("Unable to run `{}` under `{platform}`", config.target);
logger.log(msg.clone(), win).await?;
logger.log(msg.clone()).await?;
Err(Error::Run(msg))
}
}
Expand Down
15 changes: 11 additions & 4 deletions src/nvim/buffer.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "daemon")]
use super::NvimClient;
#[cfg(feature = "daemon")]
use anyhow::{Context, Result};
use crate::Result;
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, strum::EnumString, Serialize, Deserialize)]
Expand Down Expand Up @@ -37,14 +37,21 @@ impl BufferDirection {
return Ok(direction.to_nvim_command(bufnr));
};

"return require'xbase.config'.values.default_log_buffer_direction"
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(BufferDirection::from_str)
.pipe(Self::from_str)
.map(|d| d.to_nvim_command(bufnr))
.context("Convert to string to direction")
{
Ok(open_command) => open_command,
Err(e) => {
tracing::error!("Unable to convert value to string {e}");
Self::Horizontal.to_nvim_command(bufnr)
}
}
.pipe(Ok)
}
}

Expand Down
113 changes: 49 additions & 64 deletions src/nvim/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use crate::nvim::BufferDirection;
use crate::Result;
use nvim_rs::{Buffer, Window};
use std::path::Path;
use tap::Pipe;
use tokio_stream::StreamExt;

pub struct Logger<'a> {
Expand All @@ -28,7 +27,7 @@ impl<'a> Logger<'a> {
}
}

async fn clear(&self) -> Result<()> {
async fn clear_content(&self) -> Result<()> {
self.buf.set_lines(0, -1, false, vec![]).await?;
Ok(())
}
Expand All @@ -44,20 +43,7 @@ impl<'a> Logger<'a> {
})
}

async fn get_open_cmd(&self, direction: Option<BufferDirection>) -> String {
let direction =
BufferDirection::get_window_direction(self.nvim, direction, self.nvim.log_bufnr);

match direction.await {
Ok(open_command) => open_command,
Err(e) => {
tracing::error!("Unable to convert value to string {e}");
BufferDirection::Horizontal.to_nvim_command(self.nvim.log_bufnr)
}
}
}

pub async fn log(&mut self, msg: String, win: &Option<NvimWindow>) -> Result<()> {
pub async fn log(&mut self, msg: String) -> Result<()> {
tracing::debug!("{msg}");

let mut c = self.get_line_count().await?;
Expand All @@ -74,7 +60,7 @@ impl<'a> Logger<'a> {

self.current_line_count = Some(c);

if let Some(win) = win {
if let Some(win) = self.win().await {
win.set_cursor((c, 0)).await?;
}

Expand All @@ -87,23 +73,21 @@ impl<'a> Logger<'a> {
args: &Vec<String>,
clear: bool,
open: bool,
) -> Result<(bool, Option<Window<NvimConnection>>)> {
) -> Result<bool> {
let mut stream = crate::xcode::stream_build(root, args).await?;

// TODO(nvim): close log buffer if it is open for new direction
//
// Currently the buffer direction will be ignored if the buffer is opened already

if clear {
self.clear().await?;
self.clear_content().await?;
}

// TODO(nvim): build log correct height
let win = if open {
Some(self.open_win().await?)
} else {
None
};
if open {
self.open_win().await?;
}

let mut success = false;

Expand All @@ -113,51 +97,54 @@ impl<'a> Logger<'a> {
while let Some(line) = stream.next().await {
line.contains("Succeed").then(|| success = true);

self.log(line, &win).await?;
self.log(line).await?;
}

self.set_status_end(success, open).await?;
self.set_status_end(success, true).await?;

Ok((success, win))
Ok(success)
}

pub async fn log_title(&mut self) -> Result<()> {
self.log(self.title.clone(), &None).await?;
self.log(self.title.clone()).await?;
Ok(())
}

async fn open_cmd(&self) -> String {
let open_cmd = match self.open_cmd.as_ref() {
Some(s) => s.clone(),
None => self.get_open_cmd(None).await,
};
open_cmd
}

pub async fn open_win(&self) -> Result<Window<NvimConnection>> {
let (mut window, windows) = (None, self.nvim.list_wins().await?);

/// Get window if it's available
pub async fn win(&self) -> Option<NvimWindow> {
let windows = self.nvim.list_wins().await.ok()?;
for win in windows.into_iter() {
let buf = win.get_buf().await?;
if buf.get_number().await? == self.nvim.log_bufnr {
window = win.into();
let buf = win.get_buf().await.ok()?;
if buf.get_number().await.ok()? == self.nvim.log_bufnr {
return Some(win);
}
}
None
}

if let Some(win) = window {
win
} else {
let open_cmd = self.open_cmd().await;
self.nvim.exec(&open_cmd, false).await?;
let win = self.nvim.get_current_win().await?;
// NOTE: This doesn't work
win.set_option("number", false.into()).await?;
win.set_option("relativenumber", false.into()).await?;
// self.nvim.exec("setl nu nornu so=9", false).await?;
self.nvim.exec("wincmd w", false).await?;
win
/// Open Window
pub async fn open_win(&self) -> Result<Window<NvimConnection>> {
if let Some(win) = self.win().await {
return Ok(win);
}
.pipe(Ok)

tracing::info!("Openning a new window");

let open_cmd = match self.open_cmd.as_ref() {
Some(s) => s.clone(),
None => {
BufferDirection::get_window_direction(self.nvim, None, self.nvim.log_bufnr).await?
}
};
self.nvim.exec(&open_cmd, false).await?;
let win = self.nvim.get_current_win().await?;
// NOTE: This doesn't work
win.set_option("number", false.into()).await?;
win.set_option("relativenumber", false.into()).await?;
// self.nvim.exec("setl nu nornu so=9", false).await?;
self.nvim.exec("wincmd w", false).await?;

Ok(win)
}

pub async fn set_running(&mut self) -> Result<()> {
Expand All @@ -168,6 +155,7 @@ impl<'a> Logger<'a> {
}

pub async fn set_status_end(&mut self, success: bool, open: bool) -> Result<()> {
let win = self.win().await;
if success {
self.nvim
.exec("let g:xbase_watch_build_status='success'", false)
Expand All @@ -176,16 +164,13 @@ impl<'a> Logger<'a> {
self.nvim
.exec("let g:xbase_watch_build_status='failure'", false)
.await?;
if !open {
self.nvim.exec(&self.open_cmd().await, false).await?;
self.nvim
.get_current_win()
.await?
.set_cursor((self.get_line_count().await?, 0))
.await?;
self.nvim.exec("call feedkeys('zt')", false).await?;
}
}

if open && win.is_none() {
self.open_win().await?;
self.nvim.exec("call feedkeys('zt')", false).await?;
}

Ok(())
}
}
1 change: 1 addition & 0 deletions src/types/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ impl Client {

#[cfg(feature = "lua")]
use {crate::util::mlua::LuaExtension, mlua::prelude::*, tap::Pipe};

#[cfg(feature = "lua")]
impl Client {
/// Derive client from lua value
Expand Down
Loading

0 comments on commit 0cc1e09

Please sign in to comment.