commands

package
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 19, 2025 License: AGPL-3.0 Imports: 21 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var CheckCmd = &cobra.Command{
	Use:           "check <path>",
	Aliases:       []string{"ch", "c", "verify"},
	Short:         "check if config is valid",
	Long:          "Check if your current config is valid",
	Args:          cobra.MaximumNArgs(1),
	SilenceErrors: true,
	SilenceUsage:  true,
	RunE: func(cmd *cobra.Command, args []string) error {
		var filePath string
		if len(args) == 1 {
			filePath = args[0]
		} else {
			filePath = "."
		}

		log.Debugf("checking if %s is a valid template\n", filePath)
		if _, _, err := template.ParseConfig(filePath); err != nil {
			return errors.ToWakuError(err)
		}

		log.Println("Seems ok!")
		return nil
	},
}
View Source
var HealthcheckCmd = &cobra.Command{
	Use:           "healthcheck",
	Aliases:       []string{"health"},
	Args:          cobra.NoArgs,
	SilenceUsage:  true,
	SilenceErrors: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		ok, err := git.HasGit()
		if err != nil {
			return errors.ToWakuError(err)
		}

		if !ok {
			log.Warnln("Git not found in $PATH, Waku will fallback to go-git. Authentication may not work as expected.")
		}

		return nil
	},
}
View Source
var NewCmd = &cobra.Command{
	Use:           "new",
	Aliases:       []string{"init"},
	Short:         "create a new project",
	Long:          "Create a new project from a template",
	SilenceErrors: true,
	SilenceUsage:  true,
	PreRunE: func(cmd *cobra.Command, args []string) error {
		return options.NewOpts.Validate()
	},
	RunE: func(cmd *cobra.Command, args []string) error {
		var name string
		var projectRootDir string
		var license license.License

		initialPrompts := make([]*huh.Group, 0, 2)
		err := ui.RunWithSpinner("setting things up...", func() error {
			log.Debugln("creating name and license prompts...")
			namePrompt := template.PromptForProjectName(&name, &projectRootDir)
			licenseSelect, err := template.PromptForLicense(&license)
			if err != nil {
				return errors.ToWakuError(err)
			}

			if namePrompt != nil {
				initialPrompts = append(initialPrompts, huh.NewGroup(namePrompt))
			}
			if licenseSelect != nil {
				initialPrompts = append(initialPrompts, huh.NewGroup(licenseSelect))
			}

			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		log.Debugln("running prompts...")
		if err := huh.NewForm(initialPrompts...).WithAccessible(options.GlobalOpts.Accessible).Run(); err != nil {
			return errors.ToWakuError(err)
		}

		err = ui.RunWithSpinner(fmt.Sprintf("creating project at '%s'...", projectRootDir), func() error {
			if err := os.Mkdir(projectRootDir, utils.DirPerms); err != nil {
				return err
			}

			cleanup.ScheduleError(func() error {
				log.Debugf("removing project dir: %s\n", projectRootDir)
				if err := os.RemoveAll(projectRootDir); err != nil {
					return errors.NewWakuErrorf("failed to cleanup project dir: %v", err)
				}
				return nil
			})

			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		// Clone repo
		var rootDir string
		var tmpDir string
		err = ui.RunWithSpinner("retrieving template...", func() error {
			_tmpDir, err := options.NewOpts.GetSource()
			if err != nil {
				return nil
			}
			tmpDir = _tmpDir

			rootDir = tmpDir
			if options.NewOpts.Directory.Value() != "" {
				rootDir = filepath.Join(tmpDir, options.NewOpts.Directory.Value())
				log.Debugf("resolved directory to: %s\n", rootDir)

				ok, err := utils.IsDir(rootDir)
				if err != nil {
					return err
				}
				if !ok {
					return errors.NewWakuErrorf("directory '%s' does not exist", options.NewOpts.Directory.Value())
				}
			}

			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		// Parse template.json
		var configFilePath string
		var wakuTemplate *config.TemplateJson

		err = ui.RunWithSpinner("parsing waku config...", func() error {
			configFilePath, wakuTemplate, err = template.ParseConfig(rootDir)
			if err != nil {
				return err
			}

			return err
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		styleDir, styleInfo, prompts, err := resolveTemplateStylePrompts(wakuTemplate, rootDir)
		if err != nil {
			return errors.ToWakuError(err)
		}

		var licenseText string
		licenseTmpl := make(map[string]string, len(license.Wants))
		err = ui.RunWithSpinner("resolving license...", func() error {
			licenseText, err = license.GetLicenseText()
			if err != nil {
				return errors.NewWakuErrorf("failed to get license text: %v\n", err)
			}

			for _, v := range license.Wants {
				licenseTmpl[v] = fmt.Sprintf("Value for license %s?", v)
				delete(prompts, v)
			}

			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}
		log.Debugf("resolved prompts to: %v\n", prompts)

		stylePromptGroups := make([]*huh.Group, 0, len(prompts))
		finalTemplateData := make(map[string]any, len(prompts)+len(licenseTmpl))

		err = ui.RunWithSpinner("collecting prompts...", func() error {
			for _, v := range prompts {
				stylePromptGroups = append(stylePromptGroups, huh.NewGroup(v.GetPrompt(finalTemplateData)))
			}
			for n, v := range licenseTmpl {
				stylePromptGroups = append(stylePromptGroups, huh.NewGroup(huh.NewText().Title(v).Validate(func(s string) error {
					s = strings.TrimSpace(s)
					if s == "" {
						return fmt.Errorf("cannot be empty")
					}

					licenseTmpl[n] = s
					finalTemplateData[n] = s
					return nil
				})))
			}
			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		log.Debugf("resolved prompt groups to: %v\n", stylePromptGroups)
		if err := huh.NewForm(stylePromptGroups...).WithAccessible(options.GlobalOpts.Accessible).Run(); err != nil {
			return errors.ToWakuError(err)
		}

		// Get file paths
		var styleFilePaths []string
		var configRelPath string
		err = ui.RunWithSpinner("collecting files...", func() error {
			styleFilePaths, err = utils.WalkDirRecursive(styleDir)
			if err != nil {
				return err
			}
			log.Debugf("resolved file paths in style: %v\n", styleFilePaths)

			configRelPath, err = filepath.Rel(tmpDir, configFilePath)
			if err != nil {
				return err
			}
			log.Debugf("resolved config rel path to: %s\n", configRelPath)

			return err
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		// Handle ignores
		var filePathsToWrite types.Set[string]
		err = ui.RunWithSpinner("filtering files...", func() error {
			log.Infoln("applying ignore rules...")
			ignoreRules := types.NewSet(
				".git/",
				"LICENSE*",
				configRelPath,
			)
			if wakuTemplate.Ignore != nil {
				ignoreRules.Union(types.Set[string](*wakuTemplate.Ignore))
			}
			if wakuTemplate.Setup != nil {
				ignoreRules.Add(wakuTemplate.Setup.Any)
				ignoreRules.Add(wakuTemplate.Setup.Linux)
				ignoreRules.Add(wakuTemplate.Setup.Darwin)
				ignoreRules.Add(wakuTemplate.Setup.Windows)
			}
			if wakuTemplate.Styles != nil && styleInfo.Ignore != nil {
				ignoreRules.Union(types.Set[string](*styleInfo.Ignore))

				if styleInfo.Setup != nil {
					ignoreRules.Add(styleInfo.Setup.Any)
					ignoreRules.Add(styleInfo.Setup.Linux)
					ignoreRules.Add(styleInfo.Setup.Darwin)
					ignoreRules.Add(styleInfo.Setup.Windows)
				}
			}

			ignoreRules = template.ResolveGlobs(ignoreRules, types.NewSet(".git/", "LICENSE"))
			log.Debugf("ignore rules applied: %v\n", ignoreRules)

			filePathsToWrite = template.ResolveGlobs(types.NewSet(styleFilePaths...), ignoreRules)
			log.Debugf("resolved files to write: %v\n", filePathsToWrite)

			return nil
		})
		if err != nil {
			return errors.ToWakuError(err)
		}

		err = ui.RunWithSpinner("writing files...", func() error {
			finalTemplateData["Name"] = name
			finalTemplateData["License"] = license.Name
			finalTemplateData["Spdx"] = license.Spdx
			log.Debugf("final template data: %v\n", finalTemplateData)

			return WriteFiles(styleDir, projectRootDir, filePathsToWrite.ToSlice(), licenseText, finalTemplateData, licenseTmpl)
		})
		if err != nil {
			return errors.NewWakuErrorf("failed to write files: %s\n", err)
		}

		if options.NewOpts.NoGit {
			log.Infoln("skipping git initialization")
			return nil
		}

		err = ui.RunWithSpinner("initializing git...", func() error {
			return git.Init(projectRootDir)
		})
		if err != nil {
			fmt.Printf("failed to initialize git: %s\n", err)
			return errors.NewWakuErrorf("failed to initialize git: %s\n", err)
		}

		return nil
	},
}
View Source
var NewRepoCmd = &cobra.Command{
	Use:           "repo",
	Aliases:       []string{"repository", "project"},
	SilenceErrors: true,
	SilenceUsage:  true,
	Short:         NewCmd.Short,
	Long:          NewCmd.Long,
	PreRunE:       NewCmd.PreRunE,
	Run:           NewCmd.Run,
}
View Source
var VersionCmd = &cobra.Command{
	Use:           "version",
	Aliases:       []string{"ver"},
	Short:         "show version",
	Long:          "Show version of waku",
	SilenceErrors: true,
	SilenceUsage:  true,
	Run: func(cmd *cobra.Command, args []string) {
		log.Println(version.Version)
	},
}

Functions

func AddNewCmdFlags

func AddNewCmdFlags(cmd *cobra.Command)

func InitCommands

func InitCommands(root *cobra.Command)

To initialize all the commands as subcommands of root

func WriteFiles

func WriteFiles(tmpRoot, projectRoot string, paths []string, licenseText string, tmpl map[string]any, licenseTmpl map[string]string) error

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL