-
Notifications
You must be signed in to change notification settings - Fork 146
/
Copy pathcli.rs
462 lines (426 loc) · 15.1 KB
/
cli.rs
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{prelude::*, BufReader, Read};
use std::path::PathBuf;
use std::{env, process};
use crate::generate::{
self,
changes::{Changes, TOMLEdition},
};
use crate::integrate::{self, DevnetOrchestrator};
use crate::poke::load_session;
use crate::publish::{publish_all_contracts, Network};
use crate::test::run_scripts;
use crate::types::{MainConfig, MainConfigFile, RequirementConfig};
use clarity_repl::repl;
use clap::Clap;
use toml;
#[derive(Clap)]
#[clap(version = option_env!("CARGO_PKG_VERSION").expect("Unable to detect version"))]
struct Opts {
#[clap(subcommand)]
command: Command,
}
#[derive(Clap)]
enum Command {
/// Create and scaffold a new project
#[clap(name = "new")]
New(GenerateProject),
/// Contract subcommand
#[clap(name = "contract")]
Contract(Contract),
/// Load contracts in a REPL for interactions
#[clap(name = "poke")]
Poke(Poke),
#[clap(name = "console")]
Console(Poke),
/// Execute test suite
#[clap(name = "test")]
Test(Test),
/// Check contracts syntax
#[clap(name = "check")]
Check(Check),
/// Publish contracts on chain
#[clap(name = "publish")]
Publish(Publish),
/// Execute Clarinet Extension
#[clap(name = "run")]
Run(Run),
/// Work on contracts integration
#[clap(name = "integrate")]
Integrate(Integrate),
}
#[derive(Clap)]
enum Contract {
/// New contract subcommand
#[clap(name = "new")]
NewContract(NewContract),
/// Import contract subcommand
#[clap(name = "requirement")]
LinkContract(LinkContract),
/// Fork contract subcommand
#[clap(name = "fork")]
ForkContract(ForkContract),
}
#[derive(Clap)]
struct GenerateProject {
/// Project's name
pub name: String,
}
#[derive(Clap)]
struct NewContract {
/// Contract's name
pub name: String,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
}
#[derive(Clap)]
struct LinkContract {
/// Contract id
pub contract_id: String,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
}
#[derive(Clap, Debug)]
struct ForkContract {
/// Contract id
pub contract_id: String,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
// /// Fork contract and all its dependencies
// #[clap(short = 'r')]
// pub recursive: bool,
}
#[derive(Clap)]
struct Poke {
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
}
#[derive(Clap)]
struct Integrate {
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
/// Display streams of logs instead of terminal UI dashboard
#[clap(long = "no-dashboard")]
pub no_dashboard: bool,
}
#[derive(Clap)]
struct Test {
/// Generate coverage
#[clap(long = "coverage")]
pub coverage: bool,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
/// Relaunch tests on updates
#[clap(long = "watch")]
pub watch: bool,
/// Files to includes
pub files: Vec<String>,
}
#[derive(Clap)]
struct Run {
/// Script to run
pub script: String,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
/// Allow access to wallets
#[clap(long = "allow-wallets")]
pub allow_wallets: bool,
/// Allow write access to disk
#[clap(long = "allow-write")]
pub allow_disk_write: bool,
/// Allow read access to disk
#[clap(long = "allow-read")]
pub allow_disk_read: bool,
}
#[derive(Clap)]
struct Publish {
/// Deploy contracts on devnet, using settings/Devnet.toml
#[clap(
long = "devnet",
conflicts_with = "testnet",
conflicts_with = "mainnet"
)]
pub devnet: bool,
/// Deploy contracts on testnet, using settings/Testnet.toml
#[clap(
long = "testnet",
conflicts_with = "devnet",
conflicts_with = "mainnet"
)]
pub testnet: bool,
/// Deploy contracts on mainnet, using settings/Mainnet.toml
#[clap(
long = "testnet",
conflicts_with = "testnet",
conflicts_with = "devnet"
)]
pub mainnet: bool,
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
}
#[derive(Clap)]
struct Check {
/// Path to Clarinet.toml
#[clap(long = "manifest-path")]
pub manifest_path: Option<String>,
}
pub fn main() {
let opts: Opts = Opts::parse();
match opts.command {
Command::New(project_opts) => {
let current_path = {
let current_dir = env::current_dir().expect("Unable to read current directory");
current_dir.to_str().unwrap().to_owned()
};
let changes = generate::get_changes_for_new_project(current_path, project_opts.name);
execute_changes(changes);
}
Command::Contract(subcommand) => match subcommand {
Contract::NewContract(new_contract) => {
let manifest_path = get_manifest_path_or_exit(new_contract.manifest_path);
let changes = generate::get_changes_for_new_contract(
manifest_path,
new_contract.name,
None,
true,
vec![],
);
execute_changes(changes);
}
Contract::LinkContract(required_contract) => {
let manifest_path = get_manifest_path_or_exit(required_contract.manifest_path);
let change = TOMLEdition {
comment: format!(
"Adding {} as a requirement to Clarinet.toml",
required_contract.contract_id
),
manifest_path,
contracts_to_add: HashMap::new(),
requirements_to_add: vec![RequirementConfig {
contract_id: required_contract.contract_id.clone(),
}],
};
execute_changes(vec![Changes::EditTOML(change)]);
}
Contract::ForkContract(fork_contract) => {
let manifest_path = get_manifest_path_or_exit(fork_contract.manifest_path);
println!(
"Resolving {} and its dependencies...",
fork_contract.contract_id
);
let settings = repl::SessionSettings::default();
let mut session = repl::Session::new(settings);
let rt = tokio::runtime::Builder::new_current_thread()
.enable_io()
.enable_time()
.max_blocking_threads(32)
.build()
.unwrap();
let res = rt.block_on(session.resolve_link(&repl::settings::InitialLink {
contract_id: fork_contract.contract_id.clone(),
stacks_node_addr: None,
cache: None,
}));
let contracts = res.unwrap();
let mut changes = vec![];
for (contract_id, code, deps) in contracts.into_iter() {
let components: Vec<&str> = contract_id.split('.').collect();
let contract_name = components.last().unwrap();
if &contract_id == &fork_contract.contract_id {
let mut change_set = generate::get_changes_for_new_contract(
manifest_path.clone(),
contract_name.to_string(),
Some(code),
false,
vec![],
);
changes.append(&mut change_set);
for dep in deps.iter() {
let mut change_set = generate::get_changes_for_new_link(
manifest_path.clone(),
dep.clone(),
None,
);
changes.append(&mut change_set);
}
}
}
execute_changes(changes);
}
},
Command::Poke(cmd) | Command::Console(cmd) => {
let manifest_path = get_manifest_path_or_exit(cmd.manifest_path);
let start_repl = true;
load_session(manifest_path, start_repl, Network::Devnet).expect("Unable to start REPL");
}
Command::Check(cmd) => {
let manifest_path = get_manifest_path_or_exit(cmd.manifest_path);
let start_repl = false;
let res = load_session(manifest_path, start_repl, Network::Devnet);
if let Err(e) = res {
println!("{}", e);
return;
}
}
Command::Test(cmd) => {
let manifest_path = get_manifest_path_or_exit(cmd.manifest_path);
let start_repl = false;
let res = load_session(manifest_path.clone(), start_repl, Network::Devnet);
let session = match res {
Ok(session) => session,
Err(e) => {
println!("{}", e);
return;
}
};
run_scripts(
cmd.files,
cmd.coverage,
cmd.watch,
true,
false,
manifest_path,
Some(session),
);
}
Command::Run(cmd) => {
let manifest_path = get_manifest_path_or_exit(cmd.manifest_path);
let start_repl = false;
let res = load_session(manifest_path.clone(), start_repl, Network::Devnet);
let session = match res {
Ok(session) => session,
Err(e) => {
println!("{}", e);
return;
}
};
run_scripts(
vec![cmd.script],
false,
false,
cmd.allow_wallets,
cmd.allow_disk_write,
manifest_path,
Some(session),
);
}
Command::Publish(deploy) => {
let manifest_path = get_manifest_path_or_exit(deploy.manifest_path);
let network = if deploy.devnet == true {
Network::Devnet
} else if deploy.testnet == true {
Network::Testnet
} else if deploy.mainnet == true {
// Network::Mainnet
// TODO(ludo): before supporting mainnet deployments, we want to add a pass
// making sure that addresses are consistent + handle other hard coded flags.
// Search for "mainnet handling".
panic!("Target deployment must be specified with --devnet, --testnet, --mainnet")
} else {
panic!("Target deployment must be specified with --devnet, --testnet, --mainnet")
};
match publish_all_contracts(manifest_path, network) {
Ok(results) => println!("{}", results.join("\n")),
Err(results) => println!("{}", results.join("\n")),
};
}
Command::Integrate(cmd) => {
let manifest_path = get_manifest_path_or_exit(cmd.manifest_path);
let devnet = DevnetOrchestrator::new(manifest_path);
integrate::run_devnet(devnet, None, !cmd.no_dashboard);
}
};
}
fn get_manifest_path_or_exit(path: Option<String>) -> PathBuf {
println!("");
if let Some(path) = path {
let manifest_path = PathBuf::from(path);
if !manifest_path.exists() {
println!("Could not find Clarinet.toml");
process::exit(1);
}
manifest_path
} else {
let mut current_dir = env::current_dir().unwrap();
loop {
current_dir.push("Clarinet.toml");
if current_dir.exists() {
break current_dir;
}
current_dir.pop();
if !current_dir.pop() {
println!("Could not find Clarinet.toml");
process::exit(1);
}
}
}
}
fn execute_changes(changes: Vec<Changes>) {
let mut shared_config = None;
let mut path = PathBuf::new();
for mut change in changes.into_iter() {
match change {
Changes::AddFile(options) => {
if let Ok(entry) = fs::metadata(&options.path) {
if entry.is_file() {
println!("File already exists at path {}", options.path);
continue;
}
}
println!("{}", options.comment);
let mut file = File::create(options.path.clone()).expect("Unable to create file");
file.write_all(options.content.as_bytes())
.expect("Unable to write file");
}
Changes::AddDirectory(options) => {
println!("{}", options.comment);
fs::create_dir_all(options.path.clone()).expect("Unable to create directory");
}
Changes::EditTOML(ref mut options) => {
let mut config = match shared_config.take() {
Some(config) => config,
None => {
path = options.manifest_path.clone();
let file = File::open(path.clone()).unwrap();
let mut config_file_reader = BufReader::new(file);
let mut config_file = vec![];
config_file_reader.read_to_end(&mut config_file).unwrap();
let config_file: MainConfigFile =
toml::from_slice(&config_file[..]).unwrap();
MainConfig::from_config_file(config_file)
}
};
let mut requirements = match config.project.requirements.take() {
Some(requirements) => requirements,
None => vec![],
};
for requirement in options.requirements_to_add.drain(..) {
if !requirements.contains(&requirement) {
requirements.push(requirement);
}
}
config.project.requirements = Some(requirements);
for (contract_name, contract_config) in options.contracts_to_add.drain() {
config.contracts.insert(contract_name, contract_config);
}
shared_config = Some(config);
println!("{}", options.comment);
}
}
}
if let Some(config) = shared_config {
let toml = toml::to_string(&config).unwrap();
let mut file = File::create(path).unwrap();
file.write_all(&toml.as_bytes()).unwrap();
file.sync_all().unwrap();
}
}