Skip to content
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

Refactor docgen: improve error handling and file operations #6103

Merged
merged 2 commits into from
Mar 24, 2025
Merged
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
55 changes: 30 additions & 25 deletions cmd/docgen/docgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,53 +6,58 @@ import (
"os"
"reflect"
"regexp"
"strings"

"github.com/invopop/jsonschema"

"github.com/projectdiscovery/nuclei/v3/pkg/templates"
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
)

var pathRegex = regexp.MustCompile(`github\.com/projectdiscovery/nuclei/v3/(?:internal|pkg)/(?:.*/)?([A-Za-z.]+)`)

func main() {
// Generate yaml syntax documentation
data, err := templates.GetTemplateDoc().Encode()
func writeToFile(filename string, data []byte) {
file, err := os.Create(filename)
if err != nil {
log.Fatalf("Could not encode docs: %s\n", err)
log.Fatalf("Could not create file %s: %s\n", filename, err)
}
defer file.Close()

_, err = file.Write(data)
if err != nil {
log.Fatalf("Could not write to file %s: %s\n", filename, err)
}
}

func main() {
if len(os.Args) < 3 {
log.Fatalf("syntax: %s md-docs-file jsonschema-file\n", os.Args[0])
}

err = os.WriteFile(os.Args[1], data, 0644)
// Generate YAML documentation
data, err := templates.GetTemplateDoc().Encode()
if err != nil {
log.Fatalf("Could not write docs: %s\n", err)
log.Fatalf("Could not encode docs: %s\n", err)
}

// Generate jsonschema
r := &jsonschema.Reflector{}
r.Namer = func(r reflect.Type) string {
if r.Kind() == reflect.Slice {
return ""
}
return r.String()
writeToFile(os.Args[1], data)

// Generate JSON Schema
r := &jsonschema.Reflector{
Namer: func(t reflect.Type) string {
if t.Kind() == reflect.Slice {
return ""
}
return t.String()
},
}

jsonschemaData := r.Reflect(&templates.Template{})

var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetIndent("", " ")
_ = encoder.Encode(jsonschemaData)

schema := buf.String()
for _, match := range pathRegex.FindAllStringSubmatch(schema, -1) {
schema = strings.ReplaceAll(schema, match[0], match[1])
}
err = os.WriteFile(os.Args[2], []byte(schema), 0644)
if err != nil {
log.Fatalf("Could not write jsonschema: %s\n", err)
if err := encoder.Encode(jsonschemaData); err != nil {
log.Fatalf("Could not encode JSON schema: %s\n", err)
}

schema := pathRegex.ReplaceAllString(buf.String(), "$1")
writeToFile(os.Args[2], []byte(schema))
}
Loading