Skip to content

初始化 smart-doc-go,以swaggo/swag 为本项目基础依赖 #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
## Features:

- Supports generating `OpenAPI 3.0` documentation.
- Supports generating documents in formats such as `Markdown`, `HTML5`, `Word`, `Asciidoctor`, and `Postman Collection`.
- Supports generating documents in formats such as `Markdown`, `HTML5`, `Word`, `Asciidoctor`, and `Postman Collection`.
304 changes: 304 additions & 0 deletions cmd/smart-doc-go.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,304 @@
package main

//smart-doc-golang refere a github.com/swaggo/swag kòm yon depandans debaz.
import (
"fmt"
"github.com/swaggo/swag"
"github.com/swaggo/swag/format"
"github.com/swaggo/swag/gen"
"github.com/urfave/cli/v2"
"io"
"log"
"os"
"strings"
)

const (
searchDirFlag = "dir"
excludeFlag = "exclude"
generalInfoFlag = "generalInfo"
propertyStrategyFlag = "propertyStrategy"
outputFlag = "output"
outputTypesFlag = "outputTypes"
parseVendorFlag = "parseVendor"
parseDependencyFlag = "parseDependency"
parseDependencyLevelFlag = "parseDependencyLevel"
markdownFilesFlag = "markdownFiles"
codeExampleFilesFlag = "codeExampleFiles"
parseInternalFlag = "parseInternal"
generatedTimeFlag = "generatedTime"
requiredByDefaultFlag = "requiredByDefault"
parseDepthFlag = "parseDepth"
instanceNameFlag = "instanceName"
overridesFileFlag = "overridesFile"
parseGoListFlag = "parseGoList"
quietFlag = "quiet"
tagsFlag = "tags"
parseExtensionFlag = "parseExtension"
templateDelimsFlag = "templateDelims"
packageName = "packageName"
collectionFormatFlag = "collectionFormat"
packagePrefixFlag = "packagePrefix"
stateFlag = "state"
)

