Skip to content

Commit

Permalink
Merge pull request #7 from ThomasByr/service-info
Browse files Browse the repository at this point in the history
Allow boot with partial service availability
  • Loading branch information
ThomasByr authored Aug 24, 2022
2 parents d98eefb + 0e5501e commit e95850e
Show file tree
Hide file tree
Showing 27 changed files with 377 additions and 137 deletions.
3 changes: 2 additions & 1 deletion .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ LOGO_EMOJI_ID=
## Usage logging
COMPILE_LOG=
JOIN_LOG=
PANIC_LOG=

## Top.gg bot voting announcement
VOTE_CHANNEL=
Expand All @@ -44,4 +45,4 @@ DBL_WEBHOOK_PASSWORD=

## Statistics tracking API
STATS_API_LINK=
STATS_API_KEY=
STATS_API_KEY=
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "discord-compiler-bot"
description = "Discord bot to compile your spaghetti code."
version = "0.1.4"
version = "0.1.5"
authors = ["ThomasByr"]
edition = "2021"
build = "src/build.rs"
Expand Down
42 changes: 31 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@
[![Author](https://img.shields.io/badge/author-@ThomasByr-blue)](https://github.com/ThomasByr)

````txt
;compile c++ -O3 -Wall -Wextra -Werror
;compile c++ -O3 -Wall -Wextra -Werror -Wpedantic
argv1 argv2 argv3
```
stdin1
stdin2 not displayed
stdin1 on the first line
stdin2 on the second line
```
```cpp
#include <iostream>
Expand All @@ -28,9 +28,9 @@ int main(int argc, char** argv) {
(void)argc;
std::string str;
std::getline(std::cin, str);
std::cout << str << std::endl;
std::cout << argv[1] << std::endl;
return 0;
std::cout << str << "\n"
<< argv[1] << std::endl;
return EXIT_SUCCESS;
}
```
````
Expand All @@ -40,11 +40,13 @@ int main(int argc, char** argv) {
3. [💁 Get Help](#-get-help)
4. [🔰 Support](#-support)
5. [⚖️ License](#️-license)
6. [🔄 Changelog, Bugs and TODO](#-changelog-bugs-and-todo)
6. [🔄 Changelog and contributing](#-changelog-and-contributing)
7. [🐛 Bugs and TODO](#-bugs-and-todo)

## ✏️ In short

First, this project was done in a week so do not expect crazy behavior and be immune to bugs.
> **Note**
> This project was done in a week so do not expect crazy behavior and be immune to bugs.
This is a Discord compiler bot which can compile / interpret code blocks and display the result. Keep in mind that we're working in discord. This means, of course, that we have many operating restraints. Here's a few of the big ones.

Expand Down Expand Up @@ -73,12 +75,12 @@ While in discord, please type `;help` to get generic help and show a list of ava
- `;languages` will show a menu to display all languages
- `;asm` will transform the code block into Assembly \_x86_64 for linux

If you want to contribute, please read the [contributing](.github/CONTRIBUTING.md) guideline, make pull requests and be kind.

## 🔰 Support

Support for following languages : c++, c, java, python, ruby, rust, javascript, go, php, lua and many more.

On a side note, support has been added for ARM architectures. Meaning you can now host the bot yourself on a Raspberry PI without any tweaks to the code ! But you will need to compile it yourself though...

> [Create a new issue](https://github.com/ThomasByr/discord-compiler-bot/issues/new)
## ⚖️ License
Expand All @@ -93,7 +95,11 @@ This project is licensed under the GPL-3.0 new or revised license. Please read t

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

## 🔄 Changelog, Bugs and TODO
## 🔄 Changelog and contributing

Please read the [changelog](changelog.md) file for the full history !

If you ever want to contribute to this project, either request the contributor status, or, more manually, fork the repo and make a full request ! On a more generic note, please do respect the [Rust Coding Conventions](https://rustc-dev-guide.rust-lang.org/conventions.html) and wait for your PR to be reviewed. Make sure you respect and read the [contributing](.github/CONTRIBUTING.md) guideline, make pull requests and be kind.

<details>
<summary> Beta first minor release (click here to expand) </summary>
Expand Down Expand Up @@ -130,8 +136,22 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
- boilerplate code for php
- pinned serenity dependency to 0.11.1 to avoid headaches

**v0.1.4** hotfix

- compilation service unavailable

**v0.1.5** online services

- assume some service won't work
- unwrap leading to panic
- if api don't return status, assume we failed
- throw more compilation info in footer
- cared about performance for once

</details>

## 🐛 Bugs and TODO

**TODO** (first implementation version)

- [x] connect to Azure (v0.1.0)
Expand Down
12 changes: 12 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,15 @@
- new `diff` slash command with colored output
- boilerplate code for php
- pinned serenity dependency to 0.11.1 to avoid headaches

**v0.1.4** hotfix

- compilation service unavailable

**v0.1.5** online services

- assume some service won't work
- unwrap leading to panic
- if api don't return status, assume we failed
- throw more compilation info in footer
- cared about performance for once
13 changes: 8 additions & 5 deletions src/boilerplate/c.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::boilerplate::generator::BoilerPlateGenerator;
use std::fmt::Write as _;

use crate::utls::constants::C_LIKE_MAIN_REGEX;

Expand All @@ -21,15 +22,17 @@ impl BoilerPlateGenerator for CGenerator {
let lines = self.input.split('\n');
for line in lines {
let trimmed = line.trim();
if trimmed.starts_with("using") || trimmed.starts_with("#i") {
header.push_str(&format!("{}\n", trimmed));
if trimmed.starts_with("#i") || trimmed.starts_with("#d") {
// header.push_str(&format!("{}\n", trimmed));
writeln!(header, "{}", trimmed).unwrap();
} else {
main_body.push_str(&format!("{}\n", trimmed))
// main_body.push_str(&format!("{}\n", trimmed));
writeln!(main_body, "{}", trimmed).unwrap();
}
}

if main_body.contains("printf") && header.contains("stdio.h") {
header.push_str("include <stdio.h>")
if main_body.contains("printf") && !header.contains("stdio.h") {
header.push_str("#include <stdio.h>")
}
format!("{}\nint main(void) {{\n{}return 0;\n}}", header, main_body)
}
Expand Down
7 changes: 5 additions & 2 deletions src/boilerplate/cpp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::boilerplate::generator::BoilerPlateGenerator;
use std::fmt::Write as _;

use crate::utls::constants::C_LIKE_MAIN_REGEX;

Expand All @@ -22,9 +23,11 @@ impl BoilerPlateGenerator for CppGenerator {
for line in lines {
let trimmed = line.trim();
if trimmed.starts_with("using") || trimmed.starts_with("#i") {
header.push_str(&format!("{}\n", trimmed));
// header.push_str(&format!("{}\n", trimmed));
writeln!(header, "{}", trimmed).unwrap();
} else {
main_body.push_str(&format!("{}\n", trimmed))
// main_body.push_str(&format!("{}\n", trimmed));
writeln!(main_body, "{}", trimmed).unwrap();
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/boilerplate/csharp.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::boilerplate::generator::BoilerPlateGenerator;
use std::fmt::Write as _;

use crate::utls::constants::CSHARP_MAIN_REGEX;

Expand All @@ -22,9 +23,11 @@ impl BoilerPlateGenerator for CSharpGenerator {
for line in lines {
let trimmed = line.trim();
if trimmed.starts_with("using") {
header.push_str(&format!("{}\n", trimmed));
// header.push_str(&format!("{}\n", trimmed));
writeln!(header, "{}", trimmed).unwrap();
} else {
main_body.push_str(&format!("{}\n", trimmed))
// main_body.push_str(&format!("{}\n", trimmed));
writeln!(main_body, "{}", trimmed).unwrap();
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/boilerplate/java.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use crate::boilerplate::generator::BoilerPlateGenerator;
use std::fmt::Write as _;

use crate::utls::constants::JAVA_MAIN_REGEX;

Expand All @@ -22,9 +23,11 @@ impl BoilerPlateGenerator for JavaGenerator {
for line in lines {
let trimmed = line.trim();
if trimmed.starts_with("import") {
header.push_str(&format!("{}\n", trimmed));
// header.push_str(&format!("{}\n", trimmed));
writeln!(header, "{}", trimmed).unwrap();
} else {
main_body.push_str(&format!("{}\n", trimmed))
// main_body.push_str(&format!("{}\n", trimmed));
writeln!(main_body, "{}", trimmed).unwrap();
}
}

Expand Down
5 changes: 4 additions & 1 deletion src/commands/asm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ use serenity::builder::CreateEmbed;
use serenity::model::channel::{Message, ReactionType};
use serenity::model::user::User;

use std::fmt::Write as _;

use crate::utls::parser;

#[command]
Expand Down Expand Up @@ -62,7 +64,8 @@ pub async fn handle_request(
// Try to load in an attachment
let (code, ext) = parser::get_message_attachment(&msg.attachments).await?;
if !code.is_empty() {
content.push_str(&format!("\n```{}\n{}\n```\n", ext, code));
// content.push_str(&format!("\n```{}\n{}\n```\n", ext, code));
writeln!(content, "\n```{}\n{}\n```", ext, code).unwrap();
}

// parse user input
Expand Down
7 changes: 5 additions & 2 deletions src/commands/compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ use serenity::model::user::User;
use crate::cache::{CompilerCache, ConfigCache, StatsManagerCache};
use crate::managers::compilation::CompilationManager;

use std::fmt::Write as _;

#[command]
#[bucket = "nospam"]
pub async fn compile(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
Expand Down Expand Up @@ -68,7 +70,8 @@ pub async fn handle_request(
// Try to load in an attachment
let (code, ext) = parser::get_message_attachment(&msg.attachments).await?;
if !code.is_empty() {
content.push_str(&format!("\n```{}\n{}\n```\n", ext, code));
// content.push_str(&format!("\n```{}\n{}\n```\n", ext, code));
writeln!(content, "\n```{}\n{}\n```", ext, code).unwrap();
}

// parse user input
Expand Down Expand Up @@ -112,7 +115,7 @@ pub async fn handle_request(
let is_success = is_success_embed(&result.1);
let stats = data_read.get::<StatsManagerCache>().unwrap().lock().await;
if stats.should_track() {
stats.compilation(&result.0, !is_success).await;
stats.compilation(&result.0.language, !is_success).await;
}

let data = ctx.data.read().await;
Expand Down
9 changes: 8 additions & 1 deletion src/commands/compilers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@ pub async fn compilers(ctx: &Context, msg: &Message, _args: Args) -> CommandResu
let data_read = ctx.data.read().await;
let compiler_cache = data_read.get::<CompilerCache>().unwrap();
let compiler_manager = compiler_cache.read().await;
if compiler_manager.gbolt.is_none() {
return Err(CommandError::from(
"Compiler Explorer service is currently down, please try again later.",
));
}

// Get our list of compilers
let mut langs: Vec<String> = Vec::new();
Expand All @@ -31,7 +36,7 @@ pub async fn compilers(ctx: &Context, msg: &Message, _args: Args) -> CommandResu
let language = shortname_to_qualified(&lower_lang);
match compiler_manager.resolve_target(language) {
RequestHandler::CompilerExplorer => {
for cache_entry in &compiler_manager.gbolt.cache {
for cache_entry in &compiler_manager.gbolt.as_ref().unwrap().cache {
if cache_entry.language.id == language {
for compiler in &cache_entry.compilers {
langs.push(format!("{} -> **{}**", &compiler.name, &compiler.id));
Expand All @@ -42,6 +47,8 @@ pub async fn compilers(ctx: &Context, msg: &Message, _args: Args) -> CommandResu
RequestHandler::WandBox => {
match compiler_manager
.wbox
.as_ref()
.unwrap()
.get_compilers(shortname_to_qualified(language))
{
Some(s) => {
Expand Down
4 changes: 3 additions & 1 deletion src/commands/cpp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use serenity::{
prelude::*,
};

use crate::utls::discordhelpers::embeds::EmbedOptions;
use crate::{
cache::{CompilerCache, ConfigCache, MessageCache, MessageCacheEntry},
cppeval::eval::CppEval,
Expand Down Expand Up @@ -99,6 +100,7 @@ pub async fn handle_request(

// remove our loading emote
discordhelpers::delete_bot_reacts(&ctx, msg, loading_reaction).await?;
let options = EmbedOptions::new(false, fake_parse.target.clone(), String::default());

Ok(result.1.to_embed(&author, false))
Ok(result.1.to_embed(&author, &options))
}
18 changes: 14 additions & 4 deletions src/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::io::Write;
#[command]
pub async fn format(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult {
let mut fmt = String::from("clangformat");
let mut style = String::from("google");
let mut style = String::from("webkit");
if !args.is_empty() {
// do not include ``` codeblocks into arg parsing.. lets just substr and replace args
let idx = msg.content.find('`');
Expand All @@ -34,7 +34,13 @@ pub async fn format(ctx: &Context, msg: &Message, mut args: Args) -> CommandResu

let data = ctx.data.read().await;
let comp_mgr = data.get::<CompilerCache>().unwrap().read().await;
let gbolt = &comp_mgr.gbolt;
if comp_mgr.gbolt.is_none() {
return Err(CommandError::from(
"Compiler Explorer service is currently down, please try again later.",
));
}

let gbolt = comp_mgr.gbolt.as_ref().unwrap();

// validate user input
for format in &gbolt.formats {
Expand Down Expand Up @@ -123,14 +129,18 @@ pub async fn format(ctx: &Context, msg: &Message, mut args: Args) -> CommandResu

msg.channel_id
.send_message(&ctx.http, |msg| {
msg.add_file(path.as_str()).content("Powered by Azure")
msg.add_file(path.as_str())
.content("Powered by godbolt.org")
})
.await?;
let _ = std::fs::remove_file(&path);
} else {
msg.reply(
&ctx.http,
format!("\n```{}\n{}```\n*Powered by Azure*", lang_code, answer),
format!(
"\n```{}\n{}```\n*Powered by godbolt.org*",
lang_code, answer
),
)
.await?;
}
Expand Down
Loading

0 comments on commit e95850e

Please sign in to comment.