Compare commits

...

36 commits
0.4.0 ... main

Author SHA1 Message Date
yggverse
2a51b67387 update glib version to 0.21.0, update crate version to 0.7.0 2025-07-23 05:08:52 +03:00
yggverse
f83d049c60 update version 2025-03-28 00:30:15 +02:00
yggverse
2d98b66d82 fix clippy 2025-03-21 17:47:43 +02:00
yggverse
459626acb4 update minor version 2025-03-21 17:03:10 +02:00
yggverse
ff70e5410a update examples 2025-03-21 17:02:58 +02:00
yggverse
678f906f48 remove unspecified inline code tag support 2025-03-21 17:02:50 +02:00
yggverse
10ff400d8f update version 2025-03-18 01:05:23 +02:00
yggverse
25a45337ff trim members 2025-03-17 22:23:07 +02:00
yggverse
841ee2036e fix namespace example 2025-03-17 21:42:09 +02:00
yggverse
22a05a975c remove regex dependency, rename constructor, add tests 2025-03-17 21:39:07 +02:00
yggverse
0c90bbafba update headers 2025-03-17 02:46:13 +02:00
yggverse
0c6ba0c87c add trait example 2025-03-17 02:42:22 +02:00
yggverse
92e1557c9c update readme 2025-03-17 02:39:26 +02:00
yggverse
96f7d648b6 remove regex dependency, rename constructor, implement zero-copy trait 2025-03-17 02:09:52 +02:00
yggverse
7f3ea670f1 add new line separator 2025-03-16 19:54:36 +02:00
yggverse
83ec663929 skip regex operations on tag mismatch subject 2025-03-16 19:53:29 +02:00
yggverse
7345400172 update readme 2025-03-16 19:43:15 +02:00
yggverse
8eaad1dac9 enshort var name 2025-03-16 18:50:56 +02:00
yggverse
a5638fde33 implement tests 2025-03-16 18:46:12 +02:00
yggverse
d72575fdc5 simplify 2025-03-16 17:55:38 +02:00
yggverse
eedd7a73ff trim once 2025-03-16 17:53:03 +02:00
yggverse
039b1db935 test Level member 2025-03-16 17:37:20 +02:00
yggverse
f550041b55 implement test 2025-03-16 17:28:56 +02:00
yggverse
9392b39327 remove duplicated header anchors 2025-03-16 16:44:58 +02:00
yggverse
3e16995e00 reorganize header component 2025-03-16 16:39:02 +02:00
yggverse
c29f1ba529 separate traits 2025-03-16 16:38:38 +02:00
yggverse
5b751e3c7a change result data type to &str 2025-03-16 15:53:24 +02:00
yggverse
7802869d0d remove regex dependency, rename constructor, implement Gemtext trait 2025-03-16 15:43:27 +02:00
yggverse
9d27cdfb49 update readme 2025-03-16 14:45:13 +02:00
yggverse
bf4ac4bd27 rename constructor, implement zero-copy trait, remove extra regex parser 2025-03-16 14:43:08 +02:00
yggverse
1b43f6aeaf fix method name, add missed test condition 2025-03-16 13:47:00 +02:00
yggverse
9696efa02d update versions 2025-03-16 13:43:02 +02:00
yggverse
23b04f26ec update examples 2025-03-16 13:42:38 +02:00
yggverse
4ce1b20bf7 rename constructor, implement zero-copy trait, remove extra regex parser 2025-03-16 13:42:23 +02:00
yggverse
bab4e03940 define child namespaces 2025-03-16 13:12:59 +02:00
yggverse
7826104978 update version 2025-03-15 17:08:51 +02:00
17 changed files with 628 additions and 363 deletions

View file

@ -1,7 +1,7 @@
[package] [package]
name = "ggemtext" name = "ggemtext"
version = "0.4.0" version = "0.7.0"
edition = "2021" edition = "2024"
license = "MIT" license = "MIT"
readme = "README.md" readme = "README.md"
description = "Glib-oriented Gemtext API" description = "Glib-oriented Gemtext API"
@ -17,5 +17,5 @@ repository = "https://github.com/YGGverse/ggemtext"
[dependencies.glib] [dependencies.glib]
package = "glib" package = "glib"
version = "0.20.9" version = "0.21.0"
features = ["v2_66"] features = ["v2_66"]

137
README.md
View file

