commonmarker 2.10.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,171 +1,136 @@
1
- use std::path::PathBuf;
1
+ use std::collections::HashMap;
2
+ use std::path::{Path, PathBuf};
3
+ use std::sync::{Arc, Mutex, OnceLock, PoisonError};
2
4
 
3
5
  use comrak::plugins::syntect::{SyntectAdapter, SyntectAdapterBuilder};
4
6
 
5
- use magnus::value::ReprValue;
6
- use magnus::{RHash, Ruby, TryConvert, Value};
7
+ use magnus::{RHash, Ruby, TryConvert};
7
8
  use syntect::highlighting::ThemeSet;
8
9
 
9
- use crate::EMPTY_STR;
10
+ /// Adapters built so far, keyed by `(theme, path)`.
11
+ ///
12
+ /// Building a `SyntectAdapter` deserializes syntect's bundled syntax and theme
13
+ /// sets, and the syntax regexes are then compiled lazily on first use. That
14
+ /// costs far more than rendering a small document, so an adapter is built once
15
+ /// per theme/path combination and shared for the life of the process. Adapters
16
+ /// hold no Ruby objects and are immutable once built.
17
+ ///
18
+ /// The mutex only makes the static `Sync`; every caller holds the GVL, so the
19
+ /// lock is never contended.
20
+ type AdapterCache = Mutex<HashMap<(String, PathBuf), Arc<SyntectAdapter>>>;
21
+
22
+ fn adapter_cache() -> &'static AdapterCache {
23
+ static CACHE: OnceLock<AdapterCache> = OnceLock::new();
24
+ CACHE.get_or_init(|| Mutex::new(HashMap::new()))
25
+ }
10
26
 
