From 7d13cabb6af8bf0db9fae7404115d1b267aaa8c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=B8=96=E7=95=8C?= Date: Tue, 28 Apr 2026 08:10:05 +0800 Subject: [PATCH] Preserve comments between formatting --- cmd/sing-box/cmd_format.go | 2 ++ option/options.go | 13 +++++++++++++ 2 files changed, 15 insertions(+) diff --git a/cmd/sing-box/cmd_format.go b/cmd/sing-box/cmd_format.go index ab59c9ae5..a8ecb6ab7 100644 --- a/cmd/sing-box/cmd_format.go +++ b/cmd/sing-box/cmd_format.go @@ -38,10 +38,12 @@ func format() error { return err } for _, optionsEntry := range optionsList { + comments := optionsEntry.options.Comments() optionsEntry.options, err = badjson.Omitempty(globalCtx, optionsEntry.options) if err != nil { return err } + optionsEntry.options.SetComments(comments) buffer := new(bytes.Buffer) encoder := json.NewEncoder(buffer) encoder.SetIndent("", " ") diff --git a/option/options.go b/option/options.go index 1b4685bac..4e87852ac 100644 --- a/option/options.go +++ b/option/options.go @@ -11,6 +11,7 @@ import ( type _Options struct { RawMessage json.RawMessage `json:"-"` + CommentsSet *json.CommentSet `json:"-"` Schema string `json:"$schema,omitempty"` Log *LogOptions `json:"log,omitempty"` DNS *DNSOptions `json:"dns,omitempty"` @@ -28,6 +29,10 @@ type _Options struct { type Options _Options +func (o Options) MarshalJSONContext(ctx context.Context) ([]byte, error) { + return json.MarshalContext(ctx, (_Options)(o)) +} + func (o *Options) UnmarshalJSONContext(ctx context.Context, content []byte) error { decoder := json.NewDecoderContext(ctx, bytes.NewReader(content)) decoder.DisallowUnknownFields() @@ -39,6 +44,14 @@ func (o *Options) UnmarshalJSONContext(ctx context.Context, content []byte) erro return checkOptions(o) } +func (o Options) Comments() *json.CommentSet { + return o.CommentsSet +} + +func (o *Options) SetComments(comments *json.CommentSet) { + o.CommentsSet = comments +} + type LogOptions struct { Disabled bool `json:"disabled,omitempty"` Level string `json:"level,omitempty"`