-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
main.rs
346 lines (295 loc) · 10.2 KB
/
main.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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::env;
use std::env::current_dir;
use std::path::PathBuf;
use std::process::Command;
use std::sync::Arc;
use clap::ArgEnum;
use clap::Parser;
use common::ConsoleLogger;
use intern::string_key::Intern;
use intern::Lookup;
use log::error;
use log::info;
use relay_compiler::build_project::artifact_writer::ArtifactValidationWriter;
use relay_compiler::compiler::Compiler;
use relay_compiler::config::Config;
use relay_compiler::errors::Error as CompilerError;
use relay_compiler::FileSourceKind;
use relay_compiler::LocalPersister;
use relay_compiler::OperationPersister;
use relay_compiler::PersistConfig;
use relay_compiler::RemotePersister;
use relay_lsp::start_language_server;
use relay_lsp::DummyExtraDataProvider;
use schema::SDLSchema;
use schema_documentation::SchemaDocumentationLoader;
use simplelog::ColorChoice;
use simplelog::ConfigBuilder as SimpleLogConfigBuilder;
use simplelog::LevelFilter;
use simplelog::TermLogger;
use simplelog::TerminalMode;
mod errors;
use errors::Error;
#[derive(Parser)]
#[clap(
name = "Relay Compiler",
version = option_env!("CARGO_PKG_VERSION").unwrap_or("unknown"),
about = "Compiles Relay files and writes generated files.",
rename_all = "camel_case",
args_conflicts_with_subcommands = true
)]
struct Opt {
#[clap(subcommand)]
command: Option<Commands>,
#[clap(flatten)]
compile: CompileCommand,
}
#[derive(Parser)]
#[clap(
rename_all = "camel_case",
about = "Compiles Relay files and writes generated files."
)]
struct CompileCommand {
/// Compile and watch for changes
#[clap(long, short)]
watch: bool,
/// Compile only this project. You can pass this argument multiple times.
/// to compile multiple projects. If excluded, all projects will be compiled.
#[clap(name = "project", long, short)]
projects: Vec<String>,
/// Compile using this config file. If not provided, searches for a config in
/// package.json under the `relay` key or `relay.config.json` files among other up
/// from the current working directory.
config: Option<PathBuf>,
#[clap(flatten)]
cli_config: CliConfig,
/// Run the persister even if the query has not changed.
#[clap(long)]
repersist: bool,
/// Verbosity level
#[clap(long, arg_enum, default_value = "verbose")]
output: OutputKind,
/// Looks for pending changes and exits with non-zero code instead of
/// writing to disk
#[clap(long)]
validate: bool,
}
#[derive(Parser)]
#[clap(
about = "Run the language server. Used by IDEs.",
rename_all = "camel_case"
)]
struct LspCommand {
/// Run the LSP using this config file. If not provided, searches for a config in
/// package.json under the `relay` key or `relay.config.json` files among other up
/// from the current working directory.
config: Option<PathBuf>,
/// Verbosity level
#[clap(long, arg_enum, default_value = "quiet-with-errors")]
output: OutputKind,
}
#[derive(clap::Subcommand)]
enum Commands {
Compiler(CompileCommand),
Lsp(LspCommand),
}
#[derive(ArgEnum, Clone, Copy)]
enum OutputKind {
Debug,
Quiet,
QuietWithErrors,
Verbose,
}
#[derive(Parser)]
#[clap(rename_all = "camel_case")]
pub struct CliConfig {
/// Path for the directory where to search for source code
#[clap(long)]
pub src: Option<String>,
/// Path to schema file
#[clap(long)]
pub schema: Option<String>,
/// Path to a directory, where the compiler should write artifacts
#[clap(long)]
pub artifact_directory: Option<String>,
}
impl CliConfig {
fn is_defined(&self) -> bool {
self.src.is_some() || self.schema.is_some() || self.artifact_directory.is_some()
}
fn get_config_string(self) -> String {
let src = self.src.unwrap_or_else(|| "./src".into());
let schema = self.schema.unwrap_or_else(|| "./path-to-schema".into());
let artifact_directory = self.artifact_directory.map_or("".to_string(), |a| {
format!("\n \"artifactDirectory\": \"{}\",", a)
});
format!(
r#"
{{
"src": "{}",
"schema": "{}",{}
"language": "javascript"
}}"#,
src, schema, artifact_directory
)
}
}
#[tokio::main]
async fn main() {
let opt = Opt::parse();
let command = opt.command.unwrap_or(Commands::Compiler(opt.compile));
let result = match command {
Commands::Compiler(command) => handle_compiler_command(command).await,
Commands::Lsp(command) => handle_lsp_command(command).await,
};
match result {
Ok(_) => info!("Done."),
Err(err) => {
error!("{}", err);
std::process::exit(1);
}
}
}
fn get_config(config_path: Option<PathBuf>) -> Result<Config, Error> {
match config_path {
Some(config_path) => Config::load(config_path).map_err(Error::ConfigError),
None => Config::search(¤t_dir().expect("Unable to get current working directory."))
.map_err(Error::ConfigError),
}
}
fn configure_logger(output: OutputKind, terminal_mode: TerminalMode) {
let log_level = match output {
OutputKind::Debug => LevelFilter::Debug,
OutputKind::Quiet => LevelFilter::Off,
OutputKind::QuietWithErrors => LevelFilter::Error,
OutputKind::Verbose => LevelFilter::Info,
};
let log_config = SimpleLogConfigBuilder::new()
.set_time_level(LevelFilter::Off)
.set_target_level(LevelFilter::Off)
.set_location_level(LevelFilter::Off)
.set_thread_level(LevelFilter::Off)
.build();
TermLogger::init(log_level, log_config, terminal_mode, ColorChoice::Auto).unwrap();
}
/// Update Config if the `project` flag is set
fn set_project_flag(config: &mut Config, projects: Vec<String>) -> Result<(), Error> {
if projects.is_empty() {
return Ok(());
}
for project_config in config.projects.values_mut() {
project_config.enabled = false;
}
for selected_project in projects {
let selected_project = selected_project.intern();
if let Some(project_config) = config.projects.get_mut(&selected_project) {
project_config.enabled = true;
} else {
return Err(Error::ProjectFilterError {
details: format!(
"Project `{}` not found, available projects: {}.",
selected_project,
config
.projects
.keys()
.map(|name| name.lookup())
.collect::<Vec<_>>()
.join(", ")
),
});
}
}
return Ok(());
}
async fn handle_compiler_command(command: CompileCommand) -> Result<(), Error> {
configure_logger(command.output, TerminalMode::Mixed);
if command.cli_config.is_defined() {
return Err(Error::ConfigError(CompilerError::ConfigError {
details: format!(
"\nPassing Relay compiler configuration is not supported. Please add `relay.config.json` file,\nor \"relay\" section to your `package.json` file.\n\nCompiler configuration JSON:{}",
command.cli_config.get_config_string(),
),
}));
}
let mut config = get_config(command.config)?;
set_project_flag(&mut config, command.projects)?;
if command.validate {
config.artifact_writer = Box::new(ArtifactValidationWriter::default());
}
config.create_operation_persister = Some(Box::new(|project_config| {
project_config.persist.as_ref().map(
|persist_config| -> Box<dyn OperationPersister + Send + Sync> {
match persist_config {
PersistConfig::Remote(remote_config) => {
Box::new(RemotePersister::new(remote_config.clone()))
}
PersistConfig::Local(local_config) => {
Box::new(LocalPersister::new(local_config.clone()))
}
}
},
)
}));
config.file_source_config = if should_use_watchman() {
FileSourceKind::Watchman
} else {
FileSourceKind::WalkDir
};
config.repersist_operations = command.repersist;
if command.watch && !matches!(&config.file_source_config, FileSourceKind::Watchman) {
panic!(
"Cannot run relay in watch mode if `watchman` is not available (or explicitly disabled)."
);
}
let compiler = Compiler::new(Arc::new(config), Arc::new(ConsoleLogger));
if command.watch {
compiler.watch().await.map_err(|err| Error::CompilerError {
details: format!("{:?}", err),
})?;
} else {
compiler
.compile()
.await
.map_err(|err| Error::CompilerError {
details: format!("{}", err),
})?;
}
Ok(())
}
async fn handle_lsp_command(command: LspCommand) -> Result<(), Error> {
configure_logger(command.output, TerminalMode::Stderr);
let config = get_config(command.config)?;
let perf_logger = Arc::new(ConsoleLogger);
let extra_data_provider = Box::new(DummyExtraDataProvider::new());
let schema_documentation_loader: Option<Box<dyn SchemaDocumentationLoader<SDLSchema>>> = None;
let js_language_server = None;
start_language_server(
config,
perf_logger,
extra_data_provider,
schema_documentation_loader,
js_language_server,
)
.await
.map_err(|err| Error::LSPError {
details: format!("Relay LSP unexpectedly terminated: {:?}", err),
})?;
info!("Relay LSP exited successfully.");
Ok(())
}
/// Check if `watchman` is available.
/// Additionally, this method is checking for an existence of `FORCE_NO_WATCHMAN`
/// environment variable. If this `FORCE_NO_WATCHMAN` is set, this method will return `false`
/// and compiler will use non-watchman file finder.
fn should_use_watchman() -> bool {
let check_watchman = Command::new("watchman")
.args(["list-capabilities"])
.output();
check_watchman.is_ok() && env::var("FORCE_NO_WATCHMAN").is_err()
}