27
+ /// Constructs a syntax highlighter from pre-validated plugin configuration.
28
+ /// Expects the output from format_plugins():
29
+ /// - None: syntax highlighting disabled
30
+ /// - Some(RHash): contains { syntax_highlighter: { theme: String, path: String } }
11
31
  pub fn construct_syntax_highlighter_from_plugin(
12
32
  ruby: &Ruby,
13
33
  rb_plugins: Option<RHash>,
14
- ) -> Result<Option<SyntectAdapter>, magnus::Error> {
15
- match rb_plugins {
16
- None => Ok(None),
17
- Some(rb_plugins) => {
18
- let theme = match rb_plugins.get(ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN)) {
19
- Some(syntax_highlighter_options) => {
20
- match fetch_syntax_highlighter_theme(ruby, syntax_highlighter_options) {
21
- Ok(theme) => theme,
22
- Err(e) => {
23
- return Err(e);
24
- }
25
- }
26
- }
27
- None => None, // no `syntax_highlighter:` defined
28
- };
29
-
30
- let adapter: SyntectAdapter;
31
-
32
- match theme {
33
- None => Ok(None),
34
- Some(theme) => {
35
- if theme.is_empty() {
36
- // no theme? uss css classes
37
- adapter = SyntectAdapter::new(None);
38
- Ok(Some(adapter))
39
- } else {
40
- let path = match rb_plugins
41
- .get(ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN))
42
- {
43
- Some(syntax_highlighter_options) => {
44
- fetch_syntax_highlighter_path(ruby, syntax_highlighter_options)?
45
- }
46
- None => PathBuf::from("".to_string()), // no `syntax_highlighter:` defined
47
- };
48
-
49
- if path.exists() {
50
- if !path.is_dir() {
51
- return Err(magnus::Error::new(
52
- ruby.exception_arg_error(),
53
- "`path` needs to be a directory",
54
- ));
55
- }
56
-
57
- let builder = SyntectAdapterBuilder::new();
58
- let mut ts = ThemeSet::load_defaults();
59
-
60
- match ts.add_from_folder(&path) {
61
- Ok(_) => {}
62
- Err(e) => {
63
- return Err(magnus::Error::new(
64
- ruby.exception_arg_error(),
65
- format!("failed to load theme set from path: {e}"),
66
- ));
67
- }
68
- }
69
-
70
- // check if the theme exists in the dir
71
- match ts.themes.get(&theme) {
72
- Some(theme) => theme,
73
- None => {
74
- return Err(magnus::Error::new(
75
- ruby.exception_arg_error(),
76
- format!("theme `{}` does not exist", theme),
77
- ));
78
- }
79
- };
80
-
81
- adapter = builder.theme_set(ts).theme(&theme).build();
82
-
83
- Ok(Some(adapter))
84
- } else {
85
- // no path? default theme lookup
86
- ThemeSet::load_defaults()
87
- .themes
88
- .get(&theme)
89
- .ok_or_else(|| {
90
- magnus::Error::new(
91
- ruby.exception_arg_error(),
92
- format!("theme `{}` does not exist", theme),
93
- )
94
- })?;
95
- adapter = SyntectAdapter::new(Some(&theme));
96
- Ok(Some(adapter))
97
- }
98
- }
99
- }
100
- }
101
- }
102
- }
103
- }
104
-
105
- fn fetch_syntax_highlighter_theme(
106
- ruby: &Ruby,
107
- value: Value,
108
- ) -> Result<Option<String>, magnus::Error> {
109
- if value.is_nil() {
110
- // `syntax_highlighter: nil`
111
- return Ok(None);
112
- }
34
+ ) -> Result<Option<Arc<SyntectAdapter>>, magnus::Error> {
35
+ let rb_plugins = match rb_plugins {
36
+ None => return Ok(None),
37
+ Some(p) => p,
38
+ };
113
39
 
114
- let syntax_highlighter_plugin: RHash = match TryConvert::try_convert(value) {
115
- Ok(plugin) => plugin, // `syntax_highlighter: { theme: "<something>" }`
116
- Err(e) => {
117
- // not a hash!
118
- return Err(e);
119
- }
40
+ let syntax_highlighter_hash: RHash = rb_plugins
41
+ .get(ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN))
42
+ .map(TryConvert::try_convert)
43
+ .transpose()?
44
+ .ok_or_else(|| {
45
+ magnus::Error::new(
46
+ ruby.exception_arg_error(),
47
+ "missing syntax_highlighter key in plugins",
48
+ )
49
+ })?;
50
+
51
+ let theme: String = syntax_highlighter_hash
52
+ .get(ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN_THEME_KEY))
53
+ .map(TryConvert::try_convert)
54
+ .transpose()?
55
+ .unwrap_or_default();
56
+
57
+ let path: String = syntax_highlighter_hash
58
+ .get(ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN_PATH_KEY))
59
+ .map(TryConvert::try_convert)
60
+ .transpose()?
61
+ .unwrap_or_default();
62
+
63
+ // An empty or missing path means the bundled theme set. A real path is
64
+ // resolved so different spellings of one directory share one adapter.
65
+ let path = PathBuf::from(path);
66
+ let path = if path.as_os_str().is_empty() || !path.exists() {
67
+ PathBuf::new()
68
+ } else {
69
+ path.canonicalize().unwrap_or(path)
120
70
  };
121
71
 
122
- if syntax_highlighter_plugin.is_nil() || syntax_highlighter_plugin.is_empty() {
123
- return Err(magnus::Error::new(
124
- ruby.exception_type_error(),
125
- "theme cannot be blank hash",
126
- ));
127
- }
72
+ let key = (theme, path);
73
+
74
+ let mut cache = adapter_cache()
75
+ .lock()
76
+ .unwrap_or_else(PoisonError::into_inner);
128
77
 
129
- let theme_key = ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN_THEME_KEY);
130
-
131
- match syntax_highlighter_plugin.get(theme_key) {
132
- Some(theme) => {
133
- if theme.is_nil() {
134
- return Err(magnus::Error::new(
135
- ruby.exception_type_error(),
136
- "theme cannot be nil",
137
- ));
138
- }
139
- Ok(TryConvert::try_convert(theme)?)
140
- }
141
- None => {
142
- // `syntax_highlighter: { theme: nil }`
143
- Ok(None)
144
- }
78
+ if let Some(adapter) = cache.get(&key) {
79
+ return Ok(Some(Arc::clone(adapter)));
145
80
  }
81
+
82
+ let adapter = Arc::new(build_adapter(ruby, &key.0, &key.1)?);
83
+ cache.insert(key, Arc::clone(&adapter));
84
+
85
+ Ok(Some(adapter))
146
86
  }
147
87
 
