1use crate::package;
2use std::{
3 fmt::Display,
4 path::{Path, PathBuf},
5 str::FromStr,
6};
7
8use crate::config::Config;
9use itertools::Itertools;
10use miette::Diagnostic;
11use serde::{Deserialize, Serialize};
12use strum::IntoEnumIterator;
13use strum_macros::EnumIter;
14use thiserror::Error;
15
16#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, EnumIter)]
17#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
18pub enum Version {
19 #[serde(rename = "5.1")]
20 Lua51,
21 #[serde(rename = "5.2")]
22 Lua52,
23 #[serde(rename = "5.3")]
24 Lua53,
25 #[serde(rename = "5.4")]
26 Lua54,
27 #[serde(rename = "5.5")]
28 Lua55,
29 #[serde(rename = "jit")]
30 LuaJIT,
31 #[serde(rename = "jit5.2")]
32 LuaJIT52,
33 #[serde(rename = "luau")]
34 Luau,
35}
36
37#[derive(Debug, Error, Diagnostic)]
38pub enum Error {
39 #[error("unsupported Lua version: '{0}'")]
40 UnsupportedVersion(package::Version),
41 #[error("lua version not set")]
42 Unset {
43 #[help]
44 help: String,
45 },
46}
47
48impl Version {
49 pub fn as_version(&self) -> package::Version {
50 unsafe {
51 match self {
52 Version::Lua51 => "5.1.0".parse().unwrap_unchecked(),
53 Version::Lua52 => "5.2.0".parse().unwrap_unchecked(),
54 Version::Lua53 => "5.3.0".parse().unwrap_unchecked(),
55 Version::Lua54 => "5.4.0".parse().unwrap_unchecked(),
56 Version::Lua55 => "5.5.0".parse().unwrap_unchecked(),
57 Version::LuaJIT => "5.1.0".parse().unwrap_unchecked(),
58 Version::LuaJIT52 => "5.2.0".parse().unwrap_unchecked(),
59 Version::Luau => "5.1.0".parse().unwrap_unchecked(),
60 }
61 }
62 }
63 pub fn version_compatibility_str(&self) -> String {
64 match self {
65 Version::Lua51 | Version::LuaJIT | Version::Luau => "5.1".into(),
66 Version::Lua52 | Version::LuaJIT52 => "5.2".into(),
67 Version::Lua53 => "5.3".into(),
68 Version::Lua54 => "5.4".into(),
69 Version::Lua55 => "5.5".into(),
70 }
71 }
72 pub fn as_version_req(&self) -> package::VersionReq {
73 unsafe {
74 format!("~> {}", self.version_compatibility_str())
75 .parse()
76 .unwrap_unchecked()
77 }
78 }
79
80 pub fn from_version(version: package::Version) -> Result<Version, Error> {
82 let luajit_version_req: package::VersionReq = unsafe { "~> 2".parse().unwrap_unchecked() };
84 if luajit_version_req.matches(&version) {
85 Ok(Version::LuaJIT)
86 } else if Version::Lua51.as_version_req().matches(&version) {
87 Ok(Version::Lua51)
88 } else if Version::Lua52.as_version_req().matches(&version) {
89 Ok(Version::Lua52)
90 } else if Version::Lua53.as_version_req().matches(&version) {
91 Ok(Version::Lua53)
92 } else if Version::Lua54.as_version_req().matches(&version) {
93 Ok(Version::Lua54)
94 } else if Version::Lua55.as_version_req().matches(&version) {
95 Ok(Version::Lua55)
96 } else {
97 Err(Error::UnsupportedVersion(version))
98 }
99 }
100
101 pub(crate) fn is_luajit(&self) -> bool {
102 matches!(self, Self::LuaJIT | Self::LuaJIT52)
103 }
104
105 pub(crate) fn is_luau(&self) -> bool {
106 matches!(self, Self::Luau)
107 }
108
109 pub fn lux_lib_dir(&self) -> Option<PathBuf> {
111 option_env!("LUX_LIB_DIR")
112 .map(PathBuf::from)
113 .map(|path| path.join(self.to_string()))
114 .or_else(|| self.probe_lux_lib_dir())
115 .or_else(|| {
116 match self {
117 Version::LuaJIT => Some(Version::Lua51),
118 Version::LuaJIT52 => Some(Version::Lua52),
119 _ => None,
120 }
121 .and_then(|compat_version| compat_version.probe_lux_lib_dir())
122 })
123 .or_else(|| lux_lib_resource_dir().map(|path| path.join(self.to_string())))
124 }
125
126 fn probe_lux_lib_dir(&self) -> Option<PathBuf> {
127 let lib_name = format!("lux-lua{self}");
128 pkg_config::Config::new()
129 .print_system_libs(false)
130 .cargo_metadata(false)
131 .env_metadata(false)
132 .probe(&lib_name)
133 .ok()
134 .and_then(|library| library.link_paths.first().cloned())
135 }
136}
137
138impl Version {
139 pub fn from(config: &Config) -> Result<&Self, Error> {
140 config.lua_version().ok_or(Error::Unset {
141 help: format!(
142 r#"provide a version through `lx --lua-version <ver> <cmd>`
143or make sure Lux can discover your Lua installation on your PATH.
144valid versions are: {}
145"#,
146 Version::iter().join(",")
147 ),
148 })
149 }
150}
151
152impl FromStr for Version {
153 type Err = String;
154
155 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
156 match s {
157 "5.1" | "51" => Ok(Version::Lua51),
158 "5.2" | "52" => Ok(Version::Lua52),
159 "5.3" | "53" => Ok(Version::Lua53),
160 "5.4" | "54" => Ok(Version::Lua54),
161 "5.5" | "55" => Ok(Version::Lua55),
162 "jit" | "luajit" => Ok(Version::LuaJIT),
163 "jit52" | "luajit52" => Ok(Version::LuaJIT52),
164 "luau" => Ok(Version::Luau),
165 _ => Err(format!(
166 r#"unrecognized Lua version.
167supported versions: {}
168 "#,
169 Version::iter().join(",")
170 )),
171 }
172 }
173}
174
175impl Display for Version {
176 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
177 f.write_str(match self {
178 Version::Lua51 => "5.1",
179 Version::Lua52 => "5.2",
180 Version::Lua53 => "5.3",
181 Version::Lua54 => "5.4",
182 Version::Lua55 => "5.5",
183 Version::LuaJIT => "jit",
184 Version::LuaJIT52 => "jit52",
185 Version::Luau => "luau",
186 })
187 }
188}
189
190fn lux_lib_resource_dir() -> Option<PathBuf> {
192 if cfg!(target_env = "msvc") {
193 std::env::current_exe()
195 .ok()
196 .and_then(|exe_path| exe_path.parent().map(Path::to_path_buf))
197 .and_then(|exe_dir| {
198 let lib_dir = exe_dir.join("lux-lua");
199 if lib_dir.is_dir() {
200 Some(lib_dir)
201 } else {
202 None
203 }
204 })
205 } else if cfg!(target_os = "macos") {
206 std::env::current_exe()
208 .ok()
209 .and_then(|exe_path| exe_path.parent().map(Path::to_path_buf))
210 .and_then(|macos_dir| macos_dir.parent().map(Path::to_path_buf))
211 .and_then(|contents_dir| {
212 let lib_dir = contents_dir.join("Resources").join("lux-lua");
213 if lib_dir.is_dir() {
214 Some(lib_dir)
215 } else {
216 None
217 }
218 })
219 } else {
220 if let Some(appdir) = std::env::var_os("APPDIR") {
222 let lib_dir = Path::new(&appdir).join("usr/share/lux-lua");
223 if lib_dir.is_dir() {
224 return Some(lib_dir);
225 }
226 }
227 let lib_dir = PathBuf::from("/usr/share/lux-lua");
228 if lib_dir.is_dir() {
229 Some(lib_dir)
230 } else {
231 None
232 }
233 }
234}