Giter Club home page Giter Club logo

autorust's People

Contributors

ctaggart avatar rylev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

autorust's Issues

get list of rest specifications

Get a list of specifications to generate code for from:
https://github.com/Azure/azure-rest-api-specs/tree/master/specification

I think this can be done by parsing the markdown in Rust. This library looked good to me when I looked:
https://crates.io/keywords/markdown
https://github.com/kivikakk/comrak

I think it is a matter of parsing the readme.md or readme.azureresourceschema.md files

Each spec will have a list of input files. Hopefully we can also derive a Rust package name. I manually derived this name from the Python readme.

@guywaldman expressed interest in working on this.

allOf

The generated structs need to support allOf. This can be done pretty easily with serde with flatten:

pub struct TableServiceProperties {
    #[serde(flatten)]
    pub resource: Resource,

example of allOf

../azure-rest-api-specs/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/table.json

https://github.com/Azure/azure-rest-api-specs/blob/master/specification/storage/resource-manager/Microsoft.Storage/stable/2019-06-01/table.json#L388-L408

    "TableServiceProperties": {
      "properties": {
        "properties": {
          "properties": {
            "cors": {
              "$ref": "./common.json#/definitions/CorsRules",
              "description": "Specifies CORS rules for the Table service. You can include up to five CorsRule elements in the request. If no CorsRule elements are included in the request body, all CORS rules will be deleted, and CORS will be disabled for the Table service."
            }
          },
          "x-ms-client-flatten": true,
          "x-ms-client-name": "TableServiceProperties",
          "description": "The properties of a storage account’s Table service."
        }
      },
      "allOf": [
        {
          "$ref": "../../../../../common-types/resource-management/v1/types.json#/definitions/Resource"
        }
      ],
      "description": "The properties of a storage account’s Table service."
    },

For autorest csharp, this ends up being inheritance from Resource. Resource may be treated specially.

    /// <summary>
    /// The properties of a storage account’s Table service.
    /// </summary>
    [JsonTransformation]
    public partial class TableServiceProperties : Resource
    {

In this Rust code generation, composition will work.

deviceprovisioningservices has duplicated operation_name params

error[E0415]: identifier `certificate_name` is bound more than once in this parameter list
   --> services/mgmt/deviceprovisioningservices/src/package_2020_03/operations.rs:232:9
    |
232 |         certificate_name: Option<&str>,
    |         ^^^^^^^^^^^^^^^^ used as parameter more than once

Cause by operation DpsCertificate_Delete defining these parameters:

          {
            "name": "certificateName",
            "in": "path",
            "required": true,
            "type": "string",
            "description": "This is a mandatory field, and is the logical name of the certificate that the provisioning service will access by."
          },
          {
            "name": "certificate.name",
            "in": "query",
            "required": false,
            "type": "string",
            "description": "This is optional, and it is the Common Name of the certificate."
          },

path parameters

https://swagger.io/specification/v2/

A list of parameters that are applicable for all the operations described under this path. These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the Swagger Object's parameters. There can be one "body" parameter at most.

create nested types

It appears nested types are not created.

datafactory/resource-manager/Microsoft.DataFactory/stable/2018-06-01/entityTypes/Pipeline.json

