Skip to content

Commit

Permalink
restore nh search
Browse files Browse the repository at this point in the history
  • Loading branch information
viperML committed Nov 19, 2024
1 parent b22e96f commit 3d692d3
Show file tree
Hide file tree
Showing 7 changed files with 45 additions and 86 deletions.
6 changes: 6 additions & 0 deletions fix.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#! /usr/bin/env bash
set -eux

cargo fix --allow-dirty
cargo clippy --fix --allow-dirty
cargo fmt
2 changes: 1 addition & 1 deletion shell.nix
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ with pkgs;

env = {
NH_NOM = "1";
RUST_LOG = "nh=trace";
NH_LOG = "nh=trace";
RUST_SRC_PATH = "${rustPlatform.rustLibSrc}";
};
}
9 changes: 4 additions & 5 deletions src/home.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,14 @@
use std::env;
use std::path::PathBuf;

use color_eyre::eyre::{bail, Context};
use color_eyre::eyre::bail;
use color_eyre::Result;
use tracing::{debug, info, warn};
use tracing::{debug, info};

use crate::commands;
use crate::commands::Command;
use crate::installable::Installable;
use crate::interface::OsSubcommand::{self};
use crate::interface::{self, HomeRebuildArgs, OsRebuildArgs, OsReplArgs};
use crate::interface::{self, HomeRebuildArgs};

