示例#1
0
func startNotice() {
	color.Green("******")
	color.Green("~ Notice: ~\n")
	color.White("When your download is complete,\nyou will find your files under:\n")
	color.Magenta(setDownloadFolder())
	color.Green("******" + "\n\n")
}
示例#2
0
func (this *Output) Start() {
	var total int
	for path := range this.Console {
		total++
		color.Magenta(path)
	}
	fmt.Printf("%d file(s) updated\n", total)
	this.Closed <- true
}
示例#3
0
文件: retry.go 项目: rohanraja/retry
// Do accepts a function argument that returns an error. It will keep executing this
// function NumRetries times until no error is returned.
// Optionally pass another function as an argument that it will execute before retrying
// in case an error is returned from the first argument fuction.
func Do(args ...interface{}) error {

	if len(args) == 0 {
		panic("Wrong number of arguments")
	}

	task, ok := args[0].(func() error)

	beforeRetry := func() {}
	if len(args) > 1 {
		beforeRetry, ok = args[1].(func())
	}

	if ok == false {
		panic("Wrong Type of Arguments given to retry.Do")
	}

	retries := NumRetries

	var atleastOneError error
	atleastOneError = nil

	err := errors.New("Non-Nil error")
	for retries > 0 && err != nil {

		err = task()

		if err != nil {
			atleastOneError = err
			color.Magenta("\nError: %v\nRetrying #%d after %v", err, (NumRetries - retries + 1), Delay)
			time.Sleep(Delay)
			beforeRetry()
		}

		retries = retries - 1
	}

	if err != nil {

		color.Red("\nError even after %d retries:\n%v", NumRetries, err)
		if PanicEnabled == true {
			panic(err)
		}
		return err
	}

	if atleastOneError != nil {
		color.Cyan("\nRecovered from error: %v in %d tries\n", atleastOneError, (NumRetries - retries - 1))
	}

	return err

}
示例#4
0
文件: utils.go 项目: gini/gapicmd
func renderResults(obj interface{}) error {
	boldMagenta := color.New(color.FgMagenta).Add(color.Bold).Add(color.Underline)
	boldMagenta.Printf("★★★ Results ★★★\n\n")

	pretty, err := prettyJSON(obj)

	if err != nil {
		color.Red("%s: %s\n", pretty, err)
	} else {
		color.Magenta("%s\n", pretty)
	}

	return err
}
示例#5
0
func runDelete(args []string) {
	config := stash.NewConfig()
	reader := bufio.NewReader(os.Stdin)
	color.Red("WARNING! Deleted entries cannot be recovered")
	color.Blue("Please choose one of the following entries: ")
	for _, entry := range config.Entries {
		color.Magenta("	%s", entry.Name)
	}
	fmt.Println()
	fmt.Print("Entry to delete (case-sensitive): ")
	text, _ := reader.ReadString('\n')
	text = strings.TrimSpace(text)
	err := config.DeleteEntry(text)
	if err != nil {
		color.Red("Fatal error deleting an entry: %s", err)
		os.Exit(1)
	}
}
示例#6
0
func main() {
	flag.Parse()

	if *sitemapURL == "" {
		fmt.Println("-sitemap に sitemap.xml/.xml.gz のURLを指定してください")
		return
	}

	smap, err := sitemap.Get(*sitemapURL)
	if err != nil {
		fmt.Println(err)
	}

	for _, URL := range smap.URL {
		time.Sleep(time.Second)

		resp, err := http.Get(URL.Loc)
		if err != nil {
			fmt.Println(err)
			continue
		}
		defer resp.Body.Close()
		switch statusType(resp.StatusCode) {
		case 100:
			color.Cyan(resp.Status + " " + URL.Loc)
		case 200:
			color.Green(resp.Status + " " + URL.Loc)
		case 300:
			color.Magenta(resp.Status + " " + URL.Loc)
		case 400:
			color.Red(resp.Status + " " + URL.Loc)
		case 500:
			color.Yellow(resp.Status + " " + URL.Loc)
		default:
			color.White(resp.Status + " " + URL.Loc)
		}
	}
}
示例#7
0
func (this *HelpResponseCreator) CreateHelpResponse(helpContainer Container) {
	color.Magenta(helpContainer.Title)
	for _, cat := range helpContainer.Categories {
		if cat.IsChild {
			color.Yellow(SUB_CAT_SHIFT + cat.Title)
		} else {
			fmt.Println("")
			color.Yellow(cat.Title + ":")
		}
		green := color.New(color.FgGreen).SprintFunc()
		black := color.New(color.FgBlue).SprintFunc()
		for _, item := range cat.HelpRows {
			shiftLeft := ITEM_TITLE_SHIFT
			shiftMiddle := ITEM_DESCR_SHIFT
			if item.Title == "" {
				shiftLeft = ""
			}
			if item.Description == "" {
				shiftMiddle = ""
			}
			fmt.Printf(shiftLeft+"%s"+shiftMiddle+"%s\n", green(item.Title), black(item.Description))
		}
	}
}
示例#8
0
func execCmd(c *cli.Context) error {

	cert, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"cert.pem",
	))

	key, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"key.pem",
	))

	ca, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"ca.pem",
	))
	if len(cert) == 0 || len(key) == 0 || len(ca) == 0 {
		println("")
	}

	yml, err := ioutil.ReadFile(".drone.yml")
	if err != nil {
		return err
	}

	axes, err := matrix.Parse(string(yml))
	if err != nil {
		return err
	}
	if len(axes) == 0 {
		axes = append(axes, matrix.Axis{})
	}

	cli, err := newDockerClient(c.String("docker-host"), cert, key, ca)
	if err != nil {
		return err
	}

	pwd, err := os.Getwd()
	if err != nil {
		return err
	}

	proj := resolvePath(pwd)

	var exits []int

	for i, axis := range axes {
		color.Magenta("[DRONE] starting job #%d", i+1)
		if len(axis) != 0 {
			color.Magenta("[DRONE] export %s", axis)
		}

		payload := struct {
			System    drone.System    `json:"system"`
			Workspace drone.Workspace `json:"workspace"`
			Repo      drone.Repo      `json:"repo"`
			Build     drone.Build     `json:"build"`
			Job       drone.Job       `json:"job"`
			Config    string          `json:"config"`
		}{
			Job: drone.Job{
				Status:      drone.StatusRunning,
				Environment: axis,
			},
			Config: string(yml),
			Build: drone.Build{
				Status: drone.StatusRunning,
				Commit: "0000000000", // hack
			},
		}
		if len(proj) != 0 {
			payload.Repo.Link = fmt.Sprintf("https://%s", proj)
		}
		out, _ := json.Marshal(payload)

		exit, err := run(cli, pwd, string(out))
		if err != nil {
			return err
		}
		exits = append(exits, exit)

		color.Magenta("[DRONE] finished job #%d", i+1)
		color.Magenta("[DRONE] exit code %d", exit)
	}

	var passed = true
	for i, _ := range axes {
		exit := exits[i]
		if exit == 0 {
			color.Green("[DRONE] job #%d passed", i+1)
		} else {
			color.Red("[DRONE] job #%d failed", i+1)
			passed = false
		}
	}
	if passed {
		color.Green("[DRONE] build passed")
	} else {
		color.Red("[DRONE] build failed")
		os.Exit(1)
	}

	return nil
}
示例#9
0
文件: exec.go 项目: thomasf/drone-cli
func execCmd(c *cli.Context) error {
	info := git.Info()

	cert, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"cert.pem",
	))

	key, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"key.pem",
	))

	ca, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"ca.pem",
	))
	if len(cert) == 0 || len(key) == 0 || len(ca) == 0 {
		println("")
	}

	yml, err := ioutil.ReadFile(".drone.yml")
	if err != nil {
		return err
	}

	axes, err := matrix.Parse(string(yml))
	if err != nil {
		return err
	}
	if len(axes) == 0 {
		axes = append(axes, matrix.Axis{})
	}

	cli, err := newDockerClient(c.String("docker-host"), cert, key, ca)
	if err != nil {
		return err
	}

	pwd, err := os.Getwd()
	if err != nil {
		return err
	}

	execArgs := []string{"--build", "--debug", "--mount", pwd}
	for _, arg := range []string{"cache", "deploy", "notify", "pull"} {
		if c.Bool(arg) {
			execArgs = append(execArgs, "--"+arg)
		}
	}

	proj := resolvePath(pwd)

	var exits []int

	for i, axis := range axes {
		color.Magenta("[DRONE] starting job #%d", i+1)
		if len(axis) != 0 {
			color.Magenta("[DRONE] export %s", axis)
		}

		payload := struct {
			System    drone.System    `json:"system"`
			Workspace drone.Workspace `json:"workspace"`
			Repo      drone.Repo      `json:"repo"`
			Build     drone.Build     `json:"build"`
			Job       drone.Job       `json:"job"`
			Netrc     drone.Netrc     `json:"netrc"`
			Keys      drone.Key       `json:"keys"`
			Config    string          `json:"config"`
		}{
			Repo: drone.Repo{
				IsTrusted: c.Bool("trusted"),
				IsPrivate: true,
			},
			Job: drone.Job{
				Status:      drone.StatusRunning,
				Environment: axis,
			},
			Config: string(yml),
			Build: drone.Build{
				Status:  drone.StatusRunning,
				Branch:  info.Branch,
				Commit:  info.Head.Id,
				Author:  info.Head.AuthorName,
				Email:   info.Head.AuthorEmail,
				Message: info.Head.Message,
				Event:   c.String("event"),
			},
			System: drone.System{
				Link:    c.GlobalString("server"),
				Globals: c.StringSlice("e"),
				Plugins: []string{"plugins/*", "*/*"},
			},
		}

		// gets the ssh key if provided
		if len(c.String("i")) != 0 {
			key, err = ioutil.ReadFile(c.String("i"))
			if err != nil {
				return err
			}
			payload.Keys = drone.Key{
				Private: string(key),
			}
			payload.Netrc = drone.Netrc{}
		}

		if len(proj) != 0 {
			payload.Repo.Link = fmt.Sprintf("https://%s", proj)
		}
		out, _ := json.Marshal(payload)

		exit, err := run(cli, execArgs, string(out))
		if err != nil {
			return err
		}
		exits = append(exits, exit)

		color.Magenta("[DRONE] finished job #%d", i+1)
		color.Magenta("[DRONE] exit code %d", exit)
	}

	var passed = true
	for i, _ := range axes {
		exit := exits[i]
		if exit == 0 {
			color.Green("[DRONE] job #%d passed", i+1)
		} else {
			color.Red("[DRONE] job #%d failed", i+1)
			passed = false
		}
	}
	if passed {
		color.Green("[DRONE] build passed")
	} else {
		color.Red("[DRONE] build failed")
		os.Exit(1)
	}

	return nil
}
示例#10
0
// given a file path as arg, render the markdown
func Render(arg string, stats bool) {

	// get the current Directory
	workingDir, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// construct the file path
	filePath := path.Join(workingDir, arg)

	file, err := os.Open(filePath)
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	input := ""
	meta_info := make(map[string]string)

	// isolated meta info from the markdown real body
	i := 0
	for scanner.Scan() {

		line := scanner.Text()
		if strings.HasPrefix(line, "---") {
			i += 1
			continue
		}

		// until we reach the end meta block, just continue
		if i > 0 && i < 2 {
			key_value := strings.SplitN(line, ":", 2)

			if len(key_value) == 2 {
				key := strings.Trim(key_value[0], " ")
				value := strings.Trim(key_value[1], " ")
				value = strings.Trim(value, "\"")
				value = strings.Trim(value, " ")
				meta_info[key] = value

			}
			continue
		}
		if strings.HasPrefix(line, string('#')) {
			line = goarabic.RemoveTashkeel(line)
		}
		input += line + "\n"
	}

	if stats {
		current_input := input
		defer func() {
			color.Magenta("---- stats ----\n")
			fmt.Println("Length:", goarabic.SmartLength(&current_input), "chars.")
			fmt.Println("Words: ~", len(strings.Split(current_input, " ")), "words.")
			links := xurls.Relaxed.FindAllString(current_input, -1)

			for i := 0; i < len(links); i++ {
				color.White("Found external Link: " + links[i])
			}
		}()

	}

	if len(meta_info) > 0 {
		orig_link := ""
		orig_title := ""
		orig_author := ""
		title := ""

		if val, ok := meta_info["عنوان المقال"]; ok {
			title = val
			title_no_tashkeel := goarabic.RemoveTashkeel(title)
			if title != goarabic.RemoveTashkeel(title) {
				input = "# " + title_no_tashkeel + "\n" + input
			}
		}

		if val, ok := meta_info["الرابط الأصلي للمقال (إن كان مترجما)"]; ok {
			orig_link = val
		} else if val, ok := meta_info["الرابط الأصلي للمقال"]; ok {
			orig_link = val
		}

		if val, ok := meta_info["العنوان الأصلي للمقال (إن كان مترجما)"]; ok {
			orig_title = val
		} else if val, ok := meta_info["العنوان الأصلي للمقال"]; ok {
			orig_title = val
		}
		if len(orig_link) > 0 && len(orig_title) > 0 {
			input += "\nترجمة -وبتصرف- للمقال: [" + orig_title + "](" + orig_link + ")"
		}

		if val, ok := meta_info["الكاتب الأصلي (إن كان مترجما)"]; ok {
			orig_author = val
		} else if val, ok := meta_info["الكاتب الأصلي"]; ok {
			orig_author = val
		}

		if len(orig_author) > 0 {
			input += " لصاحبه: " + orig_author + ".\n"
		} else {
			input += ".\n"
		}
	}

	if err := scanner.Err(); err != nil {
		log.Fatal(err)
	}

	// set up Markdown options
	extensions := 0
	extensions |= blackfriday.EXTENSION_TABLES
	// extensions |= blackfriday.EXTENSION_FENCED_CODE
	extensions |= blackfriday.EXTENSION_AUTOLINK
	extensions |= blackfriday.EXTENSION_STRIKETHROUGH
	// extensions |= blackfriday.EXTENSION_SPACE_HEADERS
	extensions |= blackfriday.EXTENSION_HARD_LINE_BREAK
	extensions |= blackfriday.EXTENSION_NO_EMPTY_LINE_BEFORE_BLOCK
	extensions |= blackfriday.EXTENSION_LAX_HTML_BLOCKS

	// Make a custom Renderer
	var renderer blackfriday.Renderer

	htmlFlags := 0
	htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS

	renderer = blackfriday.HtmlRenderer(htmlFlags, "", "")

	output := blackfriday.Markdown([]byte(input), renderer, extensions)

	strOutput := string(output)

	err = clipboard.WriteAll(strOutput)
	// fmt.Println(strOutput)
	if err != nil {
		log.Println(err)
		color.Yellow("Content here instead.\n\n")
		fmt.Println(strOutput)
	} else {
		color.Green("Markdown content copied to clipboard.")
	}

}
示例#11
0
文件: stack.go 项目: mk2/yon
func printFuncWord(depth int, w kit.FuncWord) {

	color.Magenta(fBase, depth, w.Format())
}
示例#12
0
文件: stack.go 项目: mk2/yon
func printNumberWord(depth int, w kit.NumberWord) {

	color.Magenta(fBase, depth, w.Format())
}
示例#13
0
文件: main.go 项目: gtfierro/giles2
func main() {
	//var wg sync.WaitGroup

	var files []string
	var found []string
	var findErr error

	if len(os.Args) > 1 {
		for _, file := range os.Args[1:] {
			if strings.HasSuffix(file, ".yaml") {
				found, findErr = filepath.Glob(file)
				if findErr != nil {
					log.Fatalf("Error finding file %v (%v)", file, findErr)
				}
			} else { //directory
				found = findall(os.Args[1])
			}
			files = append(files, found...)
		}
	} else {
		files, findErr = filepath.Glob("tests/*.yaml")
		if findErr != nil {
			log.Fatalf("Error reading yaml files in current directory (%v)", findErr)
		}
	}

	totalTests := len(files)
	passedTests := 0
	for _, filename := range files {
		// create new set of references for each file
		referenceManager = NewManager()
		color.Cyan("Running file %v", filename)
		contents, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Fatalf("Error reading file %v (%v)\n", filename, err)
		}
		contents = []byte(referenceManager.ParseData(string(contents)))
		m := make(Config)
		err = yaml.Unmarshal(contents, &m)
		if err != nil {
			log.Fatalf("Error decoding yaml (%v)\n", err)
		}

		clients := GetConfigs(m)
		steps := ParseLayout(m["layout"].(string), clients)
		errors := make([]error, len(steps))
		for idx, step := range steps {
			step.Run()
			errors[idx] = step.Err()
			//wg.Add(1)
			//go func(idx int, s *Step) {
			//	s.Run()
			//	errors[idx] = s.Err()
			//	defer wg.Done()
			//}(idx, step)
		}
		//wg.Wait()
		hasError := false
		for _, e := range errors {
			if e != nil {
				color.Magenta("Error on chain: %v", e)
				hasError = true
			}
		}

		if !hasError {
			color.Green("Test [%v] passed!\n\n", m["name"].(string))
			passedTests += 1
		} else {
			color.Red("Test [%v] FAILED!\n\n", m["name"].(string))
		}

	}

	if passedTests == totalTests {
		color.Green("Passed %v of %v tests!", passedTests, totalTests)
	} else if passedTests > 0 {
		color.Yellow("Passed %v of %v tests!", passedTests, totalTests)
	} else {
		color.Red("Passed NOTHING of %v tests!", totalTests)
	}
}
示例#14
0
func execCmd(c *cli.Context) error {
	info := git.Info()

	cert, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"cert.pem",
	))

	key, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"key.pem",
	))

	ca, _ := ioutil.ReadFile(filepath.Join(
		c.String("docker-cert-path"),
		"ca.pem",
	))
	if len(cert) == 0 || len(key) == 0 || len(ca) == 0 {
		println("")
	}

	yml, err := ioutil.ReadFile(".drone.yml")
	if err != nil {
		return err
	}

	// initially populate globals from the '-e' slice
	globals := c.StringSlice("e")
	if c.IsSet("E") {
		// read the .drone.sec.yml file (plain text)
		plaintext, err := readInput(c.String("E"))
		if err != nil {
			return err
		}

		// parse the plaintext secrets file
		sec := new(secure.Secure)
		err = yaml.Unmarshal(plaintext, sec)
		if err != nil {
			return err
		}

		// prepend values into globals (allow '-e' to override the secrets file)
		for k, v := range sec.Environment.Map() {
			tmp := strings.Join([]string{k, v}, "=")
			globals = append([]string{tmp}, globals...)
		}
	}

	axes, err := matrix.Parse(string(yml))
	if err != nil {
		return err
	}
	if len(axes) == 0 {
		axes = append(axes, matrix.Axis{})
	}

	cli, err := newDockerClient(c.String("docker-host"), cert, key, ca)
	if err != nil {
		return err
	}

	pwd, err := os.Getwd()
	if err != nil {
		return err
	}

	execArgs := []string{"--build", "--debug", "--mount", pwd}
	for _, arg := range []string{"cache", "deploy", "notify", "pull"} {
		if c.Bool(arg) {
			execArgs = append(execArgs, "--"+arg)
		}
	}
	if c.Bool("pull") {
		image := "drone/drone-exec:latest"
		color.Magenta("[DRONE] pulling %s", image)
		err := cli.PullImage(image, nil)
		if err != nil {
			color.Red("[DRONE] failed to pull %s", image)
			os.Exit(1)
		}
	}

	proj := resolvePath(pwd)

	var exits []int

	for i, axis := range axes {
		color.Magenta("[DRONE] starting job #%d", i+1)
		if len(axis) != 0 {
			color.Magenta("[DRONE] export %s", axis)
		}

		payload := drone.Payload{
			Repo: &drone.Repo{
				IsTrusted: c.Bool("trusted"),
				IsPrivate: true,
			},
			Job: &drone.Job{
				Status:      drone.StatusRunning,
				Environment: axis,
			},
			Yaml: string(yml),
			Build: &drone.Build{
				Status:  drone.StatusRunning,
				Branch:  info.Branch,
				Commit:  info.Head.ID,
				Author:  info.Head.AuthorName,
				Email:   info.Head.AuthorEmail,
				Message: info.Head.Message,
				Event:   c.String("event"),
			},
			System: &drone.System{
				Link:    c.GlobalString("server"),
				Globals: globals,
				Plugins: []string{"plugins/*", "*/*"},
			},
		}

		// gets the ssh key if provided
		if len(c.String("i")) != 0 {
			key, err = ioutil.ReadFile(c.String("i"))
			if err != nil {
				return err
			}
			payload.Keys = &drone.Key{
				Private: string(key),
			}
			payload.Netrc = &drone.Netrc{}
		}

		if len(proj) != 0 {
			payload.Repo.Link = fmt.Sprintf("https://%s", proj)
		}
		out, _ := json.Marshal(payload)

		exit, err := run(cli, execArgs, string(out))
		if err != nil {
			return err
		}
		exits = append(exits, exit)

		color.Magenta("[DRONE] finished job #%d", i+1)
		color.Magenta("[DRONE] exit code %d", exit)
	}

	var passed = true
	for i, _ := range axes {
		exit := exits[i]
		if exit == 0 {
			color.Green("[DRONE] job #%d passed", i+1)
		} else {
			color.Red("[DRONE] job #%d failed", i+1)
			passed = false
		}
	}
	if passed {
		color.Green("[DRONE] build passed")
	} else {
		color.Red("[DRONE] build failed")
		os.Exit(1)
	}

	return nil
}