var initFlags = []cli.Flag{
&cli.BoolFlag{
Name: quietFlag,
Aliases: []string{"q"},
Usage: "Make the logger quiet.",
},
&cli.StringFlag{
Name: generalInfoFlag,
Aliases: []string{"g"},
Value: "main.go",
Usage: "Go file path in which 'swagger general API Info' is written",
},
&cli.StringFlag{
Name: searchDirFlag,
Aliases: []string{"d"},
Value: "./",
Usage: "Directories you want to parse,comma separated and general-info file must be in the first one",
},
&cli.StringFlag{
Name: excludeFlag,
Usage: "Exclude directories and files when searching, comma separated",
},
&cli.StringFlag{
Name: propertyStrategyFlag,
Aliases: []string{"p"},
Value: swag.CamelCase,
Usage: "Property Naming Strategy like " + swag.SnakeCase + "," + swag.CamelCase + "," + swag.PascalCase,
},
&cli.StringFlag{
Name: outputFlag,
Aliases: []string{"o"},
Value: "./docs",
Usage: "Output directory for all the generated files(swagger.json, swagger.yaml and docs.go)",
},
&cli.StringFlag{
Name: outputTypesFlag,
Aliases: []string{"ot"},
Value: "go,json,yaml",
Usage: "Output types of generated files (docs.go, swagger.json, swagger.yaml) like go,json,yaml",
},
&cli.BoolFlag{
Name: parseVendorFlag,
Usage: "Parse go files in 'vendor' folder, disabled by default",
},
&cli.IntFlag{
Name: parseDependencyLevelFlag,
Aliases: []string{"pdl"},
Usage: "Parse go files inside dependency folder, 0 disabled, 1 only parse models, 2 only parse operations, 3 parse all",
},
&cli.BoolFlag{
Name: parseDependencyFlag,
Aliases: []string{"pd"},
Usage: "Parse go files inside dependency folder, disabled by default",
},
&cli.StringFlag{
Name: markdownFilesFlag,
Aliases: []string{"md"},
Value: "",
Usage: "Parse folder containing markdown files to use as description, disabled by default",
},
&cli.StringFlag{
Name: codeExampleFilesFlag,
Aliases: []string{"cef"},
Value: "",
Usage: "Parse folder containing code example files to use for the x-codeSamples extension, disabled by default",
},
&cli.BoolFlag{
Name: parseInternalFlag,
Usage: "Parse go files in internal packages, disabled by default",
},
&cli.BoolFlag{
Name: generatedTimeFlag,
Usage: "Generate timestamp at the top of docs.go, disabled by default",
},
&cli.IntFlag{
Name: parseDepthFlag,
Value: 100,
Usage: "Dependency parse depth",
},
&cli.BoolFlag{
Name: requiredByDefaultFlag,
Usage: "Set validation required for all fields by default",
},
&cli.StringFlag{
Name: instanceNameFlag,
Value: "",
Usage: "This parameter can be used to name different swagger document instances. It is optional.",
},
&cli.StringFlag{
Name: overridesFileFlag,
Value: gen.DefaultOverridesFile,
Usage: "File to read global type overrides from.",
},
&cli.BoolFlag{
Name: parseGoListFlag,
Value: true,
Usage: "Parse dependency via 'go list'",
},
&cli.StringFlag{
Name: parseExtensionFlag,
Value: "",
Usage: "Parse only those operations that match given extension",
},
&cli.StringFlag{
Name: tagsFlag,
Aliases: []string{"t"},
Value: "",
Usage: "A comma-separated list of tags to filter the APIs for which the documentation is generated.Special case if the tag is prefixed with the '!' character then the APIs with that tag will be excluded",
},
&cli.StringFlag{
Name: templateDelimsFlag,
Aliases: []string{"td"},
Value: "",
Usage: "Provide custom delimeters for Go template generation. The format is leftDelim,rightDelim. For example: \"[[,]]\"",
},
&cli.StringFlag{
Name: packageName,
Value: "",
Usage: "A package name of docs.go, using output directory name by default (check `--output` option)",
},
&cli.StringFlag{
Name: collectionFormatFlag,
Aliases: []string{"cf"},
Value: "csv",
Usage: "Set default collection format",
},
&cli.StringFlag{
Name: packagePrefixFlag,
Value: "",
Usage: "Parse only packages whose import path match the given prefix, comma separated",
},
&cli.StringFlag{
Name: stateFlag,
Value: "",
Usage: "Set host state for swagger.json",
},
}

func initAction(ctx *cli.Context) error {
strategy := ctx.String(propertyStrategyFlag)

switch strategy {
case swag.CamelCase, swag.SnakeCase, swag.PascalCase:
default:
return fmt.Errorf("not supported %s propertyStrategy", strategy)
}

leftDelim, rightDelim := "{{", "}}"

if ctx.IsSet(templateDelimsFlag) {
delims := strings.Split(ctx.String(templateDelimsFlag), ",")
if len(delims) != 2 {
return fmt.Errorf("exactly two template delimeters must be provided, comma separated")
} else if delims[0] == delims[1] {
return fmt.Errorf("template delimiters must be different")
}
leftDelim, rightDelim = strings.TrimSpace(delims[0]), strings.TrimSpace(delims[1])
}

outputTypes := strings.Split(ctx.String(outputTypesFlag), ",")
if len(outputTypes) == 0 {
return fmt.Errorf("no output types specified")
}
logger := log.New(os.Stdout, "", log.LstdFlags)
if ctx.Bool(quietFlag) {
logger = log.New(io.Discard, "", log.LstdFlags)
}

collectionFormat := swag.TransToValidCollectionFormat(ctx.String(collectionFormatFlag))
if collectionFormat == "" {
return fmt.Errorf("not supported %s collectionFormat", ctx.String(collectionFormat))
}

var pdv = ctx.Int(parseDependencyLevelFlag)
if pdv == 0 {
if ctx.Bool(parseDependencyFlag) {
pdv = 1
}
}
return gen.New().Build(&gen.Config{
SearchDir: ctx.String(searchDirFlag),
Excludes: ctx.String(excludeFlag),
ParseExtension: ctx.String(parseExtensionFlag),
MainAPIFile: ctx.String(generalInfoFlag),
PropNamingStrategy: strategy,
OutputDir: ctx.String(outputFlag),
OutputTypes: outputTypes,
ParseVendor: ctx.Bool(parseVendorFlag),
ParseDependency: pdv,
MarkdownFilesDir: ctx.String(markdownFilesFlag),
ParseInternal: ctx.Bool(parseInternalFlag),
GeneratedTime: ctx.Bool(generatedTimeFlag),
RequiredByDefault: ctx.Bool(requiredByDefaultFlag),
CodeExampleFilesDir: ctx.String(codeExampleFilesFlag),
ParseDepth: ctx.Int(parseDepthFlag),
InstanceName: ctx.String(instanceNameFlag),
OverridesFile: ctx.String(overridesFileFlag),
ParseGoList: ctx.Bool(parseGoListFlag),
Tags: ctx.String(tagsFlag),
LeftTemplateDelim: leftDelim,
RightTemplateDelim: rightDelim,
PackageName: ctx.String(packageName),
Debugger: logger,
CollectionFormat: collectionFormat,
PackagePrefix: ctx.String(packagePrefixFlag),
})
}

