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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
use cargo_metadata::{
    camino::{Utf8Path, Utf8PathBuf},
    Metadata, Package,
};
use eyre::eyre;

use super::{DistPackageConfig, DistPackageConfigBuilder};
use crate::Result;

/// Configures and constructs [`DistConfig`].
///
/// # Examples
///
/// ```rust
/// # fn main() -> cli_xtask::Result<()> {
/// use cli_xtask::{config::DistConfigBuilder, workspace};
///
/// let workspace = workspace::current();
/// let config = DistConfigBuilder::new("app", workspace).build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DistConfigBuilder<'a> {
    name: String,
    metadata: &'a Metadata,
    dist_target_directory: Utf8PathBuf,
    dist_base_working_directory: Utf8PathBuf,
    packages: Vec<DistPackageConfig<'a>>,
    #[cfg(feature = "subcommand-dist-build-bin")]
    cargo_build_options: Vec<String>,
}

impl<'a> DistConfigBuilder<'a> {
    /// Creates a new `DistConfigBuilder` from the given name.
    ///
    /// Created `DistConfig` will be associated with current cargo workspace.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::DistConfigBuilder, workspace};
    ///
    /// let workspace = workspace::current();
    /// let config = DistConfigBuilder::new("app", workspace).build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(name: impl Into<String>, workspace: &'a Metadata) -> Self {
        let name = name.into();
        let dist_target_directory = workspace.target_directory.join("dist");
        let dist_base_working_directory = workspace.target_directory.join("xtask/dist").join(&name);

        Self {
            name,
            metadata: workspace,
            dist_target_directory,
            dist_base_working_directory,
            packages: vec![],
            #[cfg(feature = "subcommand-dist-build-bin")]
            cargo_build_options: vec![],
        }
    }

    /// Creates a new `DistConfigBuilder` from the root package of given
    /// workspace.
    ///
    /// The name of the created `DistConfig` will be generated from the name and
    /// version of the root package.
    ///
    /// # Errors
    ///
    /// Returns an error if the root package is not found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::DistConfigBuilder, workspace};
    ///
    /// let workspace = workspace::current();
    ///
    /// let (dist_config, pkg_config) = DistConfigBuilder::from_root_package(workspace)?;
    /// let dist_config = dist_config.package(pkg_config.build()?).build()?;
    ///
    /// let root_package = workspace.root_package().unwrap();
    /// assert_eq!(
    ///     dist_config.name(),
    ///     format!("{}-v{}", root_package.name, root_package.version)
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_root_package(
        workspace: &'a Metadata,
    ) -> Result<(Self, DistPackageConfigBuilder<'a>)> {
        let package = workspace
            .root_package()
            .ok_or_else(|| eyre!("no root package found"))?;
        Ok(Self::from_package(workspace, package))
    }

    /// Creates a new `DistConfigBuilder` from a package with the given name in
    /// the the given workspace.
    ///
    /// The name of the created `DistConfig` will be generated from the name and
    /// version of the given package.
    ///
    /// # Errors
    ///
    /// Returns an error if the package with the specified name is not found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::DistConfigBuilder, workspace};
    ///
    /// let workspace = workspace::current();
    /// let package = workspace.workspace_packages()[0];
    ///
    /// let (dist_config, pkg_config) = DistConfigBuilder::from_package_name(workspace, &package.name)?;
    /// let dist_config = dist_config.package(pkg_config.build()?).build()?;
    ///
    /// assert_eq!(
    ///     dist_config.name(),
    ///     format!("{}-v{}", package.name, package.version)
    /// );
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_package_name(
        workspace: &'a Metadata,
        name: &str,
    ) -> Result<(Self, DistPackageConfigBuilder<'a>)> {
        let workspace_packages = workspace.workspace_packages();
        let package = workspace_packages
            .iter()
            .find(|package| package.name == name)
            .ok_or_else(|| eyre!("no package found"))?;
        Ok(Self::from_package(workspace, package))
    }

    fn from_package(
        workspace: &'a Metadata,
        package: &'a Package,
    ) -> (Self, DistPackageConfigBuilder<'a>) {
        let name = format!("{}-v{}", package.name, package.version);

        let dist = Self::new(name, workspace);
        let package_builder = DistPackageConfigBuilder::new(package);

        (dist, package_builder)
    }

    /// Creates a new [`DistPackageConfigBuilder`] from the given package name.
    ///
    /// # Errors
    ///
    /// Returns an error if the package with the specified name is not found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::DistConfigBuilder, workspace};
    ///
    /// let workspace = workspace::current();
    /// let package = workspace.workspace_packages()[0];
    ///
    /// let dist_config = DistConfigBuilder::new("app-dist", workspace);
    /// let pkg_config = dist_config.package_by_name(&package.name)?.build()?;
    /// let dist_config = dist_config.package(pkg_config).build()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn package_by_name(&self, name: &str) -> Result<DistPackageConfigBuilder<'a>> {
        let package = self
            .metadata
            .workspace_packages()
            .into_iter()
            .find(|package| package.name == name)
            .ok_or_else(|| eyre!("no package found"))?;
        let package_builder = DistPackageConfigBuilder::new(package);
        Ok(package_builder)
    }

    /// Adds the given package to the `DistConfig`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::DistConfigBuilder, workspace};
    ///
    /// let workspace = workspace::current();
    /// let package = workspace.workspace_packages()[0];
    ///
    /// let dist_config = DistConfigBuilder::new("app-dist", workspace);
    /// let pkg_config = dist_config.package_by_name(&package.name)?.build()?;
    /// let dist_config = dist_config.package(pkg_config).build()?;
    /// # Ok(())
    /// # }
    pub fn package(mut self, package: DistPackageConfig<'a>) -> Self {
        self.packages.push(package);
        self
    }

    /// Adds the given packages to the `DistConfig`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::{DistConfigBuilder, DistPackageConfig}, workspace, Result};
    ///
    /// let workspace = workspace::current();
    /// let packages = workspace.workspace_packages();
    ///
    /// let dist_config = DistConfigBuilder::new("app-dist", workspace);
    /// let pkg_configs = packages.iter().map(|package| -> Result<DistPackageConfig> {
    ///     let pkg_config = dist_config.package_by_name(&package.name)?.build()?;
    ///     Ok(pkg_config)
    /// }).collect::<Result<Vec<_>>>()?;
    /// let dist_config = dist_config.packages(pkg_configs).build()?;
    /// # Ok(())
    /// # }
    pub fn packages(mut self, packages: impl IntoIterator<Item = DistPackageConfig<'a>>) -> Self {
        self.packages.extend(packages);
        self
    }

    /// Adds the given cargo build options to the `DistConfig`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> cli_xtask::Result<()> {
    /// use cli_xtask::{config::{DistConfigBuilder, DistPackageConfig}, workspace, Result};
    ///
    /// let workspace = workspace::current();
    /// let packages = workspace.workspace_packages();
    ///
    /// let dist_config = DistConfigBuilder::new("app-dist", workspace);
    /// dist_config.cargo_build_options(["--features", "feature-a"]).build()?;
    /// # Ok(())
    /// # }
    #[cfg(feature = "subcommand-dist-build-bin")]
    #[cfg_attr(docsrs, doc(cfg(feature = "subcommand-dist-build-bin")))]
    pub fn cargo_build_options(
        mut self,
        options: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.cargo_build_options
            .extend(options.into_iter().map(Into::into));
        self
    }

    /// Builds a [`DistConfig`] from the current configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if the [`DistConfig`] cannot be built.
    pub fn build(self) -> Result<DistConfig<'a>> {
        Ok(DistConfig {
            name: self.name,
            metadata: self.metadata,
            dist_target_directory: self.dist_target_directory,
            dist_base_working_directory: self.dist_base_working_directory,
            packages: self.packages,
            #[cfg(feature = "subcommand-dist-build-bin")]
            cargo_build_options: self.cargo_build_options,
        })
    }
}