@ -20,20 +20,6 @@ cargo add ggemtext
Line parser, useful for [TextTag](https://docs.gtk.org/gtk4/class.TextTag.html) operations in [TextBuffer](https://docs.gtk.org/gtk4/class.TextBuffer.html) context. Line parser, useful for [TextTag](https://docs.gtk.org/gtk4/class.TextTag.html) operations in [TextBuffer](https://docs.gtk.org/gtk4/class.TextBuffer.html) context.
**Connect dependencies**
``` rust
use ggemtext::line::{
code::{Inline, Multiline},
header::{Header, Level},
link::Link,
list::List,
quote::Quote,
};
```
**Prepare document**
Iterate Gemtext lines to continue with [Line](#Line) API: Iterate Gemtext lines to continue with [Line](#Line) API:
``` rust ``` rust
@ -44,89 +30,108 @@ for line in gemtext.lines() {
#### Code #### Code
##### Inline
``` rust ``` rust
match Inline::from("```inline```") { use ggemtext::line::Code;
Some(inline) => assert_eq!(inline.value, "inline"), match Code::begin_from("```alt") {
None => assert!(false), Some(mut code) => {
}; assert!(code.continue_from("line 1").is_ok());
``` assert!(code.continue_from("line 2").is_ok());
assert!(code.continue_from("```").is_ok()); // complete
##### Multiline assert!(code.is_completed);
assert_eq!(code.alt, Some("alt".into()));
``` rust assert_eq!(code.value.len(), 12 + 2); // +NL
match Multiline::begin_from("```alt") { }
Some(mut multiline) => { None => unreachable!(),
assert!(Multiline::continue_from(&mut multiline, "line 1").is_ok());
assert!(Multiline::continue_from(&mut multiline, "line 2").is_ok());
assert!(Multiline::continue_from(&mut multiline, "```").is_ok()); // complete
assert!(multiline.completed);
assert_eq!(multiline.alt, Some("alt".into()));
assert_eq!(multiline.buffer.len(), 3);
} }
None => assert!(false),
};
``` ```
#### Header #### Header
**Struct**
``` rust ``` rust
match Header::from("# H1") { use ggemtext::line::{Header, header::Level};
match Header::parse("# H1") {
Some(h1) => { Some(h1) => {
assert_eq!(h1.level as u8, Level::H1 as u8); assert_eq!(h1.level as u8, Level::H1 as u8);
assert_eq!(h1.value, "H1"); assert_eq!(h1.value, "H1");
} }
None => assert!(false), None => unreachable!(),
}; // H1, H2, H3 } // H1, H2, H3
```
**Trait**
``` rust
use ggemtext::line::header::{Gemtext, Level};
assert_eq!("# H1".as_value(), Some("H1"));
assert_eq!("H1".to_source(&Level::H1), "# H1");
// H1, H2, H3
``` ```
#### Link #### Link
``` rust ``` rust
match Link::from( use ggemtext::line::Link;
"=> gemini://geminiprotocol.net 1965-01-19 Gemini",
None, // absolute path given, base not wanted
Some(&glib::TimeZone::local()),
) {
Some(link) => {
// Alt
assert_eq!(link.alt, Some("Gemini".into()));
// Date const SOURCE: &str = "=> gemini://geminiprotocol.net 1965-01-19 Gemini";
match link.timestamp {
Some(timestamp) => {
assert_eq!(timestamp.year(), 1965);
assert_eq!(timestamp.month(), 1);
assert_eq!(timestamp.day_of_month(), 19);
}
None => assert!(false),
}
// URI let link = Link::parse(SOURCE).unwrap();
assert_eq!(link.uri.to_string(), "gemini://geminiprotocol.net");
} assert_eq!(link.alt, Some("1965-01-19 Gemini".to_string()));
None => assert!(false), assert_eq!(link.url, "gemini://geminiprotocol.net");
};
let uri = link.uri(None).unwrap();
assert_eq!(uri.scheme(), "gemini");
assert_eq!(uri.host().unwrap(), "geminiprotocol.net");
let time = link.time(Some(&glib::TimeZone::local())).unwrap();
assert_eq!(time.year(), 1965);
assert_eq!(time.month(), 1);
assert_eq!(time.day_of_month(), 19);
assert_eq!(link.to_source(), SOURCE);
``` ```
#### List #### List
**Struct**
``` rust ``` rust
match List::from("* Item") { use ggemtext::line::List;
match List::parse("* Item") {
Some(list) => assert_eq!(list.value, "Item"), Some(list) => assert_eq!(list.value, "Item"),
None => assert!(false), None => unreachable!(),
}; }
```
**Trait**
``` rust
use ggemtext::line::list::Gemtext;
assert_eq!("* Item".as_value(), Some("Item"))
assert_eq!("Item".to_source(), "* Item")
``` ```
#### Quote #### Quote
**Struct**
``` rust ``` rust
match Quote::from("> Quote") { use ggemtext::line::Quote;
match Quote::parse("> Quote") {
Some(quote) => assert_eq!(quote.value, "Quote"), Some(quote) => assert_eq!(quote.value, "Quote"),
None => assert!(false), None => unreachable!(),
}; }
```
**Trait**
``` rust
use ggemtext::line::quote::Gemtext;
assert_eq!("> Quote".as_value(), Some("Quote"))
assert_eq!("Quote".to_source(), "> Quote")
``` ```
## Integrations ## Integrations

View file

@ -3,3 +3,9 @@ pub mod header;
pub mod link; pub mod link;
pub mod list; pub mod list;
pub mod quote; pub mod quote;
pub use code::Code;
pub use header::Header;
pub use link::Link;
pub use list::List;
pub use quote::Quote;

View file

@ -1,5 +1,90 @@
pub mod inline; pub mod error;
pub mod multiline; pub use error::Error;
pub use inline::Inline; pub const TAG: &str = "```";
pub use multiline::Multiline; pub const NEW_LINE: char = '\n';
/// Multi-line [preformatted](https://geminiprotocol.net/docs/gemtext-specification.gmi#in-pre-formatted-mode) entity holder
pub struct Code {
pub alt: Option<String>,
pub value: String,
pub is_completed: bool,
}
impl Code {
// Constructors
/// Search in line string for tag open,
/// return Self constructed on success or None
pub fn begin_from(line: &str) -> Option<Self> {
if line.starts_with(TAG) {
let alt = line.trim_start_matches(TAG).trim();
return Some(Self {
alt: match alt.is_empty() {
true => None,
false => Some(alt.to_string()),
},
value: String::new(),
is_completed: false,
});
}
None
}
/// Continue preformatted buffer from line string,
/// set `completed` as True on close tag found
pub fn continue_from(&mut self, line: &str) -> Result<(), Error> {
// Make sure buffer not completed yet
if self.is_completed {
return Err(Error::Completed);
}
// Append to value, trim close tag on exists
self.value.push_str(line.trim_end_matches(TAG));
// Line contain close tag
if line.ends_with(TAG) {
self.is_completed = true;
} else {
self.value.push(NEW_LINE);
}
Ok(())
}
// Converters
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) format
pub fn to_source(&self) -> String {
format!(
"{TAG}{}{NEW_LINE}{}{TAG}",
match &self.alt {
Some(alt) => format!(" {}", alt.trim()),
None => String::new(),
},
self.value
)
}
}
#[test]
fn test() {
match Code::begin_from("```alt") {
Some(mut code) => {
assert!(code.continue_from("line 1").is_ok());
assert!(code.continue_from("line 2").is_ok());
assert!(code.continue_from("```").is_ok()); // complete
assert!(code.is_completed);
assert_eq!(code.alt, Some("alt".into()));
assert_eq!(code.value.len(), 12 + 2); // +NL
assert_eq!(
code.to_source(),
format!("{TAG} alt{NEW_LINE}line 1{NEW_LINE}line 2{NEW_LINE}{TAG}")
)
}
None => unreachable!(),
}
}

View file

@ -1,26 +0,0 @@
use glib::{Regex, RegexCompileFlags, RegexMatchFlags};
/// Inline [preformatted](https://geminiprotocol.net/docs/gemtext-specification.gmi#in-pre-formatted-mode) entity holder
pub struct Inline {
pub value: String,
}
impl Inline {
// Constructors
/// Parse `Self` from line string
pub fn from(line: &str) -> Option<Self> {
// Parse line
let regex = Regex::split_simple(
r"^`{3}([^`]+)`{3}$",
line,
RegexCompileFlags::DEFAULT,
RegexMatchFlags::DEFAULT,
);
// Extract formatted value
Some(Self {
value: regex.get(1)?.trim().to_string(),
})
}
}

View file

@ -1,58 +0,0 @@
pub mod error;
pub use error::Error;
// Shared defaults
pub const NEW_LINE: char = '\n';
pub const TAG: &str = "```";
/// Multi-line [preformatted](https://geminiprotocol.net/docs/gemtext-specification.gmi#in-pre-formatted-mode) entity holder
pub struct Multiline {
pub alt: Option<String>,
pub value: String,
pub completed: bool,
}
impl Multiline {
// Constructors
/// Search in line string for tag open,
/// return Self constructed on success or None
pub fn begin_from(line: &str) -> Option<Self> {
if line.starts_with(TAG) {
let alt = line.trim_start_matches(TAG).trim();
return Some(Self {
alt: match alt.is_empty() {
true => None,
false => Some(alt.to_string()),
},
value: String::new(),
completed: false,
});
}
None
}
/// Continue preformatted buffer from line string,
/// set `completed` as True on close tag found
pub fn continue_from(&mut self, line: &str) -> Result<(), Error> {
// Make sure buffer not completed yet
if self.completed {
return Err(Error::Completed);
}
// Append to value, trim close tag on exists
self.value.push_str(line.trim_end_matches(TAG));
// Line contain close tag
if line.ends_with(TAG) {
self.completed = true;
} else {
self.value.push(NEW_LINE);
}
Ok(())
}
}

View file

@ -1,40 +1,76 @@
use glib::{Regex, RegexCompileFlags, RegexMatchFlags}; pub mod gemtext;
pub mod level;
/// [Header](https://geminiprotocol.net/docs/gemtext-specification.gmi#heading-lines) type holder pub use gemtext::Gemtext;
pub enum Level { pub use level::Level;
H1,
H2,
H3,
}
/// [Header](https://geminiprotocol.net/docs/gemtext-specification.gmi#heading-lines) entity holder /// [Header](https://geminiprotocol.net/docs/gemtext-specification.gmi#heading-lines) entity holder
pub struct Header { pub struct Header {
pub value: String,
pub level: Level, pub level: Level,
pub value: String,
} }
impl Header { impl Header {
// Constructors // Constructors
/// Parse `Self` from line string /// Parse `Self` from line string
pub fn from(line: &str) -> Option<Self> { pub fn parse(line: &str) -> Option<Self> {
// Parse line if let Some(value) = line.as_h1_value() {
let regex = Regex::split_simple( return Some(Self {
r"^(#{1,3})\s*(.+)$", level: Level::H1,
line, value: value.to_string(),
RegexCompileFlags::DEFAULT, });
RegexMatchFlags::DEFAULT, }
); if let Some(value) = line.as_h2_value() {
return Some(Self {
level: Level::H2,
value: value.to_string(),
});
}
if let Some(value) = line.as_h3_value() {
return Some(Self {
level: Level::H3,
value: value.to_string(),
});
}
None
}
// Result // Converters
Some(Self {
level: match regex.get(1)?.len() { /// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
1 => Level::H1, pub fn to_source(&self) -> String {
2 => Level::H2, self.value.to_source(&self.level)
3 => Level::H3,
_ => return None,
},
value: regex.get(2)?.trim().to_string(),
})
} }
} }
#[test]
fn test() {
fn test(source: &str, value: &str, level: Level) {
fn f(s: &str) -> String {
s.chars().filter(|&c| c != ' ').collect()
}
let header = Header::parse(source).unwrap();
assert_eq!(header.value, value);
assert_eq!(header.level.as_tag(), level.as_tag());
assert_eq!(f(&header.to_source()), f(source));
}
// h1
test("# H1", "H1", Level::H1);
test("# H1 ", "H1", Level::H1);
test("#H1", "H1", Level::H1);
test("#H1 ", "H1", Level::H1);
// h2
test("## H2", "H2", Level::H2);
test("## H2 ", "H2", Level::H2);
test("##H2", "H2", Level::H2);
test("##H2 ", "H2", Level::H2);
// h3
test("### H3", "H3", Level::H3);
test("### H3 ", "H3", Level::H3);
test("###H3", "H3", Level::H3);
test("###H3 ", "H3", Level::H3);
// other
assert!(Header::parse("H").is_none());
assert!(Header::parse("#### H").is_none())
}

View file

@ -0,0 +1,98 @@
use super::Level;
pub trait Gemtext {
/// Get [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) value for `Self`
fn as_value(&self) -> Option<&str>;
/// Get parsed H1 header value for `Self`
fn as_h1_value(&self) -> Option<&str>;
/// Get parsed H2 header value `Self`
fn as_h2_value(&self) -> Option<&str>;
/// Get parsed H3 header value `Self`
fn as_h3_value(&self) -> Option<&str>;
/// Get parsed header value `Self` match `Level`
fn as_value_match_level(&self, level: Level) -> Option<&str>;
/// Convert `Self` to `Level`
fn to_level(&self) -> Option<Level>;
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
fn to_source(&self, level: &Level) -> String;
}
impl Gemtext for str {
fn as_value(&self) -> Option<&str> {
if let Some(value) = self.as_h1_value() {
return Some(value);
}
if let Some(value) = self.as_h2_value() {
return Some(value);
}
if let Some(value) = self.as_h3_value() {
return Some(value);
}
None
}
fn as_h1_value(&self) -> Option<&str> {
self.as_value_match_level(Level::H1)
}
fn as_h2_value(&self) -> Option<&str> {
self.as_value_match_level(Level::H2)
}
fn as_h3_value(&self) -> Option<&str> {
self.as_value_match_level(Level::H3)
}
fn as_value_match_level(&self, level: Level) -> Option<&str> {
self.strip_prefix(level.as_tag())
.map(|postfix| postfix.trim())
.filter(|value| !value.starts_with(Level::H1.as_tag()))
}
fn to_level(&self) -> Option<Level> {
if self.as_h1_value().is_some() {
return Some(Level::H1);
}
if self.as_h2_value().is_some() {
return Some(Level::H2);
}
if self.as_h3_value().is_some() {
return Some(Level::H3);
}
None
}
fn to_source(&self, level: &Level) -> String {
format!("{} {}", level.as_tag(), self.trim())
}
}
#[test]
fn test() {
const VALUE: &str = "H";
let mut value: Option<&str> = Some(VALUE);
for t in ["#", "##", "###", "####"] {
if t.len() > 3 {
value = None;
}
assert_eq!(format!("{t}{VALUE}").as_value(), value);
assert_eq!(format!("{t}{VALUE} ").as_value(), value);
assert_eq!(format!("{t} {VALUE}").as_value(), value);
assert_eq!(format!("{t} {VALUE} ").as_value(), value);
}
fn to_source(l: &Level) {
assert_eq!(VALUE.to_source(l), format!("{} {VALUE}", l.as_tag()));
}
to_source(&Level::H1);
to_source(&Level::H2);
to_source(&Level::H3);
fn to_level(l: &Level) {
fn assert(s: String, l: &str) {
assert_eq!(s.to_level().unwrap().as_tag(), l);
}
let t = l.as_tag();
assert(format!("{t} {VALUE}"), t);
assert(format!("{t} {VALUE} "), t);
assert(format!("{t}{VALUE} "), t);
assert(format!("{t} {VALUE} "), t);
}
to_level(&Level::H1);
to_level(&Level::H2);
to_level(&Level::H3);
}

16
src/line/header/level.rs Normal file
View file

@ -0,0 +1,16 @@
/// [Header](https://geminiprotocol.net/docs/gemtext-specification.gmi#heading-lines) type holder
pub enum Level {
H1,
H2,
H3,
}
impl Level {
pub fn as_tag(&self) -> &str {
match self {
Level::H1 => "#",
Level::H2 => "##",
Level::H3 => "###",
}
}
}

View file

@ -1,96 +1,119 @@
use glib::{DateTime, Regex, RegexCompileFlags, RegexMatchFlags, TimeZone, Uri, UriFlags}; use glib::{DateTime, TimeZone, Uri, UriFlags};
const S: char = ' ';
pub const TAG: &str = "=>";
/// [Link](https://geminiprotocol.net/docs/gemtext-specification.gmi#link-lines) entity holder /// [Link](https://geminiprotocol.net/docs/gemtext-specification.gmi#link-lines) entity holder
pub struct Link { pub struct Link {
pub alt: Option<String>, // [optional] alternative link description /// For performance reasons, hold Gemtext date and alternative together as the optional String
pub timestamp: Option<DateTime>, // [optional] valid link DateTime object /// * to extract valid [DateTime](https://docs.gtk.org/glib/struct.DateTime.html) use `time` implementation method
pub uri: Uri, // [required] valid link URI object pub alt: Option<String>,
/// For performance reasons, hold URL as the raw String
/// * to extract valid [Uri](https://docs.gtk.org/glib/struct.Uri.html) use `uri` implementation method
pub url: String,
} }
impl Link { impl Link {
// Constructors // Constructors
/// Parse `Self` from line string /// Parse `Self` from line string
pub fn from(line: &str, base: Option<&Uri>, timezone: Option<&TimeZone>) -> Option<Self> { pub fn parse(line: &str) -> Option<Self> {
// Define initial values let l = line.strip_prefix(TAG)?.trim();
let mut alt = None; let u = l.find(S).map_or(l, |i| &l[..i]);
let mut timestamp = None; if u.is_empty() {
return None;
}
Some(Self {
alt: l
.get(u.len()..)
.map(|a| a.trim())
.filter(|a| !a.is_empty())
.map(|a| a.to_string()),
url: u.to_string(),
})
}
// Begin line parse // Converters
let regex = Regex::split_simple(
r"^=>\s*([^\s]+)\s*(\d{4}-\d{2}-\d{2})?\s*(.+)?$", /// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
line, pub fn to_source(&self) -> String {
RegexCompileFlags::DEFAULT, let mut s = String::with_capacity(
RegexMatchFlags::DEFAULT, TAG.len() + self.url.len() + self.alt.as_ref().map_or(0, |a| a.len()) + 2,
); );
s.push_str(TAG);
s.push(S);
s.push_str(self.url.trim());
if let Some(ref alt) = self.alt {
s.push(S);
s.push_str(alt.trim());
}
s
}
// Detect address required to continue // Getters
let mut unresolved_address = regex.get(1)?.to_string();
/// Get valid [DateTime](https://docs.gtk.org/glib/struct.DateTime.html) for `Self`
pub fn time(&self, timezone: Option<&TimeZone>) -> Option<DateTime> {
let a = self.alt.as_ref()?;
let t = &a[..a.find(S).unwrap_or(a.len())];
DateTime::from_iso8601(&format!("{t}T00:00:00"), timezone).ok()
}
/// Get valid [Uri](https://docs.gtk.org/glib/struct.Uri.html) for `Self`
pub fn uri(&self, base: Option<&Uri>) -> Option<Uri> {
// Relative scheme patch // Relative scheme patch
// https://datatracker.ietf.org/doc/html/rfc3986#section-4.2 // https://datatracker.ietf.org/doc/html/rfc3986#section-4.2
if let Some(p) = unresolved_address.strip_prefix("//") { let unresolved_address = match self.url.strip_prefix("//") {
Some(p) => {
let b = base?; let b = base?;
let postfix = p.trim_start_matches(":"); let s = p.trim_start_matches(":");
unresolved_address = format!( &format!(
"{}://{}", "{}://{}",
b.scheme(), b.scheme(),
if postfix.is_empty() { if s.is_empty() {
format!("{}/", b.host()?) format!("{}/", b.host()?)
} else { } else {
postfix.into() s.into()
} }
) )
} }
// Convert address to the valid URI None => &self.url,
let uri = match base { };
// Base conversion requested // Convert address to the valid URI,
Some(base_uri) => { // resolve to absolute URL format if the target is relative
// Convert relative address to absolute match base {
match Uri::resolve_relative( Some(base_uri) => match Uri::resolve_relative(
Some(&base_uri.to_str()), Some(&base_uri.to_str()),
unresolved_address.as_str(), unresolved_address,
UriFlags::NONE, UriFlags::NONE,
) { ) {
Ok(resolved_str) => { Ok(resolved_str) => Uri::parse(&resolved_str, UriFlags::NONE).ok(),
// Try convert string to the valid URI
match Uri::parse(&resolved_str, UriFlags::NONE) {
Ok(resolved_uri) => resolved_uri,
Err(_) => return None,
}
}
Err(_) => return None,
}
}
// Base resolve not requested
None => {
// Try convert address to valid URI
match Uri::parse(&unresolved_address, UriFlags::NONE) {
Ok(unresolved_uri) => unresolved_uri,
Err(_) => return None,
}
}
};
// Timestamp
if let Some(date) = regex.get(2) {
timestamp = match DateTime::from_iso8601(&format!("{date}T00:00:00"), timezone) {
Ok(value) => Some(value),
Err(_) => None, Err(_) => None,
},
None => Uri::parse(unresolved_address, UriFlags::NONE).ok(),
}
} }
} }
// Alt #[test]
if let Some(value) = regex.get(3) { fn test() {
if !value.is_empty() { use crate::line::Link;
alt = Some(value.to_string())
}
};
Some(Self { const SOURCE: &str = "=> gemini://geminiprotocol.net 1965-01-19 Gemini";
alt,
timestamp, let link = Link::parse(SOURCE).unwrap();
uri,
}) assert_eq!(link.alt, Some("1965-01-19 Gemini".to_string()));
} assert_eq!(link.url, "gemini://geminiprotocol.net");
let uri = link.uri(None).unwrap();
assert_eq!(uri.scheme(), "gemini");
assert_eq!(uri.host().unwrap(), "geminiprotocol.net");
let time = link.time(Some(&glib::TimeZone::local())).unwrap();
assert_eq!(time.year(), 1965);
assert_eq!(time.month(), 1);
assert_eq!(time.day_of_month(), 19);
assert_eq!(link.to_source(), SOURCE);
} }

View file

@ -1,4 +1,8 @@
use glib::{Regex, RegexCompileFlags, RegexMatchFlags}; pub mod gemtext;
pub use gemtext::Gemtext;
/// [List item](https://geminiprotocol.net/docs/gemtext-specification.gmi#list-items) tag
pub const TAG: char = '*';
/// [List](https://geminiprotocol.net/docs/gemtext-specification.gmi#list-items) entity holder /// [List](https://geminiprotocol.net/docs/gemtext-specification.gmi#list-items) entity holder
pub struct List { pub struct List {
@ -8,19 +12,27 @@ pub struct List {
impl List { impl List {
// Constructors // Constructors
/// Parse `Self` from line string /// Parse `Self` from [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
pub fn from(line: &str) -> Option<Self> { pub fn parse(line: &str) -> Option<Self> {
// Parse line
let regex = Regex::split_simple(
r"^\*\s*(.*)$",
line,
RegexCompileFlags::DEFAULT,
RegexMatchFlags::DEFAULT,
);
// Extract formatted value
Some(Self { Some(Self {
value: regex.get(1)?.trim().to_string(), value: line.as_value()?.to_string(),
}) })
} }
// Converters
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
pub fn to_source(&self) -> String {
self.value.to_source()
}
}
#[test]
fn test() {
const SOURCE: &str = "* Item";
const VALUE: &str = "Item";
let list = List::parse(SOURCE).unwrap();
assert_eq!(list.value, VALUE);
assert_eq!(list.to_source(), SOURCE);
} }

26
src/line/list/gemtext.rs Normal file
View file

@ -0,0 +1,26 @@
use super::TAG;
pub trait Gemtext {
/// Get [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) value for `Self`
fn as_value(&self) -> Option<&str>;
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
fn to_source(&self) -> String;
}
impl Gemtext for str {
fn as_value(&self) -> Option<&str> {
self.strip_prefix(TAG).map(|s| s.trim())
}
fn to_source(&self) -> String {
format!("{TAG} {}", self.trim())
}
}
#[test]
fn test() {
const SOURCE: &str = "* Item";
const VALUE: &str = "Item";
assert_eq!(SOURCE.as_value(), Some(VALUE));
assert_eq!(VALUE.to_source(), SOURCE)
}

View file

@ -1,4 +1,8 @@
use glib::{Regex, RegexCompileFlags, RegexMatchFlags}; pub mod gemtext;
pub use gemtext::Gemtext;
/// [Quote item](https://geminiprotocol.net/docs/gemtext-specification.gmi#quote-lines) tag
pub const TAG: char = '>';
/// [Quote](https://geminiprotocol.net/docs/gemtext-specification.gmi#quote-lines) entity holder /// [Quote](https://geminiprotocol.net/docs/gemtext-specification.gmi#quote-lines) entity holder
pub struct Quote { pub struct Quote {
@ -8,19 +12,28 @@ pub struct Quote {
impl Quote { impl Quote {
// Constructors // Constructors
/// Parse `Self` from line string /// Parse `Self` from [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
pub fn from(line: &str) -> Option<Self> { pub fn parse(line: &str) -> Option<Self> {
// Parse line
let regex = Regex::split_simple(
r"^>\s*(.*)$",
line,
RegexCompileFlags::DEFAULT,
RegexMatchFlags::DEFAULT,
);
// Extract formatted value
Some(Self { Some(Self {
value: regex.get(1)?.trim().to_string(), value: line.as_value()?.to_string(),
}) })
} }
// Converters
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
pub fn to_source(&self) -> String {
self.value.to_source()
}
}
#[test]
fn test() {
const SOURCE: &str = "> Quote";
const VALUE: &str = "Quote";
let quote = Quote::parse(SOURCE).unwrap();
assert_eq!(quote.value, VALUE);
assert_eq!(quote.to_source(), SOURCE);
} }

26
src/line/quote/gemtext.rs Normal file
View file

@ -0,0 +1,26 @@
use super::TAG;
pub trait Gemtext {
/// Get [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) value for `Self`
fn as_value(&self) -> Option<&str>;
/// Convert `Self` to [Gemtext](https://geminiprotocol.net/docs/gemtext-specification.gmi) line
fn to_source(&self) -> String;
}
impl Gemtext for str {
fn as_value(&self) -> Option<&str> {
self.strip_prefix(TAG).map(|s| s.trim())
}
fn to_source(&self) -> String {
format!("{TAG} {}", self.trim())
}
}
#[test]
fn test() {
const SOURCE: &str = "> Quote";
const VALUE: &str = "Quote";
assert_eq!(SOURCE.as_value(), Some(VALUE));
assert_eq!(VALUE.to_source(), SOURCE)
}

View file

@ -15,8 +15,6 @@
* Listing item 1 * Listing item 1
* Listing item 2 * Listing item 2
```inline code```
``` alt text ``` alt text
multi multi
preformatted line preformatted line

View file

@ -1,9 +1,6 @@
use ggemtext::line::{ use ggemtext::line::{
code::{Inline, Multiline}, Code, Link, List, Quote,
header::{Header, Level}, header::{Header, Level},
link::Link,
list::List,
quote::Quote,
}; };
use glib::{TimeZone, Uri, UriFlags}; use glib::{TimeZone, Uri, UriFlags};
@ -14,85 +11,69 @@ fn gemtext() {
match fs::read_to_string("tests/integration.gmi") { match fs::read_to_string("tests/integration.gmi") {
Ok(gemtext) => { Ok(gemtext) => {
// Init tags collection // Init tags collection
let mut code_inline: Vec<Inline> = Vec::new(); let mut code: Vec<Code> = Vec::new();
let mut code_multiline: Vec<Multiline> = Vec::new();
let mut headers: Vec<Header> = Vec::new(); let mut headers: Vec<Header> = Vec::new();
let mut links: Vec<Link> = Vec::new(); let mut links: Vec<Link> = Vec::new();
let mut list: Vec<List> = Vec::new(); let mut list: Vec<List> = Vec::new();
let mut quote: Vec<Quote> = Vec::new(); let mut quote: Vec<Quote> = Vec::new();
// Define preformatted buffer // Define preformatted buffer
let mut code_multiline_buffer: Option<Multiline> = None; let mut code_buffer: Option<Code> = None;
// Define base URI as integration.gmi contain one relative link // Define base URI as integration.gmi contain one relative link
let base = match Uri::parse("gemini://geminiprotocol.net", UriFlags::NONE) { let base = Uri::parse("gemini://geminiprotocol.net", UriFlags::NONE).unwrap();
Ok(uri) => Some(uri),
Err(_) => None,
};
// Define timezone as integration.gmi contain one links with date // Define timezone as integration.gmi contain one links with date
let timezone = Some(TimeZone::local()); let timezone = TimeZone::local();
// Parse document by line // Parse document by line
for line in gemtext.lines() { for line in gemtext.lines() {
// Inline code match code_buffer {
if let Some(result) = Inline::from(line) {
code_inline.push(result);
continue;
}
// Multiline code
match code_multiline_buffer {
None => { None => {
if let Some(code) = Multiline::begin_from(line) { if let Some(code) = Code::begin_from(line) {
code_multiline_buffer = Some(code); code_buffer = Some(code);
continue; continue;
} }
} }
Some(ref mut result) => { Some(ref mut c) => {
assert!(Multiline::continue_from(result, line).is_ok()); assert!(c.continue_from(line).is_ok());
if result.completed { if c.is_completed {
code_multiline.push(code_multiline_buffer.take().unwrap()); code.push(code_buffer.take().unwrap());
code_multiline_buffer = None; code_buffer = None;
} }
continue; continue;
} }
}; };
// Header // Header
if let Some(result) = Header::from(line) { if let Some(result) = Header::parse(line) {
headers.push(result); headers.push(result);
continue; continue;
} }
// Link // Link
if let Some(result) = Link::from(line, base.as_ref(), timezone.as_ref()) { if let Some(result) = Link::parse(line) {
links.push(result); links.push(result);
continue; continue;
} }
// List // List
if let Some(result) = List::from(line) { if let Some(result) = List::parse(line) {
list.push(result); list.push(result);
continue; continue;
} }
// Quote // Quote
if let Some(result) = Quote::from(line) { if let Some(result) = Quote::parse(line) {
quote.push(result); quote.push(result);
continue; continue;
} }
} }
// Validate inline code // Validate code
assert_eq!(code_inline.len(), 1); assert_eq!(code.len(), 2);
assert_eq!(code_inline.first().unwrap().value, "inline code");
// Validate multiline code
assert_eq!(code_multiline.len(), 2);
{ {
let item = code_multiline.first().unwrap(); let item = code.first().unwrap();
assert_eq!(item.alt.clone().unwrap(), "alt text"); assert_eq!(item.alt.clone().unwrap(), "alt text");
assert_eq!(item.value.lines().count(), 2); assert_eq!(item.value.lines().count(), 2);
@ -103,7 +84,7 @@ fn gemtext() {
} // #1 } // #1
{ {
let item = code_multiline.get(1).unwrap(); let item = code.get(1).unwrap();
assert_eq!(item.alt.clone(), None); assert_eq!(item.alt.clone(), None);
assert_eq!(item.value.lines().count(), 2); assert_eq!(item.value.lines().count(), 2);
@ -150,52 +131,64 @@ fn gemtext() {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(item.alt, None);
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(
item.uri(Some(&base)).unwrap().to_str(),
"gemini://geminiprotocol.net"
);
} // #1 } // #1
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net"
);
let timestamp = item.timestamp.clone().unwrap(); let time = item.time(Some(&timezone)).unwrap();
assert_eq!(timestamp.year(), 1965); assert_eq!(time.year(), 1965);
assert_eq!(timestamp.month(), 1); assert_eq!(time.month(), 1);
assert_eq!(timestamp.day_of_month(), 19); assert_eq!(time.day_of_month(), 19);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(item.alt, Some("1965-01-19".to_string()));
} // #2 } // #2
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt.clone().unwrap(), "Gemini"); assert_eq!(item.alt.clone().unwrap(), "Gemini");
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net"
);
} // #3 } // #3
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt.clone().unwrap(), "Gemini"); assert_eq!(item.alt, Some("1965-01-19 Gemini".to_string()));
let timestamp = item.timestamp.clone().unwrap(); let time = item.time(Some(&timezone)).unwrap();
assert_eq!(timestamp.year(), 1965); assert_eq!(time.year(), 1965);
assert_eq!(timestamp.month(), 1); assert_eq!(time.month(), 1);
assert_eq!(timestamp.day_of_month(), 19); assert_eq!(time.day_of_month(), 19);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net"
);
} // #4 } // #4
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt.clone().unwrap(), "Gemini"); assert_eq!(item.alt, Some("1965-01-19 Gemini".to_string()));
let timestamp = item.timestamp.clone().unwrap(); let time = item.time(Some(&timezone)).unwrap();
assert_eq!(timestamp.year(), 1965); assert_eq!(time.year(), 1965);
assert_eq!(timestamp.month(), 1); assert_eq!(time.month(), 1);
assert_eq!(timestamp.day_of_month(), 19); assert_eq!(time.day_of_month(), 19);
assert_eq!( assert_eq!(
item.uri.to_str(), item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net/docs/gemtext.gmi" "gemini://geminiprotocol.net/docs/gemtext.gmi"
); );
} // #5 } // #5
@ -203,29 +196,41 @@ fn gemtext() {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(item.alt, None);
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net"
);
} // #6 } // #6
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(item.alt, None);
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net"
);
} // #7 } // #7
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(item.alt, None);
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net/path"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net/path"
);
} // #8 } // #8
{ {
let item = link.next().unwrap(); let item = link.next().unwrap();
assert_eq!(item.alt, None); assert_eq!(item.alt, None);
assert_eq!(item.timestamp, None); assert_eq!(item.time(Some(&timezone)), None);
assert_eq!(item.uri.to_str(), "gemini://geminiprotocol.net/"); assert_eq!(
item.uri(Some(&base)).unwrap().to_string(),
"gemini://geminiprotocol.net/"
);
} // #9 } // #9
// Validate lists // Validate lists