From 66ed1a0b7224cc3677e1fdc1589a083b5ced595f Mon Sep 17 00:00:00 2001 From: Erica Marigold Date: Sat, 20 Apr 2024 20:25:54 +0530 Subject: [PATCH] Use a more descriptive User-Agent header in net.request (#186) --- src/lune/builtins/net/mod.rs | 2 +- src/lune/builtins/net/util.rs | 19 +++++++++++++------ src/lune/globals/version.rs | 2 +- tests/net/request/user_agent.luau | 9 +++++++++ 4 files changed, 24 insertions(+), 8 deletions(-) create mode 100644 tests/net/request/user_agent.luau diff --git a/src/lune/builtins/net/mod.rs b/src/lune/builtins/net/mod.rs index d41b047..9943c1f 100644 --- a/src/lune/builtins/net/mod.rs +++ b/src/lune/builtins/net/mod.rs @@ -24,7 +24,7 @@ use super::serde::encode_decode::{EncodeDecodeConfig, EncodeDecodeFormat}; pub fn create(lua: &Lua) -> LuaResult { NetClientBuilder::new() - .headers(&[("User-Agent", create_user_agent_header())])? + .headers(&[("User-Agent", create_user_agent_header(lua)?)])? .build()? .into_registry(lua); TableBuilder::new(lua)? diff --git a/src/lune/builtins/net/util.rs b/src/lune/builtins/net/util.rs index 4603547..e18235e 100644 --- a/src/lune/builtins/net/util.rs +++ b/src/lune/builtins/net/util.rs @@ -7,12 +7,19 @@ use mlua::prelude::*; use crate::lune::util::TableBuilder; -pub fn create_user_agent_header() -> String { - let (github_owner, github_repo) = env!("CARGO_PKG_REPOSITORY") - .trim_start_matches("https://github.com/") - .split_once('/') - .unwrap(); - format!("{github_owner}-{github_repo}-cli") +pub fn create_user_agent_header(lua: &Lua) -> LuaResult { + let version_global = lua + .globals() + .get::<_, LuaString>("_VERSION") + .expect("Missing _VERSION global"); + + 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( diff --git a/src/lune/globals/version.rs b/src/lune/globals/version.rs index 4904144..1228fd0 100644 --- a/src/lune/globals/version.rs +++ b/src/lune/globals/version.rs @@ -13,7 +13,7 @@ pub fn create(lua: &Lua) -> LuaResult> { // If this function runs more than once, we // 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); } diff --git a/tests/net/request/user_agent.luau b/tests/net/request/user_agent.luau new file mode 100644 index 0000000..04491b7 --- /dev/null +++ b/tests/net/request/user_agent.luau @@ -0,0 +1,9 @@ +local net = require("@lune/net") + +local runtime, version = table.unpack(_VERSION:split(" ")) +local expectedUserAgent = runtime:lower() .. "/" .. version + +local userAgent: string = + net.jsonDecode(net.request("https://www.whatsmyua.info/api/v1/ua").body)[1].ua.rawUa + +assert(userAgent == expectedUserAgent, "Expected user agent to be " .. expectedUserAgent)