feat(net/util.rs): use a standardized user agent format

This commit is contained in:
Erica Marigold 2024-04-20 19:13:26 +05:30
parent fa7f6c6f51
commit 358fe3a8e4
No known key found for this signature in database
GPG key ID: 2768CC0C23D245D1
3 changed files with 17 additions and 9 deletions

View file

@ -23,7 +23,7 @@ use super::serde::encode_decode::{EncodeDecodeConfig, EncodeDecodeFormat};
pub fn create(lua: &Lua) -> LuaResult<LuaTable> { pub fn create(lua: &Lua) -> LuaResult<LuaTable> {
NetClientBuilder::new() NetClientBuilder::new()
.headers(&[("User-Agent", create_user_agent_header())])? .headers(&[("User-Agent", create_user_agent_header(lua)?)])?
.build()? .build()?
.into_registry(lua); .into_registry(lua);
TableBuilder::new(lua)? TableBuilder::new(lua)?

View file

@ -7,12 +7,19 @@ use mlua::prelude::*;
use crate::lune::util::TableBuilder; use crate::lune::util::TableBuilder;
pub fn create_user_agent_header() -> String { pub fn create_user_agent_header(lua: &Lua) -> LuaResult<String> {
let (github_owner, github_repo) = env!("CARGO_PKG_REPOSITORY") let version_global = lua
.trim_start_matches("https://github.com/") .globals()
.split_once('/') .get::<_, LuaString>("_VERSION")
.unwrap(); .expect("Missing _VERSION global");
format!("{github_owner}-{github_repo}-cli")
let version_global_str = version_global
.to_str()
.context("Invalid utf8 found in _VERSION global")?;
let (package_name, full_version) = version_global_str.split_once(' ').unwrap();
Ok(format!("{}/{}", package_name.to_lowercase(), full_version))
} }
pub fn header_map_to_table( pub fn header_map_to_table(

View file

@ -1,19 +1,20 @@
use mlua::prelude::*; use mlua::prelude::*;
pub fn create(lua: &Lua) -> LuaResult<impl IntoLua<'_>> { pub fn create(lua: &Lua) -> LuaResult<impl IntoLua<'_>> {
let lune_version = format!("Lune {}", env!("CARGO_PKG_VERSION")); let lune_version = format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
let luau_version_full = lua let luau_version_full = lua
.globals() .globals()
.get::<_, LuaString>("_VERSION") .get::<_, LuaString>("_VERSION")
.expect("Missing _VERSION global"); .expect("Missing _VERSION global");
let luau_version_str = luau_version_full let luau_version_str = luau_version_full
.to_str() .to_str()
.context("Invalid utf8 found in _VERSION global")?; .context("Invalid utf8 found in _VERSION global")?;
// If this function runs more than once, we // If this function runs more than once, we
// may get an already formatted lune version. // may get an already formatted lune version.
if luau_version_str.starts_with(&lune_version) { if luau_version_str.starts_with(lune_version.as_str()) {
return Ok(luau_version_full); return Ok(luau_version_full);
} }