func main() {
app := cli.NewApp()
app.Version = swag.Version
app.Usage = "Automatically generate RESTful API documentation with Swagger 2.0 for Go."
app.Commands = []*cli.Command{
{
Name: "init",
Aliases: []string{"i"},
Usage: "Create docs.go",
Action: initAction,
Flags: initFlags,
},
{
Name: "fmt",
Aliases: []string{"f"},
Usage: "format swag comments",
Action: func(c *cli.Context) error {
searchDir := c.String(searchDirFlag)
excludeDir := c.String(excludeFlag)
mainFile := c.String(generalInfoFlag)

return format.New().Build(&format.Config{
SearchDir: searchDir,
Excludes: excludeDir,
MainFile: mainFile,
})
},
Flags: []cli.Flag{
&cli.StringFlag{
Name: searchDirFlag,
Aliases: []string{"d"},
Value: "./",
Usage: "Directories you want to parse,comma separated and general-info file must be in the first one",
},
&cli.StringFlag{
Name: excludeFlag,
Usage: "Exclude directories and files when searching, comma separated",
},
&cli.StringFlag{
Name: generalInfoFlag,
Aliases: []string{"g"},
Value: "main.go",
Usage: "Go file path in which 'swagger general API Info' is written",
},
},
},
}

if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
67 changes: 67 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
module smart-doc-go

go 1.21

require github.com/go-swagger/go-swagger v0.30.5

require (
github.com/KyleBanks/depth v1.2.1 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.0 // indirect
github.com/Masterminds/sprig/v3 v3.2.3 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-openapi/analysis v0.21.4 // indirect
github.com/go-openapi/errors v0.20.4 // indirect
github.com/go-openapi/inflect v0.19.0 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/loads v0.21.2 // indirect
github.com/go-openapi/runtime v0.26.0 // indirect
github.com/go-openapi/spec v0.20.9 // indirect
github.com/go-openapi/strfmt v0.21.7 // indirect
github.com/go-openapi/swag v0.22.4 // indirect
github.com/go-openapi/validate v0.22.1 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/gorilla/handlers v1.5.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/huandu/xstrings v1.3.3 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/jessevdk/go-flags v1.5.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/oklog/ulid v1.3.1 // indirect
github.com/pelletier/go-toml/v2 v2.0.8 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/rogpeppe/go-internal v1.9.0 // indirect
github.com/russross/blackfriday/v2 v2.0.1 // indirect
github.com/shopspring/decimal v1.2.0 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.16.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
github.com/swaggo/swag v1.16.2 // indirect
github.com/toqueteos/webbrowser v1.2.0 // indirect
github.com/urfave/cli/v2 v2.3.0 // indirect
go.mongodb.org/mongo-driver v1.11.3 // indirect
golang.org/x/crypto v0.9.0 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.9.0 // indirect
golang.org/x/tools v0.9.3 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
Loading