示例#1
0
文件: doc.go 项目: kuuyee/peach
func initLangDocs(tocs map[string]*Toc, localRoot, lang string) {
	toc := tocs[lang]

	for _, dir := range toc.Nodes {
		if err := dir.ReloadContent(); err != nil {
			log.Error("Fail to load doc file: %v", err)
			continue
		}

		for _, file := range dir.Nodes {
			if com.IsFile(file.FileName) {
				if err := file.ReloadContent(); err != nil {
					log.Error("Fail to load doc file: %v", err)
					continue
				}
			}
		}
	}

	for _, page := range toc.Pages {
		if err := page.ReloadContent(); err != nil {
			log.Error("Fail to load doc file: %v", err)
			continue
		}
	}
}
示例#2
0
文件: models.go 项目: mehulsbhatt/fws
// FibonacciSequence generates a sequence of first n Fibonacci numbers
// starting from 0. It returns nil if num is negative.
func FibonacciSequence(num int) []int64 {
	if num < 0 {
		return nil
	} else if num == 0 {
		return []int64{}
	} else if num == 1 {
		return []int64{0}
	}

	// Calculate sequence.
	seq := []int64{0, 1}
	cursor := 2
	var lastNum int64 = 1
	for cursor < num {
		lastNum = seq[cursor-2] + seq[cursor-1]

		// Check overflow, the current number ovbiously
		// cannot be smaller then previous one.
		if lastNum < seq[cursor-1] {
			log.Error("Unable to produce %dth fibonacci value", cursor)
			return nil
		}
		seq = append(seq, lastNum)
		cursor++
	}
	return seq
}
示例#3
0
文件: toc.go 项目: 0-T-0/peach
func (n *Node) Content() []byte {
	if !setting.ProdMode {
		if err := n.ReloadContent(); err != nil {
			log.Error("Fail to reload content: %v", err)
		}
	}

	return n.content
}
示例#4
0
文件: sync.go 项目: jacobxk/bra
func receiveHandler(conn net.Conn) {
	defer conn.Close()

	remoteAddr := conn.RemoteAddr().String()
	p := make([]byte, 1024)
	n, err := conn.Read(p)
	if err != nil {
		log.Error("Cannot read header(%s): %v", remoteAddr, err)
		return
	} else if n == 0 {
		log.Error("Empty header(%s)", remoteAddr)
		return
	}

	fileName := string(p[:n])
	log.Info("File: %s", fileName)
	os.MkdirAll(path.Dir(fileName), os.ModePerm)
	f, err := os.Create(fileName)
	if err != nil {
		log.Error("Fail to create file(%s:%s): %v", remoteAddr, fileName, err)
		return
	}
	defer f.Close()

	conn.Write([]byte("ok"))

	_, err = io.Copy(f, conn)
	for {
		buffer := make([]byte, 1024*200)
		n, err := conn.Read(buffer)
		//blockSize := int64(n)
		_ = n
		if err != nil && err != io.EOF {
			log.Error("Cannot read(%s:%s): %v", remoteAddr, fileName, err)
		} else if err == io.EOF {
			break
		}
	}
	if err != nil {
		log.Error("Fail to receive file(%s:%s): %v\n", remoteAddr, fileName, err)
		return
	}
	log.Info("File received: %s", fileName)
}
示例#5
0
文件: run.go 项目: replay/bra
func notify(cmds [][]string) {
	runningLock.Lock()
	defer func() {
		runningCmd = nil
		runningLock.Unlock()
	}()

	for _, cmd := range cmds {
		command := exec.Command(cmd[0], cmd[1:]...)
		command.Stdout = os.Stdout
		command.Stderr = os.Stderr
		if err := command.Start(); err != nil {
			log.Error("Fail to start command %v - %v", cmd, err)
			fmt.Print("\x07")
			return
		}

		log.Debug("Running %v", cmd)
		runningCmd = command
		done := make(chan error)
		go func() {
			done <- command.Wait()
		}()

		isShutdown := false
		select {
		case err := <-done:
			if isShutdown {
				return
			} else if err != nil {
				log.Warn("Fail to execute command %v - %v", cmd, err)
				fmt.Print("\x07")
				return
			}
		case <-shutdown:
			isShutdown = true
			gracefulKill()
			return
		}
	}
	log.Info("Notify operations are done!")
}
示例#6
0
文件: sync.go 项目: jacobxk/bra
func sendFile(fileName string) {
	f, err := os.Open(fileName)
	if err != nil {
		log.Error("Fail to open file: %v", err)
		return
	}
	defer f.Close()

	fi, err := os.Stat(fileName)
	if err != nil {
		log.Error("Fail to stat file: %v", err)
		return
	}

	fileName = strings.Replace(fileName, "\\", "/", -1) //path.Base()
	log.Info("File name: %s; size: %s", fileName, com.HumaneFileSize(uint64(fi.Size())))

	conn, err := net.Dial("tcp", setting.Cfg.Sync.RemoteAddr)
	if err != nil {
		log.Error("Fail to establish connection: %v", err)
		return
	}
	defer conn.Close()

	log.Info("Connection established")

	conn.Write([]byte(fileName))
	p := make([]byte, 2)
	_, err = conn.Read(p)
	if err != nil {
		log.Error("Cannot get response from server: %v", err)
		return
	} else if string(p) != "ok" {
		log.Error("Invalid response: %s", string(p))
		return
	}

	log.Info("Header sent")

	start := time.Now()
	_, err = io.Copy(conn, f)
	if err != nil {
		log.Error("Fail to send file(%s): %v", fileName, err)
		return
	}
	spend := time.Since(start)
	log.Info("File sent, speed: %s/s", com.HumaneFileSize(uint64((fi.Size()*1000000000/int64(spend))/1024)))
}
示例#7
0
文件: run.go 项目: gocontrib/bra
func notify(cmds [][]string) {
	runningLock.Lock()
	defer func() {
		runningCmd = nil
		runningLock.Unlock()
	}()

	for _, cmd := range cmds {
		command := exec.Command(cmd[0], cmd[1:]...)
		command.Stdout = os.Stdout
		command.Stderr = os.Stderr
		if err := command.Start(); err != nil {
			log.Error("Fail to start command %v", cmd)
			fmt.Print("\x07")
			return
		}
		runningCmd = command
		done := make(chan error)
		go func() {
			done <- command.Wait()
		}()

		select {
		case err := <-done:
			if err != nil {
				if strings.Contains(err.Error(), "signal: killed") {
					return
				}

				log.Warn("Fail to execute command %v", cmd)
				fmt.Print("\x07")
				return
			}
		}
	}
	log.Info("Notify operations are done!")
}
示例#8
0
文件: run.go 项目: replay/bra
func runRun(ctx *cli.Context) {
	setup(ctx)

	go catchSignals()
	go notify(setting.Cfg.Run.InitCmds)

	watchPathes := append([]string{setting.WorkDir}, setting.Cfg.Run.WatchDirs...)
	if setting.Cfg.Run.WatchAll {
		subdirs := make([]string, 0, 10)
		for _, dir := range watchPathes[1:] {
			dirs, err := com.GetAllSubDirs(setting.UnpackPath(dir))
			if err != nil {
				log.Fatal("Fail to get sub-directories: %v", err)
			}
			for i := range dirs {
				if !setting.IgnoreDir(dirs[i]) {
					subdirs = append(subdirs, path.Join(dir, dirs[i]))
				}
			}
		}
		watchPathes = append(watchPathes, subdirs...)
	}

	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal("Fail to create new watcher: %v", err)
	}
	defer watcher.Close()

	go func() {
		for {
			select {
			case e := <-watcher.Events:
				needsNotify := true

				if isTmpFile(e.Name) || !hasWatchExt(e.Name) || setting.IgnoreFile(e.Name) {
					continue
				}

				// Prevent duplicated builds.
				if lastBuild.Add(time.Duration(setting.Cfg.Run.BuildDelay) * time.Millisecond).
					After(time.Now()) {
					continue
				}
				lastBuild = time.Now()

				showName := e.String()
				if !log.NonColor {
					showName = strings.Replace(showName, setting.WorkDir, "\033[47;30m$WORKDIR\033[0m", 1)
				}

				if e.Op&fsnotify.Remove != fsnotify.Remove {
					mt, err := com.FileMTime(e.Name)
					if err != nil {
						log.Error("Fail to get file modify time: %v", err)
						continue
					}
					if eventTime[e.Name] == mt {
						log.Debug("Skipped %s", showName)
						needsNotify = false
					}
					eventTime[e.Name] = mt
				}

				if needsNotify {
					log.Info(showName)
					if runningCmd != nil && runningCmd.Process != nil {
						if runningCmd.Args[0] == "sudo" && runtime.GOOS == "linux" {
							// 给父进程发送一个TERM信号,试图杀死它和它的子进程
							rootCmd := exec.Command("sudo", "kill", "-TERM", com.ToStr(runningCmd.Process.Pid))
							rootCmd.Stdout = os.Stdout
							rootCmd.Stderr = os.Stderr
							if err := rootCmd.Run(); err != nil {
								log.Error("Fail to start rootCmd %s", err.Error())
								fmt.Print("\x07")
							}
						} else {
							shutdown <- true
						}
					}
					go notify(setting.Cfg.Run.Cmds)
				}
			}
		}
	}()

	log.Info("Following directories are monitored:")
	for i, p := range watchPathes {
		if err = watcher.Add(setting.UnpackPath(p)); err != nil {
			log.Fatal("Fail to watch diretory(%s): %v", p, err)
		}
		if i > 0 && !log.NonColor {
			p = strings.Replace(p, setting.WorkDir, "\033[47;30m$WORKDIR\033[0m", 1)
			p = strings.Replace(p, "$WORKDIR", "\033[47;30m$WORKDIR\033[0m", 1)
		}
		fmt.Printf("-> %s\n", p)
	}
	select {}
}
示例#9
0
文件: event.go 项目: mehulsbhatt/cgx
func (e *Event) setError(errmsg string) {
	e.Error = errmsg
	if _, err := x.Id(e.ID).AllCols().Update(e); err != nil {
		log.Error("Event.setError[%d]: %v", e.ID, err)
	}
}
示例#10
0
文件: event.go 项目: mehulsbhatt/cgx
func (e *Event) Build() {
	defer func() {
		log.Debug("Build finished: %s", e.Ref)
	}()

	// Fetch archive for reference.
	localPath := path.Join(setting.GOPATHSrc, path.Dir(setting.Repository.ImportPath))
	name := path.Base(setting.Repository.ImportPath)
	fullLocalPath := path.Join(localPath, name)

	defer os.RemoveAll(path.Join(setting.GOPATH, "bin"))

	// Start building targets.
	for _, target := range setting.Targets {
		envs := append([]string{
			"GOPATH=" + setting.GOPATH,
			"GOOS=" + target.GOOS,
			"GOARCH=" + target.GOARCH,
			"GOARM=" + target.GOARM,
		}, os.Environ()...)
		tags := setting.Cfg.Section("tags." + target.GOOS).Key("TAGS").MustString("")

		bufErr := new(bytes.Buffer)

		log.Debug("Getting dependencies: %s", e.targetString(target))
		cmd := exec.Command("go", "get", "-v", "-u", "-tags", tags, setting.Repository.ImportPath)
		cmd.Env = envs
		cmd.Stdout = os.Stdout
		cmd.Stderr = bufErr

		if err := cmd.Run(); err != nil {
			fmt.Println(bufErr.String())
			e.setError(fmt.Sprintf("Event.Build.(get dependencies): %s", bufErr.String()))
			return
		}

		log.Debug("Checking out branch: %s", e.Ref)
		cmd = exec.Command("git", "checkout", e.Ref)
		cmd.Env = envs
		cmd.Dir = fullLocalPath
		cmd.Stdout = os.Stdout
		cmd.Stderr = bufErr

		if err := cmd.Run(); err != nil {
			fmt.Println(bufErr.String())
			e.setError(fmt.Sprintf("Event.Build.(checkout branch): %s", bufErr.String()))
			return
		}

		log.Debug("Building target: %s", e.targetString(target))
		cmd = exec.Command("go", "build", "-v", "-tags", tags)
		cmd.Env = envs
		cmd.Dir = fullLocalPath
		cmd.Stdout = os.Stdout
		cmd.Stderr = bufErr

		if err := cmd.Run(); err != nil {
			fmt.Println(bufErr.String())
			e.setError(fmt.Sprintf("Event.Build.(build target): %s", bufErr.String()))
			return
		}

		if err := e.packTarget(fullLocalPath, name, setting.ArchivePath, target); err != nil {
			e.setError(fmt.Sprintf("Event.Build.packTarget: %v", err))
			return
		}

		targetName := name + "_" + e.targetString(target)
		for i := range Targets {
			if Targets[i].Name == targetName {
				Targets[i].LastBuild = time.Now()
				break
			}
		}
	}

	e.IsSucceed = true
	if _, err := x.Id(e.ID).AllCols().Update(e); err != nil {
		log.Error("Event.Build.Update: %v", err)
	}
}