-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmanix.rs
312 lines (282 loc) · 9.7 KB
/
manix.rs
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
use anyhow::{Context, Result};
use colored::*;
use comments_docsource::CommentsDatabase;
use lazy_static::lazy_static;
use manix::*;
use options_docsource::{OptionsDatabase, OptionsDatabaseType};
use std::path::PathBuf;
use structopt::clap::arg_enum;
use structopt::StructOpt;
arg_enum! {
#[derive(Debug, PartialEq)]
#[allow(non_camel_case_types)]
enum Source {
nixos_options,
hm_options,
nd_options,
nixpkgs_doc,
nixpkgs_tree,
nixpkgs_comments,
}
}
lazy_static! {
static ref SOURCE_VARIANTS: String = Source::variants().join(",");
}
#[derive(StructOpt)]
#[structopt(name = "manix")]
struct Opt {
/// Force update cache
#[structopt(short, long)]
update_cache: bool,
/// Matches entries stricly
#[structopt(short, long)]
strict: bool,
/// Restrict search to chosen sources
#[structopt(long, possible_values = &Source::variants(), default_value = &SOURCE_VARIANTS, use_delimiter = true)]
source: Vec<Source>,
#[structopt(name = "QUERY")]
query: String,
}
fn build_source_and_add<T>(
mut source: T,
name: &str,
path: &PathBuf,
aggregate: Option<&mut AggregateDocSource>,
) -> Option<()>
where
T: 'static + DocSource + Cache + Sync,
{
eprintln!("Building {} cache...", name);
if let Err(e) = source
.update()
.with_context(|| anyhow::anyhow!("Failed to update {}", name))
{
eprintln!("{:?}", e);
return None;
}
if let Err(e) = source
.save(&path)
.with_context(|| format!("Failed to save {} cache", name))
{
eprintln!("{:?}", e);
return None;
}
if let Some(aggregate) = aggregate {
aggregate.add_source(Box::new(source));
}
Some(())
}
fn load_source_and_add<T>(
load_result: Result<Result<T, Errors>, std::io::Error>,
name: &str,
aggregate: &mut AggregateDocSource,
ignore_file_io_error: bool,
) -> Option<()>
where
T: 'static + DocSource + Cache + Sync,
{
let load_result = match load_result {
Err(e) => {
if !ignore_file_io_error {
eprintln!("Failed to load {} cache file: {:?}", name, e);
}
return None;
}
Ok(r) => r,
};
match load_result.with_context(|| anyhow::anyhow!("Failed to load {}", name)) {
Err(e) => {
eprintln!("{:?}", e);
None
}
Ok(source) => {
aggregate.add_source(Box::new(source));
Some(())
}
}
}
fn main() -> Result<()> {
let opt: Opt = Opt::from_args();
let cache_dir =
xdg::BaseDirectories::with_prefix("manix").context("Failed to get a cache directory")?;
let last_version_path = cache_dir
.place_cache_file("last_version.txt")
.context("Failed to place last version file")?;
let comment_cache_path = cache_dir
.place_cache_file("comments.bin")
.context("Failed to place cache file")?;
let nixpkgs_tree_cache_path = cache_dir
.place_cache_file("nixpkgs_tree.bin")
.context("Failed to place nixpkgs tree cache file")?;
let options_hm_cache_path = cache_dir
.place_cache_file("options_hm_database.bin")
.context("Failed to place home-manager options cache file")?;
let options_nd_cache_path = cache_dir
.place_cache_file("options_nd_database.bin")
.context("Failed to place nix-darwin options cache file")?;
let options_nixos_cache_path = cache_dir
.place_cache_file("options_nixos_database.bin")
.context("Failed to place NixOS options cache file")?;
let nixpkgs_doc_cache_path = cache_dir
.place_cache_file("nixpkgs_doc_database.bin")
.context("Failed to place Nixpkgs Documentation cache file")?;
let version = std::env!("CARGO_PKG_VERSION");
let last_version = std::fs::read(&last_version_path)
.map(|c| String::from_utf8(c))
.unwrap_or(Ok(version.to_string()))?;
let should_invalidate_cache = version != last_version;
let mut aggregate_source = AggregateDocSource::default();
let mut comment_db = if !should_invalidate_cache && comment_cache_path.exists() {
CommentsDatabase::load(&std::fs::read(&comment_cache_path)?)
.map_err(|e| anyhow::anyhow!("Failed to load Nixpkgs comments database: {:?}", e))?
} else {
CommentsDatabase::new()
};
if comment_db.hash_to_defs.len() == 0 {
eprintln!("Building Nixpkgs comments cache...");
}
let cache_invalid = comment_db
.update()
.map_err(|e| anyhow::anyhow!(e))
.context("Failed to update cache")?;
comment_db.save(&comment_cache_path)?;
if opt.source.contains(&Source::nixpkgs_comments) {
aggregate_source.add_source(Box::new(comment_db));
}
if should_invalidate_cache || opt.update_cache || cache_invalid {
if let None = build_source_and_add(
OptionsDatabase::new(OptionsDatabaseType::HomeManager),
"Home Manager Options",
&options_hm_cache_path,
if opt.source.contains(&Source::hm_options) {
Some(&mut aggregate_source)
} else {
None
},
) {
eprintln!("Tip: If you installed your home-manager through configuration.nix you can fix this error by adding the home-manager channel with this command: {}", "nix-channel --add https://github.com/rycee/home-manager/archive/master.tar.gz home-manager && nix-channel --update".bold());
}
if let None = build_source_and_add(
OptionsDatabase::new(OptionsDatabaseType::NixDarwin),
"Nix-Darwin Options",
&options_nd_cache_path,
if opt.source.contains(&Source::nd_options) {
Some(&mut aggregate_source)
} else {
None
},
) {
eprintln!("Tip: Ensure darwin is set in your NIX_PATH");
}
build_source_and_add(
OptionsDatabase::new(OptionsDatabaseType::NixOS),
"NixOS Options",
&options_nixos_cache_path,
if opt.source.contains(&Source::nixos_options) {
Some(&mut aggregate_source)
} else {
None
},
);
build_source_and_add(
nixpkgs_tree_docsource::NixpkgsTreeDatabase::new(),
"Nixpkgs Tree",
&nixpkgs_tree_cache_path,
if opt.source.contains(&Source::nixpkgs_tree) {
Some(&mut aggregate_source)
} else {
None
},
);
build_source_and_add(
xml_docsource::XmlFuncDocDatabase::new(),
"Nixpkgs Documentation",
&nixpkgs_doc_cache_path,
if opt.source.contains(&Source::nixpkgs_doc) {
Some(&mut aggregate_source)
} else {
None
},
);
std::fs::write(&last_version_path, version)?;
} else {
if opt.source.contains(&Source::nd_options) {
load_source_and_add(
std::fs::read(&options_nd_cache_path).map(|c| OptionsDatabase::load(&c)),
"Nix Darwin Options",
&mut aggregate_source,
true,
);
}
if opt.source.contains(&Source::hm_options) {
load_source_and_add(
std::fs::read(&options_hm_cache_path).map(|c| OptionsDatabase::load(&c)),
"Home Manager Options",
&mut aggregate_source,
true,
);
}
if opt.source.contains(&Source::nixos_options) {
load_source_and_add(
std::fs::read(&options_nixos_cache_path).map(|c| OptionsDatabase::load(&c)),
"NixOS Options",
&mut aggregate_source,
false,
);
}
if opt.source.contains(&Source::nixpkgs_tree) {
load_source_and_add(
std::fs::read(&nixpkgs_tree_cache_path)
.map(|c| nixpkgs_tree_docsource::NixpkgsTreeDatabase::load(&c)),
"Nixpkgs Tree",
&mut aggregate_source,
false,
);
}
if opt.source.contains(&Source::nixpkgs_doc) {
load_source_and_add(
std::fs::read(&nixpkgs_doc_cache_path)
.map(|c| xml_docsource::XmlFuncDocDatabase::load(&c)),
"Nixpkgs Documentation",
&mut aggregate_source,
false,
);
}
}
let query_lower = opt.query.to_ascii_lowercase();
let query = manix::Lowercase(query_lower.as_bytes());
let entries = if opt.strict {
aggregate_source.search(&query)
} else {
aggregate_source.search_liberal(&query)
};
let (entries, key_only_entries): (Vec<DocEntry>, Vec<DocEntry>) =
entries.into_iter().partition(|e| {
if let DocEntry::NixpkgsTreeDoc(_) = e {
false
} else {
true
}
});
if !key_only_entries.is_empty() {
const SHOW_MAX_LEN: usize = 50;
print!("{}", "Here's what I found in nixpkgs:".bold());
for entry in key_only_entries.iter().take(SHOW_MAX_LEN) {
print!(" {}", entry.name().white());
}
if key_only_entries.len() > SHOW_MAX_LEN {
print!(" and {} more.", key_only_entries.len() - SHOW_MAX_LEN);
}
println!("\n");
}
for entry in entries {
const LINE: &str = "────────────────────";
println!(
"{}\n{}\n{}",
entry.source().white(),
LINE.green(),
entry.pretty_printed()
);
}
Ok(())
}