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

Generating R code from swagger #1

Open
maelle opened this issue Nov 15, 2017 · 4 comments
Open

Generating R code from swagger #1

maelle opened this issue Nov 15, 2017 · 4 comments

Comments

@maelle
Copy link

@maelle maelle commented Nov 15, 2017

Will this package generate code from swagger like https://github.com/hrbrmstr/swagger ?

Cc @hrbrmstr

@javierluraschi

This comment has been minimized.

Copy link
Member

@javierluraschi javierluraschi commented Feb 4, 2018

@maelle no plans for this, but if you or @hrbrmstr want to include this functionality in this package, please send a PR!

See also: https://github.com/swagger-api/swagger-codegen

@hrbrmstr

This comment has been minimized.

Copy link

@hrbrmstr hrbrmstr commented Jun 8, 2018

Turns out swagger-codegen for R is pretty darned "meh" (when it even works).

@maelle Thx to the MSGitHub kerfuffle and me trying to do a write up for R folks looking to rely on a local Gitea setup with pushed to all the major external sites, I jumpstarted this idea (a bit) again. I'm not even close to having a PR for this pkg but I used this code:

library(glue)
library(styler)
library(tidyverse)

x <- jsonlite::fromJSON("http://my-gitea-rhost:3000/swagger.v1.json")

unlink("/tmp/crumpets", recursive = TRUE) # this is for my pkg hence some hard coding
dir.create("/tmp/crumpets/R", recursive = TRUE)

base_path <- sub("^/", "", x$basePath)

walk2(x$paths, names(x$paths), ~{

  obj <- .x
  path <- .y

  walk2(obj, names(obj), ~{

    verb <- toupper(.y)
    v <- .x

    # if (verb != "POST") return() # to enable targeted re-gen

    fname <- snakecase::to_snake_case(v$operationId[1])

    message(sprintf("Creating %s", fname))

    query <- "list(access_token = gitea_token)"
    body <-  "NULL"
    prox <- "#'"
    params <- ""

    make_params <- function(params) {
      if (length(params) == 0) return("")
      params <- distinct(params, name, .keep_all = TRUE)
      res <- paste0(params$name, collapse=", ")
      if (length(res) > 0) sprintf("%s, ", res) else ""
    }

    make_params_roxygen <- function(params) {
      prox <- "#'"
      if (length(params) > 0) {
        if (nrow(params) > 0) {
          params <- distinct(params, name, .keep_all = TRUE)
          prox <- paste0(glue_data(params, "#' @param {name} {description}"), collapse="\n")
        }
      }
      prox
    }

    make_get <- function(params) {
      if (length(params) > 0) {
        if (nrow(params) > 0) {
          params <- distinct(params, name, .keep_all = TRUE)
          res <- sprintf("list(
      %s,
      access_token = gitea_token
    )", paste0(glue_data(params, "`{name}` = `{name}`"), collapse=",\n"))
          return(res)
        }
      }
      "list(access_token = gitea_token)"
    }

    switch(
      verb,
      "GET" = {
        query <- make_get(v$parameters)
        params <- make_params(v$parameters)
        prox <- make_params_roxygen(v$parameters)
      }
    )

    # TODO shld try to auto-handle /path/{param} like https://github.com/hrbrmstr/crumpets/blob/master/R/user-list-repos.R#L17-L18
    # TODO customization/generation POST / PUT / DELETE / FETCH
    #      they get created now but no params or body are added

    list(
      title = v$summary[1],
      base_path = base_path,
      prox = prox,
      params = params,
      path = path[1],
      verb = verb,
      query = query,
      fname = fname
    ) -> rec

    glue_data(
      rec,
      "#' WIP - {title}
#'
#' @md
#' @note NOT IMPLEMENTED YET
{prox}
#' @param api_endpoint URL prefix for your gitea server (no trailing '/')
#' @param gitea_token NOTE: we use `access_token` in the package
#' @return something
#' @export
#' @examples \\dontrun{{
#' }
{fname} <- function({params}api_endpoint = Sys.getenv('GITEA_BASE_URL'),
                    gitea_token = Sys.getenv('GITEA_PAT')) {{

  stop('Not implemented yet')

  api_endpoint <- sub('/$', '', api_endpoint)

  gitea_url <- file.path(api_endpoint, '{base_path}', sub('^/', '', '{path}'))

  httr::VERB(
    verb = '{verb}',
    url = gitea_url,
    body = list(),
    query = {query},
    encode = 'json',
    httr::user_agent('crumpets r package <https://gitlab.com/hrbrmstr/crumpets')
  ) -> res

  httr::stop_for_status(res)

  out <- httr::content(res, as='text')
  out <- jsonlite::fromJSON(out)

  invisible(out)

}
"
    ) -> elmered

    elmered <- styler::style_text(strsplit(elmered, "\n")[[1]]) # make nicely formatted functions

    cat(elmered, sep="\n", file = gsub("_", "-", sprintf("/tmp/crumpets/R/%s.R", fname)))

  })

})

to scaffold crumpets: https://github.com/hrbrmstr/crumpets

There was no way I was writing 146 functions from scratch and I really don't like to make users have to guess at API endpoints like the gh package does.

That scaffolding made it super easy to quickly tweak a few of the ones based on GET to actually work (well!).

Hopefully it'll come in handy until I get a change to make it PR-able.

@maelle

This comment has been minimized.

Copy link
Author

@maelle maelle commented Jun 8, 2018

👏

@gaborcsardi

This comment has been minimized.

Copy link
Member

@gaborcsardi gaborcsardi commented Feb 7, 2020

I really don't like to make users have to guess at API endpoints like the gh package does.

Well, those endpoints are documented at https://developer.github.com/v3/ and you can copy them from the documentation to the code. I am not sure what exactly you need to guess here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
4 participants
You can’t perform that action at this time.