1use std::ffi::{OsStr, OsString};
2use std::iter::FromIterator;
3use std::path::{Path, PathBuf};
4use std::str::FromStr;
5use std::vec::Vec;
6
7use sha1::Digest;
8use structopt::StructOpt;
9
10use crate::errors::CargoPlayError;
11
12#[derive(Debug, Clone)]
13pub enum RustEdition {
14 E2015,
15 E2018,
16 E2021,
17}
18
19impl FromStr for RustEdition {
20 type Err = CargoPlayError;
21
22 fn from_str(s: &str) -> Result<Self, Self::Err> {
23 if s == "2021" {
24 Ok(RustEdition::E2021)
25 } else if s == "2018" {
26 Ok(RustEdition::E2018)
27 } else if s == "2015" {
28 Ok(RustEdition::E2015)
29 } else {
30 Err(CargoPlayError::InvalidEdition(s.into()))
31 }
32 }
33}
34
35impl Into<String> for RustEdition {
36 fn into(self) -> String {
37 match self {
38 RustEdition::E2015 => "2015".into(),
39 RustEdition::E2018 => "2018".into(),
40 RustEdition::E2021 => "2021".into(),
41 }
42 }
43}
44
45impl Default for RustEdition {
46 fn default() -> Self {
47 RustEdition::E2021
48 }
49}
50
51#[derive(Debug, StructOpt, Default)]
52#[structopt(
53 name = "cargo-play",
54 about = "Run your Rust program without Cargo.toml"
55)]
56pub struct Options {
57 #[structopt(short = "d", long = "debug", hidden = true)]
58 pub debug: bool,
59
60 #[structopt(short = "c", long = "clean")]
61 pub clean: bool,
63
64 #[structopt(short = "m", long = "mode", group = "modegroup")]
65 pub mode: Option<String>,
67
68 #[structopt(long = "test", group = "modegroup")]
70 pub test: bool,
71
72 #[structopt(long = "check", group = "modegroup")]
74 pub check: bool,
75
76 #[structopt(long = "expand", group = "modegroup")]
79 pub expand: bool,
80
81 #[structopt(short = "t", long = "toolchain", hidden = true)]
82 pub toolchain: Option<String>,
83
84 #[structopt(
85 parse(try_from_os_str = osstr_to_abspath),
86 required_unless = "stdin",
87 validator = file_exist
88 )]
89 pub src: Vec<PathBuf>,
91
92 #[structopt(
93 short = "e",
94 long = "edition",
95 default_value = "2021",
96 possible_values = &["2015", "2018", "2021"]
97 )]
98 pub edition: RustEdition,
100
101 #[structopt(long = "release")]
102 pub release: bool,
104
105 #[structopt(long = "cached", hidden = true)]
106 pub cached: bool,
107
108 #[structopt(long = "quiet", short = "q")]
109 pub quiet: bool,
111
112 #[structopt(long = "verbose", short = "v", parse(from_occurrences))]
113 pub verbose: u16,
115
116 #[structopt(long = "stdin")]
117 pub stdin: bool,
119
120 #[structopt(long = "cargo-option")]
121 pub cargo_option: Option<String>,
123
124 #[structopt(long = "save")]
125 pub save: Option<PathBuf>,
127
128 #[structopt(long = "infer", short = "i")]
130 pub infer: bool,
131
132 #[structopt(multiple = true, last = true)]
133 pub args: Vec<String>,
135}
136
137impl Options {
138 #[allow(unused)]
139 pub fn with_files<I: AsRef<Path>>(src: Vec<I>) -> Self {
141 Self {
142 src: src
143 .into_iter()
144 .filter_map(|x| std::fs::canonicalize(x).ok())
145 .collect(),
146 ..Default::default()
147 }
148 }
149
150 pub fn src_hash(&self) -> String {
152 let mut hash = sha1::Sha1::new();
153 let mut srcs = self.src.clone();
154
155 srcs.sort();
156
157 for file in srcs.into_iter() {
158 hash.update(file.to_string_lossy().as_bytes());
159 }
160
161 bs58::encode(hash.finalize()).into_string()
162 }
163
164 pub fn temp_dirname(&self) -> PathBuf {
165 format!("cargo-play.{}", self.src_hash()).into()
166 }
167
168 fn with_toolchain(mut self, toolchain: Option<String>) -> Self {
169 self.toolchain = toolchain;
170 self
171 }
172
173 pub fn parse(args: Vec<String>) -> Result<Self, ()> {
174 if args.len() < 2 {
175 Self::clap().print_help().unwrap_or(());
176 return Err(());
177 }
178
179 let with_cargo = args[1] == "play";
180 let mut args = args.into_iter();
181
182 if with_cargo {
183 args.next();
184 }
185
186 let toolchain = args
187 .clone()
188 .find(|x| x.starts_with('+'))
189 .map(|s| String::from_iter(s.chars().skip(1)));
190
191 Ok(Self::from_iter(args.filter(|x| !x.starts_with('+'))).with_toolchain(toolchain))
192 }
193}
194
195fn osstr_to_abspath(v: &OsStr) -> Result<PathBuf, OsString> {
197 if let Ok(r) = PathBuf::from(v).canonicalize() {
198 Ok(r)
199 } else {
200 Err(v.into())
201 }
202}
203
204fn file_exist(v: String) -> Result<(), String> {
206 let p = PathBuf::from(v);
207 if !p.is_file() {
208 Err(format!("input file does not exist: {:?}", p))
209 } else {
210 Ok(())
211 }
212}