/// Configuration for the distribution.
///
/// This struct is build from [`DistConfigBuilder`].
///
/// # Examples
///
/// ```rust
/// # fn main() -> cli_xtask::Result<()> {
/// use cli_xtask::{config::DistConfigBuilder, workspace};
///
/// let workspace = workspace::current();
/// let config = DistConfigBuilder::new("app", workspace).build()?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct DistConfig<'a> {
    name: String,
    metadata: &'a Metadata,
    dist_target_directory: Utf8PathBuf,
    dist_base_working_directory: Utf8PathBuf,
    packages: Vec<DistPackageConfig<'a>>,
    #[cfg(feature = "subcommand-dist-build-bin")]
    cargo_build_options: Vec<String>,
}

impl<'a> DistConfig<'a> {
    /// Returns the name of the distribution.
    ///
    /// By default, the name is formed as `<package-name>-v<package-version>`.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the cargo workspace [`Metadata`].
    pub fn metadata(&self) -> &'a Metadata {
        self.metadata
    }

    /// Returns the target directory that will be used to store the distribution
    /// archive.
    pub fn dist_target_directory(&self) -> &Utf8Path {
        &self.dist_target_directory
    }

    /// Returns the base working directory where the distribution artifacts will
    /// be copied at.
    pub fn dist_base_working_directory(&self) -> &Utf8Path {
        &self.dist_base_working_directory
    }

    /// Returns the working directory where the distribution artifacts will be
    /// copied at.
    pub fn dist_working_directory(&self, target_triple: Option<&str>) -> Utf8PathBuf {
        let target_triple = target_triple.unwrap_or("noarch");
        self.dist_base_working_directory.join(target_triple)
    }

    /// Returns the configurations of the packages that will be distributed.
    pub fn packages(&self) -> &[DistPackageConfig] {
        &self.packages
    }

    /// Returns the cargo build options that will be used to build the
    #[cfg(feature = "subcommand-dist-build-bin")]
    #[cfg_attr(docsrs, doc(cfg(feature = "subcommand-dist-build-bin")))]
    pub fn cargo_build_options(&self) -> &[String] {
        &self.cargo_build_options
    }
}