    "ExecuteDataFlowActivityTypeProperties": {
      "description": "Execute data flow activity properties.",
      "properties": {
        "dataFlow": {
          "description": "Data flow reference.",
          "$ref": "../datafactory.json#/definitions/DataFlowReference"
        },
        "staging": {
          "description": "Staging info for execute data flow activity.",
          "$ref": "../datafactory.json#/definitions/DataFlowStagingInfo"
        },
        "integrationRuntime": {
          "description": "The integration runtime reference.",
          "$ref": "../datafactory.json#/definitions/IntegrationRuntimeReference"
        },
        "compute": {
          "description": "Compute properties for data flow activity.",
          "type": "object",
          "properties": {
            "computeType": {
              "description": "Compute type of the cluster which will execute data flow job.",
              "type": "string",
              "enum": [
                "General",
                "MemoryOptimized",
                "ComputeOptimized"
              ],
              "x-ms-enum": {
                "name": "DataFlowComputeType",
                "modelAsString": true
              }
            },
            "coreCount": {
              "description": "Core count of the cluster which will execute data flow job. Supported values are: 8, 16, 32, 48, 80, 144 and 272.",
              "type": "integer"
            }
          }
        }
      },
mod execute_data_flow_activity_type_properties {
    use super::*;
    #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
    pub struct Compute {
        #[serde(rename = "computeType", skip_serializing_if = "Option::is_none")]
        pub compute_type: Option<compute::ComputeType>,
        #[serde(rename = "coreCount", skip_serializing_if = "Option::is_none")]
        pub core_count: Option<i64>,
    }
}

compute::ComputeType is not being created.

make basic cli

Need to make a basic cli before shipping this. Probably using clap builder pattern. Looking at autorest --help, the minimum for now would be:

  --input-file=<string | string[]>  OpenAPI file to use as input (use this setting repeatedly to pass multiple files at once)
  --output-folder=<string>      target folder for generated artifacts; default: "<base folder>/generated"

May be a reqwest option to indicate that it is the first implementation. May be only add in when there is a second option.

  --reqwest                  generate reqwest client code

Here is the autorest help for reference.

$ autorest --help

WARNING: AutoRest has not been tested with Node versions greater than v13.

AutoRest code generation utility [cli version: 3.0.6187; node: v14.7.0, max-memory: 8192 gb]
(C) 2018 Microsoft Corporation.
https://aka.ms/autorest
   Loading AutoRest core      '/usr/local/lib/node_modules/@autorest/core/dist' (3.0.6302)


Usage: autorest [configuration-file.md] [...options]

  See: https://aka.ms/autorest/cli for additional documentation

Overall Verbosity

  --verbose                     display verbose logging information
  --debug                       display debug logging information

Manage Installation

  --info                        display information about the installed version of autorest and its extensions
  --list-available              display available AutoRest versions
  --reset                       removes all autorest extensions and downloads the latest version of the autorest-core extension
  --preview                     enables using autorest extensions that are not yet released
  --latest                      installs the latest autorest-core extension
  --force                       force the re-installation of the autorest-core extension and frameworks
  --version=<string>            use the specified version of the autorest-core extension

Core Settings and Switches

  --help                        display help (combine with flags like --csharp to get further details about specific functionality)
  --input-file=<string | string[]>  OpenAPI file to use as input (use this setting repeatedly to pass multiple files at once)
  --output-folder=<string>      target folder for generated artifacts; default: "<base folder>/generated"
  --clear-output-folder         clear the output folder before writing generated artifacts to disk (use with extreme caution!)
  --base-folder=<string>        path to resolve relative paths (input/output files/folders) against; default: directory of configuration file, current directory otherwise
  --message-format=<"regular" | "json">  format of messages (e.g. from OpenAPI validation); default: "regular"
  --github-auth-token=<string>  OAuth token to use when pointing AutoRest at files living in a private GitHub repository

Core Functionality
   While AutoRest can be extended arbitrarily by 3rd parties (say, with a custom generator),
   we officially support and maintain the following functionality.
   More specific help is shown when combining the following switches with --help .

  --csharp                      generate C# client code
  --go                          generate Go client code
  --java                        generate Java client code
  --python                      generate Python client code
  --nodejs                      generate NodeJS client code
  --typescript                  generate TypeScript client code
  --ruby                        generate Ruby client code
  --php                         generate PHP client code
  --azureresourceschema         generate Azure resource schemas
  --model-validator             validates an OpenAPI document against linked examples (see https://github.com/Azure/azure-rest-api-specs/search?q=x-ms-examples )
  --azure-validator             validates an OpenAPI document against guidelines to improve quality (and optionally Azure guidelines)
[0.79 s] Generation Complete

types for local schemas

Structs need to be created for local schema definitions too. AutoRest for csharp just concatenates the parent schema name with the property name. In the below example, TableServiceProperties + properties becomes TableServicePropertiesProperties defined in the top level namespace for models.

Example based on the same table.json mentioned in #30, except I set x-ms-client-flatten to false to ignore the setting, so that the type is created:

    "TableServiceProperties": {
      "properties": {
        "properties": {
          "properties": {
            "cors": {
              "$ref": "./common.json#/definitions/CorsRules",
              "description": "Specifies CORS rules for the Table service. You can include up to five CorsRule elements in the request. If no CorsRule elements are included in the request body, all CORS rules will be deleted, and CORS will be disabled for the Table service."
            }
          },
          "x-ms-client-flatten": false,
          "x-ms-client-name": "TableServiceProperties",
          "description": "The properties of a storage account’s Table service."
        }
      },
      "allOf": [
        {
          "$ref": "../../../../../common-types/resource-management/v1/types.json#/definitions/Resource"
        }
      ],
      "description": "The properties of a storage account’s Table service."
    },

AutoRest generates this csharp model:

        public TableServicePropertiesProperties()
        {

mixedreality not generating AccountKeyRegenerateRequest

error[E0412]: cannot find type `AccountKeyRegenerateRequest` in this scope
    --> services/mgmt/mixedreality/src/package_2020_05/operations.rs:1214:22
     |
1214 |         regenerate: &AccountKeyRegenerateRequest,
     |                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^ not found in this scope

It it in an included file that is only references by a common parameter.

  "parameters": {
    "accountKeyRegenerateParameter": {
      "name": "regenerate",
      "in": "body",
      "required": true,
      "schema": {
        "$ref": "#/definitions/AccountKeyRegenerateRequest"
      },
      "x-ms-parameter-location": "method",
      "description": "Required information for key regeneration."
    },

other param named `configuration`

maintenance can't compile because another param is named config

    pub async fn create_or_update(
        configuration: &crate::Configuration,
        subscription_id: &str,
        resource_group_name: &str,
        resource_name: &str,
        configuration: &MaintenanceConfiguration,
    ) -> std::result::Result<MaintenanceConfiguration, create_or_update::Error> {

May beoperation_config: OperationConfig?

surf client

surf 2.0.0 was just released and looks pretty nice. The default codegen right now is targeting a reqwest client.

x-ms-client-flatten

x-ms-client-flatten is a way to put all the children properties in the parent Rust struct. serde flatten actually provides the opposite behavior. It allows you to flatten in the json, but have the Rust structs be flat. Without this working, a few extra local structs will be generated #31. Rust doesn't support null, so missing it isn't as big of a programming challenge as languages that do. This is a nice-to-have later if there is a clean way to do it with serde.

reqwest client

The current code targets reqwest, but may be switched to hyper because azure-sdk-for-rust is currently targeting hyper #28. This is an issue to have a reqwest client too. surf is #25. One option is to have a reqwest branch.

figure out the Language Server Protocol for AutoRest

I looked into this in August and got frustrated. https://github.com/ctaggart/autorust_lsp/blob/master/src/main.rs was enough to determine that a WASI will work if we can figure out the LSP.

I tried writing a debug file if --debug is passed in. I remember having trouble with crashing node, but wasmtime gave better errors. cargo wasi is backed by wasmtime. Here are some random notes:

node --experimental-wasi-unstable-preview1 --no-warnings main.js
cargo wasi run -- --debug
Error: Custom { kind: Other, error: "failed to find a pre-opened file descriptor through which \"autorust.log\" could be opened" }
wasmtime run target/wasm32-wasi/debug/autorest-rust.wasm --dir=. -- --debug
wasmtime run target/wasm32-wasi/debug/autorest-rust.wasm --mapdir /sandbox::. -- --debug

I also tried sticking a cmdproxy in-between autorest and the Go extension to inspect stuff, but it appears to lock up. It uses the process handling from tokio. I think another attempt with the recently released 1.0 of https://github.com/stjepang/async-process is worth trying.

I have more notes. If you are going to attempt this, please reach out for a video call if you want to discuss. cc @rylev @jonathandturner

Automatically box use of struct as a field in that struct

As hinted in #84, we should (when possible) automatically box types when they are used as the type of their own field.

For example, it should be possible to detect the following situation:

struct Foo {
   bar: Bar,
   foo: Foo
}

and turn it into:

struct Foo {
   bar: Bar,
   foo: Box<Foo>
}

howto run openapi-generator

This project has some different goals & requirements than openapi-generator.. The rust generator will produce an async reqwest client:

Here is how you may use it to generate code into a generated directory.

cd autorust
java -jar ../openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar \
    generate -g rust -o generated \
    -i ../OpenAPI-Specification/examples/v2.0/json/petstore-minimal.json

But first you have to clone and build it:

git clone [email protected]:OpenAPITools/openapi-generator.git
cd openapi-generator
mvn package

You will need Java 8 and Maven installed. Here is how I installed those on my Mac using brew:

brew cask install adoptopenjdk/openjdk/adoptopenjdk8
export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
brew install maven

I think Ubuntu is:

sudo apt install openjdk-8-jdk
sudo apt install maven

These files get produced:
image

apis/default_apis.rs

/*
 * Swagger Petstore
 *
 * A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
 *
 * The version of the OpenAPI document: 1.0.0
 * 
 * Generated by: https://openapi-generator.tech
 */


use reqwest;

use crate::apis::ResponseContent;
use super::{Error, configuration};


/// struct for typed errors of method `pets_get`
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PetsGetError {
    UnknownValue(serde_json::Value),
}


/// Returns all pets from the system that the user has access to
pub async fn pets_get(configuration: &configuration::Configuration, ) -> Result<Vec<crate::models::Pet>, Error<PetsGetError>> {

    let local_var_client = &configuration.client;

    let local_var_uri_str = format!("{}/pets", configuration.base_path);
    let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str());

    if let Some(ref local_var_user_agent) = configuration.user_agent {
        local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone());
    }

    let local_var_req = local_var_req_builder.build()?;
    let local_var_resp = local_var_client.execute(local_var_req).await?;

    let local_var_status = local_var_resp.status();
    let local_var_content = local_var_resp.text().await?;

    if local_var_status.is_success() {
        serde_json::from_str(&local_var_content).map_err(Error::from)
    } else {
        let local_var_entity: Option<PetsGetError> = serde_json::from_str(&local_var_content).ok();
        let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity };
        Err(Error::ResponseError(local_var_error))
    }
}

apis/configuration.rs

/*
 * Swagger Petstore
 *
 * A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification
 *
 * The version of the OpenAPI document: 1.0.0
 * 
 * Generated by: https://openapi-generator.tech
 */


use reqwest;

pub struct Configuration {
    pub base_path: String,
    pub user_agent: Option<String>,
    pub client: reqwest::Client,
    pub basic_auth: Option<BasicAuth>,
    pub oauth_access_token: Option<String>,
    pub bearer_access_token: Option<String>,
    pub api_key: Option<ApiKey>,
    // TODO: take an oauth2 token source, similar to the go one
}

pub type BasicAuth = (String, Option<String>);

pub struct ApiKey {
    pub prefix: Option<String>,
    pub key: String,
}

impl Configuration {
    pub fn new() -> Configuration {
        Configuration::default()
    }
}

impl Default for Configuration {
    fn default() -> Self {
        Configuration {
            base_path: "http://petstore.swagger.io/api".to_owned(),
            user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()),
            client: reqwest::Client::new(),
            basic_auth: None,
            oauth_access_token: None,
            bearer_access_token: None,
            api_key: None,
        }
    }
}

apis/mod.rs

use reqwest;
use serde_json;

#[derive(Debug, Clone)]
pub struct ResponseContent<T> {
    pub status: reqwest::StatusCode,
    pub content: String,
    pub entity: Option<T>,
}

#[derive(Debug)]
pub enum Error<T> {
    Reqwest(reqwest::Error),
    Serde(serde_json::Error),
    Io(std::io::Error),
    ResponseError(ResponseContent<T>),
}

impl <T> From<reqwest::Error> for Error<T> {
    fn from(e: reqwest::Error) -> Self {
        Error::Reqwest(e)
    }
}

impl <T> From<serde_json::Error> for Error<T> {
    fn from(e: serde_json::Error) -> Self {
        Error::Serde(e)
    }
}

impl <T> From<std::io::Error> for Error<T> {
    fn from(e: std::io::Error) -> Self {
        Error::Io(e)
    }
}

pub fn urlencode<T: AsRef<str>>(s: T) -> String {
    ::url::form_urlencoded::byte_serialize(s.as_ref().as_bytes()).collect()
}

pub mod default_api;

pub mod configuration;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.