Skip to content

Commit

Permalink
feat(format): add format functionality
Browse files Browse the repository at this point in the history
Refs: close #2
  • Loading branch information
ahaasler committed Jun 29, 2021
1 parent 8659930 commit eabb2a1
Show file tree
Hide file tree
Showing 11 changed files with 683 additions and 0 deletions.
124 changes: 124 additions & 0 deletions cmd/format.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
/*
Copyright (c) 2021 amplia-iiot
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package cmd

import (
"errors"
"fmt"

"github.com/amplia-iiot/yutil/internal/io"
"github.com/amplia-iiot/yutil/pkg/format"
"github.com/spf13/cobra"
)

type FormatOptions struct {
outputFile string
inPlace bool
suffix string
}

var formatOptions FormatOptions

// formatCmd represents the format command
var formatCmd = &cobra.Command{
Use: "format [FILE...]",
Short: "Format a yaml file",
Long: `Format a yaml file ordering its keys alphabetically and
cleaning it.
For example:
yutil format file.yml
yutil format file.yml -o file.formatted.yml
cat file.yml | yutil format > file.formatted.yml
echo "this is not a yaml" | yutil --no-input format file.yml > file.formatted.yml
`,
Args: func(cmd *cobra.Command, args []string) error {
if inPlaceEnabled(cmd) {
if canAccessStdin() {
return errors.New("stdin not compatible with in place format")
}
if formatOptions.outputFile != "" {
return errors.New("output option not compatible with in place format")
}
} else {
if canAccessStdin() && len(args) != 0 {
return errors.New("only one yaml can be formatted to output, stdin is active")
} else if !canAccessStdin() && len(args) == 0 {
if stdinBlocked() {
return errors.New("requires one file to be formatted, stdin is blocked")
} else {
return errors.New("requires one file to be formatted")
}
} else if !canAccessStdin() && len(args) != 1 {
return errors.New("only one file can be formatted to output")
}
}
for _, file := range args {
if !io.Exists(file) {
return fmt.Errorf("file %s does not exist", file)
}
}
return nil
},
Run: func(cmd *cobra.Command, args []string) {
var err error
if inPlaceEnabled(cmd) {
if formatOptions.suffix == "" {
err = format.FormatFilesInPlace(args)
} else {
err = format.FormatFilesInPlaceB(args, formatOptions.suffix)
}
} else {
var formatted string
if canAccessStdin() {
formatted, err = format.FormatStdin()
} else {
formatted, err = format.FormatFile(args[0])
}
if err != nil {
panic(err)
}
if len(formatOptions.outputFile) > 0 {
err = io.WriteToFile(formatOptions.outputFile, formatted)
} else {
err = io.WriteToStdout(formatted)
}
}
if err != nil {
panic(err)
}
},
}

func init() {
rootCmd.AddCommand(formatCmd)

formatCmd.Flags().StringVarP(&formatOptions.outputFile, "output", "o", "", "format yaml to output file instead of stdout (not compatible in place format)")
formatCmd.Flags().BoolVarP(&formatOptions.inPlace, "in-place", "i", false, "format yaml files in place (makes backup if suffix is supplied)")
formatCmd.Flags().StringVarP(&formatOptions.suffix, "suffix", "s", "", "format yaml files in place making a backup with the given suffix (-i is not necessary if suffix is passed)")
}

// Whether in place format is enabled
func inPlaceEnabled(cmd *cobra.Command) bool {
return formatOptions.inPlace || cmd.Flags().Changed("suffix")
}
5 changes: 5 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,8 @@ func canAccessStdin() bool {
noInput, err := rootCmd.Flags().GetBool("no-input")
return err == nil && io.ReceivedStdin() && !noInput
}

func stdinBlocked() bool {
noInput, err := rootCmd.Flags().GetBool("no-input")
return err == nil && noInput
}
24 changes: 24 additions & 0 deletions internal/io/writer.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ package io

import (
"bufio"
"fmt"
"io"
"os"
)

Expand All @@ -48,3 +50,25 @@ func Write(file *os.File, content string) error {
writer.Flush()
return nil
}

func Copy(src, dst string) error {
srcStat, err := os.Stat(src)
if err != nil {
return err
}
if !srcStat.Mode().IsRegular() {
return fmt.Errorf("%s is not a regular file", src)
}
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
destination, err := os.Create(dst)
if err != nil {
return err
}
defer destination.Close()
_, err = io.Copy(destination, srcFile)
return err
}
43 changes: 43 additions & 0 deletions pkg/format/content.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Copyright (c) 2021 amplia-iiot
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package format

import (
"github.com/amplia-iiot/yutil/internal/io"
"github.com/amplia-iiot/yutil/internal/yaml"
)

func FormatContent(content string) (string, error) {
contentData, err := yaml.Parse(content)
if err != nil {
return "", err
}
return yaml.Compose(contentData)
}

func FormatStdin() (string, error) {
content, err := io.ReadStdin()
if err != nil {
return "", err
}
return FormatContent(content)
}
Loading

0 comments on commit eabb2a1

Please sign in to comment.