Skip to main content

dfx_core/network/
directory.rs

1use crate::config::model::local_server_descriptor::LocalNetworkScopeDescriptor;
2use crate::config::model::network_descriptor::NetworkDescriptor;
3use crate::error::canister_id_store::EnsureCohesiveNetworkDirectoryError;
4use std::path::Path;
5
6/// A cohesive network directory is one in which the directory in question contains
7/// a file `network-id`, which contains the same contents as the `network-id` file
8/// in the network data directory.  In this way, after `dfx start --clean`, we
9/// can later clean up data in project directories.
10pub fn ensure_cohesive_network_directory(
11    network_descriptor: &NetworkDescriptor,
12    directory: &Path,
13) -> Result<(), EnsureCohesiveNetworkDirectoryError> {
14    let scope = network_descriptor
15        .local_server_descriptor
16        .as_ref()
17        .map(|d| &d.scope);
18
19    if let Some(LocalNetworkScopeDescriptor::Shared { network_id_path }) = &scope {
20        if network_id_path.is_file() {
21            let network_id = crate::fs::read_to_string(network_id_path)?;
22            let project_network_id_path = directory.join("network-id");
23            let reset = directory.is_dir()
24                && (!project_network_id_path.exists()
25                    || crate::fs::read_to_string(&project_network_id_path)? != network_id);
26
27            if reset {
28                crate::fs::remove_dir_all(directory)?;
29            };
30
31            if !directory.exists() {
32                crate::fs::create_dir_all(directory)?;
33                crate::fs::write(&project_network_id_path, &network_id)?;
34            }
35        }
36    } else if let Some(LocalNetworkScopeDescriptor::Project) = &scope {
37        // a network-id file indicates the previous configuration was for the shared local network.
38        // canister ids, at minimum, will no longer be valid
39        let network_id_path = directory.join("network-id");
40        if network_id_path.exists() {
41            crate::fs::remove_dir_all(directory)?;
42        }
43    }
44
45    Ok(())
46}