Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add prerelease #126

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/coggiebot/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ default = []
list-feature-cmd = []
basic-cmds = []
bookmark = []
prerelease = []

################
# mockingbird features
Expand Down
2 changes: 1 addition & 1 deletion crates/coggiebot/src/controllers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn setup_framework(mut cfg: StandardFramework) -> StandardFramework {
cfg,
{
["basic-cmds"] => [basic::COMMANDS_GROUP],
["prerelease"] => [features::PRERELEASE_GROUP::PRERELEASE_GROUP],
["prerelease"] => [prerelease::PRERELEASE_GROUP],
["list-feature-cmd"] => [features::FEATURES_GROUP],
["help-cmd"] => [features::HELP_GROUP],
["mockingbird-arl-cmd"] => [mockingbird::check::ARL_GROUP],
Expand Down
73 changes: 67 additions & 6 deletions crates/coggiebot/src/controllers/prerelease.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
use crate::{REPO, pkglib::{CoggiebotError}};
use serenity::model::prelude::Message;
use crate::{REPO, CoggieProc};

use serenity::{model::prelude::Message, framework::standard::Args};
use serenity::framework::standard::{
macros::{command, group},
CommandResult,
};

use tokio::sync::oneshot;

use std::{path::PathBuf, io::BufRead};
use serenity::prelude::*;
use tokio::process::Command;
use std::process::Stdio;
use std::time::Duration;
use tokio::time::timeout;


use std::os::fd::{FromRawFd, AsRawFd};

#[group]
#[commands(prerelease)]
pub struct PreRelease;

/// activate: "@botname prerelease {repo}/(branch-name)"
Expand All @@ -33,7 +41,60 @@ pub struct PreRelease;
/// --no-default-features
#[command]
#[aliases("pre-release")]
async fn prerelease(ctx: &Context, msg: &Message) -> CommandResult {
msg.reply(ctx, "ERROR: not implemented yet").await?;
async fn prerelease(ctx: &Context, msg: &Message, args: Args) -> CommandResult
{
let prelease_match = std::env::var("COGBOT_PRERELEASE_MATCH")
.unwrap_or("github:Skarlett/coggie-bot".to_string());

let uri = args.rest();

if !uri.contains(prelease_match.as_str()) {
msg.reply(ctx, "ERROR: not implemented yet").await?;
}

Command::new("nix")
.arg("--extra-experimental-features")
.arg("\"nix-command flakes\"")
.arg("build")
.arg("--no-link")
.arg(uri)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.await
.expect("failed to execute process");

let stdin = std::io::stdin();
let stdout = std::io::stdout();
let stderr = std::io::stderr();

let mut child = Command::new("nix")
.arg("run")
.arg(uri)
.stdin(unsafe { Stdio::from_raw_fd(stdin.as_raw_fd()) })
.stdout(unsafe { Stdio::from_raw_fd(stdout.as_raw_fd()) })
.stderr(unsafe { Stdio::from_raw_fd(stderr.as_raw_fd()) })
.spawn()
.expect("failed to execute process");

if let Err(_) = timeout(Duration::from_secs(10), child.wait()).await {
tracing::info!("Child Died");
}

let (stx, srx) = oneshot::channel();

tokio::spawn(async move {
let _ = child.wait().await;
stx.send(()).unwrap();
});

let tx = {
let mut glob = ctx.data.write().await;
glob.remove::<crate::ProcCtlKey>()
.expect("procctlkey not found")
};

let _ = tx.send(crate::CoggieProc::UntilSignal(srx));
Ok(())
}
}
105 changes: 79 additions & 26 deletions crates/coggiebot/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,17 @@ use serenity::{
StandardFramework,
DispatchError,
macros::hook
}
}, model::prelude::UserId, client::ClientBuilder
};

use serenity::model::channel::Message;
use serenity::prelude::*;
use structopt::StructOpt;
use tokio::sync::oneshot::{Receiver, Sender};
use std::sync::Arc;
use tokio::sync::oneshot;
use tokio::task::JoinHandle;


pub const LICENSE: &'static str = include_str!("../LICENSE");
pub const VERSION: &'static str = env!("CARGO_PKG_VERSION");
Expand All @@ -24,6 +29,13 @@ pub fn get_rev() -> &'static str {
option_env!("REV").unwrap_or("canary")
}

#[derive(Debug)]
pub enum CoggieProc {
Kill,
RestartClient,
UntilSignal(oneshot::Receiver<()>),
}

/// Environment variables used at runtime to
/// determine attributes of the program.
#[allow(non_snake_case)]
Expand Down Expand Up @@ -62,6 +74,33 @@ async fn dispatch_error(_ctx: &Context, _msg: &Message, error: DispatchError, _c
tracing::error!("Error: {:?}]", error);
}

async fn mkClient(token: &str, bot_id: UserId) -> ClientBuilder
{
let framework = StandardFramework::new()
.configure(|c| {
c.with_whitespace(true)
.ignore_bots(true)
.prefix(".")
.on_mention(Some(bot_id))
.delimiters(vec![", ", ","])
.owners(std::collections::HashSet::new())
})
.on_dispatch_error(dispatch_error);

let framework = controllers::setup_framework(framework);

controllers::setup_state(
Client::builder(token, GatewayIntents::non_privileged() | GatewayIntents::MESSAGE_CONTENT)
.framework(framework)
.event_handler(controllers::EvHandler))
.await
}

struct ProcCtlKey;
impl TypeMapKey for ProcCtlKey {
type Value = Sender<CoggieProc>;
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>>
{
Expand Down Expand Up @@ -90,30 +129,44 @@ async fn main() -> Result<(), Box<dyn std::error::Error>>
println!("{}", LICENSE);

tracing_subscriber::fmt::init();
loop {
let http = Http::new(&cli.token);
let bot_id = http.get_current_user().await?.id;

// this future never returns

let client = mkClient(&cli.token, bot_id).await;

let (tx, rx) = tokio::sync::oneshot::channel();


let client = client.type_map_insert::<ProcCtlKey>(tx);
let mut client = client.await?;

tokio::select! {
_ = client.start() => {},
ev = rx => match ev {
Ok(CoggieProc::Kill) => {
tracing::info!("Killing client");
// client.kill().await;
break;
},
Ok(CoggieProc::RestartClient) => {
tracing::info!("Restarting client");
break;
},

Ok(CoggieProc::UntilSignal(rx)) => {
tracing::info!("Halting client until signal");
tracing::info!("Received signal, restarting client");
let _ = rx.await;
}

_ => todo!(),
Err(_) => {}
}
}
}

let http = Http::new(&cli.token);
let bot_id = http.get_current_user().await?.id;

let framework = StandardFramework::new()
.configure(|c| {
c.with_whitespace(true)
.ignore_bots(true)
.prefix(".")
.on_mention(Some(bot_id))
.delimiters(vec![", ", ","])
.owners(std::collections::HashSet::new())
})
.on_dispatch_error(dispatch_error);

let framework = controllers::setup_framework(framework);

let mut client = controllers::setup_state(
Client::builder(&cli.token, GatewayIntents::non_privileged() | GatewayIntents::MESSAGE_CONTENT)
.framework(framework)
.event_handler(controllers::EvHandler))
.await
.await?;

client.start().await?;
unreachable!();
Ok(())
}