public async static Task <int> Main(string[] args2) { RunnerArgs args = RunnerArgs.FromCommandLine(args2); ProgramRunner runner = new ProgramRunner(args); try { await runner.ExecuteAsync(); } catch (ToolException ex) { if (!string.IsNullOrWhiteSpace(ex.StdOut)) { WriteLine(ex.StdOut, ConsoleColor.Red); } if (!string.IsNullOrWhiteSpace(ex.StdErr)) { WriteLine(ex.StdErr, ConsoleColor.Red); } return(-1); } catch (Exception ex) { WriteLine(ex.Message, ConsoleColor.Red); return(-1); } return(0); }
public AdditionalArgs(RunnerArgs runnerArgs) { PaketRedirectArgs = runnerArgs.Redirects ? "--redirects --create-new-binding-files --clean-redirects" : "--create-new-binding-files --clean-redirects"; PaketForceArgs = runnerArgs.Force ? "--force" : ""; PaketVerboseArgs = runnerArgs.Verbose ? "--verbose" : ""; DotnetVerboseArgs = runnerArgs.Verbose ? "--verbosity d" : ""; }
public static async Task ResponseFileAsync(RunnerArgs args) { string[] responseFiles = args.Options["-f", "--file"]?.Values ?? Array.Empty <string>(); string command = args.Options["-c", "--command"]?.Value; if (responseFiles.Length == 0) { responseFiles = GetDefaultFiles(); if (responseFiles.Length == 0) { throw new RunnerException("Please specify at least one response file with -f|--file or create a default '<command>.cli' in the current directory."); } else if (responseFiles.Length > 1) { throw new RunnerException("Multiple default '<command>.cli' files found. Please specify the right one with the -c|--command argument."); } } string[] prefixedFiles = responseFiles.Select(f => f.StartsWith('@') ? f : '@' + f).ToArray(); string[] argumentList = ResponseFile.ExpandStrings(prefixedFiles).SelectMany(ToolOptions.ToArgumentList).SkipWhile(s => s == "cli").ToArray(); if (command != null && command != "cli") { argumentList = new[] { command } }
public async static Task SqlAsync(RunnerArgs args, IConnectionFactory factory) { if (factory == null) { throw new RunnerException("Invalid factory object."); } if (string.IsNullOrWhiteSpace(args.Connection)) { throw new RunnerException("Please specify a connection string using the -c|--connection argument."); } string[] inputs = args.Options["-s", "--sql"]?.Values ?? Array.Empty <string>(); if (inputs.Length == 0) { throw new RunnerException("Please specify at least one SQL input with the -s|--sql argument."); } using (DbConnection connection = await GetOpenConnectionAsync(args, factory)) { foreach (ResponseFile responseFile in inputs.Select(ResponseFile.Parse)) { if (responseFile.IsPath) { DotNetJerryHost.WriteLine($"Executing '@{Path.GetFileName(responseFile.InputPath)}'...", ConsoleColor.Yellow); if (!File.Exists(responseFile.FullPath)) { DotNetJerryHost.WriteLine($"Skipped. File not found.", ConsoleColor.Yellow); continue; } } else if (!responseFile.Ignore) { DotNetJerryHost.WriteLine($"Executing '{responseFile.Value}'...", ConsoleColor.Yellow); } using (DbCommand command = connection.CreateCommand()) { command.CommandText = string.Join(Environment.NewLine, ResponseFile.ExpandStrings(responseFile)); if (!string.IsNullOrWhiteSpace(command.CommandText)) { int affectedRows = await command.ExecuteNonQueryAsync(); string rowsMoniker = affectedRows + " " + (affectedRows == 1 ? "row" : "rows"); DotNetJerryHost.WriteLine($"OK. {rowsMoniker} affected.", ConsoleColor.Green); } else { DotNetJerryHost.WriteLine($"Skipped. SQL text is empty.", ConsoleColor.Yellow); } } } } }
public static void Help(RunnerArgs args) { if (args.Options.Default.Length == 0) { HelpForInvalid(args); } else if (args.Options.Default.Length == 1 || args.Options.Default[1] == "help") { DotNetJerryHost.WriteHeader(); DotNetJerryHost.WriteLine("Usage: jerry [command] [options] [@file]"); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine("Execute a command with the specified options. Use @file[.cli] to expand arguments"); DotNetJerryHost.WriteLine("from an input file."); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine("Commands:"); DotNetJerryHost.WriteLine(" scaffold Generate a C# object model from an existing database."); DotNetJerryHost.WriteLine(" transpile Transpile a project of .cssql files into .cs files."); DotNetJerryHost.WriteLine(" info Show information about a database connector."); DotNetJerryHost.WriteLine(" args Show all arguments. Useful for debugging @file inputs."); DotNetJerryHost.WriteLine(" help [command] Show help information about the commands above."); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine("Examples:"); DotNetJerryHost.WriteLine(" Generate a C# model with arguments in a local 'mydb.cli' file:"); DotNetJerryHost.WriteLine(" > jerry scaffold @mydb"); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine(" Transpile .cssql files from directories 'Queries' and 'Commands':"); DotNetJerryHost.WriteLine(" > jerry transpile -d Queries -d Commands"); DotNetJerryHost.WriteLine(); } else { switch (args.Options.Default[1]) { case "scaffold": case "sf": HelpForScaffold(); break; case "transpile": case "tp": HelpForTranspile(); break; case "run": HelpForRun(); break; case "info": HelpForInfo(); break; default: throw new RunnerException($"Invalid command '{args.Options.Default[1]}'."); } } }
public static void Info(RunnerArgs info, InfoCommand command) { if (command == null) { throw new RunnerException("Invalid command object."); } Program.WriteHeader(); Program.WriteLine($"Package: {info.Proxy.PackageName}"); Program.WriteLine($"Connector: {command.Connector} v{command.ConnectorVersion}"); }
public async static Task <int> Main(string[] args) { RunnerArgs runnerArgs; try { runnerArgs = RunnerArgs.FromCommandLine(args); } catch (FileNotFoundException ex) { WriteHeader(); WriteLine(); WriteLine($"Could not expand '@{Path.GetFileName(ex.FileName)}'. File not found.", ConsoleColor.Red); return(-1); } catch (Exception ex) { WriteHeader(); WriteLine(); WriteLine(ex.Message, ConsoleColor.Red); return(-1); } try { await new ProgramRunner(runnerArgs).ExecuteAsync(); } catch (ToolException ex) { if (!string.IsNullOrWhiteSpace(ex.StdOut)) { WriteLine(ex.StdOut, ConsoleColor.Red); } if (!string.IsNullOrWhiteSpace(ex.StdErr)) { WriteLine(ex.StdErr, ConsoleColor.Red); } return(-1); } catch (Exception ex) { bool isVerbose = runnerArgs?.Verbose ?? false; WriteLine(isVerbose ? ex.ToString() : ex.Message, ConsoleColor.Red); return(-1); } return(0); }
public static async Task ScaffoldAsync(RunnerArgs args, ScaffoldCommand command) { if (command == null) { throw new RunnerException("Invalid command object."); } if (string.IsNullOrWhiteSpace(args.Connection)) { throw new RunnerException("Please specify a connection string using the -c|--connection parameter."); } DatabaseModel databaseModel; IList <TypeMapping> typeMappings; if (args.Verbose) { DotNetJerryHost.WriteHeader(); } using (DbConnection connection = await GetOpenConnectionAsync(args, command)) { DotNetJerryHost.WriteLine("Generating...", ConsoleColor.Yellow); databaseModel = await command.GetDatabaseModelAsync(connection); typeMappings = command.GetTypeMappings().ToList(); } ScaffoldProject project = ScaffoldProject.FromModel(databaseModel, typeMappings, args); await ScaffoldWriter.WriteAsync(project); if (args.Verbose) { ScaffoldWriteVerboseOutput(project); } int objectCount = project.Files.SelectMany(f => f.Objects).Count(); string classMoniker = objectCount + " " + (objectCount == 1 ? "class" : "classes"); if (project.Files.Count == 1) { DotNetJerryHost.WriteLine($"Created {classMoniker} in {project.Files[0].FileName}.", ConsoleColor.Green); } else { DotNetJerryHost.WriteLine($"Created {classMoniker} in {project.Files.Count} files.", ConsoleColor.Green); } }
public static void HelpForInvalid(RunnerArgs args) { DotNetJerryHost.WriteHeader(); DotNetJerryHost.WriteLine("Usage: jerry [command] [options]. Use 'jerry help' to show commands and options."); if (string.IsNullOrEmpty(args.Command)) { throw new RunnerException("No command specified."); } else { throw new RunnerException($"Invalid command '{args.Command}'."); } }
public static void Help(RunnerArgs args) { if (args.Options.Default.Length == 0) { HelpForInvalid(args); } else if (args.Options.Default.Length == 1 || args.Options.Default[1] == "help") { DotNetJerryHost.WriteHeader(); DotNetJerryHost.WriteLine("Usage: jerry [command] [options]"); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine("Execute a command with the Jerrycurl CLI."); DotNetJerryHost.WriteLine(); DotNetJerryHost.WriteLine("Commands:"); DotNetJerryHost.WriteLine(" scaffold Generate a C# object model from an existing database."); DotNetJerryHost.WriteLine(" transpile Transpile a collection of .cssql files into C# classes."); DotNetJerryHost.WriteLine(" cli Execute CLI with arguments read from one or more input files."); DotNetJerryHost.WriteLine(" info Show information about a database connector."); DotNetJerryHost.WriteLine(" help [command] Show help information the commands above."); DotNetJerryHost.WriteLine(); } else { switch (args.Options.Default[1]) { case "scaffold": case "sf": HelpForScaffold(); break; case "transpile": case "tp": HelpForTranspile(); break; case "cli": HelpForResponseFile(); break; case "info": HelpForInfo(); break; default: throw new RunnerException($"Invalid command '{args.Options.Default[1]}'."); } } }
public static void Transpile(RunnerArgs args) { string projectDirectory = args.Options["-p", "--project"]?.Value ?? Environment.CurrentDirectory; string rootNamespace = args.Options["-ns", "--namespace"]?.Value; string sourcePath = Path.GetDirectoryName(typeof(DotNetJerryHost).Assembly.Location); string skeletonPath = Path.Combine(sourcePath, "skeleton.jerry"); string outputDirectory = args.Options["-o", "--output"]?.Value; if (!Directory.Exists(projectDirectory)) { throw new RunnerException($"Project directory '{projectDirectory}' does not exist."); } if (!File.Exists(skeletonPath)) { throw new RunnerException("Skeleton file not found."); } projectDirectory = PathHelper.MakeAbsolutePath(Environment.CurrentDirectory, projectDirectory); outputDirectory = PathHelper.MakeAbsolutePath(projectDirectory, outputDirectory ?? RazorProjectConventions.DefaultIntermediateDirectory); RazorProject project = new RazorProject() { ProjectDirectory = projectDirectory, RootNamespace = rootNamespace, Items = new List <RazorProjectItem>(), IntermediateDirectory = outputDirectory, }; if (args.Options["-f", "--file"] != null) { foreach (string file in args.Options["-f", "--file"].Values) { foreach (string expandedFile in ResponseFile.ExpandStrings(file, project.ProjectDirectory)) { if (!HasPipeFormat(expandedFile, out var fullPath, out var projectPath)) { project.AddItem(expandedFile); } else if (!string.IsNullOrEmpty(fullPath)) { project.Items.Add(new RazorProjectItem() { FullPath = MakeAbsolutePath(fullPath), ProjectPath = projectPath }); } }
public static void WriteHeader() { NuGetVersion version = RunnerArgs.GetNuGetPackageVersion(); if (version == null) { WriteLine($"Jerrycurl CLI"); } else if (version.CommitHash != null) { WriteLine($"Jerrycurl CLI v{version.PublicVersion} ({version.CommitHash})"); } else { WriteLine($"Jerrycurl CLI v{version.PublicVersion}"); } }
private async static Task <DbConnection> GetOpenConnectionAsync(RunnerArgs args, IConnectionFactory factory) { DbConnection connection = factory.GetDbConnection(); if (connection == null) { throw new RunnerException("Connection returned null."); } try { connection.ConnectionString = args.Connection; } catch (Exception ex) { connection.Dispose(); throw new RunnerException("Invalid connection string: " + ex.Message, ex); } if (!string.IsNullOrEmpty(connection.Database)) { DotNetJerryHost.WriteLine($"Connecting to '{connection.Database}'...", ConsoleColor.Yellow); } else { DotNetJerryHost.WriteLine("Connecting to database...", ConsoleColor.Yellow); } try { await connection.OpenAsync().ConfigureAwait(false); return(connection); } catch (Exception ex) { connection.Dispose(); throw new RunnerException("Unable to open connection: " + ex.Message, ex); } }
static async Task Main(string[] args) { Console.WriteLine("Discovery API Sample"); Console.WriteLine("===================="); RunnerArgs runnerArgs = new RunnerArgs( pubSubProjectId: "pub-sub-project-id", pubSubSubscriptionId: "pub-sub-subscription-id", serviceAccountJsonFpath: "credential-json-fpath" ); Handler handler = new Handler(); Runner runner = new Runner(args: runnerArgs, handler: handler); Console.WriteLine("Runnning"); var _ = runner.Start(); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); runner.Stop().Wait(); Console.WriteLine("Stopped"); }
public static void Help(RunnerArgs args) { if (args.Command == "help") { Program.WriteHeader(); Program.WriteLine("Usage: jerry [command] [options]"); Program.WriteLine(); Program.WriteLine("Commands:"); Program.WriteLine(" scaffold Generate C# classes from an existing database."); Program.WriteLine(" info Show information about a specific vendor."); Program.WriteLine(" help Show this information."); Program.WriteLine(); Program.WriteLine("Options:"); Program.WriteLine(" -v, --vendor <moniker> Vendor used to connect to database. Moniker can"); Program.WriteLine(" be 'sqlserver', 'sqlite', 'oracle', 'postgres'"); Program.WriteLine(" or 'mysql'."); Program.WriteLine(" -c, --connection <cs> Connection string used to connect to database."); Program.WriteLine(" -ns, --namespace <ns> Namespace to place scaffolded C# classes in."); Program.WriteLine(" -o, --output <file> Path to scaffold .cs files into. Writes one"); Program.WriteLine(" file per class unless specified with .cs"); Program.WriteLine(" extension. Defaults to Database.cs."); //Program.WriteLine(" --verbose Show verbose output."); Program.WriteLine(); } else { Program.WriteHeader(); Program.WriteLine("Usage: jerry [command] [options]"); Program.WriteLine("Use 'jerry help' to show options."); if (string.IsNullOrEmpty(args.Command)) { throw new RunnerException("No command specified."); } else { throw new RunnerException($"Invalid command '{args.Command}'."); } } }
public static ScaffoldProject FromModel(DatabaseModel databaseModel, IList <TypeMapping> typeMappings, RunnerArgs args) { List <ScaffoldFile> files = new List <ScaffoldFile>(); foreach (var g1 in databaseModel.Tables.GroupBy(t => ResolveFileName(t, databaseModel.DefaultSchema, args))) { ScaffoldFile newFile = new ScaffoldFile() { FileName = g1.Key, }; foreach (TableModel table in g1.Where(t => !t.Ignore)) { ScaffoldObject newObject = new ScaffoldObject() { Table = table, Namespace = ResolveNamespace(table, databaseModel.DefaultSchema, args), ClassName = ResolveClassName(table), }; foreach (ColumnModel column in table.Columns.Where(c => !c.Ignore)) { ScaffoldProperty newProperty = new ScaffoldProperty() { Column = column, PropertyName = ResolvePropertyName(newObject, column), TypeName = ResolveTypeName(typeMappings, column), }; newObject.Properties.Add(newProperty); } newFile.Objects.Add(newObject); } if (newFile.Objects.Count > 0) { files.Add(newFile); } } return(new ScaffoldProject() { Files = files, Database = databaseModel, }); }
public static async Task ScaffoldAsync(RunnerArgs info, ScaffoldCommand command) { if (command == null) { throw new RunnerException("Invalid command object."); } if (string.IsNullOrWhiteSpace(info.Connection)) { throw new RunnerException("Please specify a connection string using the -c|--connection parameter."); } DatabaseModel databaseModel; IList <TypeMapping> typeMappings; using (DbConnection connection = command.GetDbConnection()) { try { connection.ConnectionString = info.Connection; } catch (Exception ex) { throw new RunnerException("Invalid connection string: " + ex.Message, ex); } if (!string.IsNullOrEmpty(connection.Database)) { Program.WriteLine($"Connecting to database '{connection.Database}'...", ConsoleColor.Yellow); } else { Program.WriteLine("Connecting to database...", ConsoleColor.Yellow); } try { connection.Open(); } catch (Exception ex) { throw new RunnerException("Unable to open connection: " + ex.Message, ex); } Program.WriteLine("Generating...", ConsoleColor.Yellow); databaseModel = await command.GetDatabaseModelAsync(connection); typeMappings = command.GetTypeMappings().ToList(); } ScaffoldProject project = ScaffoldProject.FromModel(databaseModel, typeMappings, info); await ScaffoldWriter.WriteAsync(project); int tableCount = project.Files.SelectMany(f => f.Objects).Count(); int columnCount = project.Files.SelectMany(f => f.Objects).SelectMany(o => o.Properties).Count(); string tablesMoniker = tableCount + " " + (tableCount == 1 ? "table" : "tables"); string columnsMoniker = columnCount + " " + (columnCount == 1 ? "column" : "columns"); Console.ForegroundColor = ConsoleColor.Green; if (project.Files.Count == 1) { Program.WriteLine($"Generated {tablesMoniker} and {columnsMoniker} in {project.Files[0].FileName}.", ConsoleColor.Green); } else { Program.WriteLine($"Generated {tablesMoniker} and {columnsMoniker} in {project.Files.Count} files.", ConsoleColor.Green); } Console.ResetColor(); }
public static void Args(RunnerArgs args) { IEnumerable <string> argumentList = args.Options.Skip(1).SelectMany(opt => opt.ToArgumentList()); Console.WriteLine(string.Join(" ", argumentList.Select(ToolOptions.Escape))); }
public async static Task SqlAsync(RunnerArgs args, IConnectionFactory factory) { if (factory == null) { throw new RunnerException("Invalid factory object."); } if (string.IsNullOrWhiteSpace(args.Connection)) { throw new RunnerException("Please specify a connection string using the -c|--connection argument."); } int numberOfInputs = 0; using (DbConnection connection = await GetOpenConnectionAsync(args, factory)) { foreach (ToolOption option in args.Options) { if (IsSqlInput(option)) { string sqlText = string.Join("\r\n", option.Values); await ExecuteSqlAsync(connection, sqlText); numberOfInputs++; } else if (IsFileInput(option)) { ResponseSettings settings = new ResponseSettings() { IgnoreWhitespace = false, }; string[] expanded = ResponseFile.ExpandFiles(option.Values, settings).ToArray(); string sqlText = string.Join("\r\n", expanded); await ExecuteSqlAsync(connection, sqlText); numberOfInputs++; } else if (IsRawInput(option)) { string sqlText = string.Join("", option.Values.Select(File.ReadAllText)); await ExecuteSqlAsync(connection, sqlText); numberOfInputs++; } } } if (numberOfInputs == 0) { throw new RunnerException("Please specify at least one SQL input with the --sql, --file or --raw arguments."); } async Task ExecuteSqlAsync(DbConnection connection, string sqlText) { using (DbCommand command = connection.CreateCommand()) { command.CommandText = sqlText; if (!string.IsNullOrWhiteSpace(command.CommandText)) { if (args.Verbose) { DotNetJerryHost.WriteLine($"Executing...", ConsoleColor.Yellow); DotNetJerryHost.WriteLine(sqlText, ConsoleColor.Blue); } else { DotNetJerryHost.WriteLine($"Executing '{GetSqlPreviewText(sqlText)}'...", ConsoleColor.Yellow); } int affectedRows = await command.ExecuteNonQueryAsync(); string rowsMoniker = affectedRows + " " + (affectedRows == 1 ? "row" : "rows"); DotNetJerryHost.WriteLine($"OK. {rowsMoniker} affected.", ConsoleColor.Green); } else { DotNetJerryHost.WriteLine($"Skipped. SQL text is empty.", ConsoleColor.Yellow); } } } string GetSqlPreviewText(string sqlText) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < sqlText.Length && builder.Length <= 30; i++) { if (!char.IsWhiteSpace(sqlText[i])) { builder.Append(sqlText[i]); } else if (builder.Length > 0 && !char.IsWhiteSpace(builder[builder.Length - 1])) { builder.Append(' '); } } return(builder.ToString()); } bool IsRawInput(ToolOption option) => (option.Name == "raw" || option.ShortName == "r"); bool IsSqlInput(ToolOption option) => (option.Name == "sql" || option.ShortName == "s"); bool IsFileInput(ToolOption option) => (option.Name == "file" || option.ShortName == "f"); }
public ProgramRunner(RunnerArgs args) { this.Args = args ?? throw new ArgumentNullException(nameof(args)); }
public static void WriteHeader() { string packageVersion = RunnerArgs.GetNuGetPackageVersion(); Console.WriteLine($"Jerrycurl CLI v{packageVersion}"); }
private static string ResolveNamespace(TableModel table, string defaultSchema, RunnerArgs info) { Namespace ns; if (!string.IsNullOrEmpty(info.Namespace) && !string.IsNullOrEmpty(table.Schema) && !table.Schema.Equals(defaultSchema)) { ns = new Namespace(info.Namespace).Add(table.Schema.ToCapitalCase()); } else if (!string.IsNullOrEmpty(info.Namespace)) { ns = new Namespace(info.Namespace); } else if (!string.IsNullOrEmpty(table.Schema) && !table.Schema.Equals(defaultSchema)) { ns = new Namespace(table.Schema.ToCapitalCase()); } else { ns = new Namespace("Database"); } return(ns.Definition); }
private static string ResolveFileName(TableModel table, string defaultSchema, RunnerArgs info) { if (info.Output == null) { return("Database.cs"); } else if (info.Output.EndsWith(".cs")) { return(info.Output); } else if (!string.IsNullOrEmpty(table.Schema) && !table.Schema.Equals(defaultSchema)) { return(Path.Combine(info.Output, $"{CSharp.Identifier(table.Schema).ToCapitalCase()}", $"{CSharp.Identifier(table.Name).ToCapitalCase()}.cs")); } else { return(Path.Combine(info.Output, $"{CSharp.Identifier(table.Name).ToCapitalCase()}.cs")); } }