コード例 #1
0
ファイル: ansicolor_test.go プロジェクト: j4ustin/go-ethereum
func TestNewAnsiColor2(t *testing.T) {
	inner := bytes.NewBufferString("")
	w1 := ansicolor.NewAnsiColorWriter(inner)
	w2 := ansicolor.NewAnsiColorWriter(w1)
	if w1 != w2 {
		t.Errorf("Get %#v, want %#v", w1, w2)
	}
}
コード例 #2
0
ファイル: log.go プロジェクト: salsaflow/salsaflow
func Replace(newWriter io.Writer) (formerWriter io.Writer) {
	lock.Lock()
	formerWriter = logWriter
	logWriter = ansicolor.NewAnsiColorWriter(newWriter)
	lock.Unlock()
	return
}
コード例 #3
0
ファイル: builder.go プロジェクト: samdec11/snag
func (b *Bob) execute() {
	b.stopCurVow()

	clearBuffer()
	b.mtx.Lock()

	if len(b.depWarning) > 0 {
		fmt.Printf("Deprecation Warnings!\n%s", b.depWarning)
	}

	// setup the first command
	firstCmd := b.buildCmds[0]
	b.curVow = vow.To(firstCmd[0], firstCmd[1:]...)

	// setup the remaining commands
	for i := 1; i < len(b.buildCmds); i++ {
		cmd := b.buildCmds[i]
		b.curVow = b.curVow.Then(cmd[0], cmd[1:]...)
	}

	// setup all parallel commands
	for i := 0; i < len(b.runCmds); i++ {
		cmd := b.runCmds[i]
		b.curVow = b.curVow.ThenAsync(cmd[0], cmd[1:]...)
	}
	b.curVow.Verbose = b.verbose
	go b.curVow.Exec(ansicolor.NewAnsiColorWriter(os.Stdout))

	b.mtx.Unlock()
}
コード例 #4
0
ファイル: ansicolor_test.go プロジェクト: j4ustin/go-ethereum
func TestNewAnsiColor1(t *testing.T) {
	inner := bytes.NewBufferString("")
	w := ansicolor.NewAnsiColorWriter(inner)
	if w == inner {
		t.Errorf("Get %#v, want %#v", w, inner)
	}
}
コード例 #5
0
func PrintUnassignedWarning(writer io.Writer, commits []*git.Commit) (n int64, err error) {
	var output bytes.Buffer

	// Let's be colorful!
	redBold := color.New(color.FgRed).Add(color.Bold).SprintFunc()
	fmt.Fprint(&output,
		redBold("Warning: There are some commits missing the Story-Id tag.\n"))

	red := color.New(color.FgRed).SprintFunc()
	fmt.Fprint(&output,
		red("Make sure that this is alright before proceeding further.\n\n"))

	hashRe := regexp.MustCompile("^[0-9a-f]{40}$")

	yellow := color.New(color.FgYellow).SprintFunc()

	for _, commit := range commits {
		var (
			sha    = commit.SHA
			source = commit.Source
			title  = prompt.ShortenCommitTitle(commit.MessageTitle)
		)
		if hashRe.MatchString(commit.Source) {
			source = "unknown commit source branch"
		}

		fmt.Fprintf(&output, "  %v | %v | %v\n", yellow(sha), yellow(source), title)
	}

	// Write the output to the writer.
	return io.Copy(ansicolor.NewAnsiColorWriter(writer), &output)
}
コード例 #6
0
ファイル: main.go プロジェクト: nocd5/crz
func main() {
	w := ansicolor.NewAnsiColorWriter(os.Stdout)
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		fmt.Fprintln(w, scanner.Text())
	}
}
コード例 #7
0
ファイル: main.go プロジェクト: parkghost/watchf
func init() {
	flag.BoolVar(&verbose, "V", false, "Show debugging messages")
	flag.StringVar(&configFile, "f", "."+Program+".conf", "Specifies a configuration file")
	flag.BoolVar(&writeConfig, "w", false, "Write command-line arguments to configuration file (write and exit)")
	flag.Usage = func() {
		fmt.Println("Usage:\n  " + os.Args[0] + " [options]\n")
		fmt.Println("Options:")
		flag.PrintDefaults()
		fmt.Println(`
Events:
     all  Create/Write/Remove/Rename/Chmod
  create  File/directory created in watched directory
  write   File written in watched directory
  remove  File/directory deleted from watched directory
  rename  File moved out of watched directory
  chmod   File Metadata changed

Variables:
      %f  The filename of changed file
      %t  The event type of file changes`)

		printExample()
	}

	log.SetOutput(ansicolor.NewAnsiColorWriter(os.Stderr))
}
コード例 #8
0
ファイル: ls.go プロジェクト: kissthink/nyagos
func cmd_ls(cmd *interpreter.Interpreter) (interpreter.NextT, error) {
	var out io.Writer
	if cmd.Stdout == os.Stdout {
		out = ansicolor.NewAnsiColorWriter(cmd.Stdout)
	} else {
		out = cmd.Stdout
	}
	return interpreter.CONTINUE, ls.Main(cmd.Args[1:], out)
}
コード例 #9
0
ファイル: ls.go プロジェクト: amnz/nyagos
func cmd_ls(cmd *interpreter.Interpreter) (interpreter.ErrorLevel, error) {
	var out io.Writer
	if cmd.Stdout == os.Stdout {
		out = ansicolor.NewAnsiColorWriter(cmd.Stdout)
	} else {
		out = cmd.Stdout
	}
	return interpreter.NOERROR, ls.Main(cmd.Args[1:], out)
}
コード例 #10
0
ファイル: images.go プロジェクト: rjeczalik/images
// Print prints the images to standard output.
func (i Images) Print(mode utils.OutputMode) error {
	if len(i) == 0 {
		return errors.New("no images found")
	}

	switch mode {
	case utils.JSON:
		out, err := i.outputJSON()
		if err != nil {
			return err
		}

		fmt.Println(out)
		return nil
	case utils.Simplified:

		green := color.New(color.FgGreen).SprintfFunc()
		output := ansicolor.NewAnsiColorWriter(os.Stdout)
		w := utils.NewImagesTabWriter(output)
		defer w.Flush()

		for region, images := range i {
			if len(images) == 0 {
				continue
			}

			fmt.Fprintln(w, green("AWS Region: %s (%d images):", region, len(images)))
			fmt.Fprintln(w, "    Name\tID\tState\tTags")

			for ix, image := range images {
				tags := make([]string, len(image.Tags))
				for i, tag := range image.Tags {
					tags[i] = *tag.Key + ":" + *tag.Value
				}

				name := ""
				if image.Name != nil {
					name = *image.Name
				}

				state := *image.State
				if *image.State == "failed" {
					state += " (" + *image.StateReason.Message + ")"
				}

				fmt.Fprintf(w, "[%d] %s\t%s\t%s\t%+v\n",
					ix+1, name, *image.ImageId, state, tags)
			}

			fmt.Fprintln(w, "")
		}
		return nil
	default:
		return fmt.Errorf("output mode '%s' is not valid", mode)
	}
}
コード例 #11
0
ファイル: cmd_interactive.go プロジェクト: sarifsystems/sarif
func (app *App) Interactive() {
	rl, err := readline.NewEx(&readline.Config{
		Prompt:      color.BlueString("say » "),
		HistoryFile: app.Config.HistoryFile,
	})
	if err != nil {
		log.Fatal(err)
	}
	defer rl.Close()
	app.Log.SetOutput(rl.Stderr())
	log.SetOutput(rl.Stderr())
	color.Output = ansicolor.NewAnsiColorWriter(rl.Stderr())

	pings := make(map[string]time.Time)

	// Subscribe to all replies and print them to stdout
	app.Client.Subscribe("", "self", func(msg sarif.Message) {
		text := msg.Text
		if text == "" {
			text = msg.Action + " from " + msg.Source
		}
		if msg.IsAction("err") {
			text = color.RedString(text)
		}

		if sent, ok := pings[msg.CorrId]; ok {
			text += color.YellowString("[%.1fms]", time.Since(sent).Seconds()*1e3)
		}
		log.Println(color.GreenString(" « ") + strings.Replace(text, "\n", "\n   ", -1))
	})

	// Interactive mode sends all lines from stdin.
	for {
		line, err := rl.Readline()
		if err != nil {
			if err == io.EOF {
				return
			}
			log.Fatal(err)
		}
		if len(line) == 0 {
			continue
		}

		// Publish natural message
		msg := sarif.Message{
			Id:     sarif.GenerateId(),
			Action: "natural/handle",
			Text:   line,
		}
		if *profile {
			pings[msg.Id] = time.Now()
		}
		app.Client.Publish(msg)
	}
}
コード例 #12
0
func TestWritePlanText(t *testing.T) {
	inner := bytes.NewBufferString("")
	w := ansicolor.NewAnsiColorWriter(inner)
	expected := "plain text"
	fmt.Fprintf(w, expected)
	actual := inner.String()
	if actual != expected {
		t.Errorf("Get %s, want %s", actual, expected)
	}
}
コード例 #13
0
ファイル: main.go プロジェクト: dasnook/godog
func buildAndRun() (status int, err error) {
	// will support Ansi colors for windows
	stdout := ansicolor.NewAnsiColorWriter(os.Stdout)
	buffer := bytes.NewBuffer([]byte(""))
	stderr := ansicolor.NewAnsiColorWriter(buffer)

	builtFile := fmt.Sprintf("%s/%dgodog.go", os.TempDir(), time.Now().UnixNano())

	buf, err := godog.Build()
	if err != nil {
		return
	}

	w, err := os.Create(builtFile)
	if err != nil {
		return
	}
	defer os.Remove(builtFile)

	if _, err = w.Write(buf); err != nil {
		w.Close()
		return
	}
	w.Close()

	cmd := exec.Command("go", append([]string{"run", builtFile}, os.Args[1:]...)...)
	cmd.Stdout = stdout
	cmd.Stderr = stderr

	defer func() {
		s := strings.TrimSpace(buffer.String())
		if s == "" {
			status = 0
		} else if m := statusMatch.FindStringSubmatch(s); len(m) > 1 {
			status, _ = strconv.Atoi(m[1])
		} else {
			io.Copy(stdout, buffer)
		}
	}()

	return status, cmd.Run()
}
コード例 #14
0
ファイル: example_test.go プロジェクト: Richardphp/noms
func ExampleNewAnsiColorWriter() {
	w := ansicolor.NewAnsiColorWriter(os.Stdout)
	text := "%sforeground %sbold%s %sbackground%s\n"
	fmt.Fprintf(w, text, "\x1b[31m", "\x1b[1m", "\x1b[21m", "\x1b[41;32m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[32m", "\x1b[1m", "\x1b[21m", "\x1b[42;31m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[33m", "\x1b[1m", "\x1b[21m", "\x1b[43;34m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[34m", "\x1b[1m", "\x1b[21m", "\x1b[44;33m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[35m", "\x1b[1m", "\x1b[21m", "\x1b[45;36m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[36m", "\x1b[1m", "\x1b[21m", "\x1b[46;35m", "\x1b[0m")
	fmt.Fprintf(w, text, "\x1b[37m", "\x1b[1m", "\x1b[21m", "\x1b[47;30m", "\x1b[0m")
}
コード例 #15
0
func writeAnsiColor(expectedText, colorCode string) (actualText string, actualAttributes uint16, err error) {
	inner := bytes.NewBufferString("")
	w := ansicolor.NewAnsiColorWriter(inner)
	fmt.Fprintf(w, "\x1b[%sm%s", colorCode, expectedText)

	actualText = inner.String()
	screenInfo := GetConsoleScreenBufferInfo(uintptr(syscall.Stdout))
	if screenInfo != nil {
		actualAttributes = screenInfo.WAttributes
	} else {
		err = &screenNotFoundError{}
	}
	return
}
コード例 #16
0
func TestWriteParseText(t *testing.T) {
	inner := bytes.NewBufferString("")
	w := ansicolor.NewAnsiColorWriter(inner)

	inputTail := "\x1b[0mtail text"
	expectedTail := "tail text"
	fmt.Fprintf(w, inputTail)
	actualTail := inner.String()
	inner.Reset()
	if actualTail != expectedTail {
		t.Errorf("Get %s, want %s", actualTail, expectedTail)
	}

	inputHead := "head text\x1b[0m"
	expectedHead := "head text"
	fmt.Fprintf(w, inputHead)
	actualHead := inner.String()
	inner.Reset()
	if actualHead != expectedHead {
		t.Errorf("Get %s, want %s", actualHead, expectedHead)
	}

	inputBothEnds := "both ends \x1b[0m text"
	expectedBothEnds := "both ends  text"
	fmt.Fprintf(w, inputBothEnds)
	actualBothEnds := inner.String()
	inner.Reset()
	if actualBothEnds != expectedBothEnds {
		t.Errorf("Get %s, want %s", actualBothEnds, expectedBothEnds)
	}

	inputManyEsc := "\x1b\x1b\x1b\x1b[0m many esc"
	expectedManyEsc := "\x1b\x1b\x1b many esc"
	fmt.Fprintf(w, inputManyEsc)
	actualManyEsc := inner.String()
	inner.Reset()
	if actualManyEsc != expectedManyEsc {
		t.Errorf("Get %s, want %s", actualManyEsc, expectedManyEsc)
	}

	expectedSplit := "split  text"
	for _, ch := range "split \x1b[0m text" {
		fmt.Fprintf(w, string(ch))
	}
	actualSplit := inner.String()
	inner.Reset()
	if actualSplit != expectedSplit {
		t.Errorf("Get %s, want %s", actualSplit, expectedSplit)
	}
}
コード例 #17
0
ファイル: images.go プロジェクト: hanscj1/images
// Print prints the stored images to standard output.
func (i Images) Print(mode utils.OutputMode) error {
	if len(i.Items) == 0 {
		return errors.New("no images found")
	}

	switch mode {
	case utils.JSON:
		out, err := i.outputJSON()
		if err != nil {
			return err
		}

		fmt.Println(out)
		return nil
	case utils.Simplified:
		green := color.New(color.FgGreen).SprintfFunc()
		output := ansicolor.NewAnsiColorWriter(os.Stdout)
		w := utils.NewImagesTabWriter(output)
		defer w.Flush()

		imageDesc := "image"
		if len(i.Items) > 1 {
			imageDesc = "images"
		}

		fmt.Fprintln(w, green("GCE (%d %s):", len(i.Items), imageDesc))
		fmt.Fprintln(w, "    Name\tID\tStatus\tType\tDeprecated\tCreation Timestamp")

		for ix, image := range i.Items {
			deprecatedState := ""
			if image.Deprecated != nil {
				deprecatedState = image.Deprecated.State
			}

			fmt.Fprintf(w, "[%d] %s (%s)\t%d\t%s\t%s (%d)\t%s\t%s\n",
				ix+1, image.Name, image.Description, image.Id,
				image.Status, image.SourceType, image.DiskSizeGb,
				deprecatedState, image.CreationTimestamp,
			)
		}

		return nil
	default:
		return fmt.Errorf("output mode '%s' is not valid", mode)
	}
}
コード例 #18
0
ファイル: lua_cmd.go プロジェクト: tyochiai/nyagos
func cmdWriteSub(L lua.Lua, out io.Writer) int {
	switch out.(type) {
	case *os.File:
		out = ansicolor.NewAnsiColorWriter(out)
	}
	n := L.GetTop()
	for i := 1; i <= n; i++ {
		str, err := L.ToString(i)
		if err != nil {
			return L.Push(nil, err)
		}
		if i > 1 {
			fmt.Fprint(out, "\t")
		}
		fmt.Fprint(out, str)
	}
	return L.Push(true)
}
コード例 #19
0
ファイル: print.go プロジェクト: LK4D4/the_platinum_searcher
func newWriter(option *Option) io.Writer {
	encoder := func() io.Writer {
		switch option.OutputEncode {
		case "sjis":
			return transform.NewWriter(os.Stdout, japanese.ShiftJIS.NewEncoder())
		case "euc":
			return transform.NewWriter(os.Stdout, japanese.EUCJP.NewEncoder())
		case "jis":
			return transform.NewWriter(os.Stdout, japanese.ISO2022JP.NewEncoder())
		default:
			return os.Stdout
		}
	}()
	if option.EnableColor {
		return ansicolor.NewAnsiColorWriter(encoder)
	}
	return encoder
}
コード例 #20
0
ファイル: clicolor.go プロジェクト: jiangshengwu/dockerf
// Initialization of supported colors
func init() {
	colors = make(map[string]string)
	colors["black"] = "30m"
	colors["red"] = "31m"
	colors["green"] = "32m"
	colors["yellow"] = "33m"
	colors["blue"] = "34m"
	colors["magenta"] = "35m"
	colors["cyan"] = "36m"
	colors["white"] = "37m"
	colors["default"] = "39m"

	if runtime.GOOS == "windows" {
		Out = ansicolor.NewAnsiColorWriter(os.Stdout)
	} else {
		Out = os.Stdout
	}
}
コード例 #21
0
ファイル: images.go プロジェクト: rjeczalik/images
// Print prints the stored images to standard output.
func (i Images) Print(mode utils.OutputMode) error {
	if len(i) == 0 {
		return errors.New("no images found")
	}

	switch mode {
	case utils.JSON:
		out, err := i.outputJSON()
		if err != nil {
			return err
		}

		fmt.Println(out)
		return nil
	case utils.Simplified:
		green := color.New(color.FgGreen).SprintfFunc()
		output := ansicolor.NewAnsiColorWriter(os.Stdout)
		w := utils.NewImagesTabWriter(output)
		defer w.Flush()

		imageDesc := "image"
		if len(i) > 1 {
			imageDesc = "images"
		}

		fmt.Fprintln(w, green("DO (%d %s):", len(i), imageDesc))
		fmt.Fprintln(w, "    Name\tID\tDistribution\tType\tRegions")

		for ix, image := range i {
			regions := make([]string, len(image.Regions))
			for i, region := range image.Regions {
				regions[i] = region
			}

			fmt.Fprintf(w, "[%d] %s\t%d\t%s\t%s (%d)\t%+v\n",
				ix+1, image.Name, image.ID, image.Distribution, image.Type, image.MinDiskSize, regions)
		}
		return nil
	default:
		return fmt.Errorf("output mode '%s' is not valid", mode)
	}

}
コード例 #22
0
ファイル: builder.go プロジェクト: zabawaba99/snag
func (b *Bob) execute() {
	b.stopCurVow()

	clearBuffer()
	b.mtx.Lock()

	// setup the first command
	firstCmd := b.cmds[0]
	b.curVow = vow.To(firstCmd[0], firstCmd[1:]...)

	// setup the remaining commands
	for i := 1; i < len(b.cmds); i++ {
		cmd := b.cmds[i]
		b.curVow = b.curVow.Then(cmd[0], cmd[1:]...)
	}
	b.curVow.Verbose = b.verbose
	go b.curVow.Exec(ansicolor.NewAnsiColorWriter(os.Stdout))

	b.mtx.Unlock()
}
コード例 #23
0
ファイル: main.go プロジェクト: rbtnn/go-filewatcher
func (t *TT) Message(e EventType, prev *TT) {
	w := ansicolor.NewAnsiColorWriter(colorable.NewColorableStdout())
	text := "[" + time.Now().Format(time.Stamp) + "] " + string(e) + ": "
	switch e {
	case Added:
		// Yellow
		size := strconv.FormatInt(t.Size, 10) + " Bytes"
		text += t.Path + " (" + size + ", " + t.Hash + ")"
		fmt.Fprintf(w, "%s%s%s\n", "\x1b[33m", text, "\x1b[0m")
	case Updated:
		// Green
		size := strconv.FormatInt(prev.Size, 10) + " -> " + strconv.FormatInt(t.Size, 10) + " Bytes"
		text += t.Path + " (" + size + ", " + prev.Hash + " -> " + t.Hash + ")"
		fmt.Fprintf(w, "%s%s%s\n", "\x1b[32m", text, "\x1b[0m")
	case Deleted:
		// Red
		size := strconv.FormatInt(t.Size, 10) + " Bytes"
		text += t.Path + " (" + size + ", " + t.Hash + ")"
		fmt.Fprintf(w, "%s%s%s\n", "\x1b[31m", text, "\x1b[0m")
	}
}
コード例 #24
0
ファイル: config.go プロジェクト: salsaflow/salsaflow
func printSalsaFlowEnabledTimestampWarning() (n int64, err error) {
	// Open the console to make sure the user can always see it.
	stdout, err := prompt.OpenConsole(os.O_WRONLY)
	if err != nil {
		return 0, err
	}
	defer stdout.Close()

	// Generate the warning.
	var output bytes.Buffer

	redBold := color.New(color.FgRed).Add(color.Bold).SprintFunc()
	fmt.Fprintln(&output, redBold("\nWarning: 'salsaflow_enabled_timestamp' key missing."))

	red := color.New(color.FgRed).SprintFunc()
	fmt.Fprintln(&output, red("Please set the key in the local configuration file."))
	fmt.Fprintln(&output, red("The format is: 2014-09-02T12:36:11.142902641+01:00\n"))

	// Dump it into the console.
	return io.Copy(ansicolor.NewAnsiColorWriter(stdout), &output)
}
コード例 #25
0
ファイル: images.go プロジェクト: rjeczalik/images
// Print prints the images to standard output.
func (img Images) Print(mode utils.OutputMode) error {
	if len(img) == 0 {
		return errors.New("no images found (use -all flag)")
	}

	switch mode {
	case utils.JSON:
		p, err := json.MarshalIndent(img, "", "    ")
		if err != nil {
			return err
		}

		fmt.Println(string(p))
		return nil
	case utils.Simplified:
		green := color.New(color.FgGreen).SprintfFunc()
		w := utils.NewImagesTabWriter(ansicolor.NewAnsiColorWriter(os.Stdout))
		defer w.Flush()

		fmt.Fprintln(w, green("Softlayer (%d images):", len(img)))
		fmt.Fprintln(w, "    Name\tID\tGlobalID\tCreated\tDatacenters\tTags")

		for i, image := range img {
			created := "-"
			if !image.CreateDate.IsZero() {
				created = image.CreateDate.Format(time.RFC3339)
			}
			fmt.Fprintf(w, "[%d] %s\t%d\t%s\t%s\t%s\t%s\n", i, image.Name, image.ID,
				image.globalID(), created, image.datacenters(), image.tags())
		}

		fmt.Fprintln(w)
		return nil
	default:
		return fmt.Errorf("output mode %q is not valid", mode)
	}
	return nil
}
コード例 #26
0
func PrintUnassignedWarning(writer io.Writer, commits []*git.Commit) (n int64, err error) {
	var output bytes.Buffer

	// Let's be colorful!
	redBold := color.New(color.FgRed).Add(color.Bold).SprintFunc()
	fmt.Fprint(&output,
		redBold("Warning: There are some commits missing the Story-Id tag.\n"))

	red := color.New(color.FgRed).SprintFunc()
	fmt.Fprint(&output,
		red("Make sure that this is alright before proceeding further.\n\n"))

	yellow := color.New(color.FgYellow).SprintFunc()
	refPrefixLen := len("refs/heads/")
	for _, commit := range commits {
		fmt.Fprintf(&output, "  %v | %v | %v\n",
			yellow(commit.SHA), yellow(commit.Source[refPrefixLen:]),
			prompt.ShortenCommitTitle(commit.MessageTitle))
	}

	// Write the output to the writer.
	return io.Copy(ansicolor.NewAnsiColorWriter(writer), &output)
}
コード例 #27
0
ファイル: crayons.go プロジェクト: apriendeau/crayons
package crayons

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"github.com/mattn/go-isatty"
	"github.com/shiena/ansicolor"
)

var (
	// Writer is a where crayons will draw too
	Writer = ansicolor.NewAnsiColorWriter(os.Stdout)
	// Monochrome checkts if it is tty
	Monochrome = !isatty.IsTerminal(os.Stdout.Fd())
)

// Style is alias type for int
type Style int

//Crayon is the structure for a crayon. It contains unexported fields
type Crayon struct {
	styles     []Style
	monochrome bool
}

const escape = "\x1b"

// Core Styles
コード例 #28
0
ファイル: nyagos.go プロジェクト: kissthink/nyagos
func main() {
	defer when_panic()

	dos.CoInitializeEx(0, dos.COINIT_MULTITHREADED)
	defer dos.CoUninitialize()

	conio.DisableCtrlC()

	completion := conio.KeyGoFuncT{F: completion.KeyFuncCompletion}

	if err := conio.BindKeySymbolFunc(conio.K_CTRL_I, "COMPLETE", &completion); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
	}

	// ANSI Escape Sequence Support
	ansiOut = ansicolor.NewAnsiColorWriter(os.Stdout)

	commands.Init()
	alias.Init()

	// Lua extension
	L := lua.New()
	L.OpenLibs()
	SetLuaFunctions(L)
	L.GetGlobal("nyagos")
	if stamp != "" {
		L.PushString(stamp)
		L.SetField(-2, "stamp")
	}
	if commit != "" {
		L.PushString(commit)
		L.SetField(-2, "commit")
	}
	if version != "" {
		L.PushString(version)
		L.SetField(-2, "version")
	}
	L.PushGoFunction(nyagosPrompt)
	L.SetField(-2, "prompt")
	L.Pop(1)
	defer L.Close()

	if !optionParse(L) {
		return
	}

	appData := filepath.Join(os.Getenv("APPDATA"), "NYAOS_ORG")
	os.Mkdir(appData, 0777)
	histPath := filepath.Join(appData, "nyagos.history")
	history.Load(histPath)
	history.Save(histPath) // cut over max-line

	exeName, exeNameErr := dos.GetModuleFileName()
	if exeNameErr != nil {
		fmt.Fprintln(os.Stderr, exeNameErr)
	}
	exeFolder := filepath.Dir(exeName)
	nyagos_lua := filepath.Join(exeFolder, "nyagos.lua")
	if _, err := os.Stat(nyagos_lua); err == nil {
		err := L.Source(nyagos_lua)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
	}

	conio.DefaultEditor.Tag = L
	conio.DefaultEditor.Prompt = printPrompt

	for {
		wd, wdErr := os.Getwd()
		if wdErr == nil {
			conio.SetTitle("NYAGOS - " + wd)
		} else {
			conio.SetTitle("NYAGOS - " + wdErr.Error())
		}
		history_count := conio.DefaultEditor.HistoryLen()
		line, cont := conio.DefaultEditor.ReadLine()
		if !cont {
			break
		}

		var isReplaced bool
		line, isReplaced = history.Replace(line)
		if isReplaced {
			fmt.Fprintln(os.Stdout, line)
		}
		if line == "" {
			continue
		}
		if conio.DefaultEditor.HistoryLen() > history_count {
			fd, err := os.OpenFile(histPath, os.O_APPEND, 0600)
			if err == nil {
				fmt.Fprintln(fd, line)
				fd.Close()
			} else {
				fmt.Fprintln(os.Stderr, err.Error())
			}
		} else {
			conio.DefaultEditor.HistoryResetPointer()
		}

		stackPos := L.GetTop()
		L.GetGlobal("nyagos")
		L.GetField(-1, "filter")
		if L.IsFunction(-1) {
			L.PushString(line)
			err := L.Call(1, 1)
			if err != nil {
				fmt.Fprintln(os.Stderr, err)
			} else {
				if L.IsString(-1) {
					line, err = L.ToString(-1)
					if err != nil {
						fmt.Fprintln(os.Stderr, err)
					}
				}
			}
		}
		L.SetTop(stackPos)

		it := interpreter.New()
		it.Tag = L
		whatToDo, err := it.Interpret(line)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		if whatToDo == interpreter.SHUTDOWN {
			break
		}
	}
}
コード例 #29
0
ファイル: colorful.go プロジェクト: Purstal/go-tieba-base
package logs

