use crate::config::CFG;
use crate::error::WorkflowError;
use crate::file_editor::launch_editor;
use crate::settings::ARGS;
use crate::settings::CLIPBOARD;
use crate::settings::HTML_EXPORT;
use crate::settings::LAUNCH_EDITOR;
use crate::settings::LAUNCH_VIEWER;
use crate::settings::STDIN;
use crate::template::template_kind_filter;
#[cfg(feature = "viewer")]
use crate::viewer::launch_viewer_thread;
use std::env;
#[cfg(not(target_family = "windows"))]
use std::matches;
use std::path::PathBuf;
#[cfg(feature = "viewer")]
use std::thread;
#[cfg(feature = "viewer")]
use std::time::Duration;
use tpnote_lib::content::ContentString;
use tpnote_lib::error::NoteError;
use tpnote_lib::workflow::create_new_note_or_synchronize_filename;
use tpnote_lib::workflow::synchronize_filename;
#[inline]
pub fn run_workflow(mut path: PathBuf) -> Result<PathBuf, WorkflowError> {
let launch_viewer;
match create_new_note_or_synchronize_filename::<ContentString, _>(
&path,
&*CLIPBOARD,
&*STDIN,
template_kind_filter,
&*HTML_EXPORT,
) {
Ok(p) => {
path = p;
#[cfg(feature = "viewer")]
{
launch_viewer = *LAUNCH_VIEWER;
}
}
Err(e) => {
if (matches!(e, NoteError::InvalidFrontMatterYaml { .. })
|| matches!(e, NoteError::MissingFrontMatter { .. })
|| matches!(e, NoteError::MissingFrontMatterField { .. })
|| matches!(e, NoteError::CompulsoryFrontMatterFieldIsEmpty { .. })
|| matches!(e, NoteError::SortTagVarInvalidChar { .. })
|| matches!(e, NoteError::FileExtNotRegistered { .. }))
&& !ARGS.batch
&& ARGS.export.is_none()
{
let missing_header = matches!(e, NoteError::MissingFrontMatter { .. })
|| matches!(e, NoteError::MissingFrontMatterField { .. });
launch_viewer = *LAUNCH_VIEWER
&& !(missing_header
&& CFG.viewer.missing_header_disables
&& !CFG.arg_default.add_header
&& !ARGS.add_header
&& !ARGS.view);
if launch_viewer || missing_header {
log::warn!("{}", e,);
} else {
log::error!("{}", e,);
};
} else {
return Err(e.into());
}
}
};
#[cfg(feature = "viewer")]
let viewer_join_handle = if launch_viewer {
Some(launch_viewer_thread(&path))
} else {
None
};
if *LAUNCH_EDITOR {
#[cfg(feature = "viewer")]
if viewer_join_handle.is_some() && CFG.viewer.startup_delay < 0 {
thread::sleep(Duration::from_millis(
CFG.viewer.startup_delay.unsigned_abs() as u64,
));
};
launch_editor(&path)?;
};
if *LAUNCH_EDITOR {
match synchronize_filename::<ContentString>(&path) {
Ok(p) => path = p,
Err(e) => {
let missing_header = matches!(e, NoteError::MissingFrontMatter { .. })
|| matches!(e, NoteError::MissingFrontMatterField { .. });
if missing_header {
log::warn!("{}", e);
} else {
return Err(e.into());
}
}
};
} else {
#[cfg(feature = "viewer")]
if let Some(jh) = viewer_join_handle {
let _ = jh.join();
};
};
Ok(path)
}
pub(crate) fn run() -> Result<PathBuf, WorkflowError> {
let path = if let Some(p) = &ARGS.path {
p.canonicalize()?
} else {
env::current_dir()?
};
run_workflow(path)
}