gitee.com/mirrors/Hugo-Go@v0.47.1/commands/gendocshelper.go (about)

     1  // Copyright 2017-present The Hugo Authors. All rights reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  // http://www.apache.org/licenses/LICENSE-2.0
     7  //
     8  // Unless required by applicable law or agreed to in writing, software
     9  // distributed under the License is distributed on an "AS IS" BASIS,
    10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package commands
    15  
    16  import (
    17  	"encoding/json"
    18  	"fmt"
    19  	"os"
    20  	"path/filepath"
    21  
    22  	"github.com/gohugoio/hugo/docshelper"
    23  	"github.com/spf13/cobra"
    24  )
    25  
    26  var (
    27  	_ cmder = (*genDocsHelper)(nil)
    28  )
    29  
    30  type genDocsHelper struct {
    31  	target string
    32  	*baseCmd
    33  }
    34  
    35  func createGenDocsHelper() *genDocsHelper {
    36  	g := &genDocsHelper{
    37  		baseCmd: newBaseCmd(&cobra.Command{
    38  			Use:    "docshelper",
    39  			Short:  "Generate some data files for the Hugo docs.",
    40  			Hidden: true,
    41  		}),
    42  	}
    43  
    44  	g.cmd.RunE = func(cmd *cobra.Command, args []string) error {
    45  		return g.generate()
    46  	}
    47  
    48  	g.cmd.PersistentFlags().StringVarP(&g.target, "dir", "", "docs/data", "data dir")
    49  
    50  	return g
    51  }
    52  
    53  func (g *genDocsHelper) generate() error {
    54  	fmt.Println("Generate docs data to", g.target)
    55  
    56  	targetFile := filepath.Join(g.target, "docs.json")
    57  
    58  	f, err := os.Create(targetFile)
    59  	if err != nil {
    60  		return err
    61  	}
    62  	defer f.Close()
    63  
    64  	enc := json.NewEncoder(f)
    65  	enc.SetIndent("", "  ")
    66  
    67  	if err := enc.Encode(docshelper.DocProviders); err != nil {
    68  		return err
    69  	}
    70  
    71  	fmt.Println("Done!")
    72  	return nil
    73  
    74  }