nfs

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2018 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var FileNotExist = errors.New("file not exist")
View Source
var Index = &ctx.Context{Name: "nfs", Help: "存储中心",
	Caches: map[string]*ctx.Cache{
		"nfile": &ctx.Cache{Name: "nfile", Value: "-1", Help: "已经打开的文件数量"},
	},
	Configs: map[string]*ctx.Config{
		"qr_size": &ctx.Config{Name: "qr_size", Value: "256", Help: "二维码的默认大小"},

		"pscolor": &ctx.Config{Name: "pscolor", Value: "2", Help: "pscolor"},
		"nfs_name": &ctx.Config{Name: "nfs_name", Value: "file", Help: "默认模块命名", Hand: func(m *ctx.Message, x *ctx.Config, arg ...string) string {
			if len(arg) > 0 {
				return arg[0]
			}
			return fmt.Sprintf("%s%d", x.Value, m.Capi("nfile", 1))

		}},
		"nfs_help": &ctx.Config{Name: "nfs_help", Value: "file", Help: "默认模块帮助"},

		"buf_size": &ctx.Config{Name: "buf_size", Value: "1024", Help: "读取文件的缓存区的大小"},
		"dir_conf": &ctx.Config{Name: "dir_conf", Value: map[string]interface{}{
			"dir_root": "usr",
		}, Help: "读取文件的缓存区的大小"},

		"dir_deep":   &ctx.Config{Name: "dir_deep(yes/no)", Value: "yes", Help: "dir命令输出目录的统计信息, info: 输出统计信息, 否则输出"},
		"dir_type":   &ctx.Config{Name: "dir_type(file/dir)", Value: "file", Help: "dir命令输出的文件类型, file: 只输出普通文件, dir: 只输出目录文件, 否则输出所有文件"},
		"dir_field":  &ctx.Config{Name: "dir_field", Value: "filename is_dir line size time", Help: "表格排序字段"},
		"dir_name":   &ctx.Config{Name: "dir_name(name/tree/path/full)", Value: "name", Help: "dir命令输出文件名的类型, name: 文件名, tree: 带缩进的文件名, path: 相对路径, full: 绝对路径"},
		"dir_info":   &ctx.Config{Name: "dir_info(sizes/lines/files/dirs)", Value: "sizes lines files dirs", Help: "dir命令输出目录的统计信息, info: 输出统计信息, 否则输出"},
		"sort_field": &ctx.Config{Name: "sort_field", Value: "line", Help: "表格排序字段"},
		"sort_order": &ctx.Config{Name: "sort_order(int/int_r/string/string_r/time/time_r)", Value: "int", Help: "表格排序类型"},

		"git_conf": &ctx.Config{Name: "git_conf", Value: map[string]interface{}{
			"dir_root": "usr",
		}, Help: "读取文件的缓存区的大小"},

		"git_branch":   &ctx.Config{Name: "git_branch", Value: "--list", Help: "版本控制状态参数"},
		"git_status":   &ctx.Config{Name: "git_status", Value: "-sb", Help: "版本控制状态参数"},
		"git_diff":     &ctx.Config{Name: "git_diff", Value: "--stat", Help: "版本控制状态参数"},
		"git_log":      &ctx.Config{Name: "git_log", Value: "--pretty=%h %an(%ad) %s  --date=format:%m/%d %H:%M  --graph", Help: "版本控制状态参数"},
		"git_log_form": &ctx.Config{Name: "git_log", Value: "stat", Help: "版本控制状态参数"},
		"git_log_skip": &ctx.Config{Name: "git_log", Value: "0", Help: "版本控制状态参数"},
		"git_log_line": &ctx.Config{Name: "git_log", Value: "3", Help: "版本控制状态参数"},
		"git_path":     &ctx.Config{Name: "git_path", Value: ".", Help: "版本控制默认路径"},
		"git_info":     &ctx.Config{Name: "git_info", Value: "branch status diff log", Help: "命令集合"},

		"paths": &ctx.Config{Name: "paths", Value: []interface{}{""}, Help: "文件路径"},
	},
	Commands: map[string]*ctx.Command{
		"listen": &ctx.Command{Name: "listen args...", Help: "启动文件服务, args: 参考tcp模块, listen命令的参数", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if _, ok := m.Target().Server.(*NFS); m.Assert(ok) {
				m.Sess("tcp").Call(func(sub *ctx.Message) *ctx.Message {
					sub.Start(fmt.Sprintf("file%d", m.Capi("nfile", 1)), "远程文件")
					return sub.Sess("target", m.Source()).Call(func(sub1 *ctx.Message) *ctx.Message {
						nfs, _ := sub.Target().Server.(*NFS)
						sub1.Remote = make(chan bool, 1)
						nfs.send <- sub1
						<-sub1.Remote
						return nil
					})
				}, m.Meta["detail"])
			}

		}},
		"dial": &ctx.Command{Name: "dial args...", Help: "连接文件服务, args: 参考tcp模块, dial命令的参数", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if _, ok := m.Target().Server.(*NFS); m.Assert(ok) {
				m.Sess("tcp").Call(func(sub *ctx.Message) *ctx.Message {
					sub.Start(fmt.Sprintf("file%d", m.Capi("nfile", 1)), "远程文件")
					return sub.Sess("target", m.Source()).Call(func(sub1 *ctx.Message) *ctx.Message {
						nfs, _ := sub.Target().Server.(*NFS)
						sub1.Remote = make(chan bool, 1)
						nfs.send <- sub1
						<-sub1.Remote
						return nil
					})
				}, m.Meta["detail"])
			}

		}},
		"send": &ctx.Command{Name: "send [file] args...", Help: "连接文件服务, args: 参考tcp模块, dial命令的参数", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.io != nil {
				m.Remote = make(chan bool, 1)
				nfs.send <- m
				<-m.Remote
			}
		}},

		"scan": &ctx.Command{Name: "scan file name", Help: "扫描文件, file: 文件名, name: 模块名", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if _, ok := m.Target().Server.(*NFS); m.Assert(ok) {
				help := fmt.Sprintf("scan %s", arg[0])

				if arg[0] == "stdio" {
					m.Optionv("in", os.Stdin)
					m.Optionv("out", os.Stdout)
					m.Start(arg[0], help, key, arg[0])
					return
				}

				if p, f, e := open(m, arg[0]); m.Assert(e) {
					m.Optionv("in", f)
					m.Start(m.Confx("nfs_name", arg, 1), help, key, p)
				}
			}
		}},
		"prompt": &ctx.Command{Name: "prompt arg", Help: "", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.out != nil {
				nfs.prompt()
				for _, v := range arg {
					nfs.out.WriteString(v)
					m.Echo(v)
				}
			}
		}},
		"exec": &ctx.Command{Name: "exec cmd", Help: "", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.out != nil {
				nfs.prompt()
				for _, v := range arg {
					nfs.out.WriteString(v)
				}
				nfs.out.WriteString("\n")

				msg := m.Find("cli.shell1").Cmd("source", arg)
				for _, v := range msg.Meta["result"] {
					nfs.out.WriteString(v)
					m.Echo(v)
				}
				nfs.out.WriteString("\n")
			}
		}},
		"show": &ctx.Command{Name: "show arg", Help: "", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.out != nil {
				for _, v := range arg {
					nfs.out.WriteString(v)
					m.Echo(v)
				}
			}
		}},

		"open": &ctx.Command{Name: "open file name", Help: "打开文件, file: 文件名, name: 模块名", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			file := arg[0]
			if m.Has("io") {
			} else if p, f, e := open(m, file, os.O_RDWR|os.O_CREATE); m.Assert(e) {
				m.Put("option", "in", f).Put("option", "out", f)
				file = p
			}

			m.Start(m.Confx("nfs_name", arg, 1), fmt.Sprintf("file %s", file), "open", file)
			m.Echo(file)
		}},
		"read": &ctx.Command{Name: "read [buf_size [pos]]", Help: "读取文件, buf_size: 读取大小, pos: 读取位置", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.in != nil {
				n, e := strconv.Atoi(m.Confx("buf_size", arg, 0))
				m.Assert(e)

				if len(arg) > 1 {
					m.Cap("pos", arg[1])
				}

				buf := make([]byte, n)
				if n, e = nfs.in.ReadAt(buf, int64(m.Capi("pos"))); e != io.EOF {
					m.Assert(e)
				}
				m.Capi("nread", n)
				m.Echo(string(buf))

				if m.Capi("pos", n); n == 0 {
					m.Cap("pos", "0")
				}
			}
		}},
		"write": &ctx.Command{Name: "write string [pos]", Help: "写入文件, string: 写入内容, pos: 写入位置", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if nfs, ok := m.Target().Server.(*NFS); m.Assert(ok) && nfs.out != nil {
				if len(arg) > 1 {
					m.Cap("pos", arg[1])
				}

				if len(arg[0]) == 0 {
					m.Assert(nfs.out.Truncate(int64(m.Capi("pos"))))
					m.Cap("size", m.Cap("pos"))
					m.Cap("pos", "0")
				} else {
					n, e := nfs.out.WriteAt([]byte(arg[0]), int64(m.Capi("pos")))
					if m.Capi("nwrite", n); m.Assert(e) && m.Capi("pos", n) > m.Capi("size") {
						m.Cap("size", m.Cap("pos"))
					}
					nfs.out.Sync()
				}

				m.Echo(m.Cap("pos"))
			}
		}},

		"load": &ctx.Command{Name: "load file [buf_size [pos]]", Help: "加载文件, buf_size: 加载大小, pos: 加载位置", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if p, f, e := open(m, arg[0]); m.Assert(e) {
				defer f.Close()

				pos := 0
				if len(arg) > 2 {
					i, e := strconv.Atoi(arg[2])
					m.Assert(e)
					pos = i
				}

				s, e := strconv.Atoi(m.Confx("buf_size", arg, 1))
				m.Assert(e)
				buf := make([]byte, s)

				if l, e := f.ReadAt(buf, int64(pos)); e == io.EOF || m.Assert(e) {
					m.Log("info", "load %s %d %d", p, l, pos)
					m.Echo(string(buf[:l]))
				}
			}
		}},
		"save": &ctx.Command{Name: "save file string...", Help: "保存文件, file: 保存的文件, string: 保存的内容", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if p, f, e := open(m, arg[0], os.O_WRONLY|os.O_CREATE|os.O_TRUNC); m.Assert(e) {
				defer f.Close()

				for _, v := range arg[1:] {
					n, e := fmt.Fprint(f, v)
					m.Assert(e)
					m.Log("info", "save %s %d", p, n)
				}
			}
		}},
		"print": &ctx.Command{Name: "print file string...", Help: "输出文件, file: 输出的文件, string: 输出的内容", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if p, f, e := open(m, arg[0], os.O_WRONLY|os.O_CREATE|os.O_APPEND); m.Assert(e) {
				defer f.Close()

				for _, v := range arg[1:] {
					n, e := fmt.Fprint(f, v)
					m.Assert(e)
					m.Log("info", "print %s %d", p, n)
				}
			}
		}},

		"pwd": &ctx.Command{Name: "pwd [all] | [[index] path] ", Help: "工作目录,all: 查看所有, index path: 设置路径, path: 设置当前路径", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if len(arg) > 0 && arg[0] == "all" {
				list := m.Confv("paths").([]interface{})
				for i, v := range list {
					m.Add("append", "index", i)
					m.Add("append", "path", v)
				}
				m.Table()
				return
			} else if len(arg) > 1 {
				m.Log("info", "paths %s %s", arg[0], arg[1])
				m.Confv("paths", arg[0], arg[1])
			} else if len(arg) > 0 {
				m.Log("info", "paths 0 %s", arg[0])
				m.Confv("paths", 0, arg[0])
			}

			p := m.Confv("paths", 0).(string)
			if path.IsAbs(p) {
				m.Echo("%s", p)
				return
			}

			wd, e := os.Getwd()
			m.Assert(e)
			m.Echo("%s", path.Join(wd, p))
		}},
		"path": &ctx.Command{Name: "path file", Help: "查找文件路径", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			for _, v := range m.Confv("paths").([]interface{}) {
				p := path.Join(v.(string), arg[0])
				if _, e := os.Stat(p); e == nil {
					m.Echo(p)
					break
				}
			}
		}},
		"json": &ctx.Command{Name: "json [key value]...", Help: "生成格式化内容, key: 参数名, value: 参数值", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if len(arg) == 1 {
				var data interface{}
				json.Unmarshal([]byte(arg[0]), &data)

				buf, e := json.MarshalIndent(data, "", "  ")
				m.Assert(e)
				m.Echo(string(buf))
				return
			}

			if len(arg) > 1 && arg[0] == "file" {
				var data interface{}
				f, e := os.Open(arg[1])
				m.Assert(e)
				d := json.NewDecoder(f)
				d.Decode(&data)

				buf, e := json.MarshalIndent(data, "", "  ")
				m.Assert(e)
				m.Echo(string(buf))
				return
			}

			data := map[string]interface{}{}
			for _, k := range m.Meta["option"] {
				if v, ok := m.Data[k]; ok {
					data[k] = v
					continue
				}
				data[k] = m.Meta[k]
			}

			for i := 1; i < len(arg)-1; i += 2 {
				data[arg[i]] = arg[i+1]
			}

			buf, e := json.Marshal(data)
			m.Assert(e)
			m.Echo(string(buf))

		}},
		"genqr": &ctx.Command{Name: "genqr [qr_size size] filename string...", Help: "生成二维码图片, qr_size: 图片大小, filename: 文件名, string: 输出内容", Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
			if size, e := strconv.Atoi(m.Confx("qr_size")); m.Assert(e) {
				p := path.Join(m.Confv("paths", 0).(string), arg[0])
				qrcode.WriteFile(strings.Join(arg[1:], ""), qrcode.Medium, size, p)
				m.Log("info", "genqr %s", p)
			}
		}},

		"dir": &ctx.Command{
			Name: "dir dir [dir_deep yes|no] [dir_info info] [dir_name name|tree|path|full] [dir_type both|file|dir] [sort_field name] [sort_order type]",
			Help: "查看目录, dir: 目录名, dir_info: 显示统计信息, dir_name: 文件名类型, dir_type: 文件类型, sort_field: 排序字段, sort_order: 排序类型",
			Form: map[string]int{
				"dir_root":   1,
				"dir_deep":   1,
				"dir_type":   1,
				"dir_name":   1,
				"dir_info":   1,
				"dir_link":   1,
				"dir_field":  1,
				"sort_field": 1,
				"sort_order": 1,
			},
			Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
				conf := m.Confv("dir_conf")

				m.Option("dir", path.Clean(ctx.Elect(m.Option("dir"), arg, 0)))
				d := path.Join(m.Confx("dir_root", conf), m.Option("dir"))
				if s, e := os.Stat(d); m.Assert(e) && !s.IsDir() {
					d = path.Dir(d)
				}

				fields := strings.Split(m.Confx("dir_field"), " ")

				trip := 0
				if m.Confx("dir_name") == "path" {
					wd, e := os.Getwd()
					m.Assert(e)
					trip = len(wd) + 1
				}

				info := strings.Split(m.Confx("dir_info"), " ")
				for _, v := range info {
					m.Option(v, 0)
				}

				m.Option("time_layout", "2006-01-02 15:04:05")
				dir(m, d, 0, ctx.Right(m.Confx("dir_deep")), fields)
				m.Sort(m.Confx("sort_field"), m.Confx("sort_order"))
				m.Table(func(maps map[string]string, list []string, line int) bool {
					for i, v := range list {
						key := m.Meta["append"][i]
						switch key {
						case "filename":
							v = maps[key]
							if line > -1 && trip > 0 && trip <= len(v) {
								v = v[trip:]
								if m.Options("dir_link") {
									m.Meta["filename"][line] = fmt.Sprintf(m.Option("dir_link"), maps["is_dir"], v)
								} else {
									m.Meta["filename"][line] = v
								}
							}
							if line > -1 {
								if m.Options("dir_link") {
									m.Meta["filename"][line] = fmt.Sprintf(m.Option("dir_link"), maps["is_dir"], v)
								}
							}
						}
					}
					return true
				})
				if !m.Options("dir_link") {
					m.Table()
				}
				for _, v := range info {
					m.Echo("%s: %s\n", v, m.Option(v))
				}
			}},
		"git": &ctx.Command{
			Name: "git branch|status|diff|log|info arg... [dir path]...",
			Help: "版本控制, branch: 分支管理, status: 查看状态, info: 查看分支与状态, dir: 指定路径",
			Form: map[string]int{"dir": 1, "git_info": 1, "git_log": 1, "git_log_form": 1},
			Hand: func(m *ctx.Message, c *ctx.Context, key string, arg ...string) {
				if len(arg) == 0 {
					arg = []string{"info"}
				}
				cmds := []string{arg[0]}
				switch arg[0] {
				case "s":
					arg[0] = "status"
				case "b":
					arg[0] = "branch"
				case "d":
					arg[0] = "diff"
				}
				if arg[0] == "info" {
					cmds = strings.Split(m.Confx("git_info"), " ")
				}
				wd, e := os.Getwd()
				m.Assert(e)
				if !m.Has("dir") {
					m.Option("dir", m.Confx("dir"))
				}
				for _, p := range m.Meta["dir"] {
					if !path.IsAbs(p) {
						p = path.Join(wd, p)
					}
					m.Echo("path: %s\n", p)
					for _, c := range cmds {
						args := []string{}
						switch c {
						case "branch", "status", "diff":
							if c != "status" {
								args = append(args, "--color")
							}
							args = append(args, strings.Split(m.Confx("git_"+c, arg, 1), "  ")...)
							if len(arg) > 2 {
								args = append(args, arg[2:]...)
							}
						case "difftool":
							cmd := exec.Command("git", "difftool", "-y")
							m.Log("info", "cmd: %s %v", "git", "difftool", "-y")
							cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
							if e := cmd.Start(); e != nil {
								m.Echo("error: ")
								m.Echo("%s\n", e)
							} else if e := cmd.Wait(); e != nil {
								m.Echo("error: ")
								m.Echo("%s\n", e)
							}
							continue
						case "csv":
							cmd := exec.Command("git", "log", "--shortstat", "--pretty=commit: %ad", "--date=format:%Y-%m-%d")
							if out, e := cmd.CombinedOutput(); e != nil {
								m.Echo("error: ")
								m.Echo("%s\n", e)
							} else {
								f, e := os.Create(arg[1])
								m.Assert(e)
								defer f.Close()

								type stat struct {
									date string
									adds int
									dels int
								}
								stats := []*stat{}
								list := strings.Split(string(out), "commit: ")
								for _, v := range list {
									l := strings.Split(v, "\n")
									if len(l) > 2 {
										fs := strings.Split(strings.Trim(l[2], " "), ", ")
										stat := &stat{date: l[0]}
										if len(fs) > 2 {
											adds := strings.Split(fs[1], " ")
											dels := strings.Split(fs[2], " ")
											a, e := strconv.Atoi(adds[0])
											m.Assert(e)
											stat.adds = a
											d, e := strconv.Atoi(dels[0])
											m.Assert(e)
											stat.dels = d
										} else {
											adds := strings.Split(fs[1], " ")
											a, e := strconv.Atoi(adds[0])
											m.Assert(e)
											if adds[1] == "insertions(+)" {
												stat.adds = a
											} else {
												stat.dels = a
											}
										}

										stats = append(stats, stat)
									}
								}

								fmt.Fprintf(f, "order,date,adds,dels,sum,top,bottom,last\n")
								l := len(stats)
								for i := 0; i < l/2; i++ {
									stats[i], stats[l-i-1] = stats[l-i-1], stats[i]
								}
								sum := 0
								for i, v := range stats {
									fmt.Fprintf(f, "%d,%s,%d,%d,%d,%d,%d,%d\n", i, v.date, v.adds, v.dels, sum, sum+v.adds, sum-v.dels, sum+v.adds-v.dels)
									sum += v.adds - v.dels
								}
							}
							continue

						case "log":
							args = append(args, "--color")
							args = append(args, strings.Split(m.Confx("git_log"), "  ")...)
							args = append(args, fmt.Sprintf("--%s", m.Confx("git_log_form")))
							args = append(args, m.Confx("git_log_skip", arg, 1, "--skip=%s"))
							args = append(args, m.Confx("git_log_line", arg, 2, "-n %s"))
						default:
							args = append(args, arg[1:]...)
						}

						m.Log("info", "cmd: %s %v", "git", ctx.Trans("-C", p, c, args))
						msg := m.Sess("cli").Cmd("system", "git", "-C", p, c, args)
						m.Copy(msg, "result").Copy(msg, "append")
						m.Echo("\n")
					}
				}
			}},
	},
}

Functions

This section is empty.

Types

type NFS

type NFS struct {
	*bufio.Reader
	*bufio.Writer

	*ctx.Message
	*ctx.Context
	// contains filtered or unexported fields
}

func (*NFS) Begin

func (nfs *NFS) Begin(m *ctx.Message, arg ...string) ctx.Server

func (*NFS) Close

func (nfs *NFS) Close(m *ctx.Message, arg ...string) bool

func (*NFS) Read

func (nfs *NFS) Read(p []byte) (n int, err error)

func (*NFS) Spawn

func (nfs *NFS) Spawn(m *ctx.Message, c *ctx.Context, arg ...string) ctx.Server

func (*NFS) Start

func (nfs *NFS) Start(m *ctx.Message, arg ...string) bool

func (*NFS) View

func (nfs *NFS) View(buf []string, top int, height int)

Jump to

Keyboard shortcuts

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