commands

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2024 License: Apache-2.0 Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FILE_NAME_MAX_SIZE int = 50

	UHD_ONLY           string = "only"
	UHD_INCLUDE        string = "include"
	UHD_NO             string = "no"
	URL_WWW_BINGIMG_CN string = "http://www.bingimg.cn/list%s"

	URL_BING_WDBYTE_COM string = "https://bing.wdbyte.com"
)

Variables

View Source
var BingImgCmd = &cobra.Command{
	Use:              "bingimg <page>",
	Short:            "下载 www.bingimg.cn 网站的壁纸",
	TraverseChildren: true,
	Args: func(cmd *cobra.Command, args []string) error {
		if err := cobra.ExactArgs(1)(cmd, args); err != nil {
			return err
		}
		if _, err := stringutils.MustGreaterThan(args[0], 1); err != nil {
			return fmt.Errorf("invalid arg 'page': %s", err)
		}
		uhd, _ := cmd.Flags().GetString("uhd")
		if err := stringutils.MustInStringChoises(uhd, UHD_CHOICES); err != nil {
			return fmt.Errorf("invalid flag 'uhd': %s", err)
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		uhd, _ := cmd.Flags().GetString("uhd")
		output, _ := cmd.Flags().GetString("output")
		endPage, _ := cmd.Flags().GetInt8("end-page")
		pageInt, _ := strconv.Atoi(args[0])
		page := int8(pageInt)
		if endPage <= 0 {
			endPage = page
		}
		for i := page; i <= endPage; i++ {
			bingImgDownload(i, uhd, output)
		}
	},
}
View Source
var BingImgWdbyteCmd = &cobra.Command{
	Use:              "bingimg-wdbyte",
	Short:            "下载 bing.wdbyte.com 网站的壁纸",
	TraverseChildren: true,
	Args: func(cmd *cobra.Command, args []string) error {
		if err := cobra.ExactArgs(0)(cmd, args); err != nil {
			return err
		}
		date, _ := cmd.Flags().GetString("date")
		if date != "" {
			if err := stringutils.MustMatch(date, "^[0-9]+-[0-9]+$"); err != nil {
				return fmt.Errorf("invalid flag 'date', %s", err)
			}
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		date, _ := cmd.Flags().GetString("date")
		output, _ := cmd.Flags().GetString("output")
		workers, _ := cmd.Flags().GetInt("workers")
		limit, _ := cmd.Flags().GetInt("limit")

		reqUrl := fmt.Sprintf("%s/%s", URL_BING_WDBYTE_COM, date)
		logging.Info("解析页面 %s", reqUrl)
		doc := httpLib.GetHtml(reqUrl)
		files := []httpLib.HttpFile{}
		doc.Find("a").Each(func(_ int, s *goquery.Selection) {
			href := s.AttrOr("href", "")
			if err := stringutils.MustMatch(href, `.*id=.+\.jpg`); err == nil {
				if limit > 0 && len(files) >= limit {
					return
				}
				urlParsed, _ := url.Parse(href)
				fileName := urlParsed.Query().Get("id")
				files = append(files, httpLib.HttpFile{Name: fileName, Url: href})
			}
		})
		if len(files) == 0 {
			logging.Warning("页面 %s 无图片链接", reqUrl)
			os.Exit(0)
		}
		type webFile struct {
			Name   string
			Size   int
			Result string
			Spend  time.Duration
		}
		webFiles := []webFile{}
		downloader := httpLib.HttpDownloader{Output: output}
		taskGroup := syncutils.TaskGroup{
			Items:        files,
			ShowProgress: true,
			MaxWorker:    workers,
			Func: func(item interface{}) error {
				file := item.(httpLib.HttpFile)
				startTime := time.Now()
				err := downloader.Download(&file)
				var result string
				if err != nil {
					logging.Error("下载失败: %s", file.Url)
					result = "😞"
				} else {
					logging.Info("下载完成: %s, Size: %d", file.Name, file.GetSize())
					result = "👌"
				}
				webFiles = append(webFiles, webFile{
					Name: file.Name, Size: file.GetSize(),
					Result: result,
					Spend:  time.Since(startTime),
				})
				return err
			},
		}
		logging.Info("开始下载(总数: %d), 保存路径: %s ...", len(files), output)
		taskGroup.Start()

		result, _ := table.NewItemsTable(
			[]string{"Result", "Name", "Size", "Spend"}, webFiles,
		).SetStyle(
			table.StyleLight, color.FgCyan,
		).EnableAutoIndex().Render()
		fmt.Println(result)
	},
}
View Source
var CSVRender = &cobra.Command{
	Use:   "csv-render [file path]",
	Short: "CSV格式渲染表格",
	Args:  cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		hasHeader, _ := cmd.Flags().GetBool("header")
		style, _ := cmd.Flags().GetString("style")
		color, _ := cmd.Flags().GetString("color")

		tableWriter := table.NewWriter()

		if _, ok := TABLE_STYLES[style]; ok {
			tableWriter.SetStyle(TABLE_STYLES[style])
		} else {
			fmt.Println("invalid style:", style)
			os.Exit(1)
		}
		if color != "" {
			if _, ok := TABLE_COLORS[color]; ok {
				tableWriter.Style().Color.Border = text.Colors{TABLE_COLORS[color]}
				tableWriter.Style().Color.Separator = text.Colors{TABLE_COLORS[color]}
			} else {
				fmt.Println("invalid color:", color)
				os.Exit(1)
			}
		}

		var (
			content string
			err     error
		)
		if len(args) != 0 {
			fp := fileutils.FilePath{Path: args[0]}
			content, err = fp.ReadAll()
			if err != nil {
				logging.Fatal("read from file %s failed", fp.Path)
			}
		} else {
			bytes, err := io.ReadAll(os.Stdin)
			if err != nil {
				logging.Fatal("read from stdin failed")
			}
			content = string(bytes)
		}

		lines := strings.Split(content, "\n")
		if len(lines) == 0 {
			return
		}
		var (
			header string
			rows   []string
		)
		if hasHeader {
			header, rows = lines[0], lines[1:]
		} else {
			rows = lines
		}

		if header != "" {
			tableWriter.AppendHeader(getRow(strings.Split(header, ",")))
		}

		for _, line := range rows {
			if line == "" {
				continue
			}
			tableWriter.AppendRow(getRow(strings.Split(line, ",")))
		}
		fmt.Println(tableWriter.Render())
		tableWriter.Render()
	},
}
View Source
var ContainerImageSync = &cobra.Command{
	Use:   "registry-sync <source repo> <image>",
	Short: "同步容器镜像",
	Long:  "同步两个仓库之间的镜像",
	Args: func(cmd *cobra.Command, args []string) error {
		if err := cobra.ExactArgs(2)(cmd, args); err != nil {
			return err
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		srcRepo := args[0]
		image := args[1]

		ctl, err := syscmd.GetDefaultContainerCli()
		if err != nil {
			logging.Error("获取客户端失败: %s", err)
			os.Exit(1)
		}
		logging.Info("使用容器客户端: %s", ctl.GetCmd())
		srcImage := ctl.GetImageRepo(srcRepo, image)

		logging.Info("拉取镜像: %s", srcImage)
		if err := ctl.Pull(srcImage); err != nil {
			logging.Error("拉取失败: %s", err)
			os.Exit(1)
		}
		for _, destRepo := range destRepos {
			destImage := ctl.GetImageRepo(destRepo, image)
			if err := ctl.Tag(srcImage, destImage); err != nil {
				logging.Error("Tag 设置失败: %s", err)
				os.Exit(1)
			}
			logging.Info("推送镜像: %s", destImage)
			if err := ctl.Push(destImage); err != nil {
				logging.Error("失败: %s", err)
				os.Exit(1)
			}
		}
		logging.Info("同步完成")
	},
}
View Source
var FetchWallpaperCmd = &cobra.Command{
	Use:   "fetch-wallpaper",
	Short: "下载壁纸",
}
View Source
var IniCrud = &cobra.Command{
	Use:   "crud-ini",
	Short: "ini 配置文件编辑器",
}
View Source
var IniDelete = &cobra.Command{
	Use:   "del <file path> <section> <key>",
	Short: "获取配置",
	Args:  cobra.ExactArgs(3),
	Run: func(cmd *cobra.Command, args []string) {
		filePath, section, key := args[0], args[1], args[2]
		err := ini.CONF.Load(filePath)
		if err != nil {
			fmt.Printf("配置文件加载异常, %s\n", err)
			os.Exit(1)
		}
		ini.CONF.Delete(section, key)
	},
}
View Source
var IniGet = &cobra.Command{
	Use:   "get <file path> <section> <key>",
	Short: "获取配置",
	Args:  cobra.ExactArgs(3),
	Run: func(cmd *cobra.Command, args []string) {
		filePath, section, key := args[0], args[1], args[2]
		err := ini.CONF.Load(filePath)
		if err != nil {
			fmt.Printf("配置文件加载异常, %s\n", err)
			os.Exit(1)
		}
		ini.CONF.SetBlockMode(true)
		fmt.Println(ini.CONF.Get(section, key))
	},
}
View Source
var IniSet = &cobra.Command{
	Use:   "set <file path> <section> <key> <value>",
	Short: "添加/更新配置",
	Args:  cobra.ExactArgs(4),
	Run: func(cmd *cobra.Command, args []string) {
		filePath, section, key, value := args[0], args[1], args[2], args[3]
		err := ini.CONF.Load(filePath)
		if err != nil {
			fmt.Printf("配置文件加载异常, %s\n", err)
			os.Exit(1)
		}
		ini.CONF.Set(section, key, value)
	},
}
View Source
var MDRender = &cobra.Command{
	Use:   "md-preview [file path]",
	Short: "Markdown预览",
	Args:  cobra.MaximumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		var content string
		var err error
		var term *terminal.Terminal
		if len(args) != 0 {
			fp := fileutils.FilePath{Path: args[0]}
			content, err = fp.ReadAll()
			if err != nil {
				logging.Fatal("read from file %s failed", fp.Path)
			}
			term = terminal.CurTerminal()
		} else {
			bytes, err := io.ReadAll(os.Stdin)
			if err != nil {
				logging.Fatal("read from stdin failed")
			}
			content = string(bytes)
		}

		spredout, _ := cmd.Flags().GetBool("spredout")
		columns, leftPad := 100, 4
		if term != nil {
			if spredout {
				columns, leftPad = term.Columns, 0
			} else {
				columns, leftPad = term.Columns*2/3, term.Columns/6
			}
		} else {
			if spredout {
				leftPad = 0
			}
		}
		result := markdown.Render(content, columns+leftPad, leftPad)
		fmt.Println(string(result))
	},
}
View Source
var SimpleHttpFS = &cobra.Command{
	Use:   "fs-server",
	Short: "一个简单的 HTTP 文件服务器",
	Args:  cobra.MaximumNArgs(2),
	Run: func(cmd *cobra.Command, args []string) {
		myHttp.FSConfig.Port = port
		myHttp.FSConfig.Root = root
		err := myHttp.SimpleHttpFS()
		if err != nil {
			logging.Fatal("启动HTTP服务失败: %s", err)
		}
	},
}
View Source
var TABLE_COLORS = map[string]text.Color{
	"cyan":   text.FgCyan,
	"blue":   text.FgBlue,
	"yellow": text.FgYellow,
	"red":    text.FgRed,
	"green":  text.FgGreen,
}
View Source
var TABLE_STYLES = map[string]table.Style{
	"default": table.StyleDefault,
	"light":   table.StyleLight,
	"rounded": table.StyleRounded,
	"bold":    table.StyleBold,
}
View Source
var UHD_CHOICES = []string{UHD_ONLY, UHD_INCLUDE, UHD_NO}
View Source
var Wget = &cobra.Command{
	Use:   "wget",
	Short: "get web file",
	Args:  cobra.ExactArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		url := args[0]
		output, _ := cmd.Flags().GetString("output")

		logging.Info("saving to %s", output)
		err := http.Download(url, output, true)
		if err != nil {
			logging.Error("download %s failed: %s", url, err)
			return
		}
	},
}
View Source
var WgetLinks = &cobra.Command{
	Use:   "wget-links <url>",
	Short: "下载网页上的链接",
	Args: func(cmd *cobra.Command, args []string) error {
		if err := cobra.ExactArgs(1)(cmd, args); err != nil {
			return err
		}
		if err := stringutils.MustMatch(args[0], "^http(s)*://.+"); err != nil {
			return fmt.Errorf("invalid flag 'url': %s", err)
		}
		return nil
	},
	Run: func(cmd *cobra.Command, args []string) {
		url := strings.TrimRight(args[0], "/")
		regex, _ := cmd.Flags().GetString("regex")
		output, _ := cmd.Flags().GetString("output")
		http.DownloadLinksInHtml(url, regex, output)
	},
}

Functions

This section is empty.

Types

type ProgressWriter added in v0.0.6

type ProgressWriter struct {
	Writer *bufio.Writer
	// contains filtered or unexported fields
}

func (ProgressWriter) Flush added in v0.0.6

func (pw ProgressWriter) Flush() error

func (ProgressWriter) Write added in v0.0.6

func (pw ProgressWriter) Write(p []byte) (n int, err error)

Jump to

Keyboard shortcuts

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