A fork of attic a self-hostable Nix Binary Cache server
at main 71 lines 2.1 kB view raw
1use anyhow::{anyhow, Result}; 2use clap::Parser; 3use reqwest::Url; 4 5use crate::api::ApiClient; 6use crate::cache::CacheRef; 7use crate::cli::Opts; 8use crate::config::Config; 9use crate::nix_config::NixConfig; 10use crate::nix_netrc::NixNetrc; 11 12/// Configure Nix to use a binary cache. 13#[derive(Debug, Parser)] 14pub struct Use { 15 /// The cache to configure. 16 /// 17 /// This can be either `servername:cachename` or `cachename` 18 /// when using the default server. 19 cache: CacheRef, 20} 21 22pub async fn run(opts: Opts) -> Result<()> { 23 let sub = opts.command.as_use().unwrap(); 24 let config = Config::load()?; 25 26 let (server_name, server, cache) = config.resolve_cache(&sub.cache)?; 27 28 let api = ApiClient::from_server_config(server.clone())?; 29 let cache_config = api.get_cache_config(cache).await?; 30 31 let substituter = cache_config 32 .substituter_endpoint 33 .ok_or_else(|| anyhow!("The server did not tell us where the binary cache endpoint is."))?; 34 let public_key = cache_config.public_key 35 .ok_or_else(|| anyhow!("The server did not tell us which public key it uses. Is signing managed by the client?"))?; 36 37 eprintln!( 38 "Configuring Nix to use \"{cache}\" on \"{server_name}\":", 39 cache = cache.as_str(), 40 server_name = server_name.as_str(), 41 ); 42 43 // Modify nix.conf 44 eprintln!("+ Substituter: {}", substituter); 45 eprintln!("+ Trusted Public Key: {}", public_key); 46 47 let mut nix_config = NixConfig::load().await?; 48 nix_config.add_substituter(&substituter); 49 nix_config.add_trusted_public_key(&public_key); 50 51 // Modify netrc 52 if let Some(token) = server.token()? { 53 eprintln!("+ Access Token"); 54 55 let mut nix_netrc = NixNetrc::load().await?; 56 let host = Url::parse(&substituter)? 57 .host() 58 .map(|h| h.to_string()) 59 .unwrap(); 60 nix_netrc.add_token(host, token.to_string()); 61 nix_netrc.save().await?; 62 63 let netrc_path = nix_netrc.path().unwrap().to_str().unwrap(); 64 65 nix_config.set_netrc_file(netrc_path); 66 } 67 68 nix_config.save().await?; 69 70 Ok(()) 71}