Skip to content

Commit

Permalink
ref(runner): rewrite and update simctl runner and log format
Browse files Browse the repository at this point in the history
  • Loading branch information
kkharji committed May 20, 2022
1 parent 0f26775 commit 295d8b1
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 125 deletions.
1 change: 0 additions & 1 deletion src/daemon/requests/run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ impl Handler for Run {
async fn handle(self) -> Result<()> {
let Client { pid, root, .. } = &self.client;

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

let state = DAEMON_STATE.clone().lock_owned().await;
Expand Down
1 change: 1 addition & 0 deletions src/nvim/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ impl<'a> Logger<'a> {
Ok(win)
}

// TODO(logger): make running different for devices and app
pub async fn set_running(&mut self) -> Result<()> {
self.nvim
.exec("let g:xbase_watch_build_status='running'", false)
Expand Down
51 changes: 27 additions & 24 deletions src/runner.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
mod simctl;
pub use self::simctl::*;

use crate::{
constants::DAEMON_STATE,
nvim::BufferDirection,
Expand Down Expand Up @@ -85,38 +88,38 @@ impl Runner {

/// Simctl Runner
impl Runner {
pub async fn run_with_simctl(
mut self,
settings: BuildSettings,
) -> Result<JoinHandle<Result<()>>> {
let nvim = self.state.clients.get(&self.client.pid)?;
let ref mut logger = nvim.new_logger("Run", &self.target, &self.direction);

pub async fn run_with_simctl(self, settings: BuildSettings) -> Result<JoinHandle<Result<()>>> {
let Self {
client,
target,
state,
udid,
direction,
..
} = self;

let ref mut logger = state
.clients
.get(&client.pid)?
.new_logger("Run", &target, &direction);
let app_id = settings.product_bundle_identifier;
let path_to_app = settings.metal_library_output_dir;

tracing::debug!("{app_id}: {:?}", path_to_app);

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

let mut device = get_device(&self.state, self.udid)?;

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

// TODO(simctl): device might change outside state
self.state.devices.insert(device);
let _runner = {
let device = get_device(&state, udid)?;
let runner = SimDeviceRunner::new(device, target.clone(), app_id, path_to_app);
runner.boot(logger).await?;
runner.install(logger).await?;
runner.launch(logger).await?;
runner
};

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

// TODO: Remove and replace with app logs
logger.set_status_end(true, false).await?;
let nvim = state.clients.get(&client.pid)?;
let ref mut _logger = nvim.new_logger("Run", &target, &direction);

state.sync_client_state().await?;

Expand Down
104 changes: 104 additions & 0 deletions src/runner/simctl.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
use crate::{nvim::Logger, types::SimDevice, Error, Result};
use std::path::PathBuf;
use tap::Pipe;

/// SimDevice ruuner
pub struct SimDeviceRunner {
device: SimDevice,
target: String,
app_id: String,
path_to_app: PathBuf,
stdout_path: String,
stderr_path: String,
}

impl SimDeviceRunner {
pub async fn boot<'a>(&self, logger: &mut Logger<'a>) -> Result<()> {
logger.log(self.booting_msg()).await?;
if let Err(e) = self.device.boot() {
let err: Error = e.into();
let err_msg = err.to_string();
if !err_msg.contains("current state Booted") {
logger.log(err_msg).await?;
logger.set_status_end(false, true).await?;
return Err(err);
}
}
Ok(())
}

pub async fn install<'a>(&self, logger: &mut Logger<'a>) -> Result<()> {
logger.log(self.installing_msg()).await?;
self.device
.install(&self.path_to_app)
.pipe(|res| self.ok_or_abort(res, logger))
.await?;
Ok(())
}

pub async fn launch<'a>(&self, logger: &mut Logger<'a>) -> Result<()> {
logger.log(self.launching_msg()).await?;
self.device
.launch(&self.app_id)
.stdout(&self.stdout_path)
.stderr(&self.stderr_path)
.exec()
.pipe(|res| self.ok_or_abort(res, logger))
.await?;
logger.log(self.connected_msg()).await?;
Ok(())
}
async fn ok_or_abort<'a, T>(
&self,
res: simctl::Result<T>,
logger: &mut Logger<'a>,
) -> Result<()> {
if let Err(e) = res {
let error: Error = e.into();
logger.log(error.to_string()).await?;
logger.set_status_end(false, true).await?;
Err(error)
} else {
Ok(())
}
}
}

impl SimDeviceRunner {
fn booting_msg(&self) -> String {
format!("[Run:{}] Booting {}", self.target, self.device.name)
}

fn installing_msg(&self) -> String {
format!("[Run:{}] Installing {}", self.target, self.app_id)
}

fn launching_msg(&self) -> String {
format!("[Run:{}] Launching {}", self.target, self.app_id)
}

fn connected_msg(&self) -> String {
format!("[Run:{}] Connected", self.target)
}
}

impl SimDeviceRunner {
pub fn new(device: SimDevice, target: String, app_id: String, path_to_app: PathBuf) -> Self {
let out_path = |out| format!("/tmp/{}_{out}_{}_runner.log", target, &device.udid).into();
let stdout_path = out_path("stdout");
let stderr_path = out_path("stderr");

tracing::debug!(
"SimDeviceRunner: {}: {app_id} [{path_to_app:?}]",
device.name
);
Self {
device,
target,
app_id,
path_to_app,
stdout_path,
stderr_path,
}
}
}
2 changes: 1 addition & 1 deletion src/store/simdevices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Default for SimDevices {
.to_vec()
.into_iter()
.filter(|d| d.is_available)
.map(SimDevice::new)
.map(Into::into)
.collect(),
)
}
Expand Down
102 changes: 7 additions & 95 deletions src/types/simdevice.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,16 @@
use crate::error::Error;
use crate::Result;
use serde::{Deserialize, Serialize};
use simctl::list::DeviceState;
use simctl::Device;
use std::hash::Hash;
use std::ops::{Deref, DerefMut};
use std::path::PathBuf;
use tap::Pipe;

use crate::nvim::Logger;
use crate::util::string_as_section;

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SimDevice {
pub is_running: bool,
#[serde(flatten)]
inner: Device,
}
pub struct SimDevice(Device);

impl Eq for SimDevice {}

impl PartialEq for SimDevice {
fn eq(&self, other: &Self) -> bool {
self.inner.udid == other.inner.udid
self.0.udid == other.0.udid
}
}

Expand All @@ -35,94 +23,18 @@ impl Hash for SimDevice {
impl Deref for SimDevice {
type Target = Device;
fn deref(&self) -> &Self::Target {
&self.inner
&self.0
}
}

impl DerefMut for SimDevice {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
&mut self.0
}
}

#[cfg(feature = "daemon")]
impl SimDevice {
pub fn new(inner: Device) -> Self {
Self {
inner,
is_running: false,
}
}

pub async fn try_boot<'a>(&mut self, logger: &mut Logger<'a>) -> Result<()> {
// FIX(run): DeviceState can get out of sync when the user shutdown device manually
logger
.log(string_as_section(format!("Booting: {}", self.name)))
.await?;

if let Err(e) = self.boot() {
let err = Error::from(e);
let err_msg = err.to_string();
if !err_msg.contains("current state Booted") {
logger.log(err_msg).await?;
logger.set_status_end(false, true).await?;
self.is_running = false;
return Err(err);
}
};

self.state = DeviceState::Booted;

Ok(())
}

pub async fn try_install<'a>(
&mut self,
path_to_app: &PathBuf,
app_id: &String,
logger: &mut Logger<'a>,
) -> Result<()> {
logger
.log(string_as_section(format!("Installing: {app_id}",)))
.await?;
self.install(path_to_app)
.pipe(|res| self.handle_error(res, logger))
.await?;
Ok(())
}

pub async fn try_launch<'a>(&mut self, app_id: &String, logger: &mut Logger<'a>) -> Result<()> {
logger
.log(string_as_section(format!("Launching: {app_id}")))
.await?;
if !self.is_running {
self.launch(app_id)
.stdout(&"/tmp/wordle_log")
.stderr(&"/tmp/wordle_log")
.exec()
.pipe(|res| self.handle_error(res, logger))
.await?;

self.is_running = true;

logger.log(string_as_section("Connected".into())).await?;
}

Ok(())
}

async fn handle_error<'a, T>(
&mut self,
res: simctl::Result<T>,
logger: &mut Logger<'a>,
) -> Result<()> {
if let Err(e) = res {
let err = Error::from(e);
logger.log(err.to_string()).await?;
logger.set_status_end(false, true).await?;
self.is_running = false;
return Err(err);
}
Ok(())
impl From<Device> for SimDevice {
fn from(d: Device) -> Self {
Self(d)
}
}
9 changes: 5 additions & 4 deletions syntax/xcodebuildlog.vim
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,29 @@ let s:cpo_save = &cpo
set cpo&vim


syn match XbaseOperations "\(Executing\|Compiling\|Generating\|Processing\|Emitting\|Compiling\|Copying\|Validating\|Signing\|Linking\|RegisterLaunchServices\)"
syn match XbaseOperations "\(Executing\|Compiling\|Generating\|Processing\|Emitting\|Compiling\|Copying\|Validating\|Signing\|Linking\|RegisterLaunchServices\|\Installing\|Booting\|Launching\)"
syn match XbaseEntitlement "Entitlement"
syn region XbaseScope display oneline start='^\[' end='\]'
syn match XbaseLogError "^\(\[Error\]\)"
syn match XbaseLogWarn "^\(\[Warning\]\)"
syn match XbaseLogSuccess "^\(\[Succeed\]\)"
syn match XbaseLogConnected "\(Connected\)"
syn match XbaseLogDone "^\(\[Done\]\)"
syn match XbaseLogPackage "^\(\[Package\]\)"
syn match XbaseLogLaunched "^\(\[Launched\]\)"
syn match XbaseLogOutput "^\(\[Output\]\)"
syn match XbaseLogOutput "^\(\[Exit\]\)"
syn match XbaseRunning "^\(\[Running\]\)"
syn match XbaseRunning "^\(\[Running\]\)"
syn match XbaseTarget "`\(\w.*\)`"
syn match XbaseFilePath "`\(\/.*\)`"
syn region XbaseSep display oneline start='-' end='-$'

hi def link XbaseScope Label
hi def link XbaseLogSuccess healthSuccess
hi def link XbaseLogConnected healthSuccess
hi def link XbaseOperations Function
hi def link XbaseEntitlement Comment
hi def link XbaseLogOutput Comment
hi def link XbaseRunning Comment
hi def link XbaseRunning Comment
hi def link XbaseSep Comment
hi def link XbaseLogPackage Comment
hi def link XbaseFilePath String
Expand Down

0 comments on commit 295d8b1

Please sign in to comment.