-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathcli.rs
418 lines (359 loc) · 14.6 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
use camino::Utf8PathBuf;
use clap::{Parser, ValueEnum};
use lazycell::{AtomicLazyCell, LazyCell};
use reqwest::blocking::Client;
use serde::Serialize;
use crate::command::{self, RoverOutput};
use crate::options::OutputOpts;
use crate::utils::{
client::{ClientBuilder, ClientTimeout, StudioClientConfig},
env::{RoverEnv, RoverEnvKey},
stringify::option_from_display,
version,
};
use crate::RoverResult;
use config::Config;
use houston as config;
use rover_client::shared::GitContext;
use sputnik::Session;
use timber::Level;
use std::{io, process, thread};
#[derive(Debug, Serialize, Parser)]
#[command(
name = "Rover",
author,
version,
about = "Rover - Your Graph Companion",
after_help = "Read the getting started guide by running:
$ rover docs open start
To begin working with Rover and to authenticate with Apollo Studio,
run the following command:
$ rover config auth
This will prompt you for an API Key that can be generated in Apollo Studio.
The most common commands from there are:
- rover graph fetch: Fetch a graph schema from the Apollo graph registry
- rover graph check: Check for breaking changes in a local graph schema against a graph schema in the Apollo graph
registry
- rover graph publish: Publish an updated graph schema to the Apollo graph registry
You can open the full documentation for Rover by running:
$ rover docs open
"
)]
#[command(next_line_help = true)]
pub struct Rover {
#[clap(subcommand)]
command: Command,
/// Specify Rover's log level
#[arg(long = "log", short = 'l', global = true)]
#[serde(serialize_with = "option_from_display")]
log_level: Option<Level>,
#[clap(flatten)]
output_opts: OutputOpts,
/// Accept invalid certificates when performing HTTPS requests.
///
/// You should think very carefully before using this flag.
///
/// If invalid certificates are trusted, any certificate for any site will be trusted for use.
/// This includes expired certificates.
/// This introduces significant vulnerabilities, and should only be used as a last resort.
#[arg(long = "insecure-accept-invalid-certs", global = true)]
accept_invalid_certs: bool,
/// Accept invalid hostnames when performing HTTPS requests.
///
/// You should think very carefully before using this flag.
///
/// If hostname verification is not used, any valid certificate for any site will be trusted for use from any other.
/// This introduces a significant vulnerability to man-in-the-middle attacks.
#[arg(long = "insecure-accept-invalid-hostnames", global = true)]
accept_invalid_hostnames: bool,
/// Configure the timeout length (in seconds) when performing HTTP(S) requests.
#[arg(
long = "client-timeout",
global = true,
default_value_t = ClientTimeout::default()
)]
client_timeout: ClientTimeout,
/// Skip checking for newer versions of rover.
#[arg(long = "skip-update-check", global = true)]
skip_update_check: bool,
#[arg(skip)]
#[serde(skip_serializing)]
env_store: LazyCell<RoverEnv>,
#[arg(skip)]
#[serde(skip_serializing)]
client_builder: AtomicLazyCell<ClientBuilder>,
#[arg(skip)]
#[serde(skip_serializing)]
client: AtomicLazyCell<Client>,
}
impl Rover {
pub fn run_from_args() -> RoverResult<()> {
Rover::parse().run()
}
pub fn run(&self) -> RoverResult<()> {
timber::init(self.log_level);
tracing::trace!(command_structure = ?self);
self.output_opts.validate_options();
// attempt to create a new `Session` to capture anonymous usage data
let rover_output = match Session::new(self) {
// if successful, report the usage data in the background
Ok(session) => {
// kicks off the reporting on a background thread
let report_thread = thread::spawn(move || {
// log + ignore errors because it is not in the critical path
let _ = session.report().map_err(|telemetry_error| {
tracing::debug!(?telemetry_error);
telemetry_error
});
});
// kicks off the app on the main thread
// don't return an error with ? quite yet
// since we still want to report the usage data
let app_result = self.execute_command();
// makes sure the reporting finishes in the background
// before continuing.
// ignore errors because it is not in the critical path
let _ = report_thread.join();
// return result of app execution
// now that we have reported our usage data
app_result
}
// otherwise just run the app without reporting
Err(_) => self.execute_command(),
};
match rover_output {
Ok(output) => {
self.output_opts.handle_output(output)?;
process::exit(0);
}
Err(error) => {
self.output_opts.handle_output(error)?;
process::exit(1);
}
}
}
pub fn execute_command(&self) -> RoverResult<RoverOutput> {
// before running any commands, we check if rover is up to date
// this only happens once a day automatically
// we skip this check for the `rover update` commands, since they
// do their own checks.
// the check is also skipped if the `--skip-update-check` flag is passed.
if let Command::Update(_) = &self.command { /* skip check */
} else if !self.skip_update_check {
let config = self.get_rover_config();
if let Ok(config) = config {
let _ = version::check_for_update(config, false, self.get_reqwest_client()?);
}
}
match &self.command {
Command::Config(command) => command.run(self.get_client_config()?),
Command::Dev(command) => {
command.run(self.get_install_override_path()?, self.get_client_config()?)
}
Command::Fed2(command) => command.run(self.get_client_config()?),
Command::Supergraph(command) => {
command.run(self.get_install_override_path()?, self.get_client_config()?)
}
Command::Docs(command) => command.run(),
Command::Graph(command) => command.run(
self.get_client_config()?,
self.get_git_context()?,
self.get_checks_timeout_seconds()?,
&self.output_opts,
),
Command::Template(command) => command.run(self.get_client_config()?),
Command::Readme(command) => command.run(self.get_client_config()?),
Command::Subgraph(command) => command.run(
self.get_client_config()?,
self.get_git_context()?,
self.get_checks_timeout_seconds()?,
&self.output_opts,
),
Command::Update(command) => {
command.run(self.get_rover_config()?, self.get_reqwest_client()?)
}
Command::Install(command) => {
command.do_install(self.get_install_override_path()?, self.get_client_config()?)
}
Command::Info(command) => command.run(),
Command::Explain(command) => command.run(),
}
}
pub(crate) fn get_rover_config(&self) -> RoverResult<Config> {
let override_home: Option<Utf8PathBuf> = self
.get_env_var(RoverEnvKey::ConfigHome)?
.map(|p| Utf8PathBuf::from(&p));
let override_api_key = self.get_env_var(RoverEnvKey::Key)?;
Ok(Config::new(override_home.as_ref(), override_api_key)?)
}
pub(crate) fn get_client_config(&self) -> RoverResult<StudioClientConfig> {
let override_endpoint = self.get_env_var(RoverEnvKey::RegistryUrl)?;
let is_sudo = if let Some(fire_flower) = self.get_env_var(RoverEnvKey::FireFlower)? {
let fire_flower = fire_flower.to_lowercase();
fire_flower == "true" || fire_flower == "1"
} else {
false
};
let config = self.get_rover_config()?;
Ok(StudioClientConfig::new(
override_endpoint,
config,
is_sudo,
self.get_reqwest_client_builder()?,
))
}
pub(crate) fn get_install_override_path(&self) -> RoverResult<Option<Utf8PathBuf>> {
Ok(self
.get_env_var(RoverEnvKey::Home)?
.map(|p| Utf8PathBuf::from(&p)))
}
pub(crate) fn get_git_context(&self) -> RoverResult<GitContext> {
// constructing GitContext with a set of overrides from env vars
let override_git_context = GitContext {
branch: self.get_env_var(RoverEnvKey::VcsBranch)?,
commit: self.get_env_var(RoverEnvKey::VcsCommit)?,
author: self.get_env_var(RoverEnvKey::VcsAuthor)?,
remote_url: self.get_env_var(RoverEnvKey::VcsRemoteUrl)?,
};
let git_context = GitContext::new_with_override(override_git_context);
tracing::debug!(?git_context);
Ok(git_context)
}
pub(crate) fn get_reqwest_client(&self) -> RoverResult<Client> {
if let Some(client) = self.client.borrow() {
Ok(client.clone())
} else {
self.client
.fill(self.get_reqwest_client_builder()?.build()?)
.expect("Could not overwrite existing request client");
self.get_reqwest_client()
}
}
pub(crate) fn get_reqwest_client_builder(&self) -> RoverResult<ClientBuilder> {
// return a copy of the underlying client builder if it's already been populated
if let Some(client_builder) = self.client_builder.borrow() {
Ok(*client_builder)
} else {
// if a request hasn't been made yet, this cell won't be populated yet
self.client_builder
.fill(
ClientBuilder::new()
.accept_invalid_certs(self.accept_invalid_certs)
.accept_invalid_hostnames(self.accept_invalid_hostnames)
.with_timeout(self.client_timeout.get_duration()),
)
.expect("Could not overwrite existing request client builder");
self.get_reqwest_client_builder()
}
}
pub(crate) fn get_checks_timeout_seconds(&self) -> RoverResult<u64> {
if let Some(seconds) = self.get_env_var(RoverEnvKey::ChecksTimeoutSeconds)? {
Ok(seconds.parse::<u64>()?)
} else {
// default to 5 minutes
Ok(300)
}
}
pub(crate) fn get_env_var(&self, key: RoverEnvKey) -> io::Result<Option<String>> {
Ok(if let Some(env_store) = self.env_store.borrow() {
env_store.get(key)
} else {
let env_store = RoverEnv::new()?;
let val = env_store.get(key);
self.env_store
.fill(env_store)
.expect("Could not overwrite the existing environment variable store");
val
})
}
#[cfg(test)]
pub(crate) fn insert_env_var(&mut self, key: RoverEnvKey, value: &str) -> io::Result<()> {
if let Some(env_store) = self.env_store.borrow_mut() {
env_store.insert(key, value)
} else {
let mut env_store = RoverEnv::new()?;
env_store.insert(key, value);
self.env_store
.fill(env_store)
.expect("Could not overwrite the existing environment variable store");
};
Ok(())
}
}
#[derive(Debug, Serialize, Parser)]
pub enum Command {
/// Configuration profile commands
Config(command::Config),
/// Combine multiple subgraphs into a local supergraph
///
/// This command starts a local router that can query across one or more
/// running GraphQL APIs (subgraphs) through one endpoint (supergraph).
/// As you add, edit, and remove subgraphs, `rover dev` automatically
/// composes all of their schemas into a new supergraph schema, and the
/// router reloads.
///
/// ⚠️ Do not run this command in production!
/// ⚠️ It is intended for local development.
///
/// The first time you run `rover dev`, a supergraph is created from the
/// GraphQL API you provide. This GraphQL API is the first subgraph
/// inside of the larger supergraph. As you make changes to the subgraph
/// schema, the supergraph schema will be re-composed and the router will
/// reload.
///
/// You can navigate to the supergraph endpoint in your browser
/// to execute operations and see query plans using Apollo Sandbox.
///
/// You can add more subgraphs by running `rover dev` again in a new
/// terminal. Subsequent subgraphs are composed into the supergraph and
/// can be queried alongside all other subgraphs from the original endpoint.
/// Changes to these schemas will also cause the supergraph schema to be
/// re-composed and the router to reload.
///
/// Terminating the first `rover dev` process terminates the entire supergraph.
/// Terminating one of the subsequent `rover dev` processes (i.e. your second
/// or third subgraph) will decompose that subgraph from your supergraph.
///
/// Think plug-n-play USB devices but with your GraphQL APIs!
Dev(command::Dev),
/// (deprecated) Federation 2 Alpha commands
#[command(hide = true)]
Fed2(command::Fed2),
/// Supergraph schema commands
Supergraph(command::Supergraph),
/// Graph API schema commands
Graph(command::Graph),
/// Commands for working with templates
Template(command::Template),
/// Readme commands
Readme(command::Readme),
/// Subgraph schema commands
Subgraph(command::Subgraph),
/// Interact with Rover's documentation
Docs(command::Docs),
/// Commands related to updating rover
Update(command::Update),
/// Installs Rover
#[command(hide = true)]
Install(command::Install),
/// Get system information
#[command(hide = true)]
Info(command::Info),
/// Explain error codes
Explain(command::Explain),
}
#[derive(ValueEnum, Debug, Serialize, Clone, Eq, PartialEq)]
pub enum RoverOutputFormatKind {
Plain,
Json,
}
#[derive(ValueEnum, Debug, Serialize, Clone, Eq, PartialEq)]
pub enum RoverOutputKind {
RoverOutput,
RoverError,
}
impl Default for RoverOutputFormatKind {
fn default() -> Self {
RoverOutputFormatKind::Plain
}
}