Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use Cargo to build a project while offline?

I am practicing rust (1.36) by creating small program using rand crate. but the problem is whenever i create new project using cargo new and then add rand dependency in cargo.toml. it connects to internet and download same rand package again.

In contrast to Python, installed packages go to site_package folder and become available for import/use to any program. Don't required to download again.

My question is, how do I tell cargo to look for already installed local crate rather than downloading again?

like image 516
owl Avatar asked Jan 27 '23 00:01

owl


1 Answers

Even in modern Python, one wouldn't just use the globally available site_packages directory and "pollute" the globally available packages, but one would use virtual environments to maintain proper versioning per project -- similar to what cargo does.

With cargo, once all the packages downloaded and their versions specified explicitly in a project, one can pass the new --offline flag while one compiles one's project, in which case cargo runs without accessing the network:

$ cargo build --offline

That being said, doing something of what you described is of course perfectly possible:

  1. Create a directory, where your dependencies go:
    $ mkdir offline_resources
    $ cd offline_resources
    
  2. Download the repository you need and build it (this is the last point where you need to use the network):
    $ git clone https://github.com/rust-random/rand.git
    $ cd rand
    $ cargo build
    
  3. Create a new project:
    $ cd ../..
    $ cargo new use_offline
    $ cd use_offline
    
  4. Edit Cargo.toml:
    [dependencies]
    rand = { path="../offline_resources/rand", version="0.7.0" }
    
  5. Build your project:
    $ cargo build --offline
    
  6. Follow the steps from 3 to 5 to create another project which will use the same rand dependency.
like image 153
Peter Varo Avatar answered Jan 29 '23 08:01

Peter Varo