github.com/exercism/v2-configlet@v3.9.2+incompatible/cmd/generate.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/exercism/configlet/track" 10 "github.com/exercism/configlet/ui" 11 "github.com/hashicorp/go-multierror" 12 "github.com/spf13/cobra" 13 ) 14 15 var ( 16 genSlug string 17 specPath string 18 ) 19 20 var ( 21 // generateCmd represents the generate command 22 generateCmd = &cobra.Command{ 23 Use: "generate " + pathExample, 24 Short: "Generate exercise READMEs for an Exercism language track", 25 Long: `Generate READMEs for Exercism exercises based on the contents of various files.`, 26 Example: generateExampleText(), 27 Run: runGenerate, 28 Args: cobra.ExactArgs(1), 29 } 30 ) 31 32 func generateExampleText() string { 33 cmds := []string{ 34 "%[1]s generate %[2]s --only <exercise>", 35 "%[1]s generate %[2]s --spec-path <path/to/problem-specifications>", 36 } 37 s := " " + strings.Join(cmds, "\n\n ") 38 return fmt.Sprintf(s, binaryName, pathExample) 39 } 40 41 func runGenerate(cmd *cobra.Command, args []string) { 42 path, err := filepath.Abs(filepath.FromSlash(args[0])) 43 if err != nil { 44 ui.PrintError(err.Error()) 45 os.Exit(1) 46 } 47 root := filepath.Dir(path) 48 trackID := filepath.Base(path) 49 50 track.ProblemSpecificationsPath = filepath.Join(root, track.ProblemSpecificationsDir) 51 if specPath != "" { 52 track.ProblemSpecificationsPath = specPath 53 } 54 55 if _, err := os.Stat(track.ProblemSpecificationsPath); os.IsNotExist(err) { 56 ui.PrintError("path not found:", track.ProblemSpecificationsPath) 57 os.Exit(1) 58 } 59 60 var exercises []track.Exercise 61 if genSlug != "" { 62 exercises = append(exercises, track.Exercise{Slug: genSlug}) 63 } else { 64 track, err := track.New(path) 65 if err != nil { 66 ui.PrintError(err.Error()) 67 os.Exit(1) 68 } 69 exercises = track.Exercises 70 } 71 72 errs := &multierror.Error{} 73 for _, exercise := range exercises { 74 readme, err := track.NewExerciseReadme(root, trackID, exercise.Slug) 75 if err != nil { 76 errs = multierror.Append(errs, err) 77 continue 78 } 79 80 if err := readme.Write(); err != nil { 81 errs = multierror.Append(errs, err) 82 } 83 } 84 85 if err := errs.ErrorOrNil(); err != nil { 86 ui.PrintError(err.Error()) 87 os.Exit(1) 88 } 89 90 } 91 92 func init() { 93 RootCmd.AddCommand(generateCmd) 94 generateCmd.Flags().StringVarP(&genSlug, "only", "o", "", "Generate READMEs for just the exercise specified (by the slug).") 95 generateCmd.Flags().StringVarP(&specPath, "spec-path", "p", "", "The location of the problem-specifications directory.") 96 }