Skip to content
This repository has been archived by the owner on Jun 16, 2022. It is now read-only.

Commit

Permalink
Added loading templates from files
Browse files Browse the repository at this point in the history
  • Loading branch information
ADRFranklin committed Sep 30, 2019
1 parent fdd192c commit 23aa6ad
Show file tree
Hide file tree
Showing 6 changed files with 85 additions and 18 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
name = "pawn-templates"
version = "1.2.0"
authors = ["Southclaws <[email protected]>", "Arron (Michael) Franklin"]
edition = "2018"

[lib]
name = "pawn_templates"
Expand Down
7 changes: 4 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
extern crate samp;
extern crate liquid;
extern crate log;
extern crate samp;

mod plugin;

use std::collections::HashMap;
use crate::plugin::*;
use samp::initialize_plugin;
use std::collections::HashMap;

initialize_plugin!(
natives: [
Expand All @@ -15,6 +15,7 @@ initialize_plugin!(
Templates::make_template_var_int,
Templates::make_template_var_float,
Templates::make_template_var_string,
Templates::load_template_from_file,
],
{
let samp_logger = samp::plugin::logger()
Expand All @@ -35,4 +36,4 @@ initialize_plugin!(
globals: liquid::value::Object::new()
}
}
);
);
80 changes: 65 additions & 15 deletions src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ use log::error;
use samp::native;
use samp::prelude::*;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::Read;

pub struct Templates {
pub pool: HashMap<i32, liquid::Template>,
Expand Down Expand Up @@ -33,18 +36,14 @@ impl ArgumentPairType {
impl Templates {
#[native(name = "CreateTemplate")]
pub fn create_template(&mut self, _: &Amx, template: AmxString) -> AmxResult<i32> {
let parser = liquid::ParserBuilder::with_liquid().build().unwrap();

let t = match parser.parse(&template.to_string()) {
let ret = match self.make_template(template.to_string()) {
Ok(v) => v,
Err(e) => {
error!("{}", e);
Err(_) => {
return Ok(1);
}
};

let id = self.alloc(t);
return Ok(id);
Ok(ret)
}

#[native(raw, name = "RenderTemplate")]
Expand Down Expand Up @@ -96,7 +95,7 @@ impl Templates {
}
ArgumentPairType::Float => {
let value = params.next::<Ref<f32>>().unwrap();
variables.insert(key.into(), liquid::value::Value::scalar(*value as f64));
variables.insert(key.into(), liquid::value::Value::scalar(f64::from(*value)));
}
_ => return Ok(3),
}
Expand All @@ -113,7 +112,7 @@ impl Templates {
let mut dest = output_str.into_sized_buffer(output_len);
let _ = samp::cell::string::put_in_buffer(&mut dest, &output);

return Ok(0);
Ok(0)
}

#[native(name = "MakeTemplateVarInt")]
Expand Down Expand Up @@ -141,7 +140,7 @@ impl Templates {
self.globals
.insert(namespace_str.into(), Value::Object(variable));

return Ok(0);
Ok(0)
}

#[native(name = "MakeTemplateVarFloat")]
Expand All @@ -165,11 +164,11 @@ impl Templates {
}

let mut variable: Object = self.get_global_variables(&namespace_str);
variable.insert(key_str.into(), Value::scalar(value as f64));
variable.insert(key_str.into(), Value::scalar(f64::from(value)));
self.globals
.insert(namespace_str.into(), Value::Object(variable));

return Ok(0);
Ok(0)
}

#[native(name = "MakeTemplateVarString")]
Expand Down Expand Up @@ -197,7 +196,43 @@ impl Templates {
self.globals
.insert(namespace_str.into(), Value::Object(variable));

return Ok(0);
Ok(0)
}

#[native(name = "LoadTemplateFromFile")]
pub fn load_template_from_file(&mut self, _: &Amx, path: AmxString) -> AmxResult<i32> {
let path_str = path.to_string();
if path_str.is_empty() {
error!("path expected a string, none given.");
return Ok(1);
}
let current_path = &path_str;
let mut file = match File::open(current_path) {
Ok(file) => file,
Err(_) => {
error!(
"the file could not be found at the path: {}",
path_str.clone()
);
return Ok(1);
}
};

let mut file_contents = String::new();
match file.read_to_string(&mut file_contents) {
Err(e) => {
error!("{}", e);
return Ok(1);
}
Ok(v) => v,
};

let ret = match self.make_template(file_contents) {
Ok(v) => v,
Err(_) => return Ok(1),
};

Ok(ret)
}

fn alloc(&mut self, template: liquid::Template) -> i32 {
Expand All @@ -206,17 +241,32 @@ impl Templates {
self.id
}

fn get_global_variables(&mut self, namespace: &String) -> Object {
fn get_global_variables(&mut self, namespace: &str) -> Object {
let mut object = Object::new();
for (key, value) in self.globals.iter() {
if key.to_string() == *namespace {
if key == namespace {
object = value.as_object().unwrap().clone();
break;
}
}

object
}

fn make_template(&mut self, template: String) -> Result<i32, Box<dyn Error>> {
let parser = liquid::ParserBuilder::with_liquid().build().unwrap();

let t = match parser.parse(&template) {
Ok(v) => v,
Err(e) => {
error!("{}", e);
return Ok(1);
}
};

let id = self.alloc(t);
Ok(id)
}
}

impl Default for Templates {
Expand Down
1 change: 1 addition & 0 deletions templates.inc
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ native RenderTemplate(Template:id, dest[], len, ...);
native MakeTemplateVarInt(const namespace[], const key[], value);
native MakeTemplateVarFloat(const namespace[], const key[], Float:value);
native MakeTemplateVarString(const namespace[], const key[], const value[]);
native Template:LoadTemplateFromFile(const path[]);
13 changes: 13 additions & 0 deletions test.pwn
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,19 @@ Test:GlobalVariables() {
new rendered[64];
new ret = RenderTemplate(t, rendered, sizeof rendered);

printf("ret: %d rendered: '%s'", ret, rendered);
ASSERT(ret == 0);
ASSERT(strcmp(rendered, "Name: Southclaws, ID: 3720, Pos X: 5.5") == 0);
}

Test:LoadFromFile() {
MakeTemplateVarString("player", "name", "Southclaws");
MakeTemplateVarInt("player", "id", 3720);
MakeTemplateVarFloat("player", "pos_x", 5.5);
new Template:t = LoadTemplateFromFile("scriptfiles/file.txt");
new rendered[64];
new ret = RenderTemplate(t, rendered, sizeof rendered);

printf("ret: %d rendered: '%s'", ret, rendered);
ASSERT(ret == 0);
ASSERT(strcmp(rendered, "Name: Southclaws, ID: 3720, Pos X: 5.5") == 0);
Expand Down
1 change: 1 addition & 0 deletions test/scriptfiles/file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Name: {{ player.name }}, ID: {{ player.id }}, Pos X: {{ player.pos_x }}

0 comments on commit 23aa6ad

Please sign in to comment.