codemod

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2025 License: MIT Imports: 10 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package codemod provides the command to apply code modifications.

Index

Constants

This section is empty.

Variables

View Source
var CodemodCmd = &cobra.Command{
	Use: "codemod [--script <file.json>]",
	Example: `  contextvibes product codemod # Looks for codemod.json
  contextvibes product codemod --script ./my_refactor_script.json`,
	Args: cobra.NoArgs,
	RunE: func(cmd *cobra.Command, _ []string) error {
		presenter := ui.NewPresenter(cmd.OutOrStdout(), cmd.ErrOrStderr())

		scriptToLoad := codemodScriptPath
		if scriptToLoad == "" {
			scriptToLoad = "codemod.json"
		}

		scriptData, err := os.ReadFile(scriptToLoad)
		if err != nil {
			return fmt.Errorf("failed to read codemod script '%s': %w", scriptToLoad, err)
		}

		var script codemod.ChangeScript
		err = json.Unmarshal(scriptData, &script)
		if err != nil {
			return fmt.Errorf("failed to parse codemod script JSON: %w", err)
		}

		for _, fileChangeSet := range script {
			presenter.Header("Processing target: %s", fileChangeSet.FilePath)

			contentBytes, err := os.ReadFile(fileChangeSet.FilePath)
			if err != nil && !os.IsNotExist(err) {
				return fmt.Errorf("failed to read target file: %w", err)
			}
			currentContent := string(contentBytes)

			for _, op := range fileChangeSet.Operations {
				switch op.Type {
				case "regex_replace":
					re, err := regexp.Compile(op.FindRegex)
					if err != nil {
						return fmt.Errorf("invalid regex '%s': %w", op.FindRegex, err)
					}
					currentContent = re.ReplaceAllString(currentContent, op.ReplaceWith)

				}
			}

			if !globals.AssumeYes {
				confirmed, err := presenter.PromptForConfirmation(
					fmt.Sprintf("Write changes to %s?", fileChangeSet.FilePath),
				)
				if err != nil || !confirmed {
					continue
				}
			}

			err = os.WriteFile(fileChangeSet.FilePath, []byte(currentContent), 0o600)
			if err != nil {
				return fmt.Errorf("failed to write file: %w", err)
			}
			globals.AppLogger.Info("Applied codemod", "file", fileChangeSet.FilePath)
		}

		return nil
	},
}

CodemodCmd represents the codemod command.

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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