1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright 2018-2022 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract.  If not, see <http://www.gnu.org/licenses/>.

mod manifest;
mod metadata;
mod profile;

#[doc(inline)]
pub use self::{
    manifest::{
        Manifest,
        ManifestPath,
    },
    profile::Profile,
};

use anyhow::Result;
use cargo_metadata::{
    Metadata as CargoMetadata,
    Package,
    PackageId,
};

use std::{
    collections::HashMap,
    path::{
        Path,
        PathBuf,
    },
};

/// Make a copy of a cargo workspace, maintaining only the directory structure and manifest
/// files. Relative paths to source files and non-workspace dependencies are rewritten to absolute
/// paths to the original locations.
///
/// This allows custom amendments to be made to the manifest files without editing the originals
/// directly.
pub struct Workspace {
    workspace_root: PathBuf,
    root_package: PackageId,
    members: HashMap<PackageId, (Package, Manifest)>,
}

impl Workspace {
    /// Create a new Workspace from the supplied cargo metadata.
    pub fn new(metadata: &CargoMetadata, root_package: &PackageId) -> Result<Self> {
        let member_manifest =
            |package_id: &PackageId| -> Result<(PackageId, (Package, Manifest))> {
                let package = metadata
                    .packages
                    .iter()
                    .find(|p| p.id == *package_id)
                    .unwrap_or_else(|| {
                        panic!(
                            "Package '{package_id}' is a member and should be in the packages list"
                        )
                    });
                let manifest_path = ManifestPath::new(&package.manifest_path)?;
                let manifest = Manifest::new(manifest_path)?;
                Ok((package_id.clone(), (package.clone(), manifest)))
            };

        let members = metadata
            .workspace_members
            .iter()
            .map(member_manifest)
            .collect::<Result<HashMap<_, _>>>()?;

        if !members.contains_key(root_package) {
            anyhow::bail!("The root package should be a workspace member")
        }

        Ok(Workspace {
            workspace_root: metadata.workspace_root.clone().into(),
            root_package: root_package.clone(),
            members,
        })
    }

    /// Amend the root package manifest using the supplied function.
    ///
    /// # Note
    ///
    /// The root package is the current workspace package being built, not to be confused with
    /// the workspace root (where the top level workspace `Cargo.toml` is defined).
    pub fn with_root_package_manifest<F>(&mut self, f: F) -> Result<&mut Self>
    where
        F: FnOnce(&mut Manifest) -> Result<()>,
    {
        let root_package_manifest = self
            .members
            .get_mut(&self.root_package)
            .map(|(_, m)| m)
            .expect("The root package should be a workspace member");
        f(root_package_manifest)?;
        Ok(self)
    }

    /// Amend the manifest of the package at `package_path` using the supplied function.
    pub fn with_contract_manifest<F>(
        &mut self,
        package_path: &Path,
        f: F,
    ) -> Result<&mut Self>
    where
        F: FnOnce(&mut Manifest) -> Result<()>,
    {
        let manifest = self
            .members
            .iter_mut()
            .find_map(|(_, (_, manifest))| {
                // `package_path` is always absolute and canonicalized. Thus we need to
                // canonicalize the manifest's directory path as well in order to compare
                // both of them.
                let manifest_path = manifest.path().directory()?;
                let manifest_path = manifest_path.canonicalize().unwrap_or_else(|_| {
                    panic!("Cannot canonicalize {}", manifest_path.display())
                });
                if manifest_path == package_path {
                    Some(manifest)
                } else {
                    None
                }
            })
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "Cannot find package with package path {} in workspace members",
                    package_path.display(),
                )
            })?;
        f(manifest)?;
        Ok(self)
    }

    /// Generates a package to invoke for generating contract metadata.
    ///
    /// The contract metadata will be generated for the package found at `package_path`.
    pub(super) fn with_metadata_gen_package(
        &mut self,
        package_path: PathBuf,
    ) -> Result<&mut Self> {
        self.with_contract_manifest(&package_path, |manifest| {
            manifest.with_metadata_package()?;
            Ok(())
        })
    }

    /// Writes the amended manifests to the `target` directory, retaining the workspace directory
    /// structure, but only with the `Cargo.toml` files.
    ///
    /// Relative paths will be rewritten to absolute paths from the original workspace root, except
    /// intra-workspace relative dependency paths which will be preserved.
    ///
    /// Returns the paths of the new manifests.
    pub fn write<P: AsRef<Path>>(
        &mut self,
        target: P,
    ) -> Result<Vec<(PackageId, ManifestPath)>> {
        let exclude_member_package_names = self
            .members
            .iter()
            .map(|(_, (p, _))| p.name.clone())
            .collect::<Vec<_>>();
        let mut new_manifest_paths = Vec::new();
        for (package_id, (package, manifest)) in self.members.iter_mut() {
            // replace the original workspace root with the temporary directory
            let mut new_path: PathBuf = target.as_ref().into();
            new_path.push(package.manifest_path.strip_prefix(&self.workspace_root)?);
            let new_manifest = ManifestPath::new(new_path)?;

            manifest.rewrite_relative_paths(&exclude_member_package_names)?;
            manifest.write(&new_manifest)?;

            new_manifest_paths.push((package_id.clone(), new_manifest));
        }
        Ok(new_manifest_paths)
    }

    /// Copy the workspace with amended manifest files to a temporary directory, executing the
    /// supplied function with the root manifest path before the directory is cleaned up.
    pub fn using_temp<F>(&mut self, f: F) -> Result<()>
    where
        F: FnOnce(&ManifestPath) -> Result<()>,
    {
        let tmp_dir = tempfile::Builder::new()
            .prefix("cargo-contract_")
            .tempdir()?;
        tracing::debug!("Using temp workspace at '{}'", tmp_dir.path().display());
        let new_paths = self.write(&tmp_dir)?;
        let tmp_root_manifest_path = new_paths
            .iter()
            .find_map(|(pid, path)| {
                if *pid == self.root_package {
                    Some(path)
                } else {
                    None
                }
            })
            .expect("root package should be a member of the temp workspace");

        // copy the `Cargo.lock` file
        let src_lockfile = self.workspace_root.clone().join("Cargo.lock");
        let dest_lockfile = tmp_root_manifest_path
            .absolute_directory()?
            .join("Cargo.lock");
        if src_lockfile.exists() {
            tracing::debug!(
                "Copying '{}' to ' '{}'",
                src_lockfile.display(),
                dest_lockfile.display()
            );
            std::fs::copy(src_lockfile, dest_lockfile)?;
        }

        f(tmp_root_manifest_path)
    }
}