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
|
//! ref: composer/src/Composer/Command/RunScriptCommand.php
use anyhow::Result;
use indexmap::IndexMap;
use shirabe_external_packages::symfony::console::command::command::Command;
use shirabe_external_packages::symfony::console::input::InputInterface;
use shirabe_external_packages::symfony::console::output::OutputInterface;
use shirabe_php_shim::PhpMixed;
use shirabe_php_shim::{InvalidArgumentException, RuntimeException};
use std::cell::RefCell;
use std::rc::Rc;
use crate::advisory::AuditConfig;
use crate::command::BaseCommand;
use crate::command::BaseCommandData;
use crate::command::base_command::base_command_initialize;
use crate::composer::PartialComposerHandle;
use crate::config::Config;
use crate::console::input::InputArgument;
use crate::console::input::InputOption;
use crate::filter::platform_requirement_filter::PlatformRequirementFilterInterface;
use crate::io::IOInterface;
use crate::io::IOInterfaceImmutable;
use crate::script::Event as ScriptEvent;
use crate::script::ScriptEvents;
use crate::util::Platform;
use crate::util::ProcessExecutor;
#[derive(Debug)]
pub struct RunScriptCommand {
base_command_data: BaseCommandData,
script_events: Vec<&'static str>,
}
impl Default for RunScriptCommand {
fn default() -> Self {
Self::new()
}
}
impl RunScriptCommand {
pub fn new() -> Self {
let mut command = RunScriptCommand {
base_command_data: BaseCommandData::new(None),
script_events: vec![
ScriptEvents::PRE_INSTALL_CMD,
ScriptEvents::POST_INSTALL_CMD,
ScriptEvents::PRE_UPDATE_CMD,
ScriptEvents::POST_UPDATE_CMD,
ScriptEvents::PRE_STATUS_CMD,
ScriptEvents::POST_STATUS_CMD,
ScriptEvents::POST_ROOT_PACKAGE_INSTALL,
ScriptEvents::POST_CREATE_PROJECT_CMD,
ScriptEvents::PRE_ARCHIVE_CMD,
ScriptEvents::POST_ARCHIVE_CMD,
ScriptEvents::PRE_AUTOLOAD_DUMP,
ScriptEvents::POST_AUTOLOAD_DUMP,
],
};
command
.configure()
.expect("RunScriptCommand::configure uses static, valid metadata");
command
}
fn list_scripts(&mut self, output: Rc<RefCell<dyn OutputInterface>>) -> Result<i64> {
let scripts = self.get_scripts()?;
if scripts.is_empty() {
return Ok(0);
}
let io = self.get_io();
io.write_error("<info>scripts:</info>");
let table: Vec<PhpMixed> = scripts
.iter()
.map(|(name, desc)| {
PhpMixed::List(vec![
Box::new(PhpMixed::String(format!(" {}", name))),
Box::new(PhpMixed::String(desc.clone())),
])
})
.collect();
self.render_table(table, output);
Ok(0)
}
fn get_scripts(&mut self) -> Result<Vec<(String, String)>> {
let composer = self.require_composer(None, None)?;
let scripts = crate::command::composer_full(&composer)
.get_package()
.get_scripts();
drop(composer);
if scripts.is_empty() {
return Ok(vec![]);
}
let mut result: Vec<(String, String)> = vec![];
for (name, _script) in scripts {
// PHP: $cmd = $this->getApplication()->find($name); $description = $cmd->getDescription();
// TODO(phase-c): Application::find returns PhpMixed (the Symfony command registry is a
// todo!() stub) and get_application() is itself deferred, so the resolved command's
// getDescription() cannot be read; the description stays empty until the typed command
// registry is modelled.
// get_application() is deferred (returns the Symfony `dyn Application` back-reference,
// not the shirabe Application with find()); the description stays empty until the
// shared Application handle and typed command registry are modelled.
let description = String::new();
result.push((name, description));
}
Ok(result)
}
}
impl Command for RunScriptCommand {
fn configure(&mut self) -> anyhow::Result<()> {
self.set_name("run-script")?;
self.set_aliases(vec!["run".to_string()])?;
self.set_description("Runs the scripts defined in composer.json");
self.set_definition(&[
// TODO(cli-completion): script-name completion was provided via a closure suggesting runtime script names
InputArgument::new(
"script",
Some(InputArgument::OPTIONAL),
"Script name to run.",
None,
)
.unwrap()
.into(),
InputArgument::new(
"args",
Some(InputArgument::IS_ARRAY | InputArgument::OPTIONAL),
"",
None,
)
.unwrap()
.into(),
InputOption::new(
"timeout",
None,
Some(InputOption::VALUE_REQUIRED),
"Sets script timeout in seconds, or 0 for never.",
None,
)
.unwrap()
.into(),
InputOption::new(
"dev",
None,
Some(InputOption::VALUE_NONE),
"Sets the dev mode.",
None,
)
.unwrap()
.into(),
InputOption::new(
"no-dev",
None,
Some(InputOption::VALUE_NONE),
"Disables the dev mode.",
None,
)
.unwrap()
.into(),
InputOption::new(
"list",
Some(PhpMixed::String("l".to_string())),
Some(InputOption::VALUE_NONE),
"List scripts.",
None,
)
.unwrap()
.into(),
]);
self.set_help(
"The <info>run-script</info> command runs scripts defined in composer.json:\n\n\
<info>shirabe run-script post-update-cmd</info>\n\n\
Read more at https://getcomposer.org/doc/03-cli.md#run-script-run",
);
Ok(())
}
fn interact(
&mut self,
input: Rc<RefCell<dyn InputInterface>>,
_output: Rc<RefCell<dyn OutputInterface>>,
) {
let _ = (|| -> anyhow::Result<()> {
let scripts = self.get_scripts()?;
if scripts.is_empty() {
return Ok(());
}
if input.borrow().get_argument("script")?.as_string().is_some()
|| input
.borrow()
.get_option("list")?
.as_bool()
.unwrap_or(false)
{
return Ok(());
}
let mut options = indexmap::IndexMap::new();
for script in &scripts {
options.insert(script.0.clone(), script.1.clone());
}
let io = self.get_io();
let script = io.select(
"Script to run: ".to_string(),
options.keys().cloned().collect(),
PhpMixed::String(String::new()),
PhpMixed::Int(1),
"Invalid script name \"%s\"".to_string(),
false,
);
input.borrow_mut().set_argument("script", script)?;
Ok(())
})();
}
fn execute(
&mut self,
input: Rc<RefCell<dyn InputInterface>>,
output: Rc<RefCell<dyn OutputInterface>>,
) -> anyhow::Result<i64> {
if input
.borrow()
.get_option("list")?
.as_bool()
.unwrap_or(false)
{
return self.list_scripts(output);
}
let script = match input.borrow().get_argument("script")?.as_string() {
None => {
return Err(RuntimeException {
message: "Missing required argument \"script\"".to_string(),
code: 0,
}
.into());
}
Some(s) => s.to_string(),
};
if !self.script_events.contains(&script.as_str()) {
let const_name = script.to_uppercase().replace('-', "_");
if ScriptEvents::is_defined(&const_name) {
return Err(InvalidArgumentException {
message: format!("Script \"{}\" cannot be run with this command", script),
code: 0,
}
.into());
}
}
let composer = self.require_composer(None, None)?;
let dispatcher = crate::command::composer_full(&composer)
.get_event_dispatcher()
.clone();
let dev_mode = input.borrow().get_option("dev")?.as_bool().unwrap_or(false)
|| !input
.borrow()
.get_option("no-dev")?
.as_bool()
.unwrap_or(false);
let io = self.get_io();
let event = ScriptEvent::new(
script.clone(),
composer
.as_full()
.expect("require_composer returns a full Composer")
.downgrade(),
io,
dev_mode,
vec![],
IndexMap::new(),
);
let has_listeners = dispatcher.borrow_mut().has_event_listeners(&event);
if !has_listeners {
return Err(InvalidArgumentException {
message: format!("Script \"{}\" is not defined in this package", script),
code: 0,
}
.into());
}
let args: Vec<String> = input
.borrow()
.get_argument("args")?
.as_list()
.map(|l| {
l.iter()
.filter_map(|v| v.as_string().map(|s| s.to_string()))
.collect()
})
.unwrap_or_default();
if let Some(timeout_val) = input.borrow().get_option("timeout")?.as_string() {
let timeout_str = timeout_val.to_string();
if !timeout_str.chars().all(|c| c.is_ascii_digit()) {
return Err(RuntimeException {
message:
"Timeout value must be numeric and positive if defined, or 0 for forever"
.to_string(),
code: 0,
}
.into());
}
let timeout: i64 = timeout_str.parse().unwrap_or(0);
ProcessExecutor::set_timeout(timeout);
}
Platform::put_env("COMPOSER_DEV_MODE", if dev_mode { "1" } else { "0" });
dispatcher
.borrow_mut()
.dispatch_script(&script, dev_mode, args, IndexMap::new())
}
fn initialize(
&mut self,
input: Rc<RefCell<dyn InputInterface>>,
output: Rc<RefCell<dyn OutputInterface>>,
) -> anyhow::Result<()> {
base_command_initialize(self, input, output)
}
shirabe_external_packages::delegate_command_trait_impls_to_inner!(base_command_data);
}
impl BaseCommand for RunScriptCommand {
fn command_data_mut(
&mut self,
) -> &mut shirabe_external_packages::symfony::console::command::command::CommandData {
self.base_command_data.command_data_mut()
}
crate::delegate_base_command_trait_impls_to_inner!(base_command_data);
}
|