@onxdev/silentium 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/update.rs ADDED
@@ -0,0 +1,385 @@
1
+ // rust — src/update.rs — detecta versão nova no GitHub e troca o próprio binário
2
+ use anyhow::{bail, Context, Result};
3
+ use serde::{Deserialize, Serialize};
4
+ use sha2::{Digest, Sha256};
5
+ use std::fs;
6
+ use std::io::Read;
7
+ use std::path::{Path, PathBuf};
8
+ use std::process::Command;
9
+ use std::time::{Duration, SystemTime, UNIX_EPOCH};
10
+
11
+ pub const REPO: &str = "onx90s/silentium";
12
+ pub const NPM_PACKAGE: &str = "@onxdev/silentium";
13
+ pub const CURRENT: &str = env!("CARGO_PKG_VERSION");
14
+
15
+ /// Duas checagens por dia, no máximo, para não bater no rate limit da API.
16
+ const CHECK_INTERVAL_SECS: u64 = 6 * 60 * 60;
17
+
18
+ #[derive(Debug, Serialize, Deserialize, Default)]
19
+ struct Cache {
20
+ checked_at: u64,
21
+ #[serde(default)]
22
+ tag: Option<String>,
23
+ }
24
+
25
+ /// Entra na tela inicial: devolve a tag nova, se houver.
26
+ pub fn check(force: bool) -> Option<String> {
27
+ let cache = read_cache();
28
+ let fresh = now().saturating_sub(cache.checked_at) < CHECK_INTERVAL_SECS;
29
+ if !force && fresh {
30
+ return cache.tag.filter(|tag| is_newer(tag, CURRENT));
31
+ }
32
+
33
+ match fetch_latest_tag() {
34
+ Ok(tag) => {
35
+ write_cache(&Cache {
36
+ checked_at: now(),
37
+ tag: Some(tag.clone()),
38
+ });
39
+ if is_newer(&tag, CURRENT) {
40
+ Some(tag)
41
+ } else {
42
+ None
43
+ }
44
+ }
45
+ // Sem rede, offline ou rate limit: silêncio, o CLI segue funcionando.
46
+ Err(_) => None,
47
+ }
48
+ }
49
+
50
+ /// `silentium update` / `silentium update --check`.
51
+ pub fn run(check_only: bool) -> Result<()> {
52
+ let latest = fetch_latest_tag().context("consultando a última release no GitHub")?;
53
+ if !is_newer(&latest, CURRENT) {
54
+ println!("já na última versão ({CURRENT})");
55
+ return Ok(());
56
+ }
57
+ if check_only {
58
+ println!("atualização disponível: {latest} (você tem {CURRENT})");
59
+ return Ok(());
60
+ }
61
+ println!("atualizando {CURRENT} → {latest}");
62
+ apply(&latest)
63
+ }
64
+
65
+ fn apply(tag: &str) -> Result<()> {
66
+ if via_npm() {
67
+ return update_via_npm(tag);
68
+ }
69
+ update_binary(tag)
70
+ }
71
+
72
+ /// Instalado como pacote npm: deixa o npm trocar o binário.
73
+ fn update_via_npm(tag: &str) -> Result<()> {
74
+ let version = tag.trim_start_matches('v');
75
+ let spec = format!("{NPM_PACKAGE}@{version}");
76
+ println!("instalando {spec} via npm");
77
+ let status = Command::new("npm")
78
+ .args(["install", "-g", &spec])
79
+ .status()
80
+ .context("npm não encontrado no PATH")?;
81
+ if !status.success() {
82
+ bail!("npm install falhou ({status}); tente manualmente: npm i -g {spec}");
83
+ }
84
+ println!("pronto — a próxima execução já usa {tag}");
85
+ Ok(())
86
+ }
87
+
88
+ fn update_binary(tag: &str) -> Result<()> {
89
+ let asset = asset_name().context("plataforma sem binário publicado")?;
90
+ let base = format!("https://github.com/{REPO}/releases/download/{tag}");
91
+ let agent = agent();
92
+
93
+ let dir = std::env::temp_dir().join(format!("silentium-update-{}", std::process::id()));
94
+ let _ = fs::remove_dir_all(&dir);
95
+ fs::create_dir_all(&dir).context("criando diretório temporário")?;
96
+ let archive = dir.join(&asset);
97
+
98
+ let mut reader = agent
99
+ .get(&format!("{base}/{asset}"))
100
+ .call()
101
+ .with_context(|| format!("baixando {asset}"))?
102
+ .into_reader();
103
+ let mut file = fs::File::create(&archive).context("criando arquivo temporário")?;
104
+ let mut hasher = Sha256::new();
105
+ let mut buf = [0u8; 64 * 1024];
106
+ loop {
107
+ let read = reader.read(&mut buf)?;
108
+ if read == 0 {
109
+ break;
110
+ }
111
+ hasher.update(&buf[..read]);
112
+ std::io::Write::write_all(&mut file, &buf[..read])?;
113
+ }
114
+ drop(file);
115
+
116
+ if let Some(expected) = expected_sha(&agent, &base, &asset) {
117
+ let actual = format!("{:x}", hasher.finalize());
118
+ if expected != actual {
119
+ bail!("checksum não bate: esperado {expected}, obtido {actual}");
120
+ }
121
+ } else {
122
+ eprintln!("[!] SHASUMS256.txt indisponível, seguindo sem verificação");
123
+ }
124
+
125
+ extract(&archive, &dir)?;
126
+ let new_bin = find_binary(&dir).context("binário não encontrado dentro do pacote")?;
127
+ let replaced = replace_self(&new_bin);
128
+ let _ = fs::remove_dir_all(&dir);
129
+ replaced?;
130
+ println!("pronto — {tag} instalado em {}", self_path()?.display());
131
+ Ok(())
132
+ }
133
+
134
+ fn expected_sha(agent: &ureq::Agent, base: &str, asset: &str) -> Option<String> {
135
+ let text = agent
136
+ .get(&format!("{base}/SHASUMS256.txt"))
137
+ .call()
138
+ .ok()?
139
+ .into_string()
140
+ .ok()?;
141
+ text.lines()
142
+ .find(|line| line.trim_end().ends_with(asset))
143
+ .and_then(|line| line.split_whitespace().next())
144
+ .map(|hash| hash.to_ascii_lowercase())
145
+ }
146
+
147
+ fn extract(archive: &Path, into: &Path) -> Result<()> {
148
+ #[cfg(windows)]
149
+ {
150
+ let status = Command::new("powershell")
151
+ .args([
152
+ "-NoProfile",
153
+ "-NonInteractive",
154
+ "-Command",
155
+ &format!(
156
+ "Expand-Archive -Path '{}' -DestinationPath '{}' -Force",
157
+ archive.display(),
158
+ into.display()
159
+ ),
160
+ ])
161
+ .status()
162
+ .context("executando powershell")?;
163
+ if !status.success() {
164
+ bail!("Expand-Archive falhou");
165
+ }
166
+ }
167
+ #[cfg(not(windows))]
168
+ {
169
+ let status = Command::new("tar")
170
+ .arg("-xzf")
171
+ .arg(archive)
172
+ .arg("-C")
173
+ .arg(into)
174
+ .status()
175
+ .context("tar não encontrado")?;
176
+ if !status.success() {
177
+ bail!("tar falhou ao extrair {archive:?}");
178
+ }
179
+ }
180
+ Ok(())
181
+ }
182
+
183
+ fn find_binary(dir: &Path) -> Option<PathBuf> {
184
+ let name = binary_name();
185
+ let direct = dir.join(name);
186
+ if direct.exists() {
187
+ return Some(direct);
188
+ }
189
+ fs::read_dir(dir)
190
+ .ok()?
191
+ .flatten()
192
+ .map(|entry| entry.path())
193
+ .find(|path| path.file_name().map(|n| n == name).unwrap_or(false))
194
+ }
195
+
196
+ fn replace_self(new_bin: &Path) -> Result<()> {
197
+ let current = self_path()?;
198
+ let staged = current.with_file_name(format!(".{}.new", binary_name()));
199
+ fs::copy(new_bin, &staged).context("copiando binário novo")?;
200
+ #[cfg(unix)]
201
+ {
202
+ use std::os::unix::fs::PermissionsExt;
203
+ fs::set_permissions(&staged, fs::Permissions::from_mode(0o755))?;
204
+ }
205
+
206
+ #[cfg(windows)]
207
+ {
208
+ let old = current.with_file_name(format!(".{}.old", binary_name()));
209
+ let _ = fs::remove_file(&old);
210
+ fs::rename(&current, &old).context("movendo binário em uso")?;
211
+ if let Err(err) = fs::rename(&staged, &current) {
212
+ let _ = fs::rename(&old, &current);
213
+ return Err(err.into());
214
+ }
215
+ let _ = fs::remove_file(&old);
216
+ return Ok(());
217
+ }
218
+
219
+ #[cfg(unix)]
220
+ {
221
+ fs::rename(&staged, &current)
222
+ .with_context(|| format!("substituindo {}", current.display()))?;
223
+ Ok(())
224
+ }
225
+ }
226
+
227
+ fn self_path() -> Result<PathBuf> {
228
+ std::env::current_exe().context("descobrindo o próprio executável")
229
+ }
230
+
231
+ fn binary_name() -> &'static str {
232
+ if cfg!(windows) {
233
+ "silentium.exe"
234
+ } else {
235
+ "silentium"
236
+ }
237
+ }
238
+
239
+ fn asset_name() -> Option<String> {
240
+ let os = match std::env::consts::OS {
241
+ "linux" => "linux",
242
+ "macos" => "darwin",
243
+ "windows" => "windows",
244
+ _ => return None,
245
+ };
246
+ let arch = match std::env::consts::ARCH {
247
+ "x86_64" => "x64",
248
+ "aarch64" => "arm64",
249
+ _ => return None,
250
+ };
251
+ let ext = if os == "windows" { "zip" } else { "tar.gz" };
252
+ Some(format!("silentium-{os}-{arch}.{ext}"))
253
+ }
254
+
255
+ fn agent() -> ureq::Agent {
256
+ ureq::AgentBuilder::new()
257
+ .timeout(Duration::from_secs(20))
258
+ .build()
259
+ }
260
+
261
+ fn fetch_latest_tag() -> Result<String> {
262
+ let url = format!("https://api.github.com/repos/{REPO}/releases/latest");
263
+ let json: serde_json::Value = agent()
264
+ .get(&url)
265
+ .set("user-agent", &format!("silentium/{CURRENT}"))
266
+ .call()
267
+ .context("GitHub API")?
268
+ .into_json()
269
+ .context("resposta da API não é JSON")?;
270
+ json.get("tag_name")
271
+ .and_then(|value| value.as_str())
272
+ .map(|tag| tag.to_string())
273
+ .context("release sem tag_name")
274
+ }
275
+
276
+ fn via_npm() -> bool {
277
+ self_path()
278
+ .map(|path| path.to_string_lossy().contains("node_modules"))
279
+ .unwrap_or(false)
280
+ }
281
+
282
+ fn now() -> u64 {
283
+ SystemTime::now()
284
+ .duration_since(UNIX_EPOCH)
285
+ .map(|elapsed| elapsed.as_secs())
286
+ .unwrap_or(0)
287
+ }
288
+
289
+ fn cache_path() -> Option<PathBuf> {
290
+ let base = cache_base()?;
291
+ Some(base.join("silentium").join("update.json"))
292
+ }
293
+
294
+ fn cache_base() -> Option<PathBuf> {
295
+ if let Some(dir) = std::env::var_os("XDG_CACHE_HOME") {
296
+ return Some(PathBuf::from(dir));
297
+ }
298
+ #[cfg(windows)]
299
+ {
300
+ std::env::var_os("LOCALAPPDATA").map(PathBuf::from)
301
+ }
302
+ #[cfg(not(windows))]
303
+ {
304
+ std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".cache"))
305
+ }
306
+ }
307
+
308
+ fn read_cache() -> Cache {
309
+ cache_path()
310
+ .and_then(|path| fs::read_to_string(path).ok())
311
+ .and_then(|text| serde_json::from_str(&text).ok())
312
+ .unwrap_or_default()
313
+ }
314
+
315
+ fn write_cache(cache: &Cache) {
316
+ let Some(path) = cache_path() else { return };
317
+ if let Some(dir) = path.parent() {
318
+ let _ = fs::create_dir_all(dir);
319
+ }
320
+ if let Ok(text) = serde_json::to_string(cache) {
321
+ let _ = fs::write(path, text);
322
+ }
323
+ }
324
+
325
+ /// Compara tags tipo `v0.2.0`. Pré-release (`v0.2.0-rc.1`) conta como menor.
326
+ pub fn is_newer(latest: &str, current: &str) -> bool {
327
+ let (latest_version, latest_pre) = parse_version(latest);
328
+ let (current_version, current_pre) = parse_version(current);
329
+ match latest_version.cmp(&current_version) {
330
+ std::cmp::Ordering::Greater => true,
331
+ std::cmp::Ordering::Less => false,
332
+ std::cmp::Ordering::Equal => current_pre && !latest_pre,
333
+ }
334
+ }
335
+
336
+ fn parse_version(raw: &str) -> (Vec<u64>, bool) {
337
+ let trimmed = raw.trim().trim_start_matches('v');
338
+ let (core, pre) = match trimmed.split_once('-') {
339
+ Some((core, _)) => (core, true),
340
+ None => (trimmed, false),
341
+ };
342
+ let parts = core
343
+ .split('.')
344
+ .map(|part| {
345
+ part.chars()
346
+ .take_while(|c| c.is_ascii_digit())
347
+ .collect::<String>()
348
+ .parse::<u64>()
349
+ .unwrap_or(0)
350
+ })
351
+ .collect();
352
+ (parts, pre)
353
+ }
354
+
355
+ #[cfg(test)]
356
+ mod tests {
357
+ use super::{is_newer, parse_version};
358
+
359
+ #[test]
360
+ fn reconhece_versao_maior() {
361
+ assert!(is_newer("v0.2.0", "0.1.0"));
362
+ assert!(is_newer("v1.0.0", "0.9.9"));
363
+ assert!(is_newer("v0.1.10", "0.1.9"));
364
+ }
365
+
366
+ #[test]
367
+ fn ignora_mesma_versao_e_menor() {
368
+ assert!(!is_newer("v0.1.0", "0.1.0"));
369
+ assert!(!is_newer("0.1.0", "v0.1.0"));
370
+ assert!(!is_newer("v0.0.9", "0.1.0"));
371
+ }
372
+
373
+ #[test]
374
+ fn pre_release_e_tratada() {
375
+ assert!(is_newer("v0.2.0", "0.2.0-rc.1"));
376
+ assert!(!is_newer("v0.2.0-rc.1", "0.2.0"));
377
+ }
378
+
379
+ #[test]
380
+ fn versao_estavel_a_partir_de_pre() {
381
+ let (atual, pre) = parse_version("v1.2.3-beta.2");
382
+ assert_eq!(atual, vec![1, 2, 3]);
383
+ assert!(pre);
384
+ }
385
+ }