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
use crate::args::Args;
use crate::artifact::{Artifact, CrateType};
use crate::error::{Error, Result};
use crate::profile::Profile;
use crate::{utils, LocalizedConfig};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};

#[derive(Debug)]
pub struct Subcommand {
    args: Args,
    package: String,
    manifest: PathBuf,
    target_dir: PathBuf,
    host_triple: String,
    profile: Profile,
    artifacts: Vec<Artifact>,
    config: Option<LocalizedConfig>,
}

impl Subcommand {
    pub fn new(args: Args) -> Result<Self> {
        // TODO: support multiple packages properly
        assert!(
            args.package.len() < 2,
            "Multiple packages are not supported yet by `cargo-subcommand`"
        );
        assert!(
            !args.workspace,
            "`--workspace` is not supported yet by `cargo-subcommand`"
        );
        assert!(
            args.exclude.is_empty(),
            "`--exclude` is not supported yet by `cargo-subcommand`"
        );

        let manifest_path = args
            .manifest_path
            .clone()
            .map(|path| {
                if path.file_name() != Some(OsStr::new("Cargo.toml")) || !path.is_file() {
                    Err(Error::ManifestPathNotFound)
                } else {
                    Ok(path)
                }
            })
            .transpose()?;

        let (manifest_path, package) = utils::find_package(
            &manifest_path.unwrap_or_else(|| std::env::current_dir().unwrap()),
            args.package.get(0).map(|s| s.as_str()),
        )?;
        let root_dir = manifest_path.parent().unwrap();

        // TODO: Find, parse, and merge _all_ config files following the hierarchical structure:
        // https://doc.rust-lang.org/cargo/reference/config.html#hierarchical-structure
        let config = LocalizedConfig::find_cargo_config_for_workspace(&root_dir)?;
        if let Some(config) = &config {
            config.set_env_vars().unwrap();
        }

        let target_dir = args
            .target_dir
            .clone()
            .or_else(|| {
                std::env::var_os("CARGO_BUILD_TARGET_DIR")
                    .or_else(|| std::env::var_os("CARGO_TARGET_DIR"))
                    .map(|os_str| os_str.into())
            })
            .map(|target_dir| {
                if target_dir.is_relative() {
                    std::env::current_dir().unwrap().join(target_dir)
                } else {
                    target_dir
                }
            });

        let target_dir = target_dir.unwrap_or_else(|| {
            utils::find_workspace(&manifest_path, &package)
                .unwrap()
                .unwrap_or_else(|| manifest_path.clone())
                .parent()
                .unwrap()
                .join(utils::get_target_dir_name(config.as_deref()).unwrap())
        });

        let mut artifacts = vec![];
        if args.examples {
            for file in utils::list_rust_files(&root_dir.join("examples"))? {
                artifacts.push(Artifact::Example(file));
            }
        } else {
            for example in &args.example {
                artifacts.push(Artifact::Example(example.into()));
            }
        }
        if args.bins {
            for file in utils::list_rust_files(&root_dir.join("src").join("bin"))? {
                artifacts.push(Artifact::Root(file));
            }
        } else {
            for bin in &args.bin {
                artifacts.push(Artifact::Root(bin.into()));
            }
        }
        if artifacts.is_empty() {
            artifacts.push(Artifact::Root(package.clone()));
        }
        let host_triple = current_platform::CURRENT_PLATFORM.to_owned();
        let profile = args.profile();
        Ok(Self {
            args,
            package,
            manifest: manifest_path,
            target_dir,
            host_triple,
            profile,
            artifacts,
            config,
        })
    }

    pub fn args(&self) -> &Args {
        &self.args
    }

    pub fn package(&self) -> &str {
        &self.package
    }

    pub fn manifest(&self) -> &Path {
        &self.manifest
    }

    pub fn target(&self) -> Option<&str> {
        self.args.target.as_deref()
    }

    pub fn profile(&self) -> &Profile {
        &self.profile
    }

    pub fn artifacts(&self) -> &[Artifact] {
        &self.artifacts
    }

    pub fn target_dir(&self) -> &Path {
        &self.target_dir
    }

    pub fn host_triple(&self) -> &str {
        &self.host_triple
    }

    pub fn quiet(&self) -> bool {
        self.args.quiet
    }

    pub fn config(&self) -> Option<&LocalizedConfig> {
        self.config.as_ref()
    }

    pub fn build_dir(&self, target: Option<&str>) -> PathBuf {
        let target_dir = dunce::simplified(self.target_dir());
        let arch_dir = if let Some(target) = target {
            target_dir.join(target)
        } else {
            target_dir.to_path_buf()
        };
        arch_dir.join(self.profile())
    }

    pub fn artifact(
        &self,
        artifact: &Artifact,
        target: Option<&str>,
        crate_type: CrateType,
    ) -> PathBuf {
        let triple = target.unwrap_or_else(|| self.host_triple());
        let file_name = artifact.file_name(crate_type, triple);
        self.build_dir(target).join(artifact).join(file_name)
    }
}