1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//! Loader context for runtime initialization.
//!
//! This module provides the LoaderContext structure that transfers
//! configuration from PastaLoader to PastaLuaRuntime.
use std::path::{Path, PathBuf};
use super::config::PastaConfig;
/// Context for runtime initialization from PastaLoader.
///
/// Contains all information needed to initialize PastaLuaRuntime
/// from the loader context, including paths and custom configuration.
#[derive(Debug, Clone)]
pub struct LoaderContext {
/// Base directory (absolute path)
pub base_dir: PathBuf,
/// Lua module search paths (relative to base_dir)
pub lua_search_paths: Vec<String>,
/// Custom configuration fields from pasta.toml
/// (everything except [loader] section)
pub custom_fields: toml::Table,
}
impl LoaderContext {
/// Create a new LoaderContext.
pub fn new(
base_dir: impl Into<PathBuf>,
lua_search_paths: Vec<String>,
custom_fields: toml::Table,
) -> Self {
Self {
base_dir: base_dir.into(),
lua_search_paths,
custom_fields,
}
}
/// Create LoaderContext from PastaConfig.
///
/// Converts base_dir to absolute path and extracts relevant settings.
pub fn from_config(base_dir: &Path, config: &PastaConfig) -> Self {
let abs_base = base_dir
.canonicalize()
.unwrap_or_else(|_| base_dir.to_path_buf());
// On Windows, canonicalize returns extended-length paths (\\?\C:\...)
// Strip this prefix for Lua compatibility
let abs_base = Self::strip_windows_prefix(&abs_base);
Self {
base_dir: abs_base,
lua_search_paths: config.loader.lua_search_paths.clone(),
custom_fields: config.custom_fields.clone(),
}
}
/// Strip Windows extended-length path prefix (\\?\) if present.
///
/// Windows `canonicalize()` returns paths like `\\?\C:\path` which
/// cause issues with Lua's package.path. This function removes the
/// prefix to get a normal path like `C:\path`.
#[cfg(windows)]
fn strip_windows_prefix(path: &Path) -> PathBuf {
let path_str = path.to_string_lossy();
if let Some(stripped) = path_str.strip_prefix(r"\\?\") {
PathBuf::from(stripped)
} else {
path.to_path_buf()
}
}
#[cfg(not(windows))]
fn strip_windows_prefix(path: &Path) -> PathBuf {
path.to_path_buf()
}
/// Generate absolute Lua module search paths.
///
/// Converts relative search paths to absolute paths based on base_dir.
pub fn absolute_search_paths(&self) -> Vec<PathBuf> {
self.lua_search_paths
.iter()
.map(|p| self.base_dir.join(p))
.collect()
}
/// Generate package.path string for Lua.
///
/// Creates a semicolon-separated path string in Lua format:
/// `/path/to/dir/?.lua;/path/to/dir/?/init.lua;/next/path/?.lua;...`
///
/// Each search path generates two patterns:
/// - `?.lua` for direct module files
/// - `?/init.lua` for directory modules (like `pasta/init.lua`)
pub fn generate_package_path(&self) -> String {
self.lua_search_paths
.iter()
.flat_map(|p| {
let abs_path = self.base_dir.join(p);
// Normalize path separators to forward slashes for Lua
let path_str = abs_path.to_string_lossy().replace('\\', "/");
// Return both patterns for each search path
vec![
format!("{}/?.lua", path_str),
format!("{}/?/init.lua", path_str),
]
})
.collect::<Vec<_>>()
.join(";")
}
/// Generate package.path bytes for Lua.
///
/// Creates a semicolon-separated path string and converts it to
/// system-native encoding bytes (ANSI on Windows, UTF-8 on Unix).
///
/// This is the preferred method for setting `package.path` in Lua
/// because Lua's file I/O functions (fopen) use ANSI encoding on Windows.
///
/// # Returns
/// * `Ok(Vec<u8>)` - Encoded path bytes ready for Lua
/// * `Err(std::io::Error)` - If encoding conversion fails
///
/// # Example
/// ```rust,ignore
/// let bytes = loader_context.generate_package_path_bytes()?;
/// let lua_string = lua.create_string(&bytes)?;
/// package.set("path", lua_string)?;
/// ```
pub fn generate_package_path_bytes(&self) -> std::io::Result<Vec<u8>> {
let path_str = self.generate_package_path();
crate::encoding::to_ansi_bytes(&path_str)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_new() {
let ctx = LoaderContext::new(
"/ghost/master",
vec!["scripts".to_string(), "lib".to_string()],
toml::Table::new(),
);
assert_eq!(ctx.base_dir, PathBuf::from("/ghost/master"));
assert_eq!(ctx.lua_search_paths, vec!["scripts", "lib"]);
assert!(ctx.custom_fields.is_empty());
}
#[test]
fn test_absolute_search_paths() {
let ctx = LoaderContext::new(
"/ghost/master",
vec!["profile/pasta/save/lua".to_string(), "scripts".to_string()],
toml::Table::new(),
);
let paths = ctx.absolute_search_paths();
assert_eq!(paths.len(), 2);
assert_eq!(
paths[0],
PathBuf::from("/ghost/master/profile/pasta/save/lua")
);
assert_eq!(paths[1], PathBuf::from("/ghost/master/scripts"));
}
#[test]
fn test_generate_package_path() {
let ctx = LoaderContext::new(
"/ghost/master",
vec!["scripts".to_string(), "lib".to_string()],
toml::Table::new(),
);
let path = ctx.generate_package_path();
assert!(path.contains("/ghost/master/scripts/?.lua"));
assert!(path.contains("/ghost/master/lib/?.lua"));
assert!(path.contains(";"));
}
#[test]
fn test_from_config() {
let config = PastaConfig::default();
let ctx = LoaderContext::from_config(Path::new("/ghost/master"), &config);
assert_eq!(ctx.lua_search_paths, config.loader.lua_search_paths);
assert!(ctx.custom_fields.is_empty());
}
#[test]
fn test_from_config_with_custom_fields() {
let mut custom = toml::Table::new();
custom.insert(
"ghost_name".to_string(),
toml::Value::String("Test".to_string()),
);
let config = PastaConfig {
loader: super::super::config::LoaderConfig::default(),
custom_fields: custom.clone(),
};
let ctx = LoaderContext::from_config(Path::new("/ghost/master"), &config);
assert_eq!(ctx.custom_fields, custom);
}
#[test]
fn test_generate_package_path_bytes_ascii() {
let ctx = LoaderContext::new(
"/ghost/master",
vec!["scripts".to_string()],
toml::Table::new(),
);
let bytes = ctx.generate_package_path_bytes().unwrap();
// ASCII paths should be unchanged
let expected = ctx.generate_package_path();
assert_eq!(bytes, expected.as_bytes());
}
#[test]
fn test_generate_package_path_bytes_not_empty() {
let ctx = LoaderContext::new(
"/ghost/master",
vec!["scripts".to_string(), "lib".to_string()],
toml::Table::new(),
);
let bytes = ctx.generate_package_path_bytes().unwrap();
assert!(!bytes.is_empty());
// Should contain semicolon separator
assert!(bytes.contains(&b';'));
}
#[test]
fn test_generate_package_path_init_patterns_in_order() {
// Each search path yields BOTH "?.lua" and "?/init.lua", in declared order.
let ctx = LoaderContext::new(
"/ghost/master",
vec!["scripts".to_string(), "lib".to_string()],
toml::Table::new(),
);
let path = ctx.generate_package_path();
assert_eq!(
path,
"/ghost/master/scripts/?.lua;/ghost/master/scripts/?/init.lua;\
/ghost/master/lib/?.lua;/ghost/master/lib/?/init.lua"
);
}
#[test]
fn test_generate_package_path_normalizes_backslashes() {
// Backslash separators (Windows style) are normalized to "/" for Lua.
let ctx = LoaderContext::new(
r"C:\ghost\master",
vec!["scripts".to_string()],
toml::Table::new(),
);
let path = ctx.generate_package_path();
assert!(!path.contains('\\'), "no backslashes expected: {}", path);
assert!(path.contains("C:/ghost/master/scripts/?.lua"));
assert!(path.contains("C:/ghost/master/scripts/?/init.lua"));
}
#[test]
fn test_generate_package_path_empty_search_paths() {
let ctx = LoaderContext::new("/ghost/master", Vec::new(), toml::Table::new());
assert_eq!(ctx.generate_package_path(), "");
assert!(ctx.absolute_search_paths().is_empty());
}
#[test]
fn test_from_config_existing_dir_is_absolute_without_extended_prefix() {
// Existing dir -> canonicalized to an absolute path; on Windows the
// \\?\ extended-length prefix must be stripped for Lua compatibility.
let temp = tempfile::TempDir::new().unwrap();
let config = PastaConfig::default();
let ctx = LoaderContext::from_config(temp.path(), &config);
assert!(ctx.base_dir.is_absolute());
assert!(
!ctx.base_dir.to_string_lossy().starts_with(r"\\?\"),
"extended-length prefix must be stripped: {}",
ctx.base_dir.display()
);
}
#[test]
fn test_from_config_nonexistent_dir_falls_back_to_input() {
// canonicalize() fails for a nonexistent path -> input path kept as-is.
let config = PastaConfig::default();
let input = Path::new("definitely_nonexistent_loader_ctx_dir/sub");
let ctx = LoaderContext::from_config(input, &config);
assert_eq!(ctx.base_dir, input.to_path_buf());
}
#[cfg(windows)]
#[test]
fn test_generate_package_path_bytes_japanese() {
let ctx = LoaderContext::new(
"C:\\ユーザー\\テスト",
vec!["scripts".to_string()],
toml::Table::new(),
);
let bytes = ctx.generate_package_path_bytes().unwrap();
// On Windows with Japanese locale, bytes should be ANSI encoded
assert!(!bytes.is_empty());
// The result should not be the same as UTF-8 bytes
let utf8_bytes = ctx.generate_package_path().into_bytes();
assert_ne!(bytes, utf8_bytes);
}
}