Skip to main content

lux_cli/
doc.rs

1use clap::Args;
2use inquire::{Confirm, Select};
3use itertools::Itertools;
4use lux_lib::package;
5use lux_lib::rockspec;
6use lux_lib::{
7    config::Config,
8    lockfile::{LockedPackage, OptState, PinnedState},
9    rockspec::Rockspec,
10    tree::{InstallTree, RockMatches, Tree},
11};
12use miette::{miette, Context, IntoDiagnostic, Result};
13use std::io::Read;
14use std::path::{Path, PathBuf};
15use url::Url;
16use walkdir::WalkDir;
17
18use crate::workspace::current_workspace_or_user_tree;
19
20#[derive(Args)]
21pub struct Doc {
22    /// The package to show documentation for.{n}
23    /// If not set, lux will use the package installed in the tree,{n}
24    /// or prompt to select one if the tree has many.
25    #[arg(short, long, visible_short_alias = 'p')]
26    package: Option<package::Req>,
27
28    /// Ignore local docs and open the package's homepage in a browser.
29    #[arg(long)]
30    online: bool,
31}
32
33fn package_label(pkg: &LockedPackage) -> String {
34    let mut modifiers = Vec::new();
35    if pkg.pinned() == PinnedState::Pinned {
36        modifiers.push("pinned".to_string());
37    }
38    if pkg.opt() == OptState::Optional {
39        modifiers.push("optional".to_string());
40    }
41    if let Some(constraint) = pkg.spec().constraint().to_string_opt() {
42        modifiers.push(format!("constraint: {constraint}"));
43    }
44    if modifiers.is_empty() {
45        format!("{}@{}", pkg.name(), pkg.version())
46    } else {
47        format!(
48            "{}@{} ({})",
49            pkg.name(),
50            pkg.version(),
51            modifiers.join(", ")
52        )
53    }
54}
55
56pub async fn doc(args: Doc, config: Config) -> Result<()> {
57    let tree = current_workspace_or_user_tree(&config)?;
58    let package_req = match &args.package {
59        Some(package_req) => package_req.clone(),
60        None => {
61            let candidates = tree
62                .list()?
63                .into_values()
64                .flatten()
65                .map(|pkg| pkg.into_package_spec().into_package_req().to_string())
66                .unique()
67                .sorted()
68                .collect_vec();
69            let selected = match candidates.as_slice() {
70                [] => {
71                    return Err(miette!(
72                        help = "install a package into this tree, or specify a package with '--package=<PACKAGE>'",
73                        "no packages found in this tree"
74                    ));
75                }
76                [candidate] => candidate.clone(),
77                candidates => {
78                    if config.no_prompt() {
79                        return Err(miette!(
80                            help = "specify the package with '--package=<PACKAGE>'",
81                            "multiple packages found in this tree, but no package specified"
82                        ));
83                    }
84                    Select::new(
85                        "Please select a package to show documentation for.",
86                        candidates.to_vec(),
87                    )
88                    .prompt()
89                    .into_diagnostic()
90                    .wrap_err("error selecting from multiple packages")?
91                }
92            };
93            package::Req::parse(&selected)?
94        }
95    };
96    let lockfile = tree.lockfile()?;
97    let package_id = match tree.match_rocks(&package_req)? {
98        RockMatches::NotFound(package_req) => {
99            Err(miette!("no package matching {package_req} found"))
100        }
101        RockMatches::Many(package_ids) => {
102            if config.no_prompt() {
103                Err(miette!(
104                    help = "specify an exact package (<name>@<version>) or narrow the version requirement",
105                    "found multiple packages matching {}",
106                    package_req
107                ))
108            } else {
109                let candidates: Vec<_> = package_ids
110                    .into_iter()
111                    .filter_map(|id| lockfile.get(&id).map(|pkg| (id, pkg.clone())))
112                    .collect();
113                let labels = candidates
114                    .iter()
115                    .map(|(_, pkg)| package_label(pkg))
116                    .collect_vec();
117                let selected = Select::new(
118                    &format!(
119                        "Multiple packages matching {} found. Please select one to open.",
120                        package_req
121                    ),
122                    labels,
123                )
124                .raw_prompt()
125                .into_diagnostic()
126                .wrap_err("error selecting from multiple packages")?;
127                Ok(candidates[selected.index].0.clone())
128            }
129        }
130        RockMatches::Single(package_id) => Ok(package_id),
131    }?;
132    let pkg = lockfile
133        .get(&package_id)
134        .ok_or_else(|| miette!("package is installed, but not found in the lockfile"))?
135        .clone();
136    if args.online {
137        open_homepage(pkg, &tree).await
138    } else {
139        open_local_docs(pkg, &tree, &config).await
140    }
141}
142
143async fn open_homepage(pkg: LockedPackage, tree: &Tree) -> Result<()> {
144    let homepage = match get_homepage(&pkg, tree)? {
145        Some(homepage) => Ok(homepage),
146        None => Err(miette!(
147            "package {} does not have a homepage in its RockSpec",
148            pkg.into_package_spec()
149        )),
150    }?;
151    open::that(homepage.to_string()).into_diagnostic()?;
152    Ok(())
153}
154
155fn get_homepage(pkg: &LockedPackage, tree: &Tree) -> Result<Option<Url>> {
156    let rockspec_content =
157        std::fs::read_to_string(tree.layout_for(pkg.spec()).rockspec_path()).into_diagnostic()?;
158    let rockspec = rockspec::lua::Remote::new(&rockspec_content)?;
159    Ok(rockspec.description().homepage.clone())
160}
161
162fn is_plain_text(path: &Path) -> Result<bool> {
163    let mut buf = Vec::with_capacity(1024);
164    std::fs::File::open(path)
165        .into_diagnostic()?
166        .take(1024)
167        .read_to_end(&mut buf)
168        .into_diagnostic()?;
169    Ok(content_inspector::inspect(&buf).is_text())
170}
171
172fn open_doc_file(path: &Path) -> Result<()> {
173    if is_plain_text(path).wrap_err_with(|| format!("error reading '{}'", path.display()))? {
174        edit::edit_file(path)
175            .into_diagnostic()
176            .wrap_err_with(|| format!("could not open '{}' for editing", path.display()))?;
177    } else {
178        open::that(path)
179            .into_diagnostic()
180            .wrap_err_with(|| format!("could not open '{}' in a browser", path.display()))?;
181    }
182    Ok(())
183}
184
185async fn open_local_docs(pkg: LockedPackage, tree: &Tree, config: &Config) -> Result<()> {
186    let doc_dir = tree.layout_for(pkg.spec()).doc;
187    let files: Vec<PathBuf> = WalkDir::new(&doc_dir)
188        .into_iter()
189        .filter_map_ok(|file| {
190            let path = file.into_path();
191            path.is_file().then_some(path)
192        })
193        .try_collect()
194        .into_diagnostic()?;
195    match files.as_slice() {
196        [file] => open_doc_file(file),
197        [_, _, ..] => {
198            let labels = files
199                .iter()
200                .map(|file| {
201                    file.strip_prefix(&doc_dir)
202                        .unwrap_or(file.as_path())
203                        .to_string_lossy()
204                        .to_string()
205                })
206                .collect_vec();
207            if config.no_prompt() {
208                return Err(miette!(
209                    help = "rerun without `--no-prompt` to select a documentation file",
210                    "found multiple documentation files for package '{}': {}",
211                    pkg.as_package_spec(),
212                    labels.join(", ")
213                ));
214            }
215            let selected = Select::new(
216                "Multiple documentation files found. Please select one to open.",
217                labels,
218            )
219            .raw_prompt()
220            .into_diagnostic()
221            .wrap_err("error selecting from multiple files")?;
222            open_doc_file(&files[selected.index])
223        }
224        [] => match get_homepage(&pkg, tree)? {
225            None => Err(miette!(
226                "no documentation found for package '{}'",
227                pkg.into_package_spec()
228            )),
229            Some(homepage) => {
230                if config.no_prompt() {
231                    return Err(miette!(
232                        "no local documentation found for package '{}'",
233                        pkg.into_package_spec()
234                    ));
235                } else if Confirm::new("No local documentation found. Open homepage?")
236                    .with_default(false)
237                    .prompt()
238                    .into_diagnostic()
239                    .wrap_err("error prompting to open homepage")?
240                {
241                    open::that(homepage.to_string()).into_diagnostic()?;
242                }
243                Ok(())
244            }
245        },
246    }
247}
248
249#[cfg(test)]
250mod tests {
251    use super::*;
252    use assert_fs::TempDir;
253    use std::io::Write;
254
255    #[test]
256    fn detects_plain_text() {
257        let dir = TempDir::new().unwrap();
258        let file = dir.path().join("README.md");
259        let mut f = std::fs::File::create(&file).unwrap();
260        writeln!(f, "# Hello, world!").unwrap();
261        assert!(is_plain_text(&file).unwrap());
262    }
263
264    #[test]
265    fn detects_binary() {
266        let dir = TempDir::new().unwrap();
267        let file = dir.path().join("diagram.png");
268        let mut f = std::fs::File::create(&file).unwrap();
269        f.write_all(b"\x89PNG\r\n\x1a\n").unwrap();
270        assert!(!is_plain_text(&file).unwrap());
271    }
272}