diff options
| author | mo khan <mo@mokhan.ca> | 2025-05-11 21:12:57 -0600 |
|---|---|---|
| committer | mo khan <mo@mokhan.ca> | 2025-05-11 21:12:57 -0600 |
| commit | 60440f90dca28e99a31dd328c5f6d5dc0f9b6a2e (patch) | |
| tree | 2f54adf55086516f162f0a55a5347e6b25f7f176 /vendor/github.com/google/yamlfmt | |
| parent | 05ca9b8d3a9c7203a3a3b590beaa400900bd9007 (diff) | |
chore: vendor go dependencies
Diffstat (limited to 'vendor/github.com/google/yamlfmt')
37 files changed, 3068 insertions, 0 deletions
diff --git a/vendor/github.com/google/yamlfmt/.gitignore b/vendor/github.com/google/yamlfmt/.gitignore new file mode 100644 index 0000000..6c713e5 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/.gitignore @@ -0,0 +1,14 @@ +# Sometimes use these for testing +.yamlfmt +!integrationtest/**/.yamlfmt +tmp + +# Goreleaser build folder +dist/ + +# build file with `make build` +yamlfmt +yamlfmt.exe + +# vscode settings +.vscode diff --git a/vendor/github.com/google/yamlfmt/.goreleaser.yaml b/vendor/github.com/google/yamlfmt/.goreleaser.yaml new file mode 100644 index 0000000..d6b2757 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/.goreleaser.yaml @@ -0,0 +1,63 @@ +# Copyright 2022 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +version: 2 + +before: + hooks: + - go mod tidy +builds: + - id: yamlfmt + main: ./cmd/yamlfmt + binary: yamlfmt + env: + - CGO_ENABLED=0 + goos: + - linux + - windows + - darwin + ldflags: + - '-s -w -X main.version={{.Version}} -X main.commit={{.ShortCommit}}' +archives: + - name_template: >- + {{ .ProjectName }}_ + {{- .Version }}_ + {{- title .Os }}_ + {{- if eq .Arch "amd64" }}x86_64 + {{- else if eq .Arch "386" }}i386 + {{- else }}{{- .Arch }}{{- end }} + {{- if .Arm }}v{{- .Arm }}{{- end }} +checksum: + name_template: 'checksums.txt' +snapshot: + version_template: "{{ incpatch .Version }}-next" +changelog: + sort: asc + filters: + exclude: + - '^docs:' + - '^test:' + - '^ci:' +signs: + - cmd: cosign + signature: "${artifact}.sig" + certificate: "${artifact}.pem" + args: + - "sign-blob" + - "--oidc-issuer=https://token.actions.githubusercontent.com" + - "--output-certificate=${certificate}" + - "--output-signature=${signature}" + - "${artifact}" + - "--yes" + artifacts: checksum diff --git a/vendor/github.com/google/yamlfmt/.pre-commit-hooks.yaml b/vendor/github.com/google/yamlfmt/.pre-commit-hooks.yaml new file mode 100644 index 0000000..e888624 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/.pre-commit-hooks.yaml @@ -0,0 +1,20 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +- id: yamlfmt + name: yamlfmt + description: This hook uses github.com/google/yamlfmt to format yaml files. Requires Go >1.18 to be installed. + entry: yamlfmt + language: golang + types: [yaml] diff --git a/vendor/github.com/google/yamlfmt/CONTRIBUTING.md b/vendor/github.com/google/yamlfmt/CONTRIBUTING.md new file mode 100644 index 0000000..9d7656b --- /dev/null +++ b/vendor/github.com/google/yamlfmt/CONTRIBUTING.md @@ -0,0 +1,29 @@ +# How to Contribute + +We'd love to accept your patches and contributions to this project. There are +just a few small guidelines you need to follow. + +## Contributor License Agreement + +Contributions to this project must be accompanied by a Contributor License +Agreement (CLA). You (or your employer) retain the copyright to your +contribution; this simply gives us permission to use and redistribute your +contributions as part of the project. Head over to +<https://cla.developers.google.com/> to see your current agreements on file or +to sign a new one. + +You generally only need to submit a CLA once, so if you've already submitted one +(even if it was for a different project), you probably don't need to do it +again. + +## Code Reviews + +All submissions, including submissions by project members, require review. We +use GitHub pull requests for this purpose. Consult +[GitHub Help](https://help.github.com/articles/about-pull-requests/) for more +information on using pull requests. + +## Community Guidelines + +This project follows +[Google's Open Source Community Guidelines](https://opensource.google/conduct/).
\ No newline at end of file diff --git a/vendor/github.com/google/yamlfmt/Dockerfile b/vendor/github.com/google/yamlfmt/Dockerfile new file mode 100644 index 0000000..a5dbd81 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/Dockerfile @@ -0,0 +1,25 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FROM golang:alpine AS build +RUN apk add --no-cache git make +WORKDIR /build +COPY . . +ENV CGO_ENABLED=0 +RUN make build + +FROM alpine:latest +COPY --from=build /build/dist/yamlfmt /bin/yamlfmt +WORKDIR /project +ENTRYPOINT ["/bin/yamlfmt"] diff --git a/vendor/github.com/google/yamlfmt/LICENSE b/vendor/github.com/google/yamlfmt/LICENSE new file mode 100644 index 0000000..7a4a3ea --- /dev/null +++ b/vendor/github.com/google/yamlfmt/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
\ No newline at end of file diff --git a/vendor/github.com/google/yamlfmt/Makefile b/vendor/github.com/google/yamlfmt/Makefile new file mode 100644 index 0000000..2790ae3 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/Makefile @@ -0,0 +1,62 @@ +.EXPORT_ALL_VARIABLES: + +VERSION := $(shell git describe --abbrev=0 --tags | tr -d v) +COMMIT := $(shell git rev-parse --short HEAD) +LDFLAGS := -X 'main.version=$(VERSION)' \ + -X 'main.commit=$(COMMIT)' + +.PHONY: build +build: + go build -ldflags "$(LDFLAGS)" -o dist/yamlfmt ./cmd/yamlfmt + +.PHONY: test +test: + go test ./... + +.PHONY: test_v +test_v: + go test -v ./... + +YAMLFMT_BIN ?= $(shell pwd)/dist/yamlfmt +.PHONY: integrationtest +integrationtest: + $(MAKE) build + go test -v -tags=integration_test ./integrationtest/command + +.PHONY: integrationtest_v +integrationtest_v: + $(MAKE) build + go test -v -tags=integration_test ./integrationtest/command + +.PHONY: integrationtest_stdout +integrationtest_stdout: + $(MAKE) build + go test -v -tags=integration_test ./integrationtest/command -stdout + +.PHONY: integrationtest_update +integrationtest_update: + $(MAKE) build + go test -tags=integration_test ./integrationtest/command -update + +.PHONY: command_test_case +command_test_case: +ifndef TESTNAME + $(error "TESTNAME undefined") +endif + ./integrationtest/command/new_test_case.sh "$(TESTNAME)" + +.PHONY: install +install: + go install -ldflags "$(LDFLAGS)" ./cmd/yamlfmt + +.PHONY: install_tools +install_tools: + go install github.com/google/addlicense@latest + +.PHONY: addlicense +addlicense: + addlicense -ignore "**/testdata/**" -c "Google LLC" -l apache . + +.PHONY: addlicense_check +addlicense_check: + addlicense -check -ignore "**/testdata/**" -c "Google LLC" -l apache . diff --git a/vendor/github.com/google/yamlfmt/README.md b/vendor/github.com/google/yamlfmt/README.md new file mode 100644 index 0000000..6052124 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/README.md @@ -0,0 +1,112 @@ +# yamlfmt + +`yamlfmt` is an extensible command line tool or library to format yaml files. + +## Goals + +* Create a command line yaml formatting tool that is easy to distribute (single binary) +* Make it simple to extend with new custom formatters +* Enable alternative use as a library, providing a foundation for users to create a tool that meets specific needs + +## Maintainers + +This tool is not yet officially supported by Google. It is currently maintained solely by @braydonk, and unless something changes primarily in spare time. + +## Blog + +I'm going to use these links to GitHub Discussions as a blog of sorts, until I can set up something more proper: +* yamlfmt's recent slow development [#149](https://github.com/google/yamlfmt/discussions/149) +* Issues related to the yaml.v3 library [#148](https://github.com/google/yamlfmt/discussions/148) + +## Installation + +To download the `yamlfmt` command, you can download the desired binary from releases or install the module directly: +``` +go install github.com/google/yamlfmt/cmd/yamlfmt@latest +``` +This currently requires Go version 1.21 or greater. + +NOTE: Recommended setup if this is your first time installing Go would be in [this DigitalOcean blog post](https://www.digitalocean.com/community/tutorials/how-to-build-and-install-go-programs). + +You can also download the binary you want from releases. The binary is self-sufficient with no dependencies, and can simply be put somewhere on your PATH and run with the command `yamlfmt`. Read more about verifying the authenticity of released artifacts [here](#verifying-release-artifacts). + +You can also install the command as a [pre-commit](https://pre-commit.com/) hook. See the [pre-commit hook](./docs/pre-commit.md) docs for instructions. + +## Basic Usage + +See [Command Usage](./docs/command-usage.md) for in-depth information and available flags. + +To run the tool with all default settings, run the command with a path argument: +```bash +yamlfmt x.yaml y.yaml <...> +``` +You can specify as many paths as you want. You can also specify a directory which will be searched recursively for any files with the extension `.yaml` or `.yml`. +```bash +yamlfmt . +``` + +You can also use an alternate mode that will search paths with doublestar globs by supplying the `-dstar` flag. +```bash +yamlfmt -dstar **/*.{yaml,yml} +``` +See the [doublestar](https://github.com/bmatcuk/doublestar) package for more information on this format. + +Yamlfmt can also be used in ci/cd pipelines which supports running containers. The following snippet shows an example job for GitLab CI: +```yaml +yaml lint: + image: ghcr.io/google/yamlfmt:latest + before_script: + - apk add git + script: + - yamlfmt . + - git diff --exit-code +``` +The Docker image can also be used to run yamlfmt without installing it on your system. Just mount the directory you want to format as a volume (`/project` is used by default): +```bash +docker run -v "$(pwd):/project" ghcr.io/google/yamlfmt:latest <yamlfmt args> +``` + +# Configuration File + +The `yamlfmt` command can be configured through a yaml file called `.yamlfmt`. This file can live in your working directory, a path specified through a [CLI flag](./docs/command-usage.md#operation-flags), or in the standard global config path on your system (see docs for specifics). +For in-depth configuration documentation see [Config](docs/config-file.md). + +## Verifying release artifacts + +NOTE: Support for verifying with cosign is present from v0.14.0 onward. + +In case you get the `yamlfmt` binary directly from a release, you may want to verify its authenticity. Checksums are applied to all released artifacts, and the resulting checksum file is signed using [cosign](https://docs.sigstore.dev/cosign/installation/). + +Steps to verify (replace `A.B.C` in the commands listed below with the version you want): + +1. Download the following files from the release: + + ```text + curl -sfLO https://github.com/google/yamlfmt/releases/download/vA.B.C/checksums.txt + curl -sfLO https://github.com/google/yamlfmt/releases/download/vA.B.C/checksums.txt.pem + curl -sfLO https://github.com/google/yamlfmt/releases/download/vA.B.C/checksums.txt.sig + ``` + +2. Verify the signature: + + ```shell + cosign verify-blob checksums.txt \ + --certificate checksums.txt.pem \ + --signature checksums.txt.sig \ + --certificate-identity-regexp 'https://github\.com/google/yamlfmt/\.github/workflows/.+' \ + --certificate-oidc-issuer "https://token.actions.githubusercontent.com" + ``` + +3. Download the compressed archive you want, and validate its checksum: + + ```shell + curl -sfLO https://github.com/google/yamlfmt/releases/download/vA.B.C/yamlfmt_A.B.C_Linux_x86_64.tar.gz + sha256sum --ignore-missing -c checksums.txt + ``` + +3. If checksum validation goes through, uncompress the archive: + + ```shell + tar -xzf yamlfmt_A.B.C_Linux_x86_64.tar.gz + ./yamlfmt + ``` diff --git a/vendor/github.com/google/yamlfmt/command/command.go b/vendor/github.com/google/yamlfmt/command/command.go new file mode 100644 index 0000000..3224f46 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/command/command.go @@ -0,0 +1,258 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package command + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + + "github.com/google/yamlfmt" + "github.com/google/yamlfmt/engine" + "github.com/mitchellh/mapstructure" + + "github.com/braydonk/yaml" +) + +type FormatterConfig struct { + Type string `mapstructure:"type"` + FormatterSettings map[string]any `mapstructure:",remain"` +} + +// NewFormatterConfig returns an empty formatter config with all fields initialized. +func NewFormatterConfig() *FormatterConfig { + return &FormatterConfig{FormatterSettings: make(map[string]any)} +} + +type Config struct { + Extensions []string `mapstructure:"extensions"` + MatchType yamlfmt.MatchType `mapstructure:"match_type"` + Include []string `mapstructure:"include"` + Exclude []string `mapstructure:"exclude"` + RegexExclude []string `mapstructure:"regex_exclude"` + FormatterConfig *FormatterConfig `mapstructure:"formatter,omitempty"` + Doublestar bool `mapstructure:"doublestar"` + ContinueOnError bool `mapstructure:"continue_on_error"` + LineEnding yamlfmt.LineBreakStyle `mapstructure:"line_ending"` + GitignoreExcludes bool `mapstructure:"gitignore_excludes"` + GitignorePath string `mapstructure:"gitignore_path"` + OutputFormat engine.EngineOutputFormat `mapstructure:"output_format"` +} + +type Command struct { + Operation yamlfmt.Operation + Registry *yamlfmt.Registry + Config *Config + Quiet bool +} + +func (c *Command) Run() error { + formatter, err := c.getFormatter() + if err != nil { + return err + } + + lineSepChar, err := c.Config.LineEnding.Separator() + if err != nil { + return err + } + + eng := &engine.ConsecutiveEngine{ + LineSepCharacter: lineSepChar, + Formatter: formatter, + Quiet: c.Quiet, + ContinueOnError: c.Config.ContinueOnError, + OutputFormat: c.Config.OutputFormat, + } + + collectedPaths, err := c.collectPaths() + if err != nil { + return err + } + if c.Config.GitignoreExcludes { + newPaths, err := yamlfmt.ExcludeWithGitignore(c.Config.GitignorePath, collectedPaths) + if err != nil { + return err + } + collectedPaths = newPaths + } + + paths, err := c.analyzePaths(collectedPaths) + if err != nil { + fmt.Printf("path analysis found the following errors:\n%v", err) + fmt.Println("Continuing...") + } + + switch c.Operation { + case yamlfmt.OperationFormat: + out, err := eng.Format(paths) + if out != nil { + fmt.Print(out) + } + if err != nil { + return err + } + case yamlfmt.OperationLint: + out, err := eng.Lint(paths) + if err != nil { + return err + } + if out != nil { + // This will be picked up by log.Fatal in main() and + // cause an exit code of 1, which is a critical + // component of the lint functionality. + return errors.New(out.String()) + } + case yamlfmt.OperationDry: + out, err := eng.DryRun(paths) + if err != nil { + return err + } + if out != nil { + fmt.Print(out) + } else if !c.Quiet { + fmt.Println("No files will be changed.") + } + case yamlfmt.OperationStdin: + stdinYaml, err := readFromStdin() + if err != nil { + return err + } + out, err := eng.FormatContent(stdinYaml) + if err != nil { + return err + } + fmt.Print(string(out)) + case yamlfmt.OperationPrintConfig: + commandConfig := map[string]any{} + err = mapstructure.Decode(c.Config, &commandConfig) + if err != nil { + return err + } + delete(commandConfig, "formatter") + out, err := yaml.Marshal(commandConfig) + if err != nil { + return err + } + fmt.Print(string(out)) + + formatterConfigMap, err := formatter.ConfigMap() + if err != nil { + return err + } + out, err = yaml.Marshal(map[string]any{ + "formatter": formatterConfigMap, + }) + if err != nil { + return err + } + fmt.Print(string(out)) + } + + return nil +} + +func (c *Command) getFormatter() (yamlfmt.Formatter, error) { + var factoryType string + + // In the existing codepaths, this value is always set. But + // it's a habit of mine to check anything that can possibly be nil + // if I remember that to be the case. :) + if c.Config.FormatterConfig != nil { + factoryType = c.Config.FormatterConfig.Type + + // The line ending set within the formatter settings takes precedence over setting + // it from the top level config. If it's not set in formatter settings, then + // we use the value from the top level. + if _, ok := c.Config.FormatterConfig.FormatterSettings["line_ending"]; !ok { + c.Config.FormatterConfig.FormatterSettings["line_ending"] = c.Config.LineEnding + } + } + + factory, err := c.Registry.GetFactory(factoryType) + if err != nil { + return nil, err + } + return factory.NewFormatter(c.Config.FormatterConfig.FormatterSettings) +} + +func (c *Command) collectPaths() ([]string, error) { + collector, err := c.makePathCollector() + if err != nil { + return nil, err + } + + return collector.CollectPaths() +} + +func (c *Command) analyzePaths(paths []string) ([]string, error) { + analyzer, err := c.makeAnalyzer() + if err != nil { + return nil, err + } + includePaths, _, err := analyzer.ExcludePathsByContent(paths) + return includePaths, err +} + +func (c *Command) makePathCollector() (yamlfmt.PathCollector, error) { + switch c.Config.MatchType { + case yamlfmt.MatchTypeDoublestar: + return &yamlfmt.DoublestarCollector{ + Include: c.Config.Include, + Exclude: c.Config.Exclude, + }, nil + case yamlfmt.MatchTypeGitignore: + files := c.Config.Include + if len(files) == 0 { + files = []string{yamlfmt.DefaultPatternFile} + } + + patternFile, err := yamlfmt.NewPatternFileCollector(files...) + if err != nil { + return nil, fmt.Errorf("NewPatternFile(%q): %w", files, err) + } + + return patternFile, nil + default: + return &yamlfmt.FilepathCollector{ + Include: c.Config.Include, + Exclude: c.Config.Exclude, + Extensions: c.Config.Extensions, + }, nil + } +} + +func (c *Command) makeAnalyzer() (yamlfmt.ContentAnalyzer, error) { + return yamlfmt.NewBasicContentAnalyzer(c.Config.RegexExclude) +} + +func readFromStdin() ([]byte, error) { + stdin := bufio.NewReader(os.Stdin) + data := []byte{} + for { + b, err := stdin.ReadByte() + if err != nil { + if err == io.EOF { + break + } else { + return nil, err + } + } + data = append(data, b) + } + return data, nil +} diff --git a/vendor/github.com/google/yamlfmt/content_analyzer.go b/vendor/github.com/google/yamlfmt/content_analyzer.go new file mode 100644 index 0000000..4083e6b --- /dev/null +++ b/vendor/github.com/google/yamlfmt/content_analyzer.go @@ -0,0 +1,90 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import ( + "os" + "regexp" + + "github.com/google/yamlfmt/internal/collections" +) + +type ContentAnalyzer interface { + ExcludePathsByContent(paths []string) ([]string, []string, error) +} + +type BasicContentAnalyzer struct { + RegexPatterns []*regexp.Regexp +} + +func NewBasicContentAnalyzer(patterns []string) (BasicContentAnalyzer, error) { + analyzer := BasicContentAnalyzer{RegexPatterns: []*regexp.Regexp{}} + compileErrs := collections.Errors{} + for _, pattern := range patterns { + re, err := regexp.Compile(pattern) + if err != nil { + compileErrs = append(compileErrs, err) + continue + } + analyzer.RegexPatterns = append(analyzer.RegexPatterns, re) + } + return analyzer, compileErrs.Combine() +} + +func (a BasicContentAnalyzer) ExcludePathsByContent(paths []string) ([]string, []string, error) { + pathsToFormat := collections.SliceToSet(paths) + pathsExcluded := []string{} + pathErrs := collections.Errors{} + + for _, path := range paths { + content, err := os.ReadFile(path) + if err != nil { + pathErrs = append(pathErrs, err) + continue + } + + // Search metadata for ignore + metadata, mdErrs := ReadMetadata(content, path) + if len(mdErrs) != 0 { + pathErrs = append(pathErrs, mdErrs...) + } + ignoreFound := false + for md := range metadata { + if md.Type == MetadataIgnore { + ignoreFound = true + break + } + } + if ignoreFound { + pathsExcluded = append(pathsExcluded, path) + pathsToFormat.Remove(path) + continue + } + + // Check if content matches any regex + matched := false + for _, pattern := range a.RegexPatterns { + if pattern.Match(content) { + matched = true + } + } + if matched { + pathsExcluded = append(pathsExcluded, path) + pathsToFormat.Remove(path) + } + } + + return pathsToFormat.ToSlice(), pathsExcluded, pathErrs.Combine() +} diff --git a/vendor/github.com/google/yamlfmt/engine.go b/vendor/github.com/google/yamlfmt/engine.go new file mode 100644 index 0000000..b98ee89 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/engine.go @@ -0,0 +1,127 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import ( + "fmt" + "os" + + "github.com/google/yamlfmt/internal/collections" + "github.com/google/yamlfmt/internal/multilinediff" +) + +type Operation int + +const ( + OperationFormat Operation = iota + OperationLint + OperationDry + OperationStdin + OperationPrintConfig +) + +type Engine interface { + FormatContent(content []byte) ([]byte, error) + Format(paths []string) (fmt.Stringer, error) + Lint(paths []string) (fmt.Stringer, error) + DryRun(paths []string) (fmt.Stringer, error) +} + +type FormatDiff struct { + Original string + Formatted string + LineSep string +} + +func (d *FormatDiff) MultilineDiff() (string, int) { + return multilinediff.Diff(d.Original, d.Formatted, d.LineSep) +} + +func (d *FormatDiff) Changed() bool { + return d.Original != d.Formatted +} + +type FileDiff struct { + Path string + Diff *FormatDiff +} + +func (fd *FileDiff) StrOutput() string { + diffStr, _ := fd.Diff.MultilineDiff() + return fmt.Sprintf("%s:\n%s\n", fd.Path, diffStr) +} + +func (fd *FileDiff) StrOutputQuiet() string { + return fd.Path + "\n" +} + +func (fd *FileDiff) Apply() error { + // If there is no diff in the format, there is no need to write the file. + if !fd.Diff.Changed() { + return nil + } + return os.WriteFile(fd.Path, []byte(fd.Diff.Formatted), 0644) +} + +type FileDiffs map[string]*FileDiff + +func (fds FileDiffs) Add(diff *FileDiff) error { + if _, ok := fds[diff.Path]; ok { + return fmt.Errorf("a diff for %s already exists", diff.Path) + } + + fds[diff.Path] = diff + return nil +} + +func (fds FileDiffs) StrOutput() string { + result := "" + for _, fd := range fds { + if fd.Diff.Changed() { + result += fd.StrOutput() + } + } + return result +} + +func (fds FileDiffs) StrOutputQuiet() string { + result := "" + for _, fd := range fds { + if fd.Diff.Changed() { + result += fd.StrOutputQuiet() + } + } + return result +} + +func (fds FileDiffs) ApplyAll() error { + applyErrs := make(collections.Errors, len(fds)) + i := 0 + for _, diff := range fds { + applyErrs[i] = diff.Apply() + i++ + } + return applyErrs.Combine() +} + +func (fds FileDiffs) ChangedCount() int { + changed := 0 + for _, fd := range fds { + if fd.Diff.Changed() { + changed++ + } + } + return changed +} diff --git a/vendor/github.com/google/yamlfmt/engine/consecutive_engine.go b/vendor/github.com/google/yamlfmt/engine/consecutive_engine.go new file mode 100644 index 0000000..650d1b7 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/engine/consecutive_engine.go @@ -0,0 +1,103 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package engine + +import ( + "fmt" + "os" + + "github.com/google/yamlfmt" +) + +// Engine that will process each file one by one consecutively. +type ConsecutiveEngine struct { + LineSepCharacter string + Formatter yamlfmt.Formatter + Quiet bool + ContinueOnError bool + OutputFormat EngineOutputFormat +} + +func (e *ConsecutiveEngine) FormatContent(content []byte) ([]byte, error) { + return e.Formatter.Format(content) +} + +func (e *ConsecutiveEngine) Format(paths []string) (fmt.Stringer, error) { + formatDiffs, formatErrs := e.formatAll(paths) + if len(formatErrs) > 0 { + if e.ContinueOnError { + fmt.Print(formatErrs) + fmt.Println("Continuing...") + } else { + return nil, formatErrs + } + } + return nil, formatDiffs.ApplyAll() +} + +func (e *ConsecutiveEngine) Lint(paths []string) (fmt.Stringer, error) { + formatDiffs, formatErrs := e.formatAll(paths) + if len(formatErrs) > 0 { + return nil, formatErrs + } + if formatDiffs.ChangedCount() == 0 { + return nil, nil + } + return getEngineOutput(e.OutputFormat, yamlfmt.OperationLint, formatDiffs, e.Quiet) +} + +func (e *ConsecutiveEngine) DryRun(paths []string) (fmt.Stringer, error) { + formatDiffs, formatErrs := e.formatAll(paths) + if len(formatErrs) > 0 { + return nil, formatErrs + } + if formatDiffs.ChangedCount() == 0 { + return nil, nil + } + return getEngineOutput(e.OutputFormat, yamlfmt.OperationDry, formatDiffs, e.Quiet) +} + +func (e *ConsecutiveEngine) formatAll(paths []string) (yamlfmt.FileDiffs, FormatErrors) { + formatDiffs := yamlfmt.FileDiffs{} + formatErrs := FormatErrors{} + for _, path := range paths { + fileDiff, err := e.formatFileContent(path) + if err != nil { + formatErrs = append(formatErrs, wrapFormatError(path, err)) + continue + } + formatDiffs.Add(fileDiff) + } + return formatDiffs, formatErrs +} + +func (e *ConsecutiveEngine) formatFileContent(path string) (*yamlfmt.FileDiff, error) { + content, err := os.ReadFile(path) + if err != nil { + return nil, err + } + formatted, err := e.FormatContent(content) + if err != nil { + return nil, err + } + return &yamlfmt.FileDiff{ + Path: path, + Diff: &yamlfmt.FormatDiff{ + Original: string(content), + Formatted: string(formatted), + LineSep: e.LineSepCharacter, + }, + }, nil +} diff --git a/vendor/github.com/google/yamlfmt/engine/errors.go b/vendor/github.com/google/yamlfmt/engine/errors.go new file mode 100644 index 0000000..27dbba1 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/engine/errors.go @@ -0,0 +1,40 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package engine + +import "fmt" + +type FormatErrors []*FormatError + +func (e FormatErrors) Error() string { + errStr := "encountered the following formatting errors:\n" + for _, err := range e { + errStr += fmt.Sprintf("%s\n", err.Error()) + } + return errStr +} + +type FormatError struct { + path string + err error +} + +func wrapFormatError(path string, err error) *FormatError { + return &FormatError{path: path, err: err} +} + +func (e *FormatError) Error() string { + return fmt.Sprintf("%s: %v", e.path, e.err) +} diff --git a/vendor/github.com/google/yamlfmt/engine/output.go b/vendor/github.com/google/yamlfmt/engine/output.go new file mode 100644 index 0000000..2d35e84 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/engine/output.go @@ -0,0 +1,138 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package engine + +import ( + "encoding/json" + "fmt" + "sort" + "strings" + + "github.com/google/yamlfmt" + "github.com/google/yamlfmt/internal/gitlab" +) + +type EngineOutputFormat string + +const ( + EngineOutputDefault EngineOutputFormat = "default" + EngineOutputSingeLine EngineOutputFormat = "line" + EngineOutputGitlab EngineOutputFormat = "gitlab" +) + +func getEngineOutput(t EngineOutputFormat, operation yamlfmt.Operation, files yamlfmt.FileDiffs, quiet bool) (fmt.Stringer, error) { + switch t { + case EngineOutputDefault: + return engineOutput{Operation: operation, Files: files, Quiet: quiet}, nil + case EngineOutputSingeLine: + return engineOutputSingleLine{Operation: operation, Files: files, Quiet: quiet}, nil + case EngineOutputGitlab: + return engineOutputGitlab{Operation: operation, Files: files, Compact: quiet}, nil + + } + return nil, fmt.Errorf("unknown output type: %s", t) +} + +type engineOutput struct { + Operation yamlfmt.Operation + Files yamlfmt.FileDiffs + Quiet bool +} + +func (eo engineOutput) String() string { + var msg string + switch eo.Operation { + case yamlfmt.OperationLint: + msg = "The following formatting differences were found:" + if eo.Quiet { + msg = "The following files had formatting differences:" + } + case yamlfmt.OperationDry: + if len(eo.Files) > 0 { + if eo.Quiet { + msg = "The following files would be formatted:" + } + } else { + return "No files will formatted." + } + } + var result string + if msg != "" { + result += fmt.Sprintf("%s\n\n", msg) + } + if eo.Quiet { + result += eo.Files.StrOutputQuiet() + } else { + result += fmt.Sprintf("%s\n", eo.Files.StrOutput()) + } + return result +} + +type engineOutputSingleLine struct { + Operation yamlfmt.Operation + Files yamlfmt.FileDiffs + Quiet bool +} + +func (eosl engineOutputSingleLine) String() string { + var msg string + for _, fileDiff := range eosl.Files { + msg += fmt.Sprintf("%s: formatting difference found\n", fileDiff.Path) + } + return msg +} + +type engineOutputGitlab struct { + Operation yamlfmt.Operation + Files yamlfmt.FileDiffs + Compact bool +} + +func (eo engineOutputGitlab) String() string { + var findings []gitlab.CodeQuality + + for _, file := range eo.Files { + if cq, ok := gitlab.NewCodeQuality(*file); ok { + findings = append(findings, cq) + } + } + + if len(findings) == 0 { + return "" + } + + sort.Sort(byPath(findings)) + + var b strings.Builder + enc := json.NewEncoder(&b) + + if !eo.Compact { + enc.SetIndent("", " ") + } + + if err := enc.Encode(findings); err != nil { + panic(err) + } + return b.String() +} + +// byPath is used to sort by Location.Path. +type byPath []gitlab.CodeQuality + +func (b byPath) Len() int { return len(b) } +func (b byPath) Less(i, j int) bool { return b[i].Location.Path < b[j].Location.Path } +func (b byPath) Swap(i, j int) { + b[i].Location.Path, b[j].Location.Path = b[j].Location.Path, b[i].Location.Path +} diff --git a/vendor/github.com/google/yamlfmt/feature.go b/vendor/github.com/google/yamlfmt/feature.go new file mode 100644 index 0000000..af56dda --- /dev/null +++ b/vendor/github.com/google/yamlfmt/feature.go @@ -0,0 +1,78 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import ( + "context" + "fmt" +) + +type FeatureFunc func(context.Context, []byte) (context.Context, []byte, error) + +type Feature struct { + Name string + BeforeAction FeatureFunc + AfterAction FeatureFunc +} + +type FeatureList []Feature + +type FeatureApplyMode string + +var ( + FeatureApplyBefore FeatureApplyMode = "Before" + FeatureApplyAfter FeatureApplyMode = "After" +) + +type FeatureApplyError struct { + err error + featureName string + mode FeatureApplyMode +} + +func (e *FeatureApplyError) Error() string { + return fmt.Sprintf("Feature %s %sAction failed with error: %v", e.featureName, e.mode, e.err) +} + +func (e *FeatureApplyError) Unwrap() error { + return e.err +} + +func (fl FeatureList) ApplyFeatures(ctx context.Context, input []byte, mode FeatureApplyMode) (context.Context, []byte, error) { + // Declare err here so the result variable doesn't get shadowed in the loop + var err error + result := make([]byte, len(input)) + copy(result, input) + for _, feature := range fl { + if mode == FeatureApplyBefore { + if feature.BeforeAction != nil { + ctx, result, err = feature.BeforeAction(ctx, result) + } + } else { + if feature.AfterAction != nil { + ctx, result, err = feature.AfterAction(ctx, result) + } + } + + if err != nil { + return ctx, nil, &FeatureApplyError{ + err: err, + featureName: feature.Name, + mode: mode, + } + } + } + return ctx, result, nil +} diff --git a/vendor/github.com/google/yamlfmt/formatter.go b/vendor/github.com/google/yamlfmt/formatter.go new file mode 100644 index 0000000..ce432ee --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatter.go @@ -0,0 +1,65 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import "fmt" + +type Formatter interface { + Type() string + Format(yamlContent []byte) ([]byte, error) + ConfigMap() (map[string]any, error) +} + +type Factory interface { + Type() string + NewFormatter(config map[string]interface{}) (Formatter, error) +} + +type Registry struct { + registry map[string]Factory + defaultType string +} + +func NewFormatterRegistry(defaultFactory Factory) *Registry { + return &Registry{ + registry: map[string]Factory{ + defaultFactory.Type(): defaultFactory, + }, + defaultType: defaultFactory.Type(), + } +} + +func (r *Registry) Add(f Factory) { + r.registry[f.Type()] = f +} + +func (r *Registry) GetFactory(fType string) (Factory, error) { + if fType == "" { + return r.GetDefaultFactory() + } + factory, ok := r.registry[fType] + if !ok { + return nil, fmt.Errorf("no formatter registered with type \"%s\"", fType) + } + return factory, nil +} + +func (r *Registry) GetDefaultFactory() (Factory, error) { + factory, ok := r.registry[r.defaultType] + if !ok { + return nil, fmt.Errorf("no default formatter registered for type \"%s\"", r.defaultType) + } + return factory, nil +} diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/README.md b/vendor/github.com/google/yamlfmt/formatters/basic/README.md new file mode 100644 index 0000000..af50a64 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/README.md @@ -0,0 +1,3 @@ +# Basic Formatter + +For formatter settings, see [the configuration docs](../../docs/config-file.md). diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/anchors/check.go b/vendor/github.com/google/yamlfmt/formatters/basic/anchors/check.go new file mode 100644 index 0000000..aef3070 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/anchors/check.go @@ -0,0 +1,37 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package anchors + +import ( + "errors" + "fmt" + + "github.com/braydonk/yaml" +) + +func Check(n yaml.Node) error { + if n.Kind == yaml.AliasNode { + return errors.New("alias node found") + } + if n.Anchor != "" { + return fmt.Errorf("node references anchor %q", n.Anchor) + } + for _, c := range n.Content { + if err := Check(*c); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/config.go b/vendor/github.com/google/yamlfmt/formatters/basic/config.go new file mode 100644 index 0000000..82e67eb --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/config.go @@ -0,0 +1,52 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package basic + +import ( + "runtime" + + "github.com/google/yamlfmt" +) + +type Config struct { + Indent int `mapstructure:"indent"` + IncludeDocumentStart bool `mapstructure:"include_document_start"` + LineEnding yamlfmt.LineBreakStyle `mapstructure:"line_ending"` + LineLength int `mapstructure:"max_line_length"` + RetainLineBreaks bool `mapstructure:"retain_line_breaks"` + RetainLineBreaksSingle bool `mapstructure:"retain_line_breaks_single"` + DisallowAnchors bool `mapstructure:"disallow_anchors"` + ScanFoldedAsLiteral bool `mapstructure:"scan_folded_as_literal"` + IndentlessArrays bool `mapstructure:"indentless_arrays"` + DropMergeTag bool `mapstructure:"drop_merge_tag"` + PadLineComments int `mapstructure:"pad_line_comments"` + TrimTrailingWhitespace bool `mapstructure:"trim_trailing_whitespace"` + EOFNewline bool `mapstructure:"eof_newline"` + StripDirectives bool `mapstructure:"strip_directives"` + ArrayIndent int `mapstructure:"array_indent"` + IndentRootArray bool `mapstructure:"indent_root_array"` +} + +func DefaultConfig() *Config { + lineBreakStyle := yamlfmt.LineBreakStyleLF + if runtime.GOOS == "windows" { + lineBreakStyle = yamlfmt.LineBreakStyleCRLF + } + return &Config{ + Indent: 2, + LineEnding: lineBreakStyle, + PadLineComments: 1, + } +} diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/errors.go b/vendor/github.com/google/yamlfmt/formatters/basic/errors.go new file mode 100644 index 0000000..02c0a89 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/errors.go @@ -0,0 +1,33 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package basic + +import "fmt" + +type BasicFormatterError struct { + err error +} + +func (e BasicFormatterError) Error() string { + return fmt.Sprintf("basic formatter error: %v", e.err) +} + +func (e BasicFormatterError) Unwrap() error { + return e.err +} + +// func wrapBasicFormatterError(err error) error { +// return BasicFormatterError{err: err} +// } diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/factory.go b/vendor/github.com/google/yamlfmt/formatters/basic/factory.go new file mode 100644 index 0000000..eb536b0 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/factory.go @@ -0,0 +1,45 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package basic + +import ( + "github.com/google/yamlfmt" + "github.com/mitchellh/mapstructure" +) + +type BasicFormatterFactory struct{} + +func (f *BasicFormatterFactory) Type() string { + return BasicFormatterType +} + +func (f *BasicFormatterFactory) NewFormatter(configData map[string]interface{}) (yamlfmt.Formatter, error) { + config := DefaultConfig() + if configData != nil { + err := mapstructure.Decode(configData, &config) + if err != nil { + return nil, err + } + } + return newFormatter(config), nil +} + +func newFormatter(config *Config) yamlfmt.Formatter { + return &BasicFormatter{ + Config: config, + Features: ConfigureFeaturesFromConfig(config), + YAMLFeatures: ConfigureYAMLFeaturesFromConfig(config), + } +} diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/features.go b/vendor/github.com/google/yamlfmt/formatters/basic/features.go new file mode 100644 index 0000000..de736f4 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/features.go @@ -0,0 +1,78 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package basic + +import ( + "github.com/braydonk/yaml" + "github.com/google/yamlfmt" + "github.com/google/yamlfmt/formatters/basic/anchors" + "github.com/google/yamlfmt/internal/features" + "github.com/google/yamlfmt/internal/hotfix" +) + +func ConfigureFeaturesFromConfig(config *Config) yamlfmt.FeatureList { + lineSep, err := config.LineEnding.Separator() + if err != nil { + lineSep = "\n" + } + configuredFeatures := []yamlfmt.Feature{} + if config.RetainLineBreaks || config.RetainLineBreaksSingle { + configuredFeatures = append( + configuredFeatures, + hotfix.MakeFeatureRetainLineBreak(lineSep, config.RetainLineBreaksSingle), + ) + } + if config.TrimTrailingWhitespace { + configuredFeatures = append( + configuredFeatures, + features.MakeFeatureTrimTrailingWhitespace(lineSep), + ) + } + if config.EOFNewline { + configuredFeatures = append( + configuredFeatures, + features.MakeFeatureEOFNewline(lineSep), + ) + } + if config.StripDirectives { + configuredFeatures = append( + configuredFeatures, + hotfix.MakeFeatureStripDirectives(lineSep), + ) + } + return configuredFeatures +} + +// These features will directly use the `yaml.Node` type and +// as such are specific to this formatter. +type YAMLFeatureFunc func(yaml.Node) error +type YAMLFeatureList []YAMLFeatureFunc + +func (y YAMLFeatureList) ApplyFeatures(node yaml.Node) error { + for _, f := range y { + if err := f(node); err != nil { + return err + } + } + return nil +} + +func ConfigureYAMLFeaturesFromConfig(config *Config) YAMLFeatureList { + var features YAMLFeatureList + if config.DisallowAnchors { + features = append(features, anchors.Check) + } + return features +} diff --git a/vendor/github.com/google/yamlfmt/formatters/basic/formatter.go b/vendor/github.com/google/yamlfmt/formatters/basic/formatter.go new file mode 100644 index 0000000..26bcc45 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/formatters/basic/formatter.go @@ -0,0 +1,133 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package basic + +import ( + "bytes" + "context" + "errors" + "io" + + "github.com/braydonk/yaml" + "github.com/google/yamlfmt" + "github.com/mitchellh/mapstructure" +) + +const BasicFormatterType string = "basic" + +type BasicFormatter struct { + Config *Config + Features yamlfmt.FeatureList + YAMLFeatures YAMLFeatureList +} + +// yamlfmt.Formatter interface + +func (f *BasicFormatter) Type() string { + return BasicFormatterType +} + +func (f *BasicFormatter) Format(input []byte) ([]byte, error) { + // Run all features with BeforeActions + ctx := context.Background() + ctx, yamlContent, err := f.Features.ApplyFeatures(ctx, input, yamlfmt.FeatureApplyBefore) + if err != nil { + return nil, err + } + + // Format the yaml content + reader := bytes.NewReader(yamlContent) + decoder := f.getNewDecoder(reader) + documents := []yaml.Node{} + for { + var docNode yaml.Node + err := decoder.Decode(&docNode) + if err != nil { + if errors.Is(err, io.EOF) { + break + } + return nil, err + } + documents = append(documents, docNode) + } + + // Run all YAML features. + for _, d := range documents { + if err := f.YAMLFeatures.ApplyFeatures(d); err != nil { + return nil, err + } + } + + var b bytes.Buffer + e := f.getNewEncoder(&b) + for _, doc := range documents { + err := e.Encode(&doc) + if err != nil { + return nil, err + } + } + + // Run all features with AfterActions + _, resultYaml, err := f.Features.ApplyFeatures(ctx, b.Bytes(), yamlfmt.FeatureApplyAfter) + if err != nil { + return nil, err + } + + return resultYaml, nil +} + +func (f *BasicFormatter) getNewDecoder(reader io.Reader) *yaml.Decoder { + d := yaml.NewDecoder(reader) + if f.Config.ScanFoldedAsLiteral { + d.SetScanBlockScalarAsLiteral(true) + } + return d +} + +func (f *BasicFormatter) getNewEncoder(buf *bytes.Buffer) *yaml.Encoder { + e := yaml.NewEncoder(buf) + e.SetIndent(f.Config.Indent) + + if f.Config.LineLength > 0 { + e.SetWidth(f.Config.LineLength) + } + + if f.Config.LineEnding == yamlfmt.LineBreakStyleCRLF { + e.SetLineBreakStyle(yaml.LineBreakStyleCRLF) + } + + e.SetExplicitDocumentStart(f.Config.IncludeDocumentStart) + e.SetAssumeBlockAsLiteral(f.Config.ScanFoldedAsLiteral) + e.SetIndentlessBlockSequence(f.Config.IndentlessArrays) + e.SetDropMergeTag(f.Config.DropMergeTag) + e.SetPadLineComments(f.Config.PadLineComments) + + if f.Config.ArrayIndent > 0 { + e.SetArrayIndent(f.Config.ArrayIndent) + } + e.SetIndentRootArray(f.Config.IndentRootArray) + + return e +} + +func (f *BasicFormatter) ConfigMap() (map[string]any, error) { + configMap := map[string]any{} + err := mapstructure.Decode(f.Config, &configMap) + if err != nil { + return nil, err + } + configMap["type"] = BasicFormatterType + return configMap, err +} diff --git a/vendor/github.com/google/yamlfmt/internal/collections/errors.go b/vendor/github.com/google/yamlfmt/internal/collections/errors.go new file mode 100644 index 0000000..c800700 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/collections/errors.go @@ -0,0 +1,34 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collections + +import "errors" + +type Errors []error + +func (errs Errors) Combine() error { + errMessage := "" + + for _, err := range errs { + if err != nil { + errMessage += err.Error() + "\n" + } + } + + if len(errMessage) == 0 { + return nil + } + return errors.New(errMessage) +} diff --git a/vendor/github.com/google/yamlfmt/internal/collections/set.go b/vendor/github.com/google/yamlfmt/internal/collections/set.go new file mode 100644 index 0000000..97f70bc --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/collections/set.go @@ -0,0 +1,71 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collections + +type Set[T comparable] map[T]struct{} + +func (s Set[T]) Add(el ...T) { + for _, el := range el { + s[el] = struct{}{} + } +} + +func (s Set[T]) Remove(el T) bool { + if !s.Contains(el) { + return false + } + delete(s, el) + return true +} + +func (s Set[T]) Contains(el T) bool { + _, ok := s[el] + return ok +} + +func (s Set[T]) ToSlice() []T { + sl := []T{} + for el := range s { + sl = append(sl, el) + } + return sl +} + +func (s Set[T]) Clone() Set[T] { + newSet := Set[T]{} + for el := range s { + newSet.Add(el) + } + return newSet +} + +func (s Set[T]) Equals(rhs Set[T]) bool { + if len(s) != len(rhs) { + return false + } + rhsClone := rhs.Clone() + for el := range s { + rhsClone.Remove(el) + } + return len(rhsClone) == 0 +} + +func SliceToSet[T comparable](sl []T) Set[T] { + set := Set[T]{} + for _, el := range sl { + set.Add(el) + } + return set +} diff --git a/vendor/github.com/google/yamlfmt/internal/collections/slice.go b/vendor/github.com/google/yamlfmt/internal/collections/slice.go new file mode 100644 index 0000000..b4a9f3b --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/collections/slice.go @@ -0,0 +1,24 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package collections + +func SliceContains[T comparable](haystack []T, needle T) bool { + for _, e := range haystack { + if e == needle { + return true + } + } + return false +} diff --git a/vendor/github.com/google/yamlfmt/internal/features/eof_newline.go b/vendor/github.com/google/yamlfmt/internal/features/eof_newline.go new file mode 100644 index 0000000..d77c390 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/features/eof_newline.go @@ -0,0 +1,39 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package features + +import ( + "context" + + "github.com/google/yamlfmt" +) + +func MakeFeatureEOFNewline(linebreakStr string) yamlfmt.Feature { + return yamlfmt.Feature{ + Name: "EOF Newline", + AfterAction: eofNewlineFeature(linebreakStr), + } +} + +func eofNewlineFeature(linebreakStr string) yamlfmt.FeatureFunc { + return func(_ context.Context, content []byte) (context.Context, []byte, error) { + // This check works in both linebreak modes. + if len(content) == 0 || content[len(content)-1] != '\n' { + linebreakBytes := []byte(linebreakStr) + content = append(content, linebreakBytes...) + } + return nil, content, nil + } +} diff --git a/vendor/github.com/google/yamlfmt/internal/features/trim_whitespace.go b/vendor/github.com/google/yamlfmt/internal/features/trim_whitespace.go new file mode 100644 index 0000000..7b5bd63 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/features/trim_whitespace.go @@ -0,0 +1,43 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package features + +import ( + "bufio" + "bytes" + "context" + "strings" + + "github.com/google/yamlfmt" +) + +func MakeFeatureTrimTrailingWhitespace(linebreakStr string) yamlfmt.Feature { + return yamlfmt.Feature{ + Name: "Trim Trailing Whitespace", + BeforeAction: trimTrailingWhitespaceFeature(linebreakStr), + } +} + +func trimTrailingWhitespaceFeature(linebreakStr string) yamlfmt.FeatureFunc { + return func(_ context.Context, content []byte) (context.Context, []byte, error) { + buf := bytes.NewBuffer(content) + s := bufio.NewScanner(buf) + newLines := []string{} + for s.Scan() { + newLines = append(newLines, strings.TrimRight(s.Text(), " ")) + } + return nil, []byte(strings.Join(newLines, linebreakStr)), nil + } +} diff --git a/vendor/github.com/google/yamlfmt/internal/gitlab/codequality.go b/vendor/github.com/google/yamlfmt/internal/gitlab/codequality.go new file mode 100644 index 0000000..e03de2d --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/gitlab/codequality.go @@ -0,0 +1,79 @@ +// Copyright 2024 GitLab, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package gitlab generates GitLab Code Quality reports. +package gitlab + +import ( + "crypto/sha256" + "fmt" + + "github.com/google/yamlfmt" +) + +// CodeQuality represents a single code quality finding. +// +// Documentation: https://docs.gitlab.com/ee/ci/testing/code_quality.html#code-quality-report-format +type CodeQuality struct { + Description string `json:"description,omitempty"` + Name string `json:"check_name,omitempty"` + Fingerprint string `json:"fingerprint,omitempty"` + Severity Severity `json:"severity,omitempty"` + Location Location `json:"location,omitempty"` +} + +// Location is the location of a Code Quality finding. +type Location struct { + Path string `json:"path,omitempty"` +} + +// NewCodeQuality creates a new CodeQuality object from a yamlfmt.FileDiff. +// +// If the file did not change, i.e. the diff is empty, an empty struct and false is returned. +func NewCodeQuality(diff yamlfmt.FileDiff) (CodeQuality, bool) { + if !diff.Diff.Changed() { + return CodeQuality{}, false + } + + return CodeQuality{ + Description: "Not formatted correctly, run yamlfmt to resolve.", + Name: "yamlfmt", + Fingerprint: fingerprint(diff), + Severity: Major, + Location: Location{ + Path: diff.Path, + }, + }, true +} + +// fingerprint returns a 256-bit SHA256 hash of the original unformatted file. +// This is used to uniquely identify a code quality finding. +func fingerprint(diff yamlfmt.FileDiff) string { + hash := sha256.New() + + fmt.Fprint(hash, diff.Diff.Original) + + return fmt.Sprintf("%x", hash.Sum(nil)) //nolint:perfsprint +} + +// Severity is the severity of a code quality finding. +type Severity string + +const ( + Info Severity = "info" + Minor Severity = "minor" + Major Severity = "major" + Critical Severity = "critical" + Blocker Severity = "blocker" +) diff --git a/vendor/github.com/google/yamlfmt/internal/hotfix/retain_line_break.go b/vendor/github.com/google/yamlfmt/internal/hotfix/retain_line_break.go new file mode 100644 index 0000000..a7a139e --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/hotfix/retain_line_break.go @@ -0,0 +1,104 @@ +// Copyright 2022 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// The features in this file are to retain line breaks. +// The basic idea is to insert/remove placeholder comments in the yaml document before and after the format process. + +package hotfix + +import ( + "bufio" + "bytes" + "context" + "strings" + + "github.com/google/yamlfmt" +) + +const lineBreakPlaceholder = "#magic___^_^___line" + +type paddinger struct { + strings.Builder +} + +func (p *paddinger) adjust(txt string) { + var indentSize int + for i := 0; i < len(txt) && txt[i] == ' '; i++ { // yaml only allows space to indent. + indentSize++ + } + // Grows if the given size is larger than us and always return the max padding. + for diff := indentSize - p.Len(); diff > 0; diff-- { + p.WriteByte(' ') + } +} + +func MakeFeatureRetainLineBreak(linebreakStr string, chomp bool) yamlfmt.Feature { + return yamlfmt.Feature{ + Name: "Retain Line Breaks", + BeforeAction: replaceLineBreakFeature(linebreakStr, chomp), + AfterAction: restoreLineBreakFeature(linebreakStr), + } +} + +func replaceLineBreakFeature(newlineStr string, chomp bool) yamlfmt.FeatureFunc { + return func(_ context.Context, content []byte) (context.Context, []byte, error) { + var buf bytes.Buffer + reader := bytes.NewReader(content) + scanner := bufio.NewScanner(reader) + var inLineBreaks bool + var padding paddinger + for scanner.Scan() { + txt := scanner.Text() + padding.adjust(txt) + if strings.TrimSpace(txt) == "" { // line break or empty space line. + if chomp && inLineBreaks { + continue + } + buf.WriteString(padding.String()) // prepend some padding incase literal multiline strings. + buf.WriteString(lineBreakPlaceholder) + buf.WriteString(newlineStr) + inLineBreaks = true + } else { + buf.WriteString(txt) + buf.WriteString(newlineStr) + inLineBreaks = false + } + } + return nil, buf.Bytes(), scanner.Err() + } +} + +func restoreLineBreakFeature(newlineStr string) yamlfmt.FeatureFunc { + return func(_ context.Context, content []byte) (context.Context, []byte, error) { + var buf bytes.Buffer + reader := bytes.NewReader(content) + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + txt := scanner.Text() + if strings.TrimSpace(txt) == "" { + // The basic yaml lib inserts newline when there is a comment(either placeholder or by user) + // followed by optional line breaks and a `---` multi-documents. + // To fix it, the empty line could only be inserted by us. + continue + } + if strings.HasPrefix(strings.TrimLeft(txt, " "), lineBreakPlaceholder) { + buf.WriteString(newlineStr) + continue + } + buf.WriteString(txt) + buf.WriteString(newlineStr) + } + return nil, buf.Bytes(), scanner.Err() + } +} diff --git a/vendor/github.com/google/yamlfmt/internal/hotfix/strip_directives.go b/vendor/github.com/google/yamlfmt/internal/hotfix/strip_directives.go new file mode 100644 index 0000000..63e1c6e --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/hotfix/strip_directives.go @@ -0,0 +1,101 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package hotfix + +import ( + "bufio" + "bytes" + "context" + "strings" + + "github.com/google/yamlfmt" +) + +type directiveKey string + +var contextDirectivesKey directiveKey = "directives" + +type Directive struct { + line int + content string +} + +func ContextWithDirectives(ctx context.Context, directives []Directive) context.Context { + return context.WithValue(ctx, contextDirectivesKey, directives) +} + +func DirectivesFromContext(ctx context.Context) []Directive { + return ctx.Value(contextDirectivesKey).([]Directive) +} + +func MakeFeatureStripDirectives(lineSepChar string) yamlfmt.Feature { + return yamlfmt.Feature{ + Name: "Strip Directives", + BeforeAction: stripDirectivesFeature(lineSepChar), + AfterAction: restoreDirectivesFeature(lineSepChar), + } +} + +func stripDirectivesFeature(lineSepChar string) yamlfmt.FeatureFunc { + return func(ctx context.Context, content []byte) (context.Context, []byte, error) { + directives := []Directive{} + reader := bytes.NewReader(content) + scanner := bufio.NewScanner(reader) + result := "" + currLine := 1 + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "%") { + directives = append(directives, Directive{ + line: currLine, + content: line, + }) + } else { + result += line + lineSepChar + } + currLine++ + } + return ContextWithDirectives(ctx, directives), []byte(result), nil + } +} + +func restoreDirectivesFeature(lineSepChar string) yamlfmt.FeatureFunc { + return func(ctx context.Context, content []byte) (context.Context, []byte, error) { + directives := DirectivesFromContext(ctx) + directiveIdx := 0 + doneDirectives := directiveIdx == len(directives) + reader := bytes.NewReader(content) + scanner := bufio.NewScanner(reader) + result := "" + currLine := 1 + for scanner.Scan() { + if !doneDirectives && currLine == directives[directiveIdx].line { + result += directives[directiveIdx].content + lineSepChar + currLine++ + directiveIdx++ + doneDirectives = directiveIdx == len(directives) + } + result += scanner.Text() + lineSepChar + currLine++ + } + // Edge case: There technically can be a directive as the final line. This would be + // useless as far as I can tell so maybe yamlfmt should just remove it anyway LOL but + // no we'll keep it. + if !doneDirectives && currLine == directives[directiveIdx].line { + result += directives[directiveIdx].content + lineSepChar + } + return ctx, []byte(result), nil + } +} diff --git a/vendor/github.com/google/yamlfmt/internal/logger/debug.go b/vendor/github.com/google/yamlfmt/internal/logger/debug.go new file mode 100644 index 0000000..a75463c --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/logger/debug.go @@ -0,0 +1,51 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package logger + +import ( + "fmt" + + "github.com/google/yamlfmt/internal/collections" +) + +type DebugCode int + +const ( + DebugCodeAny DebugCode = iota + DebugCodeConfig + DebugCodePaths +) + +var ( + supportedDebugCodes = map[string][]DebugCode{ + "config": {DebugCodeConfig}, + "paths": {DebugCodePaths}, + "all": {DebugCodeConfig, DebugCodePaths}, + } + activeDebugCodes = collections.Set[DebugCode]{} +) + +func ActivateDebugCode(code string) { + if debugCodes, ok := supportedDebugCodes[code]; ok { + activeDebugCodes.Add(debugCodes...) + } +} + +// Debug prints a message if the given debug code is active. +func Debug(code DebugCode, msg string, args ...any) { + if activeDebugCodes.Contains(code) { + fmt.Printf("[DEBUG]: %s\n", fmt.Sprintf(msg, args...)) + } +} diff --git a/vendor/github.com/google/yamlfmt/internal/multilinediff/multilinediff.go b/vendor/github.com/google/yamlfmt/internal/multilinediff/multilinediff.go new file mode 100644 index 0000000..dea8cc6 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/internal/multilinediff/multilinediff.go @@ -0,0 +1,130 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package multilinediff + +import ( + "fmt" + "strings" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" +) + +// Get the diff between two strings. +func Diff(a, b, lineSep string) (string, int) { + reporter := Reporter{LineSep: lineSep} + cmp.Diff( + a, b, + cmpopts.AcyclicTransformer("multiline", func(s string) []string { + return strings.Split(s, lineSep) + }), + cmp.Reporter(&reporter), + ) + return reporter.String(), reporter.DiffCount +} + +type diffType int + +const ( + diffTypeEqual diffType = iota + diffTypeChange + diffTypeAdd +) + +type diffLine struct { + diff diffType + old string + new string +} + +func (l diffLine) toLine(length int) string { + line := "" + + switch l.diff { + case diffTypeChange: + line += "- " + case diffTypeAdd: + line += "+ " + default: + line += " " + } + + line += l.old + + for i := 0; i < length-len(l.old); i++ { + line += " " + } + + line += " " + + line += l.new + + return line +} + +// A pretty reporter to pass into cmp.Diff using the cmd.Reporter function. +type Reporter struct { + LineSep string + DiffCount int + + path cmp.Path + lines []diffLine +} + +func (r *Reporter) PushStep(ps cmp.PathStep) { + r.path = append(r.path, ps) +} + +func (r *Reporter) Report(rs cmp.Result) { + line := diffLine{} + vOld, vNew := r.path.Last().Values() + if !rs.Equal() { + r.DiffCount++ + if vOld.IsValid() { + line.diff = diffTypeChange + line.old = fmt.Sprintf("%+v", vOld) + } + if vNew.IsValid() { + if line.diff == diffTypeEqual { + line.diff = diffTypeAdd + } + line.new = fmt.Sprintf("%+v", vNew) + } + } else { + line.old = fmt.Sprintf("%+v", vOld) + line.new = fmt.Sprintf("%+v", vOld) + } + r.lines = append(r.lines, line) +} + +func (r *Reporter) PopStep() { + r.path = r.path[:len(r.path)-1] +} + +func (r *Reporter) String() string { + maxLen := 0 + for _, l := range r.lines { + if len(l.old) > maxLen { + maxLen = len(l.old) + } + } + + diffLines := []string{} + for _, l := range r.lines { + diffLines = append(diffLines, l.toLine(maxLen)) + } + + return strings.Join(diffLines, r.LineSep) +} diff --git a/vendor/github.com/google/yamlfmt/linebreak.go b/vendor/github.com/google/yamlfmt/linebreak.go new file mode 100644 index 0000000..2012aab --- /dev/null +++ b/vendor/github.com/google/yamlfmt/linebreak.go @@ -0,0 +1,42 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import "fmt" + +type LineBreakStyle string + +const ( + LineBreakStyleLF LineBreakStyle = "lf" + LineBreakStyleCRLF LineBreakStyle = "crlf" +) + +type UnsupportedLineBreakError struct { + style LineBreakStyle +} + +func (e UnsupportedLineBreakError) Error() string { + return fmt.Sprintf("unsupported line break style %s, see package documentation for supported styles", e.style) +} + +func (s LineBreakStyle) Separator() (string, error) { + switch s { + case LineBreakStyleLF: + return "\n", nil + case LineBreakStyleCRLF: + return "\r\n", nil + } + return "", UnsupportedLineBreakError{style: s} +} diff --git a/vendor/github.com/google/yamlfmt/metadata.go b/vendor/github.com/google/yamlfmt/metadata.go new file mode 100644 index 0000000..82abfc9 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/metadata.go @@ -0,0 +1,114 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import ( + "errors" + "fmt" + "strings" + "unicode" + + "github.com/google/yamlfmt/internal/collections" +) + +const MetadataIdentifier = "!yamlfmt!" + +type MetadataType string + +const ( + MetadataIgnore MetadataType = "ignore" +) + +func IsMetadataType(mdValueStr string) bool { + mdTypes := collections.Set[MetadataType]{} + mdTypes.Add(MetadataIgnore) + return mdTypes.Contains(MetadataType(mdValueStr)) +} + +type Metadata struct { + Type MetadataType + LineNum int +} + +var ( + ErrMalformedMetadata = errors.New("metadata: malformed string") + ErrUnrecognizedMetadata = errors.New("metadata: unrecognized type") +) + +type MetadataError struct { + err error + path string + lineNum int + lineStr string +} + +func (e *MetadataError) Error() string { + return fmt.Sprintf( + "%v: %s:%d:%s", + e.err, + e.path, + e.lineNum, + e.lineStr, + ) +} + +func (e *MetadataError) Unwrap() error { + return e.err +} + +func ReadMetadata(content []byte, path string) (collections.Set[Metadata], collections.Errors) { + metadata := collections.Set[Metadata]{} + mdErrs := collections.Errors{} + // This could be `\r\n` but it won't affect the outcome of this operation. + contentLines := strings.Split(string(content), "\n") + for i, line := range contentLines { + mdidIndex := strings.Index(line, MetadataIdentifier) + if mdidIndex == -1 { + continue + } + mdStr := scanMetadata(line, mdidIndex) + mdComponents := strings.Split(mdStr, ":") + if len(mdComponents) != 2 { + mdErrs = append(mdErrs, &MetadataError{ + path: path, + lineNum: i + 1, + err: ErrMalformedMetadata, + lineStr: line, + }) + continue + } + if IsMetadataType(mdComponents[1]) { + metadata.Add(Metadata{LineNum: i + 1, Type: MetadataType(mdComponents[1])}) + } else { + mdErrs = append(mdErrs, &MetadataError{ + path: path, + lineNum: i + 1, + err: ErrUnrecognizedMetadata, + lineStr: line, + }) + } + } + return metadata, mdErrs +} + +func scanMetadata(line string, index int) string { + mdBytes := []byte{} + i := index + for i < len(line) && !unicode.IsSpace(rune(line[i])) { + mdBytes = append(mdBytes, line[i]) + i++ + } + return string(mdBytes) +} diff --git a/vendor/github.com/google/yamlfmt/path_collector.go b/vendor/github.com/google/yamlfmt/path_collector.go new file mode 100644 index 0000000..7967f3c --- /dev/null +++ b/vendor/github.com/google/yamlfmt/path_collector.go @@ -0,0 +1,336 @@ +// Copyright 2024 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package yamlfmt + +import ( + "bufio" + "bytes" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + + "github.com/bmatcuk/doublestar/v4" + "github.com/google/yamlfmt/internal/collections" + "github.com/google/yamlfmt/internal/logger" + ignore "github.com/sabhiram/go-gitignore" +) + +type MatchType string + +const ( + MatchTypeStandard MatchType = "standard" + MatchTypeDoublestar MatchType = "doublestar" + MatchTypeGitignore MatchType = "gitignore" +) + +type PathCollector interface { + CollectPaths() ([]string, error) +} + +type FilepathCollector struct { + Include []string + Exclude []string + Extensions []string +} + +func (c *FilepathCollector) CollectPaths() ([]string, error) { + logger.Debug(logger.DebugCodePaths, "using file path matching. include patterns: %s", c.Include) + pathsFound := []string{} + for _, inclPath := range c.Include { + info, err := os.Stat(inclPath) + if err != nil { + if !os.IsNotExist(err) { + return nil, err + } + continue + } + if !info.IsDir() { + pathsFound = append(pathsFound, inclPath) + continue + } + paths, err := c.walkDirectoryForYaml(inclPath) + if err != nil { + return nil, err + } + pathsFound = append(pathsFound, paths...) + } + logger.Debug(logger.DebugCodePaths, "found paths: %s", pathsFound) + + pathsFoundSet := collections.SliceToSet(pathsFound) + pathsToFormat := collections.SliceToSet(pathsFound) + for _, exclPath := range c.Exclude { + info, err := os.Stat(exclPath) + if err != nil { + if !os.IsNotExist(err) { + return nil, err + } + continue + } + + if info.IsDir() { + logger.Debug(logger.DebugCodePaths, "for exclude dir: %s", exclPath) + for foundPath := range pathsFoundSet { + if strings.HasPrefix(foundPath, exclPath) { + logger.Debug(logger.DebugCodePaths, "excluding %s", foundPath) + pathsToFormat.Remove(foundPath) + } + } + } else { + logger.Debug(logger.DebugCodePaths, "for exclude file: %s", exclPath) + removed := pathsToFormat.Remove(exclPath) + if removed { + logger.Debug(logger.DebugCodePaths, "found in paths, excluding") + } + } + } + + pathsToFormatSlice := pathsToFormat.ToSlice() + logger.Debug(logger.DebugCodePaths, "paths to format: %s", pathsToFormat) + return pathsToFormatSlice, nil +} + +func (c *FilepathCollector) walkDirectoryForYaml(dir string) ([]string, error) { + var paths []string + err := filepath.Walk(dir, func(path string, info fs.FileInfo, err error) error { + if info.IsDir() { + return nil + } + + if c.extensionMatches(info.Name()) { + paths = append(paths, path) + } + + return nil + }) + return paths, err +} + +func (c *FilepathCollector) extensionMatches(name string) bool { + for _, ext := range c.Extensions { + // Users may specify "yaml", but we only want to match ".yaml", not "buyaml". + if !strings.HasPrefix(ext, ".") { + ext = "." + ext + } + + if strings.HasSuffix(name, ext) { + return true + } + } + return false +} + +type DoublestarCollector struct { + Include []string + Exclude []string +} + +func (c *DoublestarCollector) CollectPaths() ([]string, error) { + logger.Debug(logger.DebugCodePaths, "using doublestar path matching. include patterns: %s", c.Include) + includedPaths := []string{} + for _, pattern := range c.Include { + logger.Debug(logger.DebugCodePaths, "trying pattern: %s", pattern) + globMatches, err := doublestar.FilepathGlob(pattern) + if err != nil { + return nil, err + } + logger.Debug(logger.DebugCodePaths, "pattern %s matches: %s", pattern, globMatches) + includedPaths = append(includedPaths, globMatches...) + } + + pathsToFormatSet := collections.Set[string]{} + for _, path := range includedPaths { + if len(c.Exclude) == 0 { + pathsToFormatSet.Add(path) + continue + } + excluded := false + logger.Debug(logger.DebugCodePaths, "calculating excludes for %s", path) + for _, pattern := range c.Exclude { + match, err := doublestar.PathMatch(filepath.Clean(pattern), path) + if err != nil { + return nil, err + } + if match { + logger.Debug(logger.DebugCodePaths, "pattern %s matched, excluding", pattern) + excluded = true + break + } + logger.Debug(logger.DebugCodePaths, "pattern %s did not match path", pattern) + } + if !excluded { + logger.Debug(logger.DebugCodePaths, "path %s included", path) + pathsToFormatSet.Add(path) + } + } + + pathsToFormat := pathsToFormatSet.ToSlice() + logger.Debug(logger.DebugCodePaths, "paths to format: %s", pathsToFormat) + return pathsToFormat, nil +} + +func findGitIgnorePath(gitignorePath string) (string, error) { + // if path is absolute, check if exists and return + if filepath.IsAbs(gitignorePath) { + _, err := os.Stat(gitignorePath) + return gitignorePath, err + } + + // if path is relative, search for it until the git root + dir, err := os.Getwd() + if err != nil { + return gitignorePath, fmt.Errorf("cannot get current working directory: %w", err) + } + for { + // check if gitignore is there + gitIgnore := filepath.Join(dir, gitignorePath) + if _, err := os.Stat(gitIgnore); err == nil { + return gitIgnore, nil + } + + // check if we are at the git root directory + gitRoot := filepath.Join(dir, ".git") + if _, err := os.Stat(gitRoot); err == nil { + return gitignorePath, errors.New("gitignore not found") + } + + // check if we are at the root of the filesystem + parent := filepath.Dir(dir) + if parent == dir { + return gitignorePath, errors.New("no git repository found") + } + + // level up + dir = parent + } +} + +func ExcludeWithGitignore(gitignorePath string, paths []string) ([]string, error) { + gitignorePath, err := findGitIgnorePath(gitignorePath) + if err != nil { + return nil, err + } + logger.Debug(logger.DebugCodePaths, "excluding paths with gitignore: %s", gitignorePath) + ignorer, err := ignore.CompileIgnoreFile(gitignorePath) + if err != nil { + return nil, err + } + pathsToFormat := []string{} + for _, path := range paths { + if ok, pattern := ignorer.MatchesPathHow(path); !ok { + pathsToFormat = append(pathsToFormat, path) + } else { + logger.Debug(logger.DebugCodePaths, "pattern %s matches %s, excluding", pattern.Line, path) + } + } + logger.Debug(logger.DebugCodePaths, "paths to format: %s", pathsToFormat) + return pathsToFormat, nil +} + +const DefaultPatternFile = "yamlfmt.patterns" + +// PatternFileCollector determines which files to format and which to ignore based on a pattern file in gitignore(5) syntax. +type PatternFileCollector struct { + fs fs.FS + matcher *ignore.GitIgnore +} + +// NewPatternFileCollector initializes a new PatternFile using the provided file(s). +// If multiple files are provided, their content is concatenated in order. +// All patterns are relative to the current working directory. +func NewPatternFileCollector(files ...string) (*PatternFileCollector, error) { + r, err := cat(files...) + if err != nil { + return nil, err + } + + wd, err := os.Getwd() + if err != nil { + return nil, fmt.Errorf("os.Getwd: %w", err) + } + + return NewPatternFileCollectorFS(r, os.DirFS(wd)), nil +} + +// cat concatenates the contents of all files in its argument list. +func cat(files ...string) (io.Reader, error) { + var b bytes.Buffer + + for _, f := range files { + fh, err := os.Open(f) + if err != nil { + return nil, err + } + defer fh.Close() + + if _, err := io.Copy(&b, fh); err != nil { + return nil, fmt.Errorf("copying %q: %w", f, err) + } + fh.Close() + + // Append a newline to avoid issues with files lacking a newline at end-of-file. + fmt.Fprintln(&b) + } + + return &b, nil +} + +// NewPatternFileCollectorFS reads a pattern file from r and uses fs for file lookups. +// It is used by NewPatternFile and primarily public because it is useful for testing. +func NewPatternFileCollectorFS(r io.Reader, fs fs.FS) *PatternFileCollector { + var lines []string + + s := bufio.NewScanner(r) + for s.Scan() { + lines = append(lines, s.Text()) + } + + return &PatternFileCollector{ + fs: fs, + matcher: ignore.CompileIgnoreLines(lines...), + } +} + +// CollectPaths implements the PathCollector interface. +func (c *PatternFileCollector) CollectPaths() ([]string, error) { + var files []string + + err := fs.WalkDir(c.fs, ".", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + ok, pattern := c.matcher.MatchesPathHow(path) + switch { + case ok && pattern.Negate && d.IsDir(): + return fs.SkipDir + case ok && pattern.Negate: + return nil + case ok && d.Type().IsRegular(): + files = append(files, path) + } + + return nil + }) + + if err != nil { + return nil, fmt.Errorf("WalkDir: %w", err) + } + + return files, nil +} diff --git a/vendor/github.com/google/yamlfmt/schema.json b/vendor/github.com/google/yamlfmt/schema.json new file mode 100644 index 0000000..65f5038 --- /dev/null +++ b/vendor/github.com/google/yamlfmt/schema.json @@ -0,0 +1,93 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://raw.githubusercontent.com/google/yamlfmt/main/schema.json", + "title": "yamlfmt config file", + "description": "The yamlfmt config file. For details, see https://github.com/google/yamlfmt/blob/main/docs/config-file.md.", + "type": "object", + "properties": { + "line_ending": { + "type": "string", + "enum": [ + "lf", + "crlf" + ], + "default": "lf", + "description": "Parse and write the file with 'lf' or 'crlf' line endings. This global setting will override any formatter line_ending options." + }, + "doublestar": { + "type": "boolean", + "default": false, + "description": "Use doublestar for include and exclude paths. (This was the default before 0.7.0)" + }, + "continue_on_error": { + "type": "boolean", + "default": false, + "description": "Continue formatting and don't exit with code 1 when there is an invalid yaml file found." + }, + "include": { + "type": "array", + "items": { + "type": "string" + }, + "default": [], + "description": "The paths for the command to include for formatting. See Specifying Paths for more details." + }, + "exclude": { + "type": "array", + "items": { + "type": "string" + }, + "default": [], + "description": "The paths for the command to exclude from formatting. See Specifying Paths for more details." + }, + "gitignore_excludes": { + "type": "boolean", + "default": false, + "description": "Use gitignore files for exclude paths. This is in addition to the patterns from the exclude option." + }, + "gitignore_path": { + "type": "string", + "default": ".gitignore", + "description": "The path to the gitignore file to use." + }, + "regex_exclude": { + "type": "array", + "items": { + "type": "string" + }, + "default": [], + "description": "Regex patterns to match file contents for, if the file content matches the regex the file will be excluded. Use Go regexes." + }, + "extensions": { + "type": "array", + "items": { + "type": "string" + }, + "default": [], + "description": "The extensions to use for standard mode path collection. See Specifying Paths for more details." + }, + "formatter": { + "type": "object", + "default": { + "type": "basic" + }, + "description": "Formatter settings. See Formatter for more details.", + "properties": { + "type": { + "type": "string", + "default": "basic" + } + } + }, + "output_format": { + "type": "string", + "enum": [ + "default", + "line" + ], + "default": "default", + "description": "The output format to use. See Output docs for more details." + } + }, + "additionalProperties": false +} |
