fscmd

package
v0.0.0-...-a91fe3a Latest Latest
Warning

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

Go to latest
Published: Sep 14, 2024 License: MIT Imports: 36 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DeleteCmd = &gcli.Command{
	Name:    "delete",
	Desc:    "delete files by glob pattern",
	Aliases: []string{"del", "rm"},
	Config: func(c *gcli.Command) {

	},
	Func: func(c *gcli.Command, _ []string) error {
		colorp.Infoln("TIP: please use the: kite fs find command with option '--del' to delete find files")
		return nil
	},
}

DeleteCmd instance

View Source
var FileFindCmd = &gcli.Command{
	Name:    "find",
	Desc:    "find files by match name or pattern, and support match contents",
	Aliases: []string{"glob", "search", "match"},
	Help: `
<cyan>### Mtime, Atime format</>:
  10m/<10m                    last 10 minutes
  >10m                        before 10 minutes
  1h/1hour/<1hour             last 1 hour
  1d/<1d/<24h                 last 1 day(24h)
  today                       today(00:00-24:00)
  yesterday                   yesterday(00:00-24:00)
  >24h              		  before yesterday
  >2d                         before 2 days
  // time range limit
  1h~10m                      last 1 hour to 10 minutes
  1d~1h                       last 1 day to 1 hour
  5h~1h                       last 5 hours to 1 hour

<cyan>### Variables in exec</>:
 {path} 	the file/dir path
 {name} 	the file/dir path name
 {dir}   	the directory path for {path}
`,
	Examples: `
# find files and run command
{$fullCmd} -t file --name "*.go" -x "cat {file}" .

# find and delete files
{$fullCmd} -t file --name "test,doc,[t|T]ests,[d|D]ocs" --del .

# list sub dirs and run command
{$fullCmd} -t dir --nr -x "ls -l {dir}" .
`,
	Config: func(c *gcli.Command) {
		ffOpts.BindWorkdirDryRun(c)
		c.MustFromStruct(&ffOpts, gflag.TagRuleNamed)
		c.AddArg("dirs", "the find directory, multi by comma or multi input. same as <mga>--dirs</>").
			SetArrayed().
			WithAfterFn(func(a *gflag.CliArg) error {
				ffOpts.dirs = a.Strings()
				return nil
			})
	},
	Func: func(c *gcli.Command, _ []string) error {
		if ffOpts.Dirs != "" {
			ffOpts.dirs = strutil.SplitValid(ffOpts.Dirs, ",")
		}
		if len(ffOpts.dirs) == 0 {
			return fmt.Errorf("please input find directory")
		}

		ff := buildFinder()

		if ffOpts.Verb {
			show.AList("Configuration:", ff.Config())

		}

		if !ffOpts.Clear {
			colorp.Warnln("Finding and results:")
		}

		st := time.Now()
		spl := textutil.NewVarReplacer("{,}")
		ers := errorx.Errors{}

		var old, nw []byte
		if ffOpts.Replace != "" {
			old, nw = byteutil.SafeCut([]byte(ffOpts.Replace), '/')
			colorp.Infof("Will replace contents: %q -> %q\n", old, nw)
		}

		ff.EachElem(func(el finder.Elem) {
			elPath := el.Path()
			if ffOpts.Clear {
				fmt.Println(elPath)
				return
			}

			if ffOpts.Delete {
				colorp.Warnf("Delete path: %s\n", elPath)
				if ffOpts.DryRun {
					colorp.Infoln("Dry run, skip delete")
				} else if err := os.RemoveAll(elPath); err != nil {
					ers = append(ers, err)
				}
				return
			}

			if ffOpts.Replace != "" {
				if ffOpts.DryRun {
					colorp.Infoln("Dry run replace contents")
				} else {
					colorp.Infof("Replace contents for: %s\n", elPath)
					err := fsutil.UpdateContents(elPath, func(bs []byte) []byte {
						return bytes.Replace(bs, old, nw, -1)
					})
					if err != nil {
						ers = append(ers, err)
					}
				}
				return
			}

			if ffOpts.Exec == "" {
				fmt.Println(el)
				return
			}

			vs := map[string]string{
				"path": elPath,
				"name": el.Name(),
				"dir":  fsutil.Dir(elPath),
			}

			execCmd := cmdr.NewCmdline(spl.RenderSimple(ffOpts.Exec, vs)).
				WithWorkDir(ffOpts.Workdir).
				WithDryRun(ffOpts.DryRun).
				OutputToOS().
				PrintCmdline()

			if err := execCmd.Run(); err != nil {
				ers = append(ers, err)
			}
		})

		if ffOpts.Clear {
			return ff.Err()
		}

		if ff.Num() > 0 {
			colorp.Successf("Total found %d paths, elapsed time: %s\n", ff.Num(), timex.ElapsedNow(st))
		} else {
			colorp.Infoln("... Not found any paths")
		}
		return ff.Err()
	},
}