import (
	"fmt"
	"io"
	"os"

	"github.com/shiena/ansicolor"
)

var cStdout io.Writer = ansicolor.NewAnsiColorWriter(os.Stdout)
var cStderr io.Writer = ansicolor.NewAnsiColorWriter(os.Stderr)

func (logger *Logger) LogColorful(prefix, colorCode string, content ...interface{}) {
	logger.Lock.Lock()
	logger.LogTime()
	for _, writer := range logger.Writers {
		logColorful(writer, logger.Name, prefix, colorCode, content...)
	}
	logger.Lock.Unlock()
}

func logColorful(writer io.Writer, loggerName, prefix, colorCode string, content ...interface{}) {
	if writer == os.Stdout {
		io.WriteString(cStdout, "\x1b["+colorCode+"m"+"\x1b[30;1m"+loggerName+"\x1b[0m#\x1b["+colorCode+"m"+prefix+"\x1b[0m# "+fmt.Sprintln(content...))
	} else if writer == os.Stderr {
		io.WriteString(cStderr, "\x1b["+colorCode+"m"+"\x1b[30;1m"+loggerName+"\x1b[0m#\x1b["+colorCode+"m"+prefix+"\x1b[0m# "+fmt.Sprintln(content...))
	} else {
		log(writer, loggerName, prefix, content...)
	}
}
コード例 #30
0
ファイル: console.go プロジェクト: fwessels/mc
	"github.com/fatih/color"
	"github.com/mattn/go-isatty"
	"github.com/shiena/ansicolor"
)

var (
	// DebugPrint enables/disables console debug printing.
	DebugPrint = false

	// Used by the caller to print multiple lines atomically. Exposed by Lock/Unlock methods.
	publicMutex = &sync.Mutex{}
	// Used internally by console.
	privateMutex = &sync.Mutex{}

	stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr)

	// Print prints a message.
	Print = func(data ...interface{}) {
		consolePrint("Print", Theme["Print"], data...)
		return
	}

	// PrintC prints a message with color.
	PrintC = func(data ...interface{}) {
		consolePrint("PrintC", Theme["PrintC"], data...)
		return
	}

	// Printf prints a formatted message.
	Printf = func(format string, data ...interface{}) {