Use a more descriptive User-Agent header in net.request (#186)

This commit is contained in:
Erica Marigold 2024-04-20 20:25:54 +05:30 committed by GitHub
parent f830ce7fad
commit 66ed1a0b72
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 24 additions and 8 deletions

View file

@ -24,7 +24,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

@ -13,7 +13,7 @@ pub fn create(lua: &Lua) -> LuaResult<impl IntoLua<'_>> {
// 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);
} }

View file

@ -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)