more env config (VERBOSE/TRACE, TODAY)

This commit is contained in:
nobody 2024-08-17 21:52:54 +02:00 committed by murmeldin
parent 88450b7a61
commit 2d3549a200
5 changed files with 86 additions and 17 deletions

View file

@ -199,7 +199,9 @@ impl<'a> CfgField<'a> {
match self { match self {
CfgField::Silent { default, .. } => Ok(Some(default.to_string())), CfgField::Silent { default, .. } => Ok(Some(default.to_string())),
CfgField::Default { default, .. } => Ok(Some(default.to_string())), CfgField::Default { default, .. } => Ok(Some(default.to_string())),
CfgField::Generated { key, generator, .. } => generator(key, config, is_dry_run()).map(Some), CfgField::Generated { key, generator, .. } => {
generator(key, config, is_dry_run()).map(Some)
},
_ => Ok(None), _ => Ok(None),
} }
} }

View file

@ -49,7 +49,7 @@ pub const CONFIG: CfgGroup<'static> = CfgGroup {
], ],
}; };
#[derive(Clone)] #[derive(Clone, Debug)]
pub struct Email { pub struct Email {
server: String, server: String,
credentials: Credentials, credentials: Credentials,
@ -57,6 +57,7 @@ pub struct Email {
is_dry_run: bool, is_dry_run: bool,
} }
#[derive(Debug)]
pub struct SimpleEmail { pub struct SimpleEmail {
base: Email, base: Email,
from: String, from: String,

View file

@ -32,6 +32,7 @@ pub const CONFIG: CfgGroup<'static> = CfgGroup {
], ],
}; };
#[derive(Debug)]
pub struct HedgeDoc { pub struct HedgeDoc {
server_url: String, server_url: String,
is_dry_run: bool, is_dry_run: bool,

View file

@ -117,6 +117,44 @@ fn is_dry_run() -> bool {
env::var("DRY_RUN").map(|v| !v.is_empty()).unwrap_or(false) env::var("DRY_RUN").map(|v| !v.is_empty()).unwrap_or(false)
} }
/// Checks environment variable `VERBOSE` to see if status messages should be
/// printed.
///
/// Use `verboseln!` to print stuff only if `VERBOSE` (or `TRACE`) is set.
fn is_verbose() -> bool {
env::var("VERBOSE").map(|v| !v.is_empty()).unwrap_or(false)
}
/// Like `println!`, but only if `is_verbose` (or `is_trace`) is true (due to
/// the environment variable `VERBOSE` being set.)
macro_rules! verboseln {
($($arg:tt)*) => {
if is_verbose() || is_trace() {
println!($($arg)*);
}
};
}
/// (A. k. a. "*very* verbose".) Checks environment variable `TRACE` to see if
/// detailed small-step status messages should be printed.
///
/// Use `traceln!` to print stuff only if `TRACE` is set.
fn is_trace() -> bool {
env::var("TRACE").map(|v| !v.is_empty()).unwrap_or(false)
}
macro_rules! traceln {
($($arg:tt)*) => {
if is_trace() {
println!($($arg)*);
}
};
}
fn today() -> NaiveDate {
env::var("TODAY")
.map(|v| NaiveDate::parse_from_str(&v, "%F").expect("'TODAY' hat nicht format YYYY-MM-DD"))
.unwrap_or(Local::now().date_naive())
}
struct Args { struct Args {
check_mode: bool, check_mode: bool,
config_file: String, config_file: String,
@ -153,14 +191,16 @@ fn main() -> Result<(), Box<dyn Error>> {
// set up config file access // set up config file access
let args = parse_args(); let args = parse_args();
let config_file = args.config_file.as_str(); let config_file = args.config_file.as_str();
verboseln!("Using config file {config_file}.");
let config = KV::new(config_file).unwrap(); let config = KV::new(config_file).unwrap();
config_spec::populate_defaults(&CONFIG_SPEC, &config); config_spec::populate_defaults(&CONFIG_SPEC, &config);
if args.check_mode { if args.check_mode {
println!(include_str!("chaosknoten.txt"), VERSION=env!("CARGO_PKG_VERSION")); println!(include_str!("chaosknoten.txt"), VERSION = env!("CARGO_PKG_VERSION"));
return config_spec::interactive_check(&CONFIG_SPEC, config); return config_spec::interactive_check(&CONFIG_SPEC, config);
} }
// get config // get config
let hedgedoc = HedgeDoc::new(&config["hedgedoc-server-url"], is_dry_run()); let hedgedoc = HedgeDoc::new(&config["hedgedoc-server-url"], is_dry_run());
traceln!("Hedgedoc: {:?}", hedgedoc);
let email_ = Email::new( let email_ = Email::new(
&config["email-server"], &config["email-server"],
&config["email-user"], &config["email-user"],
@ -173,14 +213,16 @@ fn main() -> Result<(), Box<dyn Error>> {
&config["email-to"], &config["email-to"],
config.get("email-in-reply-to").ok(), config.get("email-in-reply-to").ok(),
); );
traceln!("Email: {:?}", email);
let wiki = Mediawiki::new( let wiki = Mediawiki::new(
&config["wiki-server-url"], &config["wiki-server-url"],
&config["wiki-http-user"], &config["wiki-http-user"],
&config["wiki-http-password"], &config["wiki-http-password"],
is_dry_run(), is_dry_run(),
); );
traceln!("Wiki: {:?}", wiki);
// get next plenum days // get next plenum days
let today = Local::now().date_naive(); let today = today();
let plenum_spec = date::parse_spec(&config["date-spec"])?; let plenum_spec = date::parse_spec(&config["date-spec"])?;
let nearest_plenum_days = date::get_matching_dates_around(today, plenum_spec); let nearest_plenum_days = date::get_matching_dates_around(today, plenum_spec);
// figure out where we are // figure out where we are
@ -301,6 +343,8 @@ fn main() -> Result<(), Box<dyn Error>> {
println!("---AUTH RESULT:---\n{}\n-----------", auth_result); println!("---AUTH RESULT:---\n{}\n-----------", auth_result);
// TEMPORÄR ENDE // TEMPORÄR ENDE
// AAAAAAAAAA
let pad_content = hedgedoc.download(&current_pad_id).expect("Fehler beim Download des Pads!"); let pad_content = hedgedoc.download(&current_pad_id).expect("Fehler beim Download des Pads!");
let pad_content_without_top_instructions = try_to_remove_top_instructions(pad_content); let pad_content_without_top_instructions = try_to_remove_top_instructions(pad_content);
println!("Pad-content geladen!"); println!("Pad-content geladen!");
@ -517,12 +561,12 @@ fn try_to_remove_top_instructions(pad_content: String) -> String {
/* ***** formatting helpers ***** */ /* ***** formatting helpers ***** */
fn relative_date( ttp: i64 ) -> String { fn relative_date(ttp: i64) -> String {
if ttp.abs() > 2 { if ttp.abs() > 2 {
if ttp.is_negative() { if ttp.is_negative() {
format!( "vor {} Tagen", -ttp ) format!("vor {} Tagen", -ttp)
} else { } else {
format!( "in {} Tagen", ttp ) format!("in {} Tagen", ttp)
} }
} else { } else {
match ttp { match ttp {
@ -532,7 +576,8 @@ fn relative_date( ttp: i64 ) -> String {
-1 => "gestern", -1 => "gestern",
-2 => "vorgestern", -2 => "vorgestern",
_ => unreachable!(), _ => unreachable!(),
}.to_string() }
.to_string()
} }
} }
@ -546,22 +591,27 @@ fn upper_first(s: &str) -> String {
/* ***** transition actions ***** */ /* ***** transition actions ***** */
// BBBBBBBBBB
fn do_announcement( fn do_announcement(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
// use TTP to adjust text if needed (in {ttp} days) // use TTP to adjust text if needed (in {ttp} days)
todo!() todo!()
} }
fn do_reminder( fn do_reminder(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
// use TTP to adjust text if needed (tomorrow or today / in {ttp} days) // use TTP to adjust text if needed (tomorrow or today / in {ttp} days)
todo!() todo!()
} }
fn do_protocol( fn do_protocol(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
// use TTP to adjust text if needed ({-ttp} days ago) // use TTP to adjust text if needed ({-ttp} days ago)
todo!() todo!()
@ -570,7 +620,8 @@ fn do_protocol(
/// General cleanup function. Call as `(999, today, …)` for a complete reset /// General cleanup function. Call as `(999, today, …)` for a complete reset
/// based on today as the base date. /// based on today as the base date.
fn do_cleanup( fn do_cleanup(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
todo!() todo!()
} }
@ -596,19 +647,23 @@ const TRANSITION_LUT: [[TransitionFunction; 5]; 5] = [
/* LOGGED */ [do_cleanup, do_clean_announcement, do_clean_reminder, nop, do_cleanup], /* LOGGED */ [do_cleanup, do_clean_announcement, do_clean_reminder, nop, do_cleanup],
]; ];
fn nop(_: i64, _: &NaiveDate, _: &KV, _: &HedgeDoc, _: &SimpleEmail, _: &Mediawiki) -> Result<(), Box<dyn Error>> { fn nop(
_: i64, _: &NaiveDate, _: &KV, _: &HedgeDoc, _: &SimpleEmail, _: &Mediawiki,
) -> Result<(), Box<dyn Error>> {
Ok(()) Ok(())
} }
fn do_clean_announcement( fn do_clean_announcement(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
do_cleanup(ttp, plenum_day, config, hedgedoc, email, wiki)?; do_cleanup(ttp, plenum_day, config, hedgedoc, email, wiki)?;
do_announcement(ttp, plenum_day, config, hedgedoc, email, wiki) do_announcement(ttp, plenum_day, config, hedgedoc, email, wiki)
} }
fn do_clean_reminder( fn do_clean_reminder(
ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail, wiki: &Mediawiki, ttp: i64, plenum_day: &NaiveDate, config: &KV, hedgedoc: &HedgeDoc, email: &SimpleEmail,
wiki: &Mediawiki,
) -> Result<(), Box<dyn Error>> { ) -> Result<(), Box<dyn Error>> {
do_cleanup(ttp, plenum_day, config, hedgedoc, email, wiki)?; do_cleanup(ttp, plenum_day, config, hedgedoc, email, wiki)?;
do_reminder(ttp, plenum_day, config, hedgedoc, email, wiki) do_reminder(ttp, plenum_day, config, hedgedoc, email, wiki)

View file

@ -35,6 +35,7 @@ pub const CONFIG: CfgGroup<'static> = CfgGroup {
], ],
}; };
#[derive(Debug)]
pub struct Mediawiki { pub struct Mediawiki {
server_url: String, server_url: String,
http_user: String, http_user: String,
@ -103,7 +104,10 @@ pub fn pad_ins_wiki(old_pad_content: String) {
} }
/// Converts one file type into another using pandoc and saves the result as a txt file /// Converts one file type into another using pandoc and saves the result as a txt file
fn pandoc_convert(old_pad_content: String, output_filepath: &str, input_format: pandoc::InputFormat, output_format: pandoc::OutputFormat) -> Result<PandocOutput, PandocError> { fn pandoc_convert(
old_pad_content: String, output_filepath: &str, input_format: pandoc::InputFormat,
output_format: pandoc::OutputFormat,
) -> Result<PandocOutput, PandocError> {
//Convert Markdown into Mediawiki //Convert Markdown into Mediawiki
// Vanilla pandoc Befehl: pandoc --from markdown --to mediawiki --no-highlight // Vanilla pandoc Befehl: pandoc --from markdown --to mediawiki --no-highlight
let mut p = pandoc::new(); let mut p = pandoc::new();
@ -129,6 +133,12 @@ fn convert_md_to_mediawiki(old_pad_content: String) -> String {
// TODO: use tempfile="3.3", make it a NamedTempFile::new()?; // TODO: use tempfile="3.3", make it a NamedTempFile::new()?;
// or alternatively use piped stdout to avoid files entirely // or alternatively use piped stdout to avoid files entirely
let output_filepath: &str = "./pandoc_mediawiki.txt"; let output_filepath: &str = "./pandoc_mediawiki.txt";
pandoc_convert(old_pad_content, output_filepath, pandoc::InputFormat::Markdown, pandoc::OutputFormat::MediaWiki).expect("Fehler beim Umwandeln des und speichern des Pads in eine mediawiki-Textdatei"); pandoc_convert(
old_pad_content,
output_filepath,
pandoc::InputFormat::Markdown,
pandoc::OutputFormat::MediaWiki,
)
.expect("Fehler beim Umwandeln des und speichern des Pads in eine mediawiki-Textdatei");
read_txt_file(output_filepath) read_txt_file(output_filepath)
} }