# apigenie format

Source: https://apigenie.pl/docs/reference/cli/format
Part of the reference of [apigenie](https://apigenie.pl/docs/reference/cli.md).
Its other pages: [bundle](https://apigenie.pl/docs/reference/cli/bundle.md), [changelog](https://apigenie.pl/docs/reference/cli/changelog.md), [config](https://apigenie.pl/docs/reference/cli/config.md), [convert](https://apigenie.pl/docs/reference/cli/convert.md), [credits](https://apigenie.pl/docs/reference/cli/credits.md), [diff](https://apigenie.pl/docs/reference/cli/diff.md), [evolve](https://apigenie.pl/docs/reference/cli/evolve.md), [i18n](https://apigenie.pl/docs/reference/cli/i18n.md), [init](https://apigenie.pl/docs/reference/cli/init.md), [license](https://apigenie.pl/docs/reference/cli/license.md), [lint](https://apigenie.pl/docs/reference/cli/lint.md), [overlay](https://apigenie.pl/docs/reference/cli/overlay.md), [test](https://apigenie.pl/docs/reference/cli/test.md).

Formats OpenAPI, Swagger 2.0 and AsyncAPI documents, written in JSON or YAML, Protobuf files and
GraphQL documents in place, or checks that they are formatted. What it changes comes from the
configuration file: the [layout and the YAML styles](/docs/reference/cli/format/styles) of a document, the
[order of the properties](/docs/reference/cli/format/property-order) of every object its specification defines, and
what is sorted in [Protobuf](/docs/reference/cli/format/protobuf) and [GraphQL](/docs/reference/cli/format/graphql) files. A document keeps
its comments and its meaning.

## Topics

- [Layout and YAML styles](/docs/reference/cli/format/styles): The output format, indentation, line endings and folding, and the YAML styles of strings, keys, sequences and mappings, for a whole document or chosen fields, and the layout of JSON arrays and objects.
- [Property order](/docs/reference/cli/format/property-order): `original`, `sorted` or a fixed order for each kind of OpenAPI object, and how the objects are recognized in OpenAPI 3.0, 3.1 and 3.2 documents.
- [AsyncAPI documents](/docs/reference/cli/format/asyncapi): The `asyncapi` section, and the objects of AsyncAPI 3 with their recommended order.
- [Swagger 2.0 documents](/docs/reference/cli/format/swagger): The `swagger` section, and the objects of Swagger 2.0 with their recommended order.
- [Protobuf files](/docs/reference/cli/format/protobuf): The layout of `.proto` files, and the imports, options, declarations, fields and values `sort` can reorder.
- [GraphQL documents](/docs/reference/cli/format/graphql): The Prettier layout of schemas and operations, where the output differs from Prettier's, and what `sort` can reorder.

## Usage

```sh
apigenie format [OPTIONS] FILES...
apigenie format --check [OPTIONS] FILES...
apigenie format --output OUTPUT [OPTIONS] FILE
```

Without options, the files are formatted with the settings of the project's configuration file, or
the defaults, and written back in their own format:

```sh
apigenie format api/openapi.yaml api/events.yaml
```

`--check` lists the files that are not formatted instead of writing them, for a CI job, and
`--output` writes one file elsewhere, in JSON or YAML:

```sh
apigenie format --check api/*.yaml
apigenie format api/openapi.yaml --output build/openapi.json
```

## What the formatter changes

The formatter recognizes a file by the root field of its document or by its extension, and reads its
settings from the section of the configuration named after it:

| File                         | Recognized by                                   | Section    |
| ---------------------------- | ----------------------------------------------- | ---------- |
| OpenAPI 3.0, 3.1 or 3.2      | the `openapi` field of the root                 | `openapi`  |
| Swagger 2.0                  | the `swagger` field of the root, a string       | `swagger`  |
| AsyncAPI 3                   | the `asyncapi` field of the root                | `asyncapi` |
| Protobuf (proto3)            | the `.proto` extension                          | `protobuf` |
| GraphQL schema or operations | the `.graphql`, `.graphqls` or `.gql` extension | `graphql`  |

A JSON or YAML file with none of the three fields is reported
(`'FILE' is not an OpenAPI, Swagger, AsyncAPI, Protobuf or GraphQL document.`) and left untouched;
the other files are still formatted, and the command exits with 2.

In an OpenAPI, Swagger or AsyncAPI document, the formatter changes:

- the indentation, the line endings, the final line break and the width at which long YAML values
  are folded
- the YAML styles of strings, keys, sequences and mappings, for the whole document or for chosen
  fields, and the layout of JSON arrays and objects for the whole document
- the order of the properties of every object the specification defines, at every depth of the
  document, and of the names in maps such as components, properties or media types

A Protobuf file gets one statement per line, normalized spacing and blank lines between its
declarations, and its imports and options sorted; a GraphQL document gets the layout of Prettier.
The pages of [Protobuf files](/docs/reference/cli/format/protobuf) and [GraphQL documents](/docs/reference/cli/format/graphql) list what
else can be sorted.

The formatter never changes what a document means: the output holds the same values as the input,
and formatting it again gives the same output. YAML anchors and aliases are the one construct it
does not keep: each alias is written as a copy of its anchor's value, in YAML as in JSON.

A YAML or JSON document is formatted even when it is not a valid document of its specification,
and only a syntax error stops the formatter, unlike `lint` and `diff`, which read valid documents
only. A Protobuf or GraphQL file with syntax errors is reported with the position of each error and
left untouched.

## Comments

The formatter keeps comments: the YAML comments of OpenAPI, Swagger and
AsyncAPI documents (at the top and the end of the file, above keys, at the end
of lines, inside sequences, between entries and after the last entry), the
comments of Protobuf files and the `#` comments of GraphQL documents. A comment
directly above a key belongs to that key and moves with it when properties are
sorted; a comment at the top of the file that a blank line separates from the
first key stays at the top. JSON has no comments, so a YAML document written as

## Options

### --config FILE

The configuration file. Without it, the first of `apigenie.yaml`, `apigenie.yml`, `apigenie.json`,
`.apigenie.yaml`, `.apigenie.yml` and `.apigenie.json` found in the current directory or its
parents, up to the root of the git repository, is read. See [Configuration](#configuration).

```sh
apigenie format --config api-style-guide.yaml api/openapi.yaml api/events.json
```

### --no-config

Formats with the default settings, without looking for a configuration file.

### --check

Checks that the files are formatted, without writing anything. The path of every file that
formatting would change is printed on standard output, one per line, with
`N file(s) would be reformatted.` on standard error, and the command exits with 1 when there is at
least one. A file whose output format differs from its own (see [format](/docs/reference/cli/format/styles#format))
always counts as a change. Files with syntax errors and unsupported documents are reported as
without `--check`. Not with `--output`.

```sh
apigenie format --check api/*.yaml
```

### --strip-comments

Drops the comments of the files instead of keeping them: YAML comments of
OpenAPI, Swagger and AsyncAPI documents, `//` and `/* */` comments of Protobuf
files and `#` comments of GraphQL documents. GraphQL descriptions are part of
the schema and are kept. A `# prettier-ignore` comment is dropped too, so the
definition after it is formatted.

```sh
apigenie format --strip-comments api/openapi.yaml
```

### --openapi-fragment KIND

Formats the files as fragments of OpenAPI documents, such as a schema kept in
its own file and referenced with `$ref`. `KIND` is the object at the root of the
files: `schema`, `pathItem`, `operation`, `parameter`, `requestBody`,
`response`, `header`, `example`, `link`, `securityScheme` or `components`. The
objects inside the fragment are recognized as in a whole document. Protobuf and
GraphQL files are formatted as usual.

```sh
apigenie format --openapi-fragment schema schemas/*.yaml
```

### --output OUTPUT

Writes the result to `OUTPUT` instead of the input file, and takes one input file. For an OpenAPI,
Swagger or AsyncAPI document, the extension of `OUTPUT` chooses its format, `.json`, `.yaml` or
`.yml`, so the option converts between JSON and YAML; another extension is an error. A Protobuf or
GraphQL file is written in its own format, whatever the extension. Not with `--check`.

```sh
apigenie format api/openapi.yaml --output build/openapi.json
```

## Exit status

| Status | When                                                                                                                                                                                                        |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 0      | Every file was formatted or, with `--check`, is already formatted.                                                                                                                                          |
| 1      | With `--check`, at least one file would change.                                                                                                                                                             |
| 2      | A file has syntax errors or is not a supported document (the other files are still formatted or checked), the configuration file is invalid, or the options cannot be used together.                        |

See the [exit statuses](/docs/reference/cli#exit-status) shared by the commands.

## Configuration

The settings live under `commands.format` of the [configuration file](/docs/reference/cli/configuration):
`extends`, and a section per kind of file. Every section is optional, so a configuration can hold
the settings of some kinds only.

| Section    | Keys                                                                                                                                      | Page                                                                               |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `extends`  | A list of the presets `recommended` and `original`, applied in order                                                                      | [Presets](#presets)                                                                |
| `openapi`  | `format`, `indent`, `force_array_indent`, `line_width`, `newline`, `final_newline`, `document_marker`, `style`, `style_overrides`, `property_order` | [Layout and YAML styles](/docs/reference/cli/format/styles), [Property order](/docs/reference/cli/format/property-order) |
| `asyncapi` | `format`, `indent`, `force_array_indent`, `style`, `property_order`                                                                       | [AsyncAPI documents](/docs/reference/cli/format/asyncapi)                                              |
| `swagger`  | `format`, `indent`, `force_array_indent`, `style`, `property_order`                                                                       | [Swagger 2.0 documents](/docs/reference/cli/format/swagger)                                            |
| `protobuf` | `indent`, `sort`                                                                                                                          | [Protobuf files](/docs/reference/cli/format/protobuf)                                                  |
| `graphql`  | `indent`, `line_width`, `sort`                                                                                                            | [GraphQL documents](/docs/reference/cli/format/graphql)                                                |

**Example** - Recommended settings, with CRLF line endings and the descriptions of OpenAPI
documents written as literal blocks

```yaml
commands:
  format:
    extends:
      - recommended
    openapi:
      newline: crlf
      style_overrides:
        - fields: [description]
          string: literal
```

### Presets

A configuration starts from the defaults: the presets named by `extends` are applied first, in
order, to every kind of file, then the keys of the sections replace what the presets set.

- `recommended` indents OpenAPI, Swagger and AsyncAPI documents by 2 spaces, writes their values in
  the `best-fit` styles and puts the properties of their objects in the fixed orders listed on the
  pages of the [OpenAPI](/docs/reference/cli/format/property-order#objects), [AsyncAPI](/docs/reference/cli/format/asyncapi#objects) and
  [Swagger 2.0](/docs/reference/cli/format/swagger#objects) objects, with path templates and response codes sorted. In
  Protobuf files it sorts imports and options; in GraphQL documents it sorts nothing.
- `original` indents by 2 spaces and keeps the styles and the property order of the input. In
  Protobuf files and GraphQL documents it sorts nothing.

Without a configuration file, an OpenAPI, Swagger or AsyncAPI document is formatted as with
`original`: it keeps its format, its styles and its property order, indented by 2 spaces. A Protobuf
or GraphQL file is formatted with the `recommended` settings.

Unknown keys, unknown object names and values outside their range are errors, reported as
`FILE:LINE:COLUMN: POINTER: MESSAGE`, for example
`apigenie.yaml:5:15: /commands/format/openapi/indent: number is greater than maximum`; nothing is
formatted then, and the command exits with 2.

## See also

- [Configuration](/docs/reference/cli/configuration): The configuration file, and where it is looked for.
- [lint](/docs/reference/cli/lint): Checks the content of the documents the formatter lays out.
- [GitHub Action](/docs/ci/github-action): Runs `apigenie format --check` in a workflow.
