Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unify cli input parsing #549

Merged
merged 1 commit into from Mar 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 6 additions & 6 deletions README.md
Expand Up @@ -76,8 +76,8 @@ USAGE:
prisma [FLAGS] [OPTIONS] [SUBCOMMAND]

FLAGS:
--always_force_transactions Runs all queries in a transaction, including all the reads
--enable_raw_queries Enables raw SQL queries with executeRaw mutation
--always-force-transactions Runs all queries in a transaction, including all the reads
--enable-raw-queries Enables raw SQL queries with executeRaw mutation
-h, --help Prints help information
--legacy Switches query schema generation to Prisma 1 compatible mode
-V, --version Prints version information
Expand All @@ -101,10 +101,10 @@ FLAGS:
-V, --version Prints version information

SUBCOMMANDS:
--dmmf Output the DMMF from the loaded data model
--dmmf_to_dml Convert the given DMMF JSON file to a data model
--execute_request Executes one request and then terminates
--get_config Get the configuration from the given data model
dmmf Output the DMMF from the loaded data model
dmmf-to-dml Convert the given DMMF JSON file to a data model
execute-request Executes one request and then terminates
get-config Get the configuration from the given data model
help Prints this message or the help of the given subcommand(s)
```

Expand Down
1 change: 1 addition & 0 deletions introspection-engine/core/Cargo.toml
Expand Up @@ -12,6 +12,7 @@ introspection-connector = { path = "../connectors/introspection-connector" }
sql-introspection-connector = { path = "../connectors/sql-introspection-connector" }

clap = "2.33"
structopt = "0.3"
serde = "1.0"
anyhow = "1.0.26"
thiserror = "1.0.9"
Expand Down
12 changes: 0 additions & 12 deletions introspection-engine/core/src/cli.rs

This file was deleted.

25 changes: 13 additions & 12 deletions introspection-engine/core/src/main.rs
@@ -1,26 +1,27 @@
use jsonrpc_core::*;
use rpc::{Rpc, RpcImpl};
pub mod cli;
mod command_error;
mod error;
mod error_rendering;
mod rpc;

use jsonrpc_core::*;
use rpc::{Rpc, RpcImpl};
use structopt::StructOpt;

#[derive(Debug, StructOpt, Clone)]
#[structopt(version = env!("GIT_HASH"))]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh I didn't know that option, it's great!

pub struct IntrospectionOpt {}

#[tokio::main]
async fn main() {
let matches = cli::clap_app().get_matches();
init_logger();

if matches.is_present("version") {
println!(env!("GIT_HASH"));
} else {
user_facing_errors::set_panic_hook();
let _ = IntrospectionOpt::from_args();
user_facing_errors::set_panic_hook();

let mut io_handler = IoHandler::new();
io_handler.extend_with(RpcImpl::new().to_delegate());
let mut io_handler = IoHandler::new();
io_handler.extend_with(RpcImpl::new().to_delegate());

json_rpc_stdio::run(&io_handler).await.unwrap();
}
json_rpc_stdio::run(&io_handler).await.unwrap();
}

fn init_logger() {
Expand Down
7 changes: 7 additions & 0 deletions libs/test-cli/build.rs
@@ -0,0 +1,7 @@
use std::process::Command;

fn main() {
let output = Command::new("git").args(&["rev-parse", "HEAD"]).output().unwrap();
let git_hash = String::from_utf8(output.stdout).unwrap();
println!("cargo:rustc-env=GIT_HASH={}", git_hash);
}
9 changes: 4 additions & 5 deletions libs/test-cli/src/main.rs
Expand Up @@ -3,18 +3,18 @@ use colored::Colorize;
use structopt::*;

#[derive(StructOpt)]
#[structopt(version = env!("GIT_HASH"))]
enum Command {
/// Apply a prisma schema to a database
#[structopt(name = "apply-schema")]
ApplySchema {
/// The path to the prisma schema file. Either this or --stdin should be provided.
#[structopt(long = "file-path")]
#[structopt(long)]
file_path: Option<String>,
/// Try to read the prisma schema from stdin. Either this or --file-path should be provided.
#[structopt(long = "stdin")]
#[structopt(long)]
stdin: bool,
/// Whether to ignore warnings from the migration engine regarding data loss. Default: false.
#[structopt(long = "force")]
#[structopt(long)]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

didn't know that either, great!

force: Option<bool>,
},
}
Expand Down Expand Up @@ -58,7 +58,6 @@ fn main() -> anyhow::Result<()> {
};

let result = api.apply_migration(&apply_input).await?;

let warnings = result.warnings.into_iter().map(|warning| warning.description).collect();

Ok::<Vec<String>, anyhow::Error>(warnings)
Expand Down
6 changes: 3 additions & 3 deletions migration-engine/cli/README.md
Expand Up @@ -13,7 +13,7 @@ USAGE:

FLAGS:
-h, --help Prints help information
-s, --single_cmd Run only a single command, then exit
-s, --single-cmd Run only a single command, then exit
--version Prints the server commit ID

OPTIONS:
Expand Down Expand Up @@ -41,7 +41,7 @@ OPTIONS:
-d, --datasource <datasource> The connection string to the database

SUBCOMMANDS:
--can_connect_to_database Does the database connection string work?
--create_database Create an empty database defined in the configuration string
can-connect-to-database Does the database connection string work?
create-database Create an empty database defined in the configuration string
help Prints this message or the help of the given subcommand(s)
```
4 changes: 1 addition & 3 deletions migration-engine/cli/src/commands.rs
Expand Up @@ -16,7 +16,7 @@ use url::Url;
#[derive(Debug, StructOpt)]
pub(crate) struct Cli {
/// The connection string to the database
#[structopt(long = "datasource", short = "d")]
#[structopt(long, short = "d")]
datasource: String,
#[structopt(subcommand)]
command: CliCommand,
Expand Down Expand Up @@ -63,10 +63,8 @@ impl Cli {
#[derive(Debug, StructOpt)]
enum CliCommand {
/// Create an empty database defined in the configuration string.
#[structopt(name = "--create_database")]
CreateDatabase,
/// Does the database connection string work?
#[structopt(name = "--can_connect_to_database")]
CanConnectToDatabase,
}

Expand Down
20 changes: 10 additions & 10 deletions migration-engine/cli/src/commands/tests.rs
Expand Up @@ -24,7 +24,7 @@ fn mysql_url(db: Option<&str>) -> String {

#[tokio::test]
async fn test_connecting_with_a_working_mysql_connection_string() {
let result = run(&["--datasource", &mysql_url(None), "--can_connect_to_database"])
let result = run(&["--datasource", &mysql_url(None), "can-connect-to-database"])
.await
.unwrap();

Expand All @@ -34,7 +34,7 @@ async fn test_connecting_with_a_working_mysql_connection_string() {
#[tokio::test]
async fn test_connecting_with_a_non_working_mysql_connection_string() {
let datasource = mysql_url(Some("this_does_not_exist"));
let err = run(&["--datasource", &datasource, "--can_connect_to_database"])
let err = run(&["--datasource", &datasource, "can-connect-to-database"])
.await
.unwrap_err();

Expand All @@ -44,7 +44,7 @@ async fn test_connecting_with_a_non_working_mysql_connection_string() {
#[tokio::test]
async fn test_connecting_with_a_working_psql_connection_string() {
let datasource = postgres_url(None);
let result = run(&["--datasource", &datasource, "--can_connect_to_database"])
let result = run(&["--datasource", &datasource, "can-connect-to-database"])
.await
.unwrap();

Expand All @@ -56,7 +56,7 @@ async fn test_connecting_with_a_working_psql_connection_string_with_postgres_sch
let result = run(&[
"--datasource",
&postgres_url_with_scheme(None, "postgres"),
"--can_connect_to_database",
"can-connect-to-database",
])
.await
.unwrap();
Expand All @@ -67,7 +67,7 @@ async fn test_connecting_with_a_working_psql_connection_string_with_postgres_sch
#[tokio::test]
async fn test_connecting_with_a_non_working_psql_connection_string() {
let datasource = postgres_url(Some("this_does_not_exist"));
let err = run(&["--datasource", &datasource, "--can_connect_to_database"])
let err = run(&["--datasource", &datasource, "can-connect-to-database"])
.await
.unwrap_err();

Expand All @@ -78,15 +78,15 @@ async fn test_connecting_with_a_non_working_psql_connection_string() {
async fn test_create_mysql_database() {
let url = mysql_url(Some("this_should_exist"));

let res = run(&["--datasource", &url, "--create_database"]).await;
let res = run(&["--datasource", &url, "create-database"]).await;

assert_eq!(
"Database 'this_should_exist' created successfully.",
res.as_ref().unwrap()
);

if let Ok(_) = res {
let res = run(&["--datasource", &url, "--can_connect_to_database"]).await;
let res = run(&["--datasource", &url, "can-connect-to-database"]).await;
assert_eq!("Connection successful", res.as_ref().unwrap());

{
Expand Down Expand Up @@ -120,14 +120,14 @@ async fn test_create_psql_database() {

let url = postgres_url(Some(db_name));

let res = run(&["--datasource", &url, "--create_database"]).await;
let res = run(&["--datasource", &url, "create-database"]).await;

assert_eq!(
"Database 'this_should_exist' created successfully.",
res.as_ref().unwrap()
);

let res = run(&["--datasource", &url, "--can_connect_to_database"]).await;
let res = run(&["--datasource", &url, "can-connect-to-database"]).await;
assert_eq!("Connection successful", res.as_ref().unwrap());

res.unwrap();
Expand All @@ -146,7 +146,7 @@ async fn test_create_sqlite_database() {

let url = format!("file:{}", sqlite_path.to_string_lossy());

let res = run(&["--datasource", &url, "--create_database"]).await;
let res = run(&["--datasource", &url, "create-database"]).await;
assert_eq!("", res.as_ref().unwrap());

assert!(sqlite_path.exists());
Expand Down
6 changes: 3 additions & 3 deletions migration-engine/cli/src/error_tests.rs
Expand Up @@ -16,7 +16,7 @@ async fn database_already_exists_must_return_a_proper_error() {
.await
.ok();

let error = get_cli_error(&["migration-engine", "cli", "--datasource", &url, "--create_database"]).await;
let error = get_cli_error(&["migration-engine", "cli", "--datasource", &url, "create-database"]).await;

let (host, port) = {
let url = Url::parse(&url).unwrap();
Expand Down Expand Up @@ -60,7 +60,7 @@ async fn database_access_denied_must_return_a_proper_error_in_cli() {
"cli",
"--datasource",
url.as_str(),
"--can_connect_to_database",
"can-connect-to-database",
])
.await;

Expand Down Expand Up @@ -89,7 +89,7 @@ async fn tls_errors_must_be_mapped_in_the_cli() {
"cli",
"--datasource",
&url,
"--can_connect_to_database",
"can-connect-to-database",
])
.await;

Expand Down
14 changes: 3 additions & 11 deletions migration-engine/cli/src/main.rs
Expand Up @@ -9,17 +9,14 @@ use structopt::StructOpt;
/// When no subcommand is specified, the migration engine will default to starting as a JSON-RPC
/// server over stdio.
#[derive(Debug, StructOpt)]
#[structopt(no_version)]
#[structopt(version = env!("GIT_HASH"))]
struct MigrationEngineCli {
/// Run only a single command, then exit
#[structopt(short = "s", long = "single_cmd")]
#[structopt(short = "s", long)]
single_cmd: bool,
/// Path to the datamodel
#[structopt(short = "d", long = "datamodel", name = "FILE")]
#[structopt(short = "d", long, name = "FILE")]
datamodel: Option<String>,
/// Prints the server commit ID
#[structopt(long = "version")]
version: bool,
#[structopt(subcommand)]
cli_subcommand: Option<SubCommand>,
}
Expand Down Expand Up @@ -47,11 +44,6 @@ async fn main() {

let input = MigrationEngineCli::from_args();

if input.version {
println!(env!("GIT_HASH"));
std::process::exit(0);
}

match input.cli_subcommand {
None => {
if let Some(datamodel_location) = input.datamodel.as_ref() {
Expand Down
4 changes: 2 additions & 2 deletions prisma-fmt/Cargo.toml
Expand Up @@ -6,6 +6,6 @@ edition = "2018"

[dependencies]
datamodel = { path = "../libs/datamodel/core" }
clap = "2.33.0"
structopt = "0.3"
serde = { version = "1.0.90", features = ["derive"] }
serde_json = "1.0"
serde_json = "1.0"
36 changes: 36 additions & 0 deletions prisma-fmt/src/format.rs
@@ -0,0 +1,36 @@
use datamodel::ast::reformat::Reformatter;
use std::{
fs::{self, File},
io::{self, BufWriter, Read},
};

use crate::FormatOpts;

pub fn run(opts: FormatOpts) {
let datamodel_string = match opts.input {
Some(file_name) => {
fs::read_to_string(&file_name).expect(&format!("Unable to open file {}", file_name.display()))
}
None => {
let mut buf = String::new();

io::stdin()
.read_to_string(&mut buf)
.expect("Unable to read from stdin.");

buf
}
};

match opts.output {
Some(file_name) => {
let file = File::open(&file_name).expect(&format!("Unable to open file {}", file_name.display()));
let mut stream = BufWriter::new(file);

Reformatter::reformat_to(&datamodel_string, &mut stream, opts.tabwidth);
}
None => {
Reformatter::reformat_to(&datamodel_string, &mut io::stdout().lock(), opts.tabwidth);
}
}
}