main.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. use anyhow::{bail, Result};
  2. use cache::relative_to_absolute;
  3. use clap::{Parser, Subcommand};
  4. use std::env;
  5. use std::fs::File;
  6. use std::path::PathBuf;
  7. use std::io::{BufRead, BufReader}; // , Write, stdout};
  8. use std::process::Command;
  9. mod cache;
  10. // see reqwest/web-o/src/cache.rs for example cache
  11. // It restores reqwest::header::HeaderMap
  12. // (which allows duplicates... and ignores case on keys)
  13. #[derive(Parser)]
  14. #[command(about = "Go updater")]
  15. struct Cli {
  16. /// Cache directory path
  17. #[arg(default_value = "cache")]
  18. cache: PathBuf,
  19. #[command(subcommand)]
  20. command: Option<Commands>,
  21. }
  22. #[derive(Subcommand)]
  23. enum Commands {
  24. /// Update go
  25. Update {},
  26. /// Display information
  27. Info {},
  28. }
  29. /// Query `go version`
  30. #[must_use]
  31. fn find_go_version() -> Result<String> {
  32. let output = Command::new("go").arg("version").output()?;
  33. if output.status.success() {
  34. // Ok! We have something!
  35. return Ok(String::from_utf8_lossy(output.stdout.as_slice()).to_string());
  36. }
  37. bail!("Failed to query go version.");
  38. }
  39. /// Locate the go binary
  40. ///
  41. /// This is redundant, it should be located via GO_PATH.
  42. #[allow(dead_code)]
  43. #[must_use]
  44. fn find_go() -> Result<String> {
  45. let output = Command::new("which").arg("go").output()?;
  46. if output.status.success() {
  47. return Ok(String::from_utf8_lossy(output.stdout.as_slice()).to_string());
  48. }
  49. bail!("Failed to locate go binary.");
  50. }
  51. const GO_URL: &str = "https://go.dev/dl/";
  52. const GO_FILE: &str = "go-dl.html";
  53. // 2 MB download of html...
  54. // static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
  55. /*
  56. CSS Selector elements of interest: (a href="" part).
  57. href are relative...
  58. div[class="downloadWrapper"] > a[class="download downloadBox"]
  59. <a class="download downloadBox" href="/dl/go1.24.0.windows-amd64.msi">
  60. <a class="download downloadBox" href="/dl/go1.24.0.linux-amd64.tar.gz">
  61. table[class="downloadtable"] > tr[class=" "] > td[class="filename"] > a[class="download"]
  62. Or possibly,
  63. table[class="downloadtable"] > tr[class=" "]
  64. or tr[class="highlight "] ?
  65. and grab the section of td's. class=filename has a href, last has SHA256.
  66. <a class="download" href="/dl/go1.24.0.src.tar.gz">go1.24.0.src.tar.gz</a>
  67. <a class="download" href="/dl/go1.24.0.linux-amd64.tar.gz">go1.24.0.linux-amd64.tar.gz</a>
  68. <a class="download" href="/dl/go1.24.0.linux-arm64.tar.gz">go1.24.0.linux-arm64.tar.gz</a>
  69. <a class="download" href="/dl/go1.24.0.windows-amd64.zip">go1.24.0.windows-amd64.zip</a>
  70. <a class="download" href="/dl/go1.24.0.windows-amd64.msi">go1.24.0.windows-amd64.msi</a>
  71. */
  72. /*
  73. fn download_and_save(url: &str, filename: &str) -> Result<()> {
  74. let client = reqwest::blocking::Client::builder()
  75. .user_agent(APP_USER_AGENT)
  76. .build()?;
  77. print!("Downloading: {url} ");
  78. let _ = stdout().flush();
  79. let mut resp = client.get(url).send().context("Failed get")?;
  80. if resp.status().is_success() {
  81. let mut file =
  82. File::create(filename).with_context(|| format!("Creating file {filename} failed."))?;
  83. resp.copy_to(&mut file)?;
  84. } else {
  85. bail!("Status Code: {:?}", resp.status());
  86. }
  87. println!("OK");
  88. Ok(())
  89. }
  90. */
  91. // URL: https://go.dev/dl/go1.24.1.linux-amd64.tar.gz
  92. #[must_use]
  93. /// Get go version from download URL.
  94. fn version_from_url(url: &str, arch: &str) -> Option<String> {
  95. if let Some(parts) = url.split_once(arch) {
  96. if let Some(part) = parts.0.rsplit_once("/go") {
  97. let part = part.1.trim_matches('.');
  98. return Some(part.to_string());
  99. }
  100. }
  101. None
  102. }
  103. #[must_use]
  104. /// Get go version from `go version` output.
  105. fn version_from_go(text: &str) -> Option<String> {
  106. let parts : Vec<&str> = text.split(' ').collect();
  107. if parts.len() == 4 {
  108. return Some(parts[2].to_string().replace("go", ""))
  109. }
  110. None
  111. }
  112. /// Return just the href="<return this part>".
  113. #[must_use]
  114. fn just_href(link: &str) -> Result<String> {
  115. let parts = link.split_once("href=\"").unwrap_or(("","")).1;
  116. let href = parts.split_once("\"").unwrap_or(("", "")).0;
  117. if !href.is_empty() {
  118. return Ok(href.to_string());
  119. }
  120. bail!("Unable to locate href");
  121. }
  122. /// Find a href link for given arch (architecture)
  123. ///
  124. /// Look for <a class="download" href="
  125. #[must_use]
  126. fn find_arch_link(arch: &str, fp:&File) -> Result<String> {
  127. let reader = BufReader::new(fp);
  128. for line in reader.lines() {
  129. if let Ok(line) = line {
  130. if line.contains("a class=\"download\"") {
  131. if line.contains(arch) {
  132. // Return just the href part.
  133. return just_href(&line);
  134. }
  135. }
  136. }
  137. }
  138. bail!("Unable to locate architecture download link");
  139. }
  140. /// find_link for given arch (architecture)
  141. ///
  142. /// Look for <a class="download" href=""
  143. #[must_use]
  144. fn find_link(arch: &str) -> Result<String> { // , Box<dyn Error>> {
  145. let fp = File::open(GO_FILE)?;
  146. let reader = BufReader::new(fp);
  147. for line in reader.lines() {
  148. if let Ok(line) = line {
  149. if line.contains("a class=\"download\"") {
  150. if line.contains(arch) {
  151. // Return just the href part.
  152. return just_href(&line);
  153. }
  154. }
  155. }
  156. }
  157. bail!("Unable to locate architecture download link");
  158. }
  159. fn main() -> Result<()> {
  160. let cli = Cli::parse();
  161. // Get go environment
  162. let go_path = env::var("GOPATH").unwrap_or(String::new());
  163. let go_root = env::var("GOROOT").unwrap_or(String::new());
  164. let go_version: String;
  165. if let Ok(version) = find_go_version() {
  166. go_version = version.as_str().trim().to_string();
  167. } else {
  168. panic!("I wasn't able to locate go. I need `go version` to know what arch to dl.");
  169. }
  170. let version = version_from_go(&go_version).unwrap();
  171. // Since I have GO_PATH, I really don't need to do `where go`...
  172. // $GOROOT/bin/go
  173. let go_where: String;
  174. if let Ok(location) = find_go() {
  175. go_where = location.as_str().trim().to_string();
  176. } else {
  177. panic!("I wasn't able to locate the go binary.");
  178. }
  179. // Get arch (from `go version` output)
  180. let parts = go_version.split(" ");
  181. let mut arch = parts.last().unwrap().to_string();
  182. arch = arch.replace("/", "-");
  183. /*
  184. println!("GO_PATH {}", go_path);
  185. println!("GO_ROOT {}", go_root);
  186. println!("version: {}", go_version);
  187. println!("where: {}", go_where);
  188. println!("arch: {}", arch);
  189. */
  190. let cache = cache::Cache::new(cli.cache, None)?;
  191. // println!("Result: {:?}", get_go_downloads().await );
  192. // Get go version and path
  193. match &cli.command {
  194. Some(Commands::Update {}) => {
  195. let status = cache.fetch(GO_URL);
  196. // Check to see if file already exists AND
  197. // Check version against go's version.
  198. // Since the go.dev site doesn't allow caching or knowing when it changed...
  199. match status {
  200. cache::Status::Fetched(fp) => {
  201. let link = find_arch_link(&arch, &fp);
  202. if let Ok(relative) = link {
  203. let abs = relative_to_absolute(GO_URL, &relative).unwrap();
  204. println!("URL: {}", abs);
  205. let latest_version = version_from_url(&abs, &arch);
  206. if let Some(latest) = latest_version {
  207. println!("Version: {} [have {}]", latest, version);
  208. if version != latest {
  209. let latest_status = cache.fetch(&abs);
  210. println!("Latest: {:?}", latest_status);
  211. }
  212. } else {
  213. println!("Finding version failed for string: [{}]", abs);
  214. }
  215. }
  216. },
  217. cache::Status::Cached(fp) => {
  218. println!("(from cache)"); // I wish I could see this.
  219. let link = find_arch_link(&arch, &fp);
  220. if let Ok(relative) = link {
  221. let abs = relative_to_absolute(GO_URL, &relative).unwrap();
  222. println!("URL: {}", abs);
  223. }
  224. }
  225. _ => {
  226. println!("Status = {:?}", status);
  227. }
  228. }
  229. }
  230. Some(Commands::Info {}) => {
  231. println!("GO_PATH {}", go_path);
  232. println!("GO_ROOT {}", go_root);
  233. println!("go ver: {}", go_version);
  234. println!("version: {}", version);
  235. println!("where: {}", go_where);
  236. println!("arch: {}", arch);
  237. }
  238. None => {
  239. // Display help.
  240. let _show_help: Cli = Cli::parse_from(["--help"]);
  241. }
  242. }
  243. Ok(())
  244. }