forked from nix-community/nh
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearch.rs
More file actions
223 lines (193 loc) · 7.31 KB
/
search.rs
File metadata and controls
223 lines (193 loc) · 7.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
use std::process::Stdio;
use std::time::Instant;
use color_eyre::eyre::{bail, Context};
use elasticsearch_dsl::*;
use interface::SearchArgs;
use regex::Regex;
use serde::Deserialize;
use tracing::{debug, trace};
use crate::*;
#[derive(Debug, Deserialize)]
#[allow(non_snake_case, dead_code)]
struct SearchResult {
// r#type: String,
package_attr_name: String,
package_attr_set: String,
package_pname: String,
package_pversion: String,
package_platforms: Vec<String>,
package_outputs: Vec<String>,
package_default_output: Option<String>,
package_programs: Vec<String>,
// package_license: Vec<License>,
package_license_set: Vec<String>,
// package_maintainers: Vec<HashMap<String, String>>,
package_description: Option<String>,
package_longDescription: Option<String>,
package_hydra: (),
package_system: String,
package_homepage: Vec<String>,
package_position: Option<String>,
}
macro_rules! print_hyperlink {
($text:expr, $link:expr) => {
print!("\x1b]8;;{}\x07", $link);
print!("{}", $text.underline());
println!("\x1b]8;;\x07");
};
}
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", "-f", "<nixpkgs>", "path"])
.output()
});
let query_s = self.query.join(" ");
debug!(?query_s);
let query = Search::new().from(0).size(self.limit).query(
Query::bool().filter(Query::term("type", "package")).must(
Query::dis_max()
.tie_breaker(0.7)
.query(
Query::multi_match(
[
"package_attr_name^9",
"package_attr_name.*^5.3999999999999995",
"package_programs^9",
"package_programs.*^5.3999999999999995",
"package_pname^6",
"package_pname.*^3.5999999999999996",
"package_description^1.3",
"package_description.*^0.78",
"package_longDescription^1",
"package_longDescription.*^0.6",
"flake_name^0.5",
"flake_name.*^0.3",
],
query_s.clone(),
)
.r#type(TextQueryType::CrossFields)
.analyzer("whitespace")
.auto_generate_synonyms_phrase_query(false)
.operator(Operator::And),
)
.query(
Query::wildcard("package_attr_name", format!("*{}*", &query_s))
.case_insensitive(true),
),
),
);
println!(
"Querying search.nixos.org, with channel {}...",
self.channel
);
let then = Instant::now();
let client = reqwest::blocking::Client::new();
let req = client
// I guess 42 is the version of the backend API
// TODO: have a GH action or something check if they updated this thing
.post(format!(
"https://search.nixos.org/backend/latest-42-{}/_search",
self.channel
))
.json(&query)
.header("User-Agent", format!("nh/{}", crate::NH_VERSION))
// Hardcoded upstream
// https://github.com/NixOS/nixos-search/blob/744ec58e082a3fcdd741b2c9b0654a0f7fda4603/frontend/src/index.js
.basic_auth("aWVSALXpZv", Some("X8gPHnzL52wFEekuxsfQ9cSh"))
.build()
.context("building search query")?;
debug!(?req);
let response = client
.execute(req)
.context("querying the elasticsearch API")?;
let elapsed = then.elapsed();
debug!(?elapsed);
trace!(?response);
println!("Took {}ms", elapsed.as_millis());
println!("Most relevant results at the end");
println!();
let parsed_response: SearchResponse = response
.json()
.context("parsing response into the elasticsearch format")?;
trace!(?parsed_response);
let documents = parsed_response
.documents::<SearchResult>()
.context("parsing search document")?;
let hyperlinks = supports_hyperlinks::supports_hyperlinks();
debug!(?hyperlinks);
let nixpkgs_path = String::from_utf8(
nixpkgs_path
.join()
.unwrap()
.context("Evaluating the nixpkgs path location")?
.stdout,
)
.unwrap();
for elem in documents.iter().rev() {
println!();
use owo_colors::OwoColorize;
trace!("{elem:#?}");
print!("{}", elem.package_attr_name.blue());
let v = &elem.package_pversion;
if !v.is_empty() {
print!(" ({})", v.green());
}
println!();
if let Some(ref desc) = elem.package_description {
let desc = desc.replace('\n', " ");
for line in textwrap::wrap(&desc, textwrap::Options::with_termwidth()) {
println!(" {}", line);
}
}
for url in elem.package_homepage.iter() {
print!(" Homepage: ");
if hyperlinks {
print_hyperlink!(url, url);
} else {
println!("{}", url);
}
}
if self.platforms && !elem.package_platforms.is_empty() {
println!(" Platforms: {}", elem.package_platforms.join(", "));
}
if let Some(position) = &elem.package_position {
let position = position.split(':').next().unwrap();
print!(" Defined at: ");
if hyperlinks {
let postion_trimmed = position
.split(':')
.next()
.expect("Removing line number from position");
print_hyperlink!(position, format!("file://{nixpkgs_path}/{postion_trimmed}"));
} else {
println!("{}", position);
}
}
}
Ok(())
}
}
fn supported_branch<S: AsRef<str>>(branch: S) -> bool {
let branch = branch.as_ref();
if branch == "nixos-unstable" {
return true;
}
let re = Regex::new(r"nixos-[0-9]+\.[0-9]+").unwrap();
re.is_match(branch)
}
#[test]
fn test_supported_branch() {
assert!(supported_branch("nixos-unstable"));
assert!(!supported_branch("nixos-unstable-small"));
assert!(supported_branch("nixos-24.05"));
assert!(!supported_branch("24.05"));
assert!(!supported_branch("nixpkgs-darwin"));
assert!(!supported_branch("nixpks-21.11-darwin"));
}