Struct tpnote_lib::context::Context

source ·
pub struct Context {
    pub path: PathBuf,
    pub dir_path: PathBuf,
    pub root_path: PathBuf,
    /* private fields */
}
Expand description

Tiny wrapper around “Tera context” with some additional information.

Fields§

§path: PathBuf

First positional command line argument.

§dir_path: PathBuf

The directory (only) path corresponding to the first positional command line argument. The is our working directory and the directory where the note file is (will be) located.

§root_path: PathBuf

dir_path is a subdirectory of root_path. root_path is the first directory, that upwards from dir_path, contains a file named FILENAME_ROOT_PATH_MARKER (or, / if not marker file can be found). The root directory is interpreted by Tp-Note’s viewer as its base directory: only files within this directory are served.

Implementations§

source§

impl Context

A thin wrapper around tera::Context storing some additional information.

source

pub fn from(path: &Path) -> Self

Constructor: path is the first positional command line parameter <path> (see man page). path must point to a directory or a file.

A copy of path is stored in self.ct as key TMPL_VAR_PATH. It directory path as key TMPL_VAR_DIR_PATH.

use std::path::Path;
use tpnote_lib::settings::ENV_VAR_TPNOTE_EXTENSION_DEFAULT;
use tpnote_lib::settings::update_settings;
use tpnote_lib::config::TMPL_VAR_DIR_PATH;
use tpnote_lib::config::TMPL_VAR_PATH;
use tpnote_lib::context::Context;
std::env::remove_var(ENV_VAR_TPNOTE_EXTENSION_DEFAULT);
update_settings().unwrap();

let mut context = Context::from(&Path::new("/path/to/mynote.md"));

assert_eq!(context.path, Path::new("/path/to/mynote.md"));
assert_eq!(context.dir_path, Path::new("/path/to/"));
assert_eq!(&context.get(TMPL_VAR_PATH).unwrap().to_string(),
            r#""/path/to/mynote.md""#);
assert_eq!(&context.get(TMPL_VAR_DIR_PATH).unwrap().to_string(),
            r#""/path/to""#);
source

pub fn insert_content( &mut self, tmpl_var: &str, tmpl_var_header: &str, input: &impl Content ) -> Result<(), NoteError>

Inserts clipboard or stdin data into the context. The data may contain some copied text with or without a YAML header. The latter usually carries front matter variable. These are added separately via insert_front_matter(). The input data below is registered with the key name given by tmpl_var. Typical names are "clipboard" or "stdin". If the below input contains a valid YAML header, it will be registered in the context with the key name given by tmpl_var_header. This string is typically one of clipboard_header or std_header. The raw data that will be inserted into the context.

use std::path::Path;
use tpnote_lib::settings::ENV_VAR_TPNOTE_EXTENSION_DEFAULT;
use tpnote_lib::settings::update_settings;
use tpnote_lib::context::Context;
use tpnote_lib::content::Content;
use tpnote_lib::content::ContentString;
std::env::remove_var(ENV_VAR_TPNOTE_EXTENSION_DEFAULT);
update_settings().unwrap();

let mut context = Context::from(&Path::new("/path/to/mynote.md"));

context.insert_content("clipboard", "clipboard_header",
     &ContentString::from(String::from("Data from clipboard.")));
assert_eq!(&context.get("clipboard").unwrap().to_string(),
    "\"Data from clipboard.\"");

context.insert_content("stdin", "stdin_header",
     &ContentString::from("---\ntitle: \"My Stdin.\"\n---\nbody".to_string()));
assert_eq!(&context.get("stdin").unwrap().to_string(),
    r#""body""#);
assert_eq!(&context.get("stdin_header").unwrap().to_string(),
    r#""title: \"My Stdin.\"""#);
// "fm_title" is dynamically generated from the header variable "title".
assert_eq!(&context.get("fm_title").unwrap().to_string(),
    r#""My Stdin.""#);

Methods from Deref<Target = Context>§

source

pub fn insert<T, S>(&mut self, key: S, val: &T)where T: Serialize + ?Sized, S: Into<String>,

Converts the val parameter to Value and insert it into the context.

Panics if the serialization fails.

let mut context = tera::Context::new();
context.insert("number_users", &42);
source

pub fn try_insert<T, S>(&mut self, key: S, val: &T) -> Result<(), Error>where T: Serialize + ?Sized, S: Into<String>,

Converts the val parameter to Value and insert it into the context.

Returns an error if the serialization fails.

let mut context = Context::new();
// user is an instance of a struct implementing `Serialize`
if let Err(_) = context.try_insert("number_users", &user) {
    // Serialization failed
}
source

pub fn extend(&mut self, source: Context)

Appends the data of the source parameter to self, overwriting existing keys. The source context will be dropped.

let mut target = Context::new();
target.insert("a", &1);
target.insert("b", &2);
let mut source = Context::new();
source.insert("b", &3);
source.insert("d", &4);
target.extend(source);
source

pub fn get(&self, index: &str) -> Option<&Value>

Returns the value at a given key index.

source

pub fn remove(&mut self, index: &str) -> Option<Value>

Remove a key from the context, returning the value at the key if the key was previously inserted into the context.

source

pub fn contains_key(&self, index: &str) -> bool

Checks if a value exists at a specific index.

Trait Implementations§

source§

impl Clone for Context

source§

fn clone(&self) -> Context

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Context

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Deref for Context

Auto-dereference for convenient access to tera::Context.

§

type Target = Context

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for Context

Auto-dereference for convenient access to tera::Context.

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl PartialEq<Context> for Context

source§

fn eq(&self, other: &Context) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl StructuralPartialEq for Context

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

§

impl<T> Pointable for T

§

const ALIGN: usize = _

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for Twhere V: MultiLane<T>,

§

fn vzip(self) -> V