-
Notifications
You must be signed in to change notification settings - Fork 13
/
init.go
231 lines (198 loc) · 7 KB
/
init.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package cmd
import (
"context"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"text/template"
"time"
"github.com/hashicorp/copywrite/addlicense"
"github.com/hashicorp/copywrite/config"
"github.com/hashicorp/copywrite/github"
"github.com/jedib0t/go-pretty/v6/text"
"github.com/mattn/go-isatty"
"github.com/samber/lo"
"github.com/AlecAivazis/survey/v2"
"github.com/spf13/cobra"
)
var (
force bool
)
var initCmd = &cobra.Command{
Use: "init",
Short: "Generates a .copywrite.hcl config for a new project",
Long: `Generates a .copywrite.hcl config for a new project with helpful comments.
License type and copyright year are inferred from GitHub, and prompts are made
for any unknown values. If you are running this command in CI, please use the
--year and --spdx flags, as prompts are disabled when no TTY is present.`,
GroupID: "common", // Let's put this command in the common section of the help
PreRun: func(cmd *cobra.Command, args []string) {
// Validate we aren't going to write over an existing config
_, err := os.Stat(".copywrite.hcl")
if !errors.Is(err, os.ErrNotExist) && !force {
cobra.CheckErr(fmt.Errorf(".copywrite.hcl config already exists. If you wish to override it, use the `--force` flag"))
}
// Input Validation
spdx, err := cmd.Flags().GetString("spdx")
cobra.CheckErr(err)
// SPDX flag must either be an empty string _or_ a valid SPDX list option
if spdx != "" && !addlicense.ValidSPDX(spdx) {
err := fmt.Errorf("invalid SPDX license identifier: %s", spdx)
cobra.CheckErr(err)
}
},
Run: func(cmd *cobra.Command, args []string) {
// We create a new config object here to ensure any existing
// .copywrite.hcl does not influence the new configuration file
newConfig, err := config.New()
cobra.CheckErr(err)
// Map command flags to config keys
mapping := map[string]string{
`spdx`: `project.license`,
`year`: `project.copyright_year`,
}
// update the running config with any command-line flags
clobberWithDefaults := false
err = newConfig.LoadCommandFlags(cmd.Flags(), mapping, clobberWithDefaults)
cobra.CheckErr(err)
// Try to autodiscover license and year
if repo, err := github.DiscoverRepo(); err == nil {
client := github.NewGHClient().Raw()
data, _, err := client.Repositories.Get(context.Background(), repo.Owner, repo.Name)
if err == nil {
cobra.CheckErr(err)
// fall back to GitHub repo creation year if --year wasn't set
if !cmd.Flags().Changed("year") {
newConfig.Project.CopyrightYear = data.CreatedAt.Year()
}
// fall back to GitHub's reported SPDX identifier if --spdx wasn't set
if !cmd.Flags().Changed("spdx") {
license := data.GetLicense()
newConfig.Project.License = license.GetSPDXID()
}
}
}
// Let's prompt the user to validate the current values
if cmd.OutOrStdout() == os.Stdout && isatty.IsTerminal(os.Stdout.Fd()) {
err = promptForConfigValues(newConfig)
cobra.CheckErr(err)
} else {
cmd.Println("No TTY detected: if running in CI, use `--year` and `--spdx` flags to set values as needed")
}
// Render it out!
f, err := os.Create(".copywrite.hcl")
cobra.CheckErr(err)
defer f.Close()
err = configToHCL(*newConfig, f)
cobra.CheckErr(err)
successText := text.Color(text.FgGreen).Sprintf("✔️ A config has been successfully generated at: ./%s", f.Name())
cmd.Println(successText)
cmd.Println("Please commit this file to your repo")
},
}
func init() {
rootCmd.AddCommand(initCmd)
initCmd.Flags().BoolVarP(&force, "force", "f", false, "Overwrite an existing .copywrite.hcl file, if one exists")
// These flags will get mapped to keys in the the global Config
initCmd.Flags().IntP("year", "y", 0, "Year that the copyright statement should include")
initCmd.Flags().StringP("spdx", "s", "", "SPDX License Identifier indicating what the project should be licensed under")
}
// configToHCL takes in a Config object and writes an example HCL configuration,
// filling in the `project.license` and `project.copyright_year` keys, along
// with helpful comments. Any io.Writer interface is accepted, be it stdout
// or a file writer.
//
// Config keys other than license and copyright year are currently unsupported.
func configToHCL(c config.Config, wr io.Writer) error {
tmpl, err := template.New(".copywrite.hcl").Parse(`schema_version = {{.SchemaVersion}}
project {
license = "{{.Project.License}}"
copyright_year = {{.Project.CopyrightYear}}
# (OPTIONAL) A list of globs that should not have copyright/license headers.
# Supports doublestar glob patterns for more flexibility in defining which
# files or folders should be ignored
header_ignore = [
# "vendor/**",
# "**autogen**",
]
}
`)
if err != nil {
return err
}
err = tmpl.Execute(wr, c)
if err != nil {
return err
}
return nil
}
// promptForConfigValues takes in a pointer to a Config object and prompts the
// user to select or confirm selections for project license type (SPDX ID) and
// copyright year, which then get written back to the config object.
func promptForConfigValues(c *config.Config) error {
noLicenseText := "" // Copywrite uses an empty string to represent no license
currentLicense := strings.ToUpper(c.Project.License)
licenseOptions := lo.Uniq([]string{noLicenseText, currentLicense, "MPL-2.0", "MIT", "Apache-2.0"})
prompts := []*survey.Question{
{
Name: "License",
Prompt: &survey.Select{
Message: "Choose a license:",
Options: licenseOptions,
Default: currentLicense, // default to using the current license
Help: "HashiCorp defaults to using MPL-2.0 for public projects",
Description: func(value string, index int) string {
switch value {
case noLicenseText:
return "Proceed without a license"
// Current repo license is before MPL-2.0 intentionally for UX clarity
case c.Project.License:
return "Current Repo License"
case "MPL-2.0":
return "HashiCorp default for public repos"
default:
return ""
}
},
},
},
{
Name: "CopyrightYear",
Prompt: &survey.Input{
Message: "Choose a copyright year:",
Default: strconv.Itoa(c.Project.CopyrightYear),
Help: "HashiCorp defaults to the earlier of the repo creation year or when the project was first published",
},
Validate: func(val interface{}) error {
i, err := strconv.Atoi(val.(string))
if err != nil {
return fmt.Errorf("year must be a number")
}
// Let's do some minor sanity checking here
minYear := 1970
maxYear := time.Now().Year() + 1
if i < minYear || i > maxYear {
return fmt.Errorf("copyright year is expected to be between %v and %v", minYear, maxYear)
}
return nil
},
},
}
answers := struct {
License string `survey:"License"`
CopyrightYear int `survey:"CopyrightYear"`
}{}
// prompt the user
err := survey.Ask(prompts, &answers)
if err != nil {
return err
}
c.Project.License = answers.License
c.Project.CopyrightYear = answers.CopyrightYear
return nil
}