Packages
open_api_spex
3.21.0
3.22.3
3.22.2
3.22.1
3.22.0
3.21.5
3.21.4
3.21.3
3.21.2
3.21.1
3.21.0
3.20.1
3.20.0
3.19.1
3.19.0
3.18.3
3.18.2
3.18.1
3.18.0
3.17.3
3.17.2
3.17.1
3.17.0
3.16.4
3.16.3
3.16.2
3.16.1
3.16.0
3.15.0
3.14.0
3.13.0
3.12.0
3.11.0
3.10.0
3.9.0
3.8.0
3.7.0
3.6.0
3.5.2
3.5.1
3.5.0
3.4.0
3.3.0
3.2.1
3.2.0
3.1.0
3.0.0
2.3.1
2.3.0
2.2.0
2.1.1
2.1.0
2.0.0
1.1.4
1.1.3
1.1.2
1.1.1
1.1.0
1.0.1
1.0.0
Leverage Open Api Specification 3 (swagger) to document, test, validate and explore your Plug and Phoenix APIs.
Current section
Files
Jump to
Current section
Files
lib/open_api_spex/export_spec.ex
defmodule OpenApiSpex.ExportSpec do
@moduledoc """
Export spec in specified encoding
"""
require Mix.Generator
defmodule Options do
@moduledoc false
defstruct filename: nil,
spec: nil,
pretty: false,
check: false,
vendor_extensions: true,
quiet: false
end
def call(argv, encode_spec, default_filename) do
opts = parse_options(argv, default_filename)
encoded_spec =
opts
|> generate_spec()
|> encode_spec.(opts)
if opts.check do
check_spec(encoded_spec, opts)
else
write_spec(encoded_spec, opts)
end
end
defp generate_spec(%{spec: spec, vendor_extensions: vendor_extensions}) do
case Code.ensure_compiled(spec) do
{:module, _} ->
if function_exported?(spec, :spec, 0) do
OpenApiSpex.OpenApi.to_map(spec.spec(), vendor_extensions: vendor_extensions)
else
Mix.raise(
"module #{inspect(spec)} is not a OpenApiSpex.Spec. " <>
"Please pass a spec with the --spec option."
)
end
{:error, error} ->
Mix.raise(
"could not load #{inspect(spec)}, error: #{inspect(error)}. " <>
"Please pass a spec with the --spec option."
)
end
end
defp parse_options(argv, default_filename) do
parse_options = [
strict: [
spec: :string,
endpoint: :string,
pretty: :boolean,
check: :boolean,
vendor_extensions: :boolean,
quiet: :boolean
]
]
{opts, args, _} = OptionParser.parse(argv, parse_options)
%Options{
filename: args |> List.first() || default_filename,
spec: find_spec(opts),
pretty: Keyword.get(opts, :pretty, false),
check: Keyword.get(opts, :check, false),
vendor_extensions: Keyword.get(opts, :vendor_extensions, true),
quiet: Keyword.get(opts, :quiet, false)
}
end
defp check_spec(content, opts) do
unless content == File.read!(opts.filename) do
Mix.raise("The OpenAPI spec file does not match the generated spec:\n\n#{content}")
end
end
defp write_spec(content, opts) do
case Path.dirname(opts.filename) do
"." -> true
dir -> Mix.Generator.create_directory(dir, quiet: opts.quiet)
end
Mix.Generator.create_file(opts.filename, content, force: true, quiet: opts.quiet)
end
defp find_spec(opts) do
if spec = Keyword.get(opts, :spec) do
Module.concat([spec])
else
Mix.raise("No spec available. Please pass a spec with the --spec option")
end
end
end