FileFindCmd command

View Source
var FsCmd = &gcli.Command{
	Name:    "fs",
	Aliases: []string{"file"},
	Desc:    "provide some useful file system commands",
	Subs: []*gcli.Command{
		FileFindCmd,
		ListFilesCmd,
		DeleteCmd,
		RenameCmd,
		NewFileCatCmd(),
		NewReplaceCmd(),
		NewTemplateCmd(),
		convcmd.NewConvPathSepCmd(),
	},
}

FsCmd command

View Source
var ListFilesCmd = &gcli.Command{
	Name:    "ls",
	Aliases: []string{"list"},
	Desc:    "list files or dirs like `ls` command",
	Config: func(c *gcli.Command) {
		c.MustFromStruct(&lfOpt)
	},
	Func: func(c *gcli.Command, _ []string) error {
		return errors.New("TODO")
	},
}

ListFilesCmd instance

View Source
var RenameCmd = &gcli.Command{
	Name: "rename",
	Desc: "rename files by glob or regexp pattern",
	Config: func(c *gcli.Command) {

	},
	Func: func(c *gcli.Command, _ []string) error {
		colorp.Infoln("TIP: please use the: kite fs find command with option '--exec' to rename find files")
		return nil
	},
}

RenameCmd instance

Functions

func FileWatcher

func FileWatcher(handler func(event fsnotify.Event)) *gcli.Command

FileWatcher command definition

func NewFileCatCmd

func NewFileCatCmd() *gcli.Command

NewFileCatCmd instance

func NewRenderMultiCmd

func NewRenderMultiCmd() *gcli.Command

NewRenderMultiCmd create a command

func NewReplaceCmd

func NewReplaceCmd() *gcli.Command

NewReplaceCmd create a command

func NewTemplateCmd

func NewTemplateCmd() *gcli.Command

NewTemplateCmd instance

Types

type MultiRenderOpt

type MultiRenderOpt struct {
	VarFmt  string         `flag:"desc=custom sets the variable format in template;shorts=vf;default={{,}}"`
	VarFile string         `flag:"desc=custom sets the variables file path. eg: --var-file tpl-vars.json"`
	Vars    gflag.KVString `flag:"desc=set template vars. allow multi, like: --vars name=Tom -v age=18;shorts=v"`

	// dir for template files
	Dir   string       `flag:"desc=the directory for find and render template files;shorts=d"`
	Exts  string       `flag:"desc=want render template files exts. multi by comma, like: .go,.md;shorts=ext"`
	Files gflag.String `flag:"desc=the template files. multi by comma, like: file1.tpl,file2.tpl;shorts=f"`

	// Include and Exclude match template files.
	// eg: --include name:*.go --exclude name:*_test.go
	Include gcli.Strings `flag:"desc=the include files rules;shorts=i,add"`
	Exclude gcli.Strings `flag:"desc=the exclude files rules;shorts=e,not"`

	Write bool `flag:"desc=write result to src file;shorts=w"`
	// contains filtered or unexported fields
}

MultiRenderOpt options

func (*MultiRenderOpt) RenderFile

func (o *MultiRenderOpt) RenderFile(fPath string) error

RenderFile render a template file

type RenderFn

type RenderFn func(src string, vars map[string]any) string

Jump to

Keyboard shortcuts

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