Skip to content

Commit

Permalink
Run the generator code through mix format (#829)
Browse files Browse the repository at this point in the history
  • Loading branch information
chingor13 committed Dec 8, 2018
1 parent ecee861 commit 850875a
Show file tree
Hide file tree
Showing 26 changed files with 130 additions and 72 deletions.
4 changes: 4 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
5 changes: 2 additions & 3 deletions lib/google_apis.ex
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ defmodule GoogleApis do

with {:ok, {body, _format}} <- GoogleApis.Discovery.fetch(api_config.url),
:ok <- File.mkdir_p(Path.dirname(file)),
:ok <- File.write(file, body)
do
:ok <- File.write(file, body) do
{:ok, file}
else
error -> IO.inspect(error)
Expand Down Expand Up @@ -56,7 +55,7 @@ defmodule GoogleApis do
name = GoogleApis.ApiConfig.library_name(api_config)

["clients/#{name}/lib/**/*.{ex,exs}"]
|> Mix.Tasks.Format.run
|> Mix.Tasks.Format.run()
end

def publish(api_config) do
Expand Down
1 change: 0 additions & 1 deletion lib/google_apis/api_config.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

defmodule GoogleApis.ApiConfig do

defstruct name: nil, version: nil, url: nil, publish: true

def file(%{name: name, version: version}), do: "#{name}-#{version}.json"
Expand Down
2 changes: 1 addition & 1 deletion lib/google_apis/converter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@
# limitations under the License.

defmodule GoogleApis.Converter do
@callback convert(GoogleApis.ApiConfig.t) :: any()
@callback convert(GoogleApis.ApiConfig.t()) :: any()
end
17 changes: 13 additions & 4 deletions lib/google_apis/converter/api_spec_converter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

defmodule GoogleApis.Converter.ApiSpecConverter do

@behaviour GoogleApis.Converter
alias GoogleApis.ApiConfig
require Logger
Expand All @@ -23,9 +22,19 @@ defmodule GoogleApis.Converter.ApiSpecConverter do
output = ApiConfig.openapi_spec_file(api_config)
Logger.info("Converting #{file} to #{output}")

with {swagger, 0} <- System.cmd("npm", ["run", "-s", "api-spec-converter", "--", file, "-f", "google", "-t", "swagger_2"]),
:ok <- File.write(output, swagger)
do
with {swagger, 0} <-
System.cmd("npm", [
"run",
"-s",
"api-spec-converter",
"--",
file,
"-f",
"google",
"-t",
"swagger_2"
]),
:ok <- File.write(output, swagger) do
{:ok, output}
else
{"", exit_code} -> {:error, "convert failed. exit code #{exit_code}"}
Expand Down
14 changes: 12 additions & 2 deletions lib/google_apis/directory_item.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,18 @@
# limitations under the License.

defmodule GoogleApis.DirectoryItem do

defstruct [:id, :struct, :name, :version, :title, :description, :discoveryRestUrl, :icons, :documentationLink, :preferred]
defstruct [
:id,
:struct,
:name,
:version,
:title,
:description,
:discoveryRestUrl,
:icons,
:documentationLink,
:preferred
]

def preferred?(%{"preferred" => true}), do: true
def preferred?(_), do: false
Expand Down
17 changes: 11 additions & 6 deletions lib/google_apis/discovery.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,16 @@ defmodule GoogleApis.Discovery do
require Logger

def fetch(""), do: {:error, "No URL"}

def fetch(url) do
case Regex.run(~r/(https:\/\/.*\.googleapis.com\/\$discovery\/)([^?]*)(\?.*)?/, url) do
[_, base, format, query] ->
try_formats(base, query, ["GOOGLE_REST_SIMPLE_URI", format])

nil ->
case fetch_direct(url) do
{:ok, body} -> {:ok, {body, "default"}}
error -> error
error -> error
end
end
end
Expand All @@ -36,7 +38,7 @@ defmodule GoogleApis.Discovery do
Download the list of preferred APIs from the Discovery service
"""
def discover() do
conn = Connection.new
conn = Connection.new()
{:ok, %{items: items}} = Apis.discovery_apis_list(conn, preferred: true)

Enum.map(items, fn item ->
Expand All @@ -49,24 +51,27 @@ defmodule GoogleApis.Discovery do
end

defp try_formats(_base, _query, []), do: {:error, "All formats failed"}

defp try_formats(base, query, [format | rest]) do
case fetch_direct(base <> format <> query) do
{:ok, body} ->
{:ok, {body, format}}

_ ->
try_formats(base, query, rest)
end
end

defp fetch_direct(url) do
Logger.info "FETCHING: #{url}"
with {:ok, %Tesla.Env{status: 200, body: body}} <- Tesla.get(url)
do
Logger.info "FOUND: #{url}"
Logger.info("FETCHING: #{url}")

with {:ok, %Tesla.Env{status: 200, body: body}} <- Tesla.get(url) do
Logger.info("FOUND: #{url}")
{:ok, body}
else
{:ok, %Tesla.Env{status: status}} ->
{:error, "Error received status: #{status} from discovery endpoint"}

err ->
err
end
Expand Down
9 changes: 6 additions & 3 deletions lib/google_apis/generator.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
# limitations under the License.

defmodule GoogleApis.Generator do
@callback generate_client(GoogleApis.ApiConfig.t) :: any()
@callback generate_client(GoogleApis.ApiConfig.t()) :: any()
alias GoogleApis.ApiConfig

def bump_version(api_config) do
mixfile = Path.join(ApiConfig.library_directory(api_config), "mix.exs")

new_contents =
mixfile
|> File.stream!
|> File.stream!()
|> Stream.map(&replace_version/1)
|> Stream.into([])
|> Enum.join("")
Expand All @@ -30,8 +30,11 @@ defmodule GoogleApis.Generator do
end

defp replace_version(line) do
Regex.replace(~r/@version "(\d+\.\d+\.\d+)"/, line, fn _, version_str -> bump_version_string(version_str) end)
Regex.replace(~r/@version "(\d+\.\d+\.\d+)"/, line, fn _, version_str ->
bump_version_string(version_str)
end)
end

defp bump_version_string(str) do
v =
str
Expand Down
4 changes: 3 additions & 1 deletion lib/google_apis/generator/swagger_cli.ex
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ defmodule GoogleApis.Generator.SwaggerCli do
client_library_name
}",
{:ok, _} <- run_docker_command(generate_command),
{:ok, _} <- run_docker_command("cp #{container}:/data/#{client_library_name} #{tmp_dir}"),
{:ok, _} <-
run_docker_command("cp #{container}:/data/#{client_library_name} #{tmp_dir}"),
{:ok, _} <- run_docker_command("rm #{container}") do
{:ok, tmp_dir}
else
Expand All @@ -64,6 +65,7 @@ defmodule GoogleApis.Generator.SwaggerCli do
defp temp_path(client_library_name, nil) do
Temp.path!("codegen-out-#{client_library_name}")
end

defp temp_path(client_library_name, basedir) do
Temp.path!(prefix: "codegen-out-#{client_library_name}", basedir: basedir)
end
Expand Down
6 changes: 3 additions & 3 deletions lib/google_apis/oauth_strategy.ex
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,15 @@ defmodule GoogleApis.OauthStrategy do

# Public API
def client(client_id, client_secret) do
OAuth2.Client.new([
OAuth2.Client.new(
strategy: __MODULE__,
client_id: client_id,
client_secret: client_secret,
site: "https://accounts.google.com",
authorize_url: "/o/oauth2/auth",
token_url: "/o/oauth2/token",
redirect_uri: "http://localhost/auth/callback"
])
)
end

def authorize_url!(client, params \\ []) do
Expand All @@ -48,4 +48,4 @@ defmodule GoogleApis.OauthStrategy do
|> put_header("accept", "application/json")
|> OAuth2.Strategy.AuthCode.get_token(params, headers)
end
end
end
29 changes: 17 additions & 12 deletions lib/google_apis/publisher.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,19 @@ defmodule GoogleApis.Publisher do

def publish(api_config) do
api_name = ApiConfig.library_name(api_config)
directory = Path.join([
System.cwd(),
"clients",
api_name
])

directory =
Path.join([
System.cwd(),
"clients",
api_name
])

if api_config.publish && should_publish?(directory) do
Logger.info "publishing #{api_name}"
Logger.info("publishing #{api_name}")
do_publish(directory)
else
Logger.info "skipping #{api_name}"
Logger.info("skipping #{api_name}")
{:ok, "skipped"}
end
end
Expand All @@ -41,14 +43,14 @@ defmodule GoogleApis.Publisher do
app = Keyword.fetch!(project_info, :app)
version = Keyword.fetch!(project_info, :version)

Logger.info "Checking app: #{app} version: #{version}"
Logger.info("Checking app: #{app} version: #{version}")
!version_exists?(app, version)
end

def version_exists?(app, version) do
case Tesla.get("https://hex.pm/packages/#{app}/#{version}") do
{:ok, %{status: 200}} -> true
_ -> false
_ -> false
end
end

Expand All @@ -59,14 +61,17 @@ defmodule GoogleApis.Publisher do
"hex.publish",
"--yes"
]

env = [{"HEX_API_KEY", Application.get_env(:google_apis, :hex_api_key)}]

case System.cmd("mix", args, cd: directory, env: env, stderr_to_stdout: true) do
{output, 0} ->
Logger.info output
Logger.info(output)
{:ok, output}

{output, exit_code} ->
Logger.error "Failed with exit code #{exit_code}"
Logger.error output
Logger.error("Failed with exit code #{exit_code}")
Logger.error(output)
{:error, output}
end
end
Expand Down
1 change: 0 additions & 1 deletion lib/google_apis/swagger_config.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# limitations under the License.

defmodule GoogleApis.SwaggerConfig do

defstruct [:licenseHeader, :invokerPackage, :packageName]

@license_header """
Expand Down
1 change: 1 addition & 0 deletions lib/mix/google_apis.bump_version.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ defmodule Mix.Tasks.GoogleApis.BumpVersion do
|> GoogleApis.ApiConfig.load()
|> bump()
end

def run(_) do
bump(GoogleApis.ApiConfig.load_all())
end
Expand Down
31 changes: 17 additions & 14 deletions lib/mix/tasks/google_apis.auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ defmodule Mix.Tasks.GoogleApis.Auth do
@shortdoc "Fetch an OAuth token for a user"

def run([]) do
Mix.Shell.IO.error "Please add a comma-separated list of scopes to authenticate for."
Mix.Shell.IO.error("Please add a comma-separated list of scopes to authenticate for.")
end

def run(scopes) when is_list(scopes) do
Application.ensure_all_started(:google_apis)

Expand All @@ -32,32 +33,34 @@ defmodule Mix.Tasks.GoogleApis.Auth do

defp build_client(nil, _), do: {:error, "Please set the Google OAuth client id"}
defp build_client(_, nil), do: {:error, "Please set the Google OAuth client secret"}

defp build_client(client_id, client_secret) do
{:ok,
OauthStrategy.client(client_id, client_secret)
}
{:ok, OauthStrategy.client(client_id, client_secret)}
end

defp get_verification_code(authorize_url) do
Mix.Shell.IO.info "Open the following link in your brower:"
Mix.Shell.IO.info authorize_url
Mix.Shell.IO.prompt "Enter verification code:"
|> String.trim
Mix.Shell.IO.info("Open the following link in your brower:")
Mix.Shell.IO.info(authorize_url)

Mix.Shell.IO.prompt(
"Enter verification code:"
|> String.trim()
)
end

defp authenticate(client_id, client_secret, scopes) do
with {:ok, client} <- build_client(client_id, client_secret),
authorize_url <- OauthStrategy.authorize_url!(client, scope: scopes),
code <- get_verification_code(authorize_url),
{:ok, oauth} <- OAuth2.Client.get_token(client, code: code)
do
Mix.Shell.IO.info "Access Token: #{oauth.token.access_token}"
Mix.Shell.IO.info "Refresh Token: #{oauth.token.refresh_token}"
{:ok, oauth} <- OAuth2.Client.get_token(client, code: code) do
Mix.Shell.IO.info("Access Token: #{oauth.token.access_token}")
Mix.Shell.IO.info("Refresh Token: #{oauth.token.refresh_token}")
else
{:error, %{body: %{"error" => error, "error_description" => description}}} ->
Mix.Shell.IO.error "#{error} - #{description}"
Mix.Shell.IO.error("#{error} - #{description}")

{:error, msg} ->
Mix.Shell.IO.error msg
Mix.Shell.IO.error(msg)
end
end
end
1 change: 1 addition & 0 deletions lib/mix/tasks/google_apis.build.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ defmodule Mix.Tasks.GoogleApis.Build do
|> GoogleApis.ApiConfig.load()
|> builder()
end

def run(_) do
builder(GoogleApis.ApiConfig.load_all())
end
Expand Down
1 change: 1 addition & 0 deletions lib/mix/tasks/google_apis.convert.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ defmodule Mix.Tasks.GoogleApis.Convert do
|> GoogleApis.ApiConfig.load()
|> Enum.each(&GoogleApis.convert_spec/1)
end

def run(_) do
Enum.each(GoogleApis.ApiConfig.load_all(), &GoogleApis.convert_spec/1)
end
Expand Down
1 change: 1 addition & 0 deletions lib/mix/tasks/google_apis.discover.ex
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ defmodule Mix.Tasks.GoogleApis.Discover do
GoogleApis.Discovery.discover()
|> write_file(output)
end

def run(_) do
run(["apis-candidate.json"])
end
Expand Down
1 change: 1 addition & 0 deletions lib/mix/tasks/google_apis.fetch.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ defmodule Mix.Tasks.GoogleApis.Fetch do
|> GoogleApis.ApiConfig.load()
|> Enum.each(&GoogleApis.fetch/1)
end

def run(_) do
Enum.each(GoogleApis.ApiConfig.load_all(), &GoogleApis.fetch/1)
end
Expand Down
Loading

0 comments on commit 850875a

Please sign in to comment.