148
- fn fetch_syntax_highlighter_path(ruby: &Ruby, value: Value) -> Result<PathBuf, magnus::Error> {
149
- if value.is_nil() {
150
- // `syntax_highlighter: nil`
151
- return Ok(PathBuf::from(EMPTY_STR));
88
+ /// Builds the adapter for one `(theme, path)`; see `adapter_cache` for why this
89
+ /// runs at most once per combination.
90
+ fn build_adapter(ruby: &Ruby, theme: &str, path: &Path) -> Result<SyntectAdapter, magnus::Error> {
91
+ // Empty theme means use CSS classes instead of inline styles
92
+ if theme.is_empty() {
93
+ return Ok(SyntectAdapter::new(None));
152
94
  }
153
95
 
154
- let syntax_highlighter_plugin: RHash = TryConvert::try_convert(value)?;
155
- let path_key = ruby.to_symbol(super::SYNTAX_HIGHLIGHTER_PLUGIN_PATH_KEY);
156
-
157
- match syntax_highlighter_plugin.get(path_key) {
158
- Some(path) => {
159
- if path.is_nil() {
160
- // `syntax_highlighter: { path: nil }`
161
- return Ok(PathBuf::from(EMPTY_STR));
162
- }
163
- let val: String = TryConvert::try_convert(path)?;
164
- Ok(PathBuf::from(val))
165
- }
166
- None => {
167
- // `syntax_highlighter: { }`
168
- Ok(PathBuf::from(EMPTY_STR))
169
- }
96
+ if path.as_os_str().is_empty() {
97
+ // No custom path, use default themes
98
+ ThemeSet::load_defaults().themes.get(theme).ok_or_else(|| {
99
+ magnus::Error::new(
100
+ ruby.exception_arg_error(),
101
+ format!("theme `{theme}` does not exist"),
102
+ )
103
+ })?;
104
+ return Ok(SyntectAdapter::new(Some(theme)));
170
105
  }
106
+
107
+ // Custom theme path provided
108
+ if !path.is_dir() {
109
+ return Err(magnus::Error::new(
110
+ ruby.exception_arg_error(),
111
+ "`path` needs to be a directory",
112
+ ));
113
+ }
114
+
115
+ let mut ts = ThemeSet::load_defaults();
116
+
117
+ ts.add_from_folder(path).map_err(|e| {
118
+ magnus::Error::new(
119
+ ruby.exception_arg_error(),
120
+ format!("failed to load theme set from path: {e}"),
121
+ )
122
+ })?;
123
+
124
+ // Verify theme exists in the loaded set
125
+ ts.themes.get(theme).ok_or_else(|| {
126
+ magnus::Error::new(
127
+ ruby.exception_arg_error(),
128
+ format!("theme `{theme}` does not exist"),
129
+ )
130
+ })?;
131
+
132
+ Ok(SyntectAdapterBuilder::new()
133
+ .theme_set(ts)
134
+ .theme(theme)
135
+ .build())
171
136
  }
@@ -1,6 +1,120 @@
1
1
  pub mod syntax_highlighting;
2
2
 
3
- pub const SYNTAX_HIGHLIGHTER_PLUGIN: &str = "syntax_highlighter";
3
+ use magnus::value::ReprValue;
4
+ use magnus::{Error, RHash, Ruby, TryConvert, Value};
4
5
 
6
+ pub const SYNTAX_HIGHLIGHTER_PLUGIN: &str = "syntax_highlighter";
5
7
  pub const SYNTAX_HIGHLIGHTER_PLUGIN_THEME_KEY: &str = "theme";
6
8
  pub const SYNTAX_HIGHLIGHTER_PLUGIN_PATH_KEY: &str = "path";
9
+
10
+ pub const DEFAULT_THEME: &str = "base16-ocean.dark";
11
+ pub const DEFAULT_PATH: &str = "";
12
+
13
+ /// Formats and validates plugins from Ruby.
14
+ ///
15
+ /// No plugin is enabled by default, as in comrak. Returns None unless the Hash
16
+ /// asks for the syntax highlighter (`syntax_highlighter: {}` enables it with
17
+ /// the default theme), and otherwise Some(RHash) holding
18
+ /// `{ syntax_highlighter: { theme: String, path: String } }` with the defaults
19
+ /// filled in.
20
+ pub fn format_plugins(ruby: &Ruby, rb_plugins: Option<Value>) -> Result<Option<RHash>, Error> {
21
+ let rb_plugins = match rb_plugins {
22
+ None => return Ok(None),
23
+ Some(v) if v.is_nil() => return Ok(None),
24
+ Some(v) => v,
25
+ };
26
+
27
+ let plugins_hash: RHash = TryConvert::try_convert(rb_plugins).map_err(|_| {
28
+ Error::new(
29
+ ruby.exception_type_error(),
30
+ format!(
31
+ "plugins must be a Hash; got {}",
32
+ crate::utils::get_classname(rb_plugins)
33
+ ),
34
+ )
35
+ })?;
36
+
37
+ // The syntax highlighter is the only plugin, and it is off unless asked for.
38
+ let syntax_highlighter_value = plugins_hash.get(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN));
39
+
40
+ match syntax_highlighter_value {
41
+ None => Ok(None),
42
+ Some(v) if v.is_nil() => Ok(None),
43
+ Some(v) => {
44
+ // Validate it's a hash
45
+ let sh_hash: RHash = TryConvert::try_convert(v).map_err(|_| {
46
+ Error::new(
47
+ ruby.exception_type_error(),
48
+ format!(
49
+ "syntax_highlighter must be a Hash; got {}",
50
+ crate::utils::get_classname(v)
51
+ ),
52
+ )
53
+ })?;
54
+
55
+ // Merge with the plugin's defaults; `{}` enables it with the default theme.
56
+ let result = ruby.hash_new();
57
+ let merged_sh = ruby.hash_new();
58
+
59
+ // Get theme - nil is an error, missing key uses default
60
+ let theme: String =
61
+ match sh_hash.get(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN_THEME_KEY)) {
62
+ Some(t) if t.is_nil() => {
63
+ return Err(Error::new(
64
+ ruby.exception_type_error(),
65
+ "syntax_highlighter theme cannot be nil",
66
+ ));
67
+ }
68
+ Some(t) => TryConvert::try_convert(t).map_err(|_| {
69
+ Error::new(
70
+ ruby.exception_type_error(),
71
+ format!(
72
+ "syntax_highlighter theme must be a String; got {}",
73
+ crate::utils::get_classname(t)
74
+ ),
75
+ )
76
+ })?,
77
+ None => DEFAULT_THEME.to_string(),
78
+ };
79
+ merged_sh.aset(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN_THEME_KEY), theme)?;
80
+
81
+ // Get path (use default if not provided)
82
+ let path: String = match sh_hash.get(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN_PATH_KEY))
83
+ {
84
+ Some(p) if !p.is_nil() => TryConvert::try_convert(p).map_err(|_| {
85
+ Error::new(
86
+ ruby.exception_type_error(),
87
+ format!(
88
+ "syntax_highlighter path must be a String; got {}",
89
+ crate::utils::get_classname(p)
90
+ ),
91
+ )
92
+ })?,
93
+ _ => DEFAULT_PATH.to_string(),
94
+ };
95
+ merged_sh.aset(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN_PATH_KEY), path)?;
96
+
97
+ result.aset(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN), merged_sh)?;
98
+ Ok(Some(result))
99
+ }
100
+ }
101
+ }
102
+
103
+ /// Returns the default plugins as a Ruby Hash for introspection: every known
104
+ /// plugin, each `nil` because none is enabled by default.
105
+ pub fn default_plugins_to_hash(ruby: &Ruby) -> Result<RHash, Error> {
106
+ let result = ruby.hash_new();
107
+ result.aset(ruby.to_symbol(SYNTAX_HIGHLIGHTER_PLUGIN), ruby.qnil())?;
108
+ Ok(result)
109
+ }
110
+
111
+ /// Builds comrak's plugin set around an optional syntax highlighter.
112
+ pub fn comrak_plugins(
113
+ adapter: Option<&comrak::plugins::syntect::SyntectAdapter>,
114
+ ) -> comrak::options::Plugins<'_> {
115
+ let mut plugins = comrak::options::Plugins::default();
116
+ if let Some(adapter) = adapter {
117
+ plugins.render.codefence_syntax_highlighter = Some(adapter);
118
+ }
119
+ plugins
120
+ }