package main import ( "errors" "flag" "fmt" "os" "os/exec" "strings" "text/template" "time" ) type LicensingData struct { ProgramName string AuthorName string AuthorEmail string Year int } func getGitUser() (string, string, error) { var userData [2]string for i, v := range []string{"user.name", "user.email"} { cmd := exec.Command("git", "config", "--get", v) out, err := cmd.Output() if err != nil { return "", "", errors.New("Can't read Git config") } userData[i] = strings.TrimSpace(string(out)) } return userData[0], userData[1], nil } func getLicenseList() []string { d, err := os.Open("templates") if err != nil { panic(err) } files, err := d.Readdir(0) if err != nil { panic(err) } var lcnsList []string for _, v := range files { lcnsList = append(lcnsList, strings.Replace(v.Name(), ".template", "", 1)) } return lcnsList } func main() { OutputFile := flag.String("output", "LICENSE", "Specify different output file") License := flag.String("license", "", "Choose a license") ProgramName := flag.String("program", "", "Choose a program name") authorName := flag.String("name", "", "Set the author name") authorEmail := flag.String("email", "", "Set the author email") ListTemplates := flag.Bool("list", false, "List available licenses") flag.Parse() if *ListTemplates { fmt.Println(strings.Join(getLicenseList(), ", ")) return } if *License == "" { fmt.Printf( "Error: No license specified\n\nUse --license LICENSE\n\nAvailable licenses:\n%s\n", strings.Join(getLicenseList(), ", "), ) return } tmplFile := "templates/" + *License + ".template" tmpl, err := template.ParseFiles(tmplFile) if err != nil { fmt.Printf("Error: There is no '%s' license\n", *License) return } if *authorName == "" || *authorEmail == "" { *authorName, *authorEmail, err = getGitUser() if err != nil { fmt.Printf( "Error: Can't read Git config.\n\nUse --name \"NAME\" and --email EMAIL instead.\n", ) return } } licenseData := LicensingData{ ProgramName: *ProgramName, AuthorName: *authorName, AuthorEmail: *authorEmail, Year: time.Now().Year(), } outFile, err := os.Create(*OutputFile) if err != nil { panic(err) } defer outFile.Close() err = tmpl.Execute(outFile, licenseData) if err != nil { panic(err) } }