-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmain.rs
More file actions
317 lines (268 loc) · 10.3 KB
/
Copy pathmain.rs
File metadata and controls
317 lines (268 loc) · 10.3 KB
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
use clap::{CommandFactory, Parser, Subcommand, ValueEnum};
use clap_complete::{generate, Shell};
use dsync::{error::IOErrorToError, GenerationConfig, TableOptions};
use dsync::{BytesType, FileChangeStatus, GenerationConfigOpts, StringType};
use std::collections::HashMap;
use std::io::{BufWriter, Write};
use std::path::PathBuf;
#[derive(Debug, Parser, Clone, PartialEq)]
#[command(author, version, about, long_about = None)]
#[command(bin_name("dsync"))]
#[command(disable_help_subcommand(true))] // Disable subcommand "help", only "-h" or "--help" should be used
#[command(subcommand_negates_reqs(true))]
#[command(infer_subcommands(true))]
pub struct CliDerive {
// use extra struct, otherwise clap subcommands require all options
#[clap(flatten)]
pub args: Option<MainOptions>,
#[command(subcommand)]
pub subcommands: Option<SubCommands>,
}
#[derive(Debug, Subcommand, Clone, PartialEq)]
pub enum SubCommands {
/// Generate shell completions
Completions(CommandCompletions),
}
#[derive(Debug, Parser, Clone, PartialEq)]
pub struct CommandCompletions {
/// Set which shell completions should be generated
/// Supported are: Bash, Elvish, Fish, PowerShell, Zsh
#[arg(short = 's', long = "shell", value_enum)]
pub shell: Shell,
/// Output path where to output the completions to
/// Not specifying this will print to STDOUT
#[arg(short = 'o', long = "out")]
pub output_file_path: Option<PathBuf>,
}
#[derive(Debug, Parser, Clone, PartialEq)]
pub struct MainOptions {
/// Input diesel schema file
#[arg(short = 'i', long = "input")]
pub input: PathBuf,
/// Output file, stdout if not present
#[arg(short = 'o', long = "output")]
pub output: PathBuf,
/// adds the #[tsync] attribute to all structs; see https://github.com/Wulf/tsync
#[arg(long = "tsync")]
#[cfg(feature = "tsync")]
pub tsync: bool,
/// uses diesel_async for generated functions; see https://github.com/weiznich/diesel_async
#[arg(long = "async")]
#[cfg(feature = "async")]
pub use_async: bool,
/// List of columns which are automatically generated but are not primary keys (for example: "created_at", "updated_at", etc.)
#[arg(short = 'g', long = "autogenerated-columns")]
pub autogenerated_columns: Option<Vec<String>>,
/// rust type which describes a connection
///
/// For example:
/// - `diesel::pg::PgConnection`
/// - `diesel::sqlite::SqliteConnection`
/// - `diesel::mysql::MysqlConnection`
/// - `diesel::r2d2::PooledConnection<diesel::r2d2::ConnectionManager<diesel::pg::PgConnection>>`
/// - or, your custom diesel connection type (struct which implements `diesel::connection::Connection`)
#[arg(short = 'c', long = "connection-type", verbatim_doc_comment)]
pub connection_type: String,
/// Disable generating serde implementations
#[arg(long = "no-serde")]
pub no_serde: bool,
/// Set custom schema use path
#[arg(long = "schema-path", default_value = dsync::DEFAULT_SCHEMA_PATH)]
pub schema_path: String,
/// Set custom model use path
#[arg(long = "model-path", default_value = dsync::DEFAULT_MODEL_PATH)]
pub model_path: String,
/// Do not generate the CRUD (impl) functions for generated models
#[arg(long = "no-crud")]
pub no_crud: bool,
/// Set which string type to use for Create* structs
#[arg(long = "create-str", default_value = "string")]
pub create_str: StringTypeCli,
/// Set which string type to use for Update* structs
#[arg(long = "update-str", default_value = "string")]
pub update_str: StringTypeCli,
/// Set which bytes type to use for Create* structs
#[arg(long = "create-bytes", default_value = "vec")]
pub create_bytes: BytesTypeCli,
/// Set which bytes type to use for Update* structs
#[arg(long = "update-bytes", default_value = "vec")]
pub update_bytes: BytesTypeCli,
/// Only Generate a single model file instead of a directory with "mod.rs" and "generated.rs"
#[arg(long = "single-model-file")]
pub single_model_file: bool,
/// Generate common structs only once in a "common.rs" file
#[arg(long = "once-common-structs")]
pub once_common_structs: bool,
/// Generate the "ConnectionType" type only once in a "common.rs" file
#[arg(long = "once-connection-type")]
pub once_connection_type: bool,
/// A Prefix to treat a table matching this as readonly (only generate the Read struct)
#[arg(long = "readonly-prefix")]
pub readonly_prefixes: Vec<String>,
/// A Suffix to treat a table matching this as readonly (only generate the Read struct)
#[arg(long = "readonly-suffix")]
pub readonly_suffixes: Vec<String>,
#[cfg(feature = "advanced-queries")]
/// Set which diesel backend to use (something which implements `diesel::backend::Backend`)
/// Diesel provides the following backends:
/// - `diesel::pg::Pg`
/// - `diesel::sqlite::Sqlite`
/// - `diesel::mysql::Mysql`
///
/// See `crate::GenerationConfig::diesel_backend` for more details.
#[arg(short = 'b', long = "diesel-backend")]
pub diesel_backend: String,
/// Add these additional derives to each generated `struct`
#[arg(short = 'd', long = "derive")]
pub additional_derives: Vec<String>,
}
#[derive(Debug, ValueEnum, Clone, PartialEq, Default)]
pub enum StringTypeCli {
/// Use "String"
#[default]
String,
/// Use "&str"
Str,
/// Use "Cow<str>"
Cow,
}
impl From<StringTypeCli> for StringType {
fn from(value: StringTypeCli) -> Self {
match value {
StringTypeCli::String => StringType::String,
StringTypeCli::Str => StringType::Str,
StringTypeCli::Cow => StringType::Cow,
}
}
}
#[derive(Debug, ValueEnum, Clone, PartialEq, Default)]
pub enum BytesTypeCli {
/// Use "Vec<u8>"
#[default]
Vec,
/// Use "&[u8]"
Slice,
/// Use "Cow<[u8]>"
Cow,
}
impl From<BytesTypeCli> for BytesType {
fn from(value: BytesTypeCli) -> Self {
match value {
BytesTypeCli::Vec => BytesType::Vec,
BytesTypeCli::Slice => BytesType::Slice,
BytesTypeCli::Cow => BytesType::Cow,
}
}
}
fn main() {
let res = actual_main();
if let Err(err) = res {
eprintln!("Error:\n{err}");
#[cfg(feature = "backtrace")]
{
let backtrace = err.backtrace().to_string();
if backtrace == "disabled backtrace" {
eprintln!(
"note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace"
);
} else {
eprintln!("{}", backtrace);
}
}
#[cfg(not(feature = "backtrace"))]
{
eprintln!("backtrace support is disabled, enable feature \"backtrace\"");
}
std::process::exit(1);
}
}
fn actual_main() -> dsync::Result<()> {
let cli = CliDerive::parse();
if let Some(subcommand) = cli.subcommands {
return match subcommand {
SubCommands::Completions(subcommand) => command_completions(&subcommand),
};
}
let args = cli
.args
.expect("cli.args should be defined if no subcommand is given");
let cols = args.autogenerated_columns.unwrap_or_default();
let mut default_table_options = TableOptions::default()
.autogenerated_columns(cols.iter().map(|t| t.as_str()).collect::<Vec<&str>>())
.create_str_type(args.create_str.into())
.update_str_type(args.update_str.into())
.create_bytes_type(args.create_bytes.into())
.update_bytes_type(args.update_bytes.into());
#[cfg(feature = "tsync")]
if args.tsync {
default_table_options = default_table_options.tsync();
}
#[cfg(feature = "async")]
if args.use_async {
default_table_options = default_table_options.use_async();
}
if args.no_serde {
default_table_options = default_table_options.disable_serde();
}
if args.no_crud {
default_table_options = default_table_options.disable_fns();
}
if args.single_model_file {
default_table_options = default_table_options.single_model_file();
}
let changes = dsync::generate_files(
&args.input,
&args.output,
GenerationConfig {
connection_type: args.connection_type,
#[cfg(feature = "advanced-queries")]
diesel_backend: args.diesel_backend,
options: GenerationConfigOpts {
default_table_options,
table_options: HashMap::from([]),
schema_path: args.schema_path,
model_path: args.model_path,
once_common_structs: args.once_common_structs,
once_connection_type: args.once_connection_type,
readonly_prefixes: args.readonly_prefixes,
readonly_suffixes: args.readonly_suffixes,
additional_derives: args.additional_derives,
},
},
)?;
let mut modified: usize = 0;
for change in changes {
println!("{} {}", change.status, change.file.to_string_lossy());
if change.status != FileChangeStatus::Unchanged {
modified += 1;
}
}
println!("Modified {} files", modified);
Ok(())
}
/// Handler function for the "completions" subcommand
/// This function is mainly to keep the code structured and sorted
#[inline]
pub fn command_completions(sub_args: &CommandCompletions) -> dsync::Result<()> {
// if there is a output file path, use that path, otherwise use stdout
let mut writer: BufWriter<Box<dyn Write>> = match &sub_args.output_file_path {
Some(v) => {
if v.exists() {
return Err(dsync::Error::other("Output file already exists"));
}
let v_parent = v
.parent()
.expect("Expected input filename to have a parent");
std::fs::create_dir_all(v_parent).attach_path_err(v_parent)?;
BufWriter::new(Box::from(std::fs::File::create(v).attach_path_err(v)?))
}
None => BufWriter::new(Box::from(std::io::stdout())),
};
let mut parsed = CliDerive::command();
let bin_name = parsed
.get_bin_name()
.expect("Expected binary to have a binary name")
.to_string();
generate(sub_args.shell, &mut parsed, bin_name, &mut writer);
Ok(())
}