forge/cmd/
install.rs

1use crate::{DepIdentifier, FOUNDRY_LOCK, Lockfile};
2use clap::{Parser, ValueHint};
3use eyre::{Context, Result};
4use foundry_cli::{
5    opts::Dependency,
6    utils::{CommandUtils, Git, LoadConfig},
7};
8use foundry_common::fs;
9use foundry_config::{Config, impl_figment_convert_basic};
10use regex::Regex;
11use semver::Version;
12use soldeer_commands::{Command, Verbosity, commands::install::Install};
13use std::{
14    io::IsTerminal,
15    path::{Path, PathBuf},
16    str,
17    sync::LazyLock,
18};
19use yansi::Paint;
20
21static DEPENDENCY_VERSION_TAG_REGEX: LazyLock<Regex> =
22    LazyLock::new(|| Regex::new(r"^v?\d+(\.\d+)*$").unwrap());
23
24/// CLI arguments for `forge install`.
25#[derive(Clone, Debug, Parser)]
26#[command(override_usage = "forge install [OPTIONS] [DEPENDENCIES]...
27    forge install [OPTIONS] <github username>/<github project>@<tag>...
28    forge install [OPTIONS] <alias>=<github username>/<github project>@<tag>...
29    forge install [OPTIONS] <https://<github token>@git url>...)]
30    forge install [OPTIONS] <https:// git url>...")]
31pub struct InstallArgs {
32    /// The dependencies to install.
33    ///
34    /// A dependency can be a raw URL, or the path to a GitHub repository.
35    ///
36    /// Additionally, a ref can be provided by adding @ to the dependency path.
37    ///
38    /// A ref can be:
39    /// - A branch: master
40    /// - A tag: v1.2.3
41    /// - A commit: 8e8128
42    ///
43    /// For exact match, a ref can be provided with `@tag=`, `@branch=` or `@rev=` prefix.
44    ///
45    /// Target installation directory can be added via `<alias>=` suffix.
46    /// The dependency will installed to `lib/<alias>`.
47    dependencies: Vec<Dependency>,
48
49    /// The project's root path.
50    ///
51    /// By default root of the Git repository, if in one,
52    /// or the current working directory.
53    #[arg(long, value_hint = ValueHint::DirPath, value_name = "PATH")]
54    pub root: Option<PathBuf>,
55
56    #[command(flatten)]
57    opts: DependencyInstallOpts,
58}
59
60impl_figment_convert_basic!(InstallArgs);
61
62impl InstallArgs {
63    pub async fn run(self) -> Result<()> {
64        let mut config = self.load_config()?;
65        self.opts.install(&mut config, self.dependencies).await
66    }
67}
68
69#[derive(Clone, Copy, Debug, Default, Parser)]
70pub struct DependencyInstallOpts {
71    /// Perform shallow clones instead of deep ones.
72    ///
73    /// Improves performance and reduces disk usage, but prevents switching branches or tags.
74    #[arg(long)]
75    pub shallow: bool,
76
77    /// Install without adding the dependency as a submodule.
78    #[arg(long)]
79    pub no_git: bool,
80
81    /// Create a commit after installing the dependencies.
82    #[arg(long)]
83    pub commit: bool,
84}
85
86impl DependencyInstallOpts {
87    pub fn git(self, config: &Config) -> Git<'_> {
88        Git::from_config(config).shallow(self.shallow)
89    }
90
91    /// Installs all missing dependencies.
92    ///
93    /// See also [`Self::install`].
94    ///
95    /// Returns true if any dependency was installed.
96    pub async fn install_missing_dependencies(self, config: &mut Config) -> bool {
97        let lib = config.install_lib_dir();
98        if self.git(config).has_missing_dependencies(Some(lib)).unwrap_or(false) {
99            // The extra newline is needed, otherwise the compiler output will overwrite the message
100            let _ = sh_println!("Missing dependencies found. Installing now...\n");
101
102            if self.install(config, Vec::new()).await.is_err() {
103                let _ =
104                    sh_warn!("Your project has missing dependencies that could not be installed.");
105            }
106            true
107        } else {
108            false
109        }
110    }
111
112    /// Installs all dependencies
113    pub async fn install(self, config: &mut Config, dependencies: Vec<Dependency>) -> Result<()> {
114        let Self { no_git, commit, .. } = self;
115
116        let git = self.git(config);
117
118        let install_lib_dir = config.install_lib_dir();
119        let libs = git.root.join(install_lib_dir);
120
121        let mut lockfile = Lockfile::new(&config.root);
122        if !no_git {
123            lockfile = lockfile.with_git(&git);
124
125            // Check if submodules are uninitialized, if so, we need to fetch all submodules
126            // This is to ensure that foundry.lock syncs successfully and doesn't error out, when
127            // looking for commits/tags in submodules
128            if git.submodules_uninitialized()? {
129                trace!(lib = %libs.display(), "submodules uninitialized");
130                git.submodule_update(false, false, false, true, Some(&libs))?;
131            }
132        }
133
134        let out_of_sync_deps = lockfile.sync(config.install_lib_dir())?;
135
136        if dependencies.is_empty() && !no_git {
137            // Use the root of the git repository to look for submodules.
138            let root = Git::root_of(git.root)?;
139            match git.has_submodules(Some(&root)) {
140                Ok(true) => {
141                    sh_println!("Updating dependencies in {}", libs.display())?;
142
143                    // recursively fetch all submodules (without fetching latest)
144                    git.submodule_update(false, false, false, true, Some(&libs))?;
145                    lockfile.write()?;
146                }
147                Err(err) => {
148                    sh_err!("Failed to check for submodules: {err}")?;
149                }
150                _ => {
151                    // no submodules, nothing to do
152                }
153            }
154        }
155
156        fs::create_dir_all(&libs)?;
157
158        let installer = Installer { git, commit };
159        for dep in dependencies {
160            let path = libs.join(dep.name());
161            let rel_path = path
162                .strip_prefix(git.root)
163                .wrap_err("Library directory is not relative to the repository root")?;
164            sh_println!(
165                "Installing {} in {} (url: {}, tag: {})",
166                dep.name,
167                path.display(),
168                dep.url.as_deref().unwrap_or("None"),
169                dep.tag.as_deref().unwrap_or("None")
170            )?;
171
172            // this tracks the actual installed tag
173            let installed_tag;
174            let mut dep_id = None;
175            if no_git {
176                installed_tag = installer.install_as_folder(&dep, &path)?;
177            } else {
178                if commit {
179                    git.ensure_clean()?;
180                }
181                installed_tag = installer.install_as_submodule(&dep, &path)?;
182
183                let mut new_insertion = false;
184                // Pin branch to submodule if branch is used
185                if let Some(tag_or_branch) = &installed_tag {
186                    // First, check if this tag has a branch
187                    dep_id = Some(DepIdentifier::resolve_type(&git, &path, tag_or_branch)?);
188                    if git.has_branch(tag_or_branch, &path)?
189                        && dep_id.as_ref().is_some_and(|id| id.is_branch())
190                    {
191                        // always work with relative paths when directly modifying submodules
192                        git.cmd()
193                            .args(["submodule", "set-branch", "-b", tag_or_branch])
194                            .arg(rel_path)
195                            .exec()?;
196
197                        let rev = git.get_rev(tag_or_branch, &path)?;
198
199                        dep_id = Some(DepIdentifier::Branch {
200                            name: tag_or_branch.to_string(),
201                            rev,
202                            r#override: false,
203                        });
204                    }
205
206                    trace!(?dep_id, ?tag_or_branch, "resolved dep id");
207                    if let Some(dep_id) = &dep_id {
208                        new_insertion = true;
209                        lockfile.insert(rel_path.to_path_buf(), dep_id.clone());
210                    }
211
212                    if commit {
213                        // update .gitmodules which is at the root of the repo,
214                        // not necessarily at the root of the current Foundry project
215                        let root = Git::root_of(git.root)?;
216                        git.root(&root).add(Some(".gitmodules"))?;
217                    }
218                }
219
220                if new_insertion
221                    || out_of_sync_deps.as_ref().is_some_and(|o| !o.is_empty())
222                    || !lockfile.exists()
223                {
224                    lockfile.write()?;
225                }
226
227                // commit the installation
228                if commit {
229                    let mut msg = String::with_capacity(128);
230                    msg.push_str("forge install: ");
231                    msg.push_str(dep.name());
232
233                    if let Some(tag) = &installed_tag {
234                        msg.push_str("\n\n");
235
236                        if let Some(dep_id) = &dep_id {
237                            msg.push_str(&dep_id.to_string());
238                        } else {
239                            msg.push_str(tag);
240                        }
241                    }
242
243                    if !lockfile.is_empty() {
244                        git.root(&config.root).add(Some(FOUNDRY_LOCK))?;
245                    }
246                    git.commit(&msg)?;
247                }
248            }
249
250            let mut msg = format!("    {} {}", "Installed".green(), dep.name);
251            if let Some(tag) = dep.tag.or(installed_tag) {
252                msg.push(' ');
253
254                if let Some(dep_id) = dep_id {
255                    msg.push_str(&dep_id.to_string());
256                } else {
257                    msg.push_str(tag.as_str());
258                }
259            }
260            sh_println!("{msg}")?;
261
262            // Check if the dependency has soldeer.lock and install soldeer dependencies
263            if let Err(e) = install_soldeer_deps_if_needed(&path).await {
264                sh_warn!("Failed to install soldeer dependencies for {}: {e}", dep.name)?;
265            }
266        }
267
268        // update `libs` in config if not included yet
269        if !config.libs.iter().any(|p| p == install_lib_dir) {
270            config.libs.push(install_lib_dir.to_path_buf());
271            config.update_libs()?;
272        }
273
274        Ok(())
275    }
276}
277
278pub async fn install_missing_dependencies(config: &mut Config) -> bool {
279    DependencyInstallOpts::default().install_missing_dependencies(config).await
280}
281
282/// Checks if a dependency has soldeer.lock and installs soldeer dependencies if needed.
283async fn install_soldeer_deps_if_needed(dep_path: &Path) -> Result<()> {
284    let soldeer_lock = dep_path.join("soldeer.lock");
285
286    if soldeer_lock.exists() {
287        sh_println!("    Found soldeer.lock, installing soldeer dependencies...")?;
288
289        // Change to the dependency directory and run soldeer install
290        let original_dir = std::env::current_dir()?;
291        std::env::set_current_dir(dep_path)?;
292
293        let result = soldeer_commands::run(
294            Command::Install(Install::default()),
295            Verbosity::new(
296                foundry_common::shell::verbosity(),
297                if foundry_common::shell::is_quiet() { 1 } else { 0 },
298            ),
299        )
300        .await;
301
302        // Change back to original directory
303        std::env::set_current_dir(original_dir)?;
304
305        result.map_err(|e| eyre::eyre!("Failed to run soldeer install: {e}"))?;
306        sh_println!("    Soldeer dependencies installed successfully")?;
307    }
308
309    Ok(())
310}
311
312#[derive(Clone, Copy, Debug)]
313struct Installer<'a> {
314    git: Git<'a>,
315    commit: bool,
316}
317
318impl Installer<'_> {
319    /// Installs the dependency as an ordinary folder instead of a submodule
320    fn install_as_folder(self, dep: &Dependency, path: &Path) -> Result<Option<String>> {
321        let url = dep.require_url()?;
322        Git::clone(dep.tag.is_none(), url, Some(&path))?;
323        let mut dep = dep.clone();
324
325        if dep.tag.is_none() {
326            // try to find latest semver release tag
327            dep.tag = self.last_tag(path);
328        }
329
330        // checkout the tag if necessary
331        self.git_checkout(&dep, path, false)?;
332
333        trace!("updating dependency submodules recursively");
334        self.git.root(path).submodule_update(
335            false,
336            false,
337            false,
338            true,
339            std::iter::empty::<PathBuf>(),
340        )?;
341
342        // remove git artifacts
343        fs::remove_dir_all(path.join(".git"))?;
344
345        Ok(dep.tag)
346    }
347
348    /// Installs the dependency as new submodule.
349    ///
350    /// This will add the git submodule to the given dir, initialize it and checkout the tag if
351    /// provided or try to find the latest semver, release tag.
352    fn install_as_submodule(self, dep: &Dependency, path: &Path) -> Result<Option<String>> {
353        // install the dep
354        self.git_submodule(dep, path)?;
355
356        let mut dep = dep.clone();
357        if dep.tag.is_none() {
358            // try to find latest semver release tag
359            dep.tag = self.last_tag(path);
360        }
361
362        // checkout the tag if necessary
363        self.git_checkout(&dep, path, true)?;
364
365        trace!("updating dependency submodules recursively");
366        self.git.root(path).submodule_update(
367            false,
368            false,
369            false,
370            true,
371            std::iter::empty::<PathBuf>(),
372        )?;
373
374        // sync submodules config with changes in .gitmodules, see <https://github.com/foundry-rs/foundry/issues/9611>
375        self.git.root(path).submodule_sync()?;
376
377        if self.commit {
378            self.git.add(Some(path))?;
379        }
380
381        Ok(dep.tag)
382    }
383
384    fn last_tag(self, path: &Path) -> Option<String> {
385        if self.git.shallow {
386            None
387        } else {
388            self.git_semver_tags(path).ok().and_then(|mut tags| tags.pop()).map(|(tag, _)| tag)
389        }
390    }
391
392    /// Returns all semver git tags sorted in ascending order
393    fn git_semver_tags(self, path: &Path) -> Result<Vec<(String, Version)>> {
394        let out = self.git.root(path).tag()?;
395        let mut tags = Vec::new();
396        // tags are commonly prefixed which would make them not semver: v1.2.3 is not a semantic
397        // version
398        let common_prefixes = &["v-", "v", "release-", "release"];
399        for tag in out.lines() {
400            let mut maybe_semver = tag;
401            for &prefix in common_prefixes {
402                if let Some(rem) = tag.strip_prefix(prefix) {
403                    maybe_semver = rem;
404                    break;
405                }
406            }
407            match Version::parse(maybe_semver) {
408                Ok(v) => {
409                    // ignore if additional metadata, like rc, beta, etc...
410                    if v.build.is_empty() && v.pre.is_empty() {
411                        tags.push((tag.to_string(), v));
412                    }
413                }
414                Err(err) => {
415                    warn!(?err, ?maybe_semver, "No semver tag");
416                }
417            }
418        }
419
420        tags.sort_by(|(_, a), (_, b)| a.cmp(b));
421
422        Ok(tags)
423    }
424
425    /// Install the given dependency as git submodule in `target_dir`.
426    fn git_submodule(self, dep: &Dependency, path: &Path) -> Result<()> {
427        let url = dep.require_url()?;
428
429        // make path relative to the git root, already checked above
430        let path = path.strip_prefix(self.git.root).unwrap();
431
432        trace!(?dep, url, ?path, "installing git submodule");
433        self.git.submodule_add(true, url, path)
434    }
435
436    fn git_checkout(self, dep: &Dependency, path: &Path, recurse: bool) -> Result<String> {
437        // no need to checkout if there is no tag
438        let Some(mut tag) = dep.tag.clone() else { return Ok(String::new()) };
439
440        let mut is_branch = false;
441        // only try to match tag if current terminal is a tty
442        if std::io::stdout().is_terminal() {
443            if tag.is_empty() {
444                tag = self.match_tag(&tag, path)?;
445            } else if let Some(branch) = self.match_branch(&tag, path)? {
446                trace!(?tag, ?branch, "selecting branch for given tag");
447                tag = branch;
448                is_branch = true;
449            }
450        }
451        let url = dep.url.as_ref().unwrap();
452
453        let res = self.git.root(path).checkout(recurse, &tag);
454        if let Err(mut e) = res {
455            // remove dependency on failed checkout
456            fs::remove_dir_all(path)?;
457            if e.to_string().contains("did not match any file(s) known to git") {
458                e = eyre::eyre!("Tag: \"{tag}\" not found for repo \"{url}\"!")
459            }
460            return Err(e);
461        }
462
463        if is_branch { Ok(tag) } else { Ok(String::new()) }
464    }
465
466    /// disambiguate tag if it is a version tag
467    fn match_tag(self, tag: &str, path: &Path) -> Result<String> {
468        // only try to match if it looks like a version tag
469        if !DEPENDENCY_VERSION_TAG_REGEX.is_match(tag) {
470            return Ok(tag.into());
471        }
472
473        // generate candidate list by filtering `git tag` output, valid ones are those "starting
474        // with" the user-provided tag (ignoring the starting 'v'), for example, if the user
475        // specifies 1.5, then v1.5.2 is a valid candidate, but v3.1.5 is not
476        let trimmed_tag = tag.trim_start_matches('v').to_string();
477        let output = self.git.root(path).tag()?;
478        let mut candidates: Vec<String> = output
479            .trim()
480            .lines()
481            .filter(|x| x.trim_start_matches('v').starts_with(&trimmed_tag))
482            .map(|x| x.to_string())
483            .rev()
484            .collect();
485
486        // no match found, fall back to the user-provided tag
487        if candidates.is_empty() {
488            return Ok(tag.into());
489        }
490
491        // have exact match
492        for candidate in &candidates {
493            if candidate == tag {
494                return Ok(tag.into());
495            }
496        }
497
498        // only one candidate, ask whether the user wants to accept or not
499        if candidates.len() == 1 {
500            let matched_tag = &candidates[0];
501            let input = prompt!(
502                "Found a similar version tag: {matched_tag}, do you want to use this instead? [Y/n] "
503            )?;
504            return if match_yn(input) { Ok(matched_tag.clone()) } else { Ok(tag.into()) };
505        }
506
507        // multiple candidates, ask the user to choose one or skip
508        candidates.insert(0, String::from("SKIP AND USE ORIGINAL TAG"));
509        sh_println!("There are multiple matching tags:")?;
510        for (i, candidate) in candidates.iter().enumerate() {
511            sh_println!("[{i}] {candidate}")?;
512        }
513
514        let n_candidates = candidates.len();
515        loop {
516            let input: String =
517                prompt!("Please select a tag (0-{}, default: 1): ", n_candidates - 1)?;
518            let s = input.trim();
519            // default selection, return first candidate
520            let n = if s.is_empty() { Ok(1) } else { s.parse() };
521            // match user input, 0 indicates skipping and use original tag
522            match n {
523                Ok(0) => return Ok(tag.into()),
524                Ok(i) if (1..=n_candidates).contains(&i) => {
525                    let c = &candidates[i];
526                    sh_println!("[{i}] {c} selected")?;
527                    return Ok(c.clone());
528                }
529                _ => continue,
530            }
531        }
532    }
533
534    fn match_branch(self, tag: &str, path: &Path) -> Result<Option<String>> {
535        // fetch remote branches and check for tag
536        let output = self.git.root(path).cmd().args(["branch", "-r"]).get_stdout_lossy()?;
537
538        let mut candidates = output
539            .lines()
540            .map(|x| x.trim().trim_start_matches("origin/"))
541            .filter(|x| x.starts_with(tag))
542            .map(ToString::to_string)
543            .rev()
544            .collect::<Vec<_>>();
545
546        trace!(?candidates, ?tag, "found branch candidates");
547
548        // no match found, fall back to the user-provided tag
549        if candidates.is_empty() {
550            return Ok(None);
551        }
552
553        // have exact match
554        for candidate in &candidates {
555            if candidate == tag {
556                return Ok(Some(tag.to_string()));
557            }
558        }
559
560        // only one candidate, ask whether the user wants to accept or not
561        if candidates.len() == 1 {
562            let matched_tag = &candidates[0];
563            let input = prompt!(
564                "Found a similar branch: {matched_tag}, do you want to use this instead? [Y/n] "
565            )?;
566            return if match_yn(input) { Ok(Some(matched_tag.clone())) } else { Ok(None) };
567        }
568
569        // multiple candidates, ask the user to choose one or skip
570        candidates.insert(0, format!("{tag} (original branch)"));
571        sh_println!("There are multiple matching branches:")?;
572        for (i, candidate) in candidates.iter().enumerate() {
573            sh_println!("[{i}] {candidate}")?;
574        }
575
576        let n_candidates = candidates.len();
577        let input: String = prompt!(
578            "Please select a tag (0-{}, default: 1, Press <enter> to cancel): ",
579            n_candidates - 1
580        )?;
581        let input = input.trim();
582
583        // default selection, return None
584        if input.is_empty() {
585            sh_println!("Canceled branch matching")?;
586            return Ok(None);
587        }
588
589        // match user input, 0 indicates skipping and use original tag
590        match input.parse::<usize>() {
591            Ok(0) => Ok(Some(tag.into())),
592            Ok(i) if (1..=n_candidates).contains(&i) => {
593                let c = &candidates[i];
594                sh_println!("[{i}] {c} selected")?;
595                Ok(Some(c.clone()))
596            }
597            _ => Ok(None),
598        }
599    }
600}
601
602/// Matches on the result of a prompt for yes/no.
603///
604/// Defaults to true.
605fn match_yn(input: String) -> bool {
606    let s = input.trim().to_lowercase();
607    matches!(s.as_str(), "" | "y" | "yes")
608}
609
610#[cfg(test)]
611mod tests {
612    use super::*;
613    use tempfile::tempdir;
614
615    #[test]
616    #[ignore = "slow"]
617    fn get_oz_tags() {
618        let tmp = tempdir().unwrap();
619        let git = Git::new(tmp.path());
620        let installer = Installer { git, commit: false };
621
622        git.init().unwrap();
623
624        let dep: Dependency = "openzeppelin/openzeppelin-contracts".parse().unwrap();
625        let libs = tmp.path().join("libs");
626        fs::create_dir(&libs).unwrap();
627        let submodule = libs.join("openzeppelin-contracts");
628        installer.git_submodule(&dep, &submodule).unwrap();
629        assert!(submodule.exists());
630
631        let tags = installer.git_semver_tags(&submodule).unwrap();
632        assert!(!tags.is_empty());
633        let v480: Version = "4.8.0".parse().unwrap();
634        assert!(tags.iter().any(|(_, v)| v == &v480));
635    }
636}