const SYSTEM_PROFILE: &str = "/nix/var/nix/profiles/system";
const CURRENT_PROFILE: &str = "/run/current-system";
Expand Down Expand Up @@ -138,7 +137,7 @@ fn toplevel_for(installable: Installable) -> Result<Installable> {

let mut tried = vec![];

for attr in [format!("{username}@{hostname}"), format!("{username}")] {
for attr in [format!("{username}@{hostname}"), username.to_string()] {
let func = format!(r#" x: x ? "{}" "#, attr);
let res = commands::Command::new("nix")
.args(["eval", "--apply"])
Expand Down
21 changes: 15 additions & 6 deletions src/interface.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::path::PathBuf;

use anstyle::Style;
use clap::ValueEnum;
use clap::{builder::Styles, Args, Parser, Subcommand};

use crate::installable::Installable;
Expand Down Expand Up @@ -54,7 +55,7 @@ impl NHCommand {
pub fn run(self) -> Result<()> {
match self {
NHCommand::Os(args) => args.run(),
NHCommand::Search(_args) => todo!(),
NHCommand::Search(args) => args.run(),
NHCommand::Clean(proxy) => proxy.command.run(),
NHCommand::Completions(args) => args.run(),
NHCommand::Home(args) => args.run(),
Expand Down Expand Up @@ -155,15 +156,23 @@ pub struct SearchArgs {
/// Number of search results to display
pub limit: u64,

#[arg(long, short)]
/// Name of the channel to query (e.g nixos-23.11, nixos-unstable)
pub channel: Option<String>,
#[arg(
long,
short,
env = "NH_SEARCH_CHANNEL",
default_value = "nixos-unstable"
)]
/// Name of the channel to query (e.g nixos-23.11, nixos-unstable, ...)
pub channel: String,

/// Name of the package to search
pub query: String,
}

#[command(flatten)]
pub installable: Installable,
#[derive(Debug, Clone, ValueEnum)]
pub enum SearchNixpkgsFrom {
Flake,
Path,
}

// Needed a struct to have multiple sub-subcommands
Expand Down
2 changes: 1 addition & 1 deletion src/logging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub(crate) fn setup_logging(verbose: bool) -> Result<()> {
.without_time()
.compact()
.with_line_number(true)
.with_filter(EnvFilter::from_default_env().or(filter_fn(move |_| verbose)))
.with_filter(EnvFilter::from_env("NH_LOG").or(filter_fn(move |_| verbose)))
.with_filter(filter_fn(|meta| *meta.level() > Level::INFO));

let layer_info = fmt::layer()
Expand Down
4 changes: 2 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
mod clean;
mod commands;
mod completion;
mod home;
mod installable;
mod interface;
mod json;
mod logging;
mod nixos;
// mod search;
mod home;
mod search;
mod util;

use color_eyre::Result;
Expand Down
87 changes: 16 additions & 71 deletions src/search.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use std::{process::Stdio, time::Instant};
use std::process::Stdio;
use std::time::Instant;

use color_eyre::eyre::{eyre, Context, ContextCompat};
use color_eyre::eyre::{bail, Context, ContextCompat};
use elasticsearch_dsl::*;
use interface::SearchArgs;
use regex::Regex;
use serde::Deserialize;
use tracing::{debug, trace, warn};
use tracing::{debug, trace};

use crate::*;

Expand Down Expand Up @@ -44,16 +45,17 @@ impl SearchArgs {
pub fn run(&self) -> Result<()> {
trace!("args: {self:?}");

if !supported_branch(&self.channel) {
bail!("Channel {} is not supported!", self.channel);
}

let nixpkgs_path = std::thread::spawn(|| {
std::process::Command::new("nix")
.stderr(Stdio::inherit())
.args(["eval", "nixpkgs#path"])
.args(["eval", "-f", "<nixpkgs>", "path"])
.output()
});

// let mut nixpkgs_path = std::process::Command::new("nix")
// .context("Evaluating the nixpkgs path for results positions")?;

let query = Search::new().from(0).size(self.limit).query(
Query::bool().filter(Query::term("type", "package")).must(
Query::dis_max()
Expand Down Expand Up @@ -88,32 +90,10 @@ impl SearchArgs {
),
);

let channel: String = match (&self.channel, &self.flake) {
(Some(c), _) => c.clone(),
(None, Some(f)) => {
let c = my_nix_branch(f);
match c {
Ok(s) => s,
Err(err) => {
warn!(
"Failed to read the nixpkgs input for the flake {}",
f.as_str()
);
for e in err.chain() {
warn!("{}", e);
}
String::from("nixos-unstable")
}
}
}
(None, None) => {
debug!("Using default search channel");
String::from("nixos-unstable")
}
};
debug!(?channel);

println!("Querying search.nixos.org, with channel {}...", channel);
println!(
"Querying search.nixos.org, with channel {}...",
self.channel
);
let then = Instant::now();

let client = reqwest::blocking::Client::new();
Expand All @@ -122,7 +102,7 @@ impl SearchArgs {
// TODO: have a GH action or something check if they updated this thing
.post(format!(
"https://search.nixos.org/backend/latest-42-{}/_search",
channel
self.channel
))
.json(&query)
.header("User-Agent", format!("nh/{}", crate::NH_VERSION))
Expand Down Expand Up @@ -195,7 +175,8 @@ impl SearchArgs {
}

if let Some(position) = &elem.package_position {
print!(" Position: ");
let position = position.split(':').next().unwrap();
print!(" Defined at: ");
if hyperlinks {
let postion_trimmed = position
.split(':')
Expand All @@ -213,42 +194,6 @@ impl SearchArgs {
}
}

fn my_nix_branch(flake: &FlakeRef) -> Result<String> {
let output = std::process::Command::new("nix")
.args(["flake", "metadata", "--json"])
.arg(flake.as_str())
.output()?;

let metadata: serde_json::Value = serde_json::from_slice(&output.stdout)?;
let m = crate::json::Value::new(&metadata);

let nixpkgs_input = m
.get("locks")?
.get("nodes")?
.get("root")?
.get("inputs")?
.get("nixpkgs")?
.inner
.as_str()
.wrap_err("Failed to read as string")?;

let branch = m
.get("locks")?
.get("nodes")?
.get(nixpkgs_input)?
.get("original")?
.get("ref")?
.inner
.as_str()
.wrap_err("Failed to read as string")?;

if supported_branch(branch) {
Ok(branch.to_owned())
} else {
Err(eyre!("Branch {} is not supported", &branch))
}
}

fn supported_branch<S: AsRef<str>>(branch: S) -> bool {
let branch = branch.as_ref();

Expand Down

0 comments on commit 3d692d3

Please sign in to comment.