1use clap::Args;
2use inquire::{Confirm, Select};
3use itertools::Itertools;
4use lux_lib::{
5 config::Config,
6 lockfile::LocalPackage,
7 lua_rockspec::RemoteLuaRockspec,
8 lua_version::LuaVersion,
9 package::PackageReq,
10 rockspec::Rockspec,
11 tree::{InstallTree, RockMatches, Tree},
12};
13use miette::{miette, Context, IntoDiagnostic, Result};
14use std::io::Read;
15use std::path::Path;
16use url::Url;
17use walkdir::WalkDir;
18
19#[derive(Args)]
20pub struct Doc {
21 package: PackageReq,
22
23 #[arg(long)]
25 online: bool,
26}
27
28pub async fn doc(args: Doc, config: Config) -> Result<()> {
29 let tree = config.user_tree(LuaVersion::from(&config)?.clone())?;
30 let package_id = match tree.match_rocks(&args.package)? {
31 RockMatches::NotFound(package_req) => {
32 Err(miette!("no package matching {package_req} found"))
33 }
34 RockMatches::Many(_package_ids) => Err(miette!(
35 help = "specify an exact package (<name>@<version>) or narrow the version requirement",
36 "found multiple packages matching {}",
37 &args.package
38 )),
39 RockMatches::Single(package_id) => Ok(package_id),
40 }?;
41 let lockfile = tree.lockfile()?;
42 let pkg = lockfile
43 .get(&package_id)
44 .ok_or_else(|| miette!("package is installed, but not found in the lockfile"))?
45 .clone();
46 if args.online {
47 open_homepage(pkg, &tree).await
48 } else {
49 open_local_docs(pkg, &tree, &config).await
50 }
51}
52
53async fn open_homepage(pkg: LocalPackage, tree: &Tree) -> Result<()> {
54 let homepage = match get_homepage(&pkg, tree)? {
55 Some(homepage) => Ok(homepage),
56 None => Err(miette!(
57 "package {} does not have a homepage in its RockSpec",
58 pkg.into_package_spec()
59 )),
60 }?;
61 open::that(homepage.to_string()).into_diagnostic()?;
62 Ok(())
63}
64
65fn get_homepage(pkg: &LocalPackage, tree: &Tree) -> Result<Option<Url>> {
66 let rockspec_content =
67 std::fs::read_to_string(tree.layout_for(pkg).rockspec_path()).into_diagnostic()?;
68 let rockspec = RemoteLuaRockspec::new(&rockspec_content)?;
69 Ok(rockspec.description().homepage.clone())
70}
71
72fn is_plain_text(path: &Path) -> Result<bool> {
73 let mut buf = Vec::with_capacity(1024);
74 std::fs::File::open(path)
75 .into_diagnostic()?
76 .take(1024)
77 .read_to_end(&mut buf)
78 .into_diagnostic()?;
79 Ok(content_inspector::inspect(&buf).is_text())
80}
81
82fn open_doc_file(path: &Path) -> Result<()> {
83 if is_plain_text(path)? {
84 edit::edit_file(path).into_diagnostic()?;
85 } else {
86 open::that(path).into_diagnostic()?;
87 }
88 Ok(())
89}
90
91async fn open_local_docs(pkg: LocalPackage, tree: &Tree, config: &Config) -> Result<()> {
92 let doc_dir = tree.layout_for(&pkg).doc;
93 let files: Vec<String> = WalkDir::new(&doc_dir)
94 .into_iter()
95 .filter_map_ok(|file| {
96 let path = file.into_path();
97 if path.is_file() {
98 path.file_name()
99 .map(|file_name| file_name.to_string_lossy().to_string())
100 } else {
101 None
102 }
103 })
104 .try_collect()
105 .into_diagnostic()?;
106 match files.first() {
107 Some(file) if files.len() == 1 => {
108 open_doc_file(&doc_dir.join(file))?;
109 Ok(())
110 }
111 Some(_) => {
112 let file = Select::new(
113 "Multiple documentation files found. Please select one to open.",
114 files,
115 )
116 .prompt()
117 .into_diagnostic()
118 .wrap_err("error selecting from multiple files")?;
119 open_doc_file(&doc_dir.join(file))?;
120 Ok(())
121 }
122 None => match get_homepage(&pkg, tree)? {
123 None => Err(miette!(
124 "no documentation found for package '{}'",
125 pkg.into_package_spec()
126 )),
127 Some(homepage) => {
128 if config.no_prompt() {
129 return Err(miette!(
130 "no local documentation found for package '{}'",
131 pkg.into_package_spec()
132 ));
133 } else if Confirm::new("No local documentation found. Open homepage?")
134 .with_default(false)
135 .prompt()
136 .into_diagnostic()
137 .wrap_err("error prompting to open homepage")?
138 {
139 open::that(homepage.to_string()).into_diagnostic()?;
140 }
141 Ok(())
142 }
143 },
144 }
145}
146
147#[cfg(test)]
148mod tests {
149 use super::*;
150 use assert_fs::TempDir;
151 use std::io::Write;
152
153 #[test]
154 fn detects_plain_text() {
155 let dir = TempDir::new().unwrap();
156 let file = dir.path().join("README.md");
157 let mut f = std::fs::File::create(&file).unwrap();
158 writeln!(f, "# Hello, world!").unwrap();
159 assert!(is_plain_text(&file).unwrap());
160 }
161
162 #[test]
163 fn detects_binary() {
164 let dir = TempDir::new().unwrap();
165 let file = dir.path().join("diagram.png");
166 let mut f = std::fs::File::create(&file).unwrap();
167 f.write_all(b"\x89PNG\r\n\x1a\n").unwrap();
168 assert!(!is_plain_text(&file).unwrap());
169 }
170}