2022-02-27 20:35:22 +01:00
|
|
|
use std::path::PathBuf;
|
|
|
|
|
|
|
|
use diesel::{PgConnection, QueryResult};
|
|
|
|
|
2022-07-16 21:22:03 +02:00
|
|
|
use crate::{db, util::gen_alphanumeric, GlobalConfig};
|
2022-02-27 20:35:22 +01:00
|
|
|
|
2022-07-07 19:13:55 +02:00
|
|
|
/// Save a string containing bot code as a code bundle.
|
2022-07-23 23:40:25 +02:00
|
|
|
/// If a bot was provided, set the saved bundle as its active version.
|
2022-07-07 19:13:55 +02:00
|
|
|
pub fn save_code_string(
|
2022-02-27 20:35:22 +01:00
|
|
|
bot_code: &str,
|
|
|
|
bot_id: Option<i32>,
|
|
|
|
conn: &PgConnection,
|
2022-07-16 21:22:03 +02:00
|
|
|
config: &GlobalConfig,
|
2022-07-06 22:41:27 +02:00
|
|
|
) -> QueryResult<db::bots::BotVersion> {
|
2022-02-27 20:35:22 +01:00
|
|
|
let bundle_name = gen_alphanumeric(16);
|
|
|
|
|
2022-07-16 21:22:03 +02:00
|
|
|
let code_bundle_dir = PathBuf::from(&config.bots_directory).join(&bundle_name);
|
2022-02-27 20:35:22 +01:00
|
|
|
std::fs::create_dir(&code_bundle_dir).unwrap();
|
|
|
|
std::fs::write(code_bundle_dir.join("bot.py"), bot_code).unwrap();
|
|
|
|
|
2022-07-07 18:57:46 +02:00
|
|
|
let new_code_bundle = db::bots::NewBotVersion {
|
2022-02-27 20:35:22 +01:00
|
|
|
bot_id,
|
2022-07-07 18:57:46 +02:00
|
|
|
code_bundle_path: Some(&bundle_name),
|
|
|
|
container_digest: None,
|
2022-02-27 20:35:22 +01:00
|
|
|
};
|
2022-07-23 23:40:25 +02:00
|
|
|
let version = db::bots::create_bot_version(&new_code_bundle, conn)?;
|
|
|
|
// Leave this coupled for now - this is how the behaviour was bevore.
|
|
|
|
// It would be cleaner to separate version setting and bot selection, though.
|
|
|
|
if let Some(bot_id) = bot_id {
|
|
|
|
db::bots::set_active_version(bot_id, Some(version.id), conn)?;
|
|
|
|
}
|
|
|
|
Ok(version)
|
2022-02-27 20:35:22 +01:00
|
|
|
}
|