<commit_before>// Package dyndns provides a tool for running a
// dynamic dns updating service.
package dyndns

import (
	"fmt"
	"github.com/mfycheng/name-dyndns/api"
	"github.com/mfycheng/name-dyndns/log"
	"strings"
	"sync"
	"time"
)

var wg sync.WaitGroup

func contains(c api.Config, val string) bool {
	if val == c.Domain {
		return true
	}

	for _, v := range c.Hostnames {
		if fmt.Sprintf("%s.%s", v, c.Domain) == val {
			return true
		}
	}
	return false
}

func updateDNSRecord(a api.API, domain, recordId string, newRecord api.DNSRecord) error {
	log.Logger.Printf("Deleting DNS record for %s.\n", newRecord.Name)
	err := a.DeleteDNSRecord(domain, newRecord.RecordId)
	if err != nil {
		return err
	}

	log.Logger.Printf("Creating DNS record for %s: %s\n", newRecord.Name, newRecord)

	// Remove the domain from the DNSRecord name.
	// This is an unfortunate inconsistency from the API
	// implementation (returns full name, but only requires host)
	if newRecord.Name == domain {
		newRecord.Name = ""
	} else {
		newRecord.Name = strings.TrimSuffix(newRecord.Name, fmt.Sprintf(".%s", domain))
	}

	return a.CreateDNSRecord(domain, newRecord)
}

func runConfig(c api.Config, daemon bool) {
	defer wg.Done()

	a := api.NewAPIFromConfig(c)
	for {
		ip, err := GetExternalIP()
		if err != nil {
			log.Logger.Print("Failed to retreive IP: ")
			if daemon {
				log.Logger.Printf("Will retry in %d seconds...\n", c.Interval)
				time.Sleep(time.Duration(c.Interval) * time.Second)
				continue
			} else {
				log.Logger.Println("Giving up.")
				break
			}
		}

		// GetRecords retrieves a list of DNSRecords,
		// 1 per hostname with the associated domain.
		// If the content is not the current IP, then
		// update it.
		records, err := a.GetDNSRecords(c.Domain)
		if err != nil {
			log.Logger.Printf("Failed to retreive records for %s:\n\t%s\n", c.Domain, err)
			if daemon {
				log.Logger.Printf("Will retry in %d seconds...\n", c.Interval)
				time.Sleep(time.Duration(c.Interval) * time.Second)
				continue
			} else {
				log.Logger.Print("Giving up.")
				break
			}
		}

		for _, r := range records {
			if !contains(c, r.Name) {
				continue
			}

			log.Logger.Printf("Running update check for %s.", r.Name)
			if r.Content != ip {
				r.Content = ip
				err = updateDNSRecord(a, c.Domain, r.RecordId, r)
				if err != nil {
					log.Logger.Printf("Failed to update record %s [%s] with IP: %s\n\t%s\n", r.RecordId, r.Name, ip, err)
				} else {
					log.Logger.Printf("Updated record %s [%s] with IP: %s\n", r.RecordId, r.Name, ip)
				}
			}
		}

		log.Logger.Println("Update complete.")
		if !daemon {
			log.Logger.Println("Non daemon mode, stopping.")
			return
		}
		log.Logger.Printf("Will update again in %d seconds.\n", c.Interval)

		time.Sleep(time.Duration(c.Interval) * time.Second)
	}
}

// For each domain, check if the host record matches
// the current external IP. If it does not, it updates.
// If daemon is true, then Run will run forever, polling at
// an interval specified in each config.
func Run(configs []api.Config, daemon bool) {
	for _, config := range configs {
		wg.Add(1)
		go runConfig(config, daemon)
	}

	wg.Wait()
}
<commit_msg>Don't always run check on root domain<commit_after>// Package dyndns provides a tool for running a
// dynamic dns updating service.
package dyndns

import (
	"fmt"
	"github.com/mfycheng/name-dyndns/api"
	"github.com/mfycheng/name-dyndns/log"
	"strings"
	"sync"
	"time"
)

var wg sync.WaitGroup

func contains(c api.Config, val string) bool {
	for _, v := range c.Hostnames {
		// We have a special case where an empty hostname
		// is equivalent to the domain (i.e. val == domain).
		if val == c.Domain && v == "" {
			return true
		} else if fmt.Sprintf("%s.%s", v, c.Domain) == val {
			return true
		}
	}
	return false
}

func updateDNSRecord(a api.API, domain, recordId string, newRecord api.DNSRecord) error {
	log.Logger.Printf("Deleting DNS record for %s.\n", newRecord.Name)
	err := a.DeleteDNSRecord(domain, newRecord.RecordId)
	if err != nil {
		return err
	}

	log.Logger.Printf("Creating DNS record for %s: %s\n", newRecord.Name, newRecord)

	// Remove the domain from the DNSRecord name.
	// This is an unfortunate inconsistency from the API
	// implementation (returns full name, but only requires host)
	if newRecord.Name == domain {
		newRecord.Name = ""
	} else {
		newRecord.Name = strings.TrimSuffix(newRecord.Name, fmt.Sprintf(".%s", domain))
	}

	return a.CreateDNSRecord(domain, newRecord)
}

func runConfig(c api.Config, daemon bool) {
	defer wg.Done()

	a := api.NewAPIFromConfig(c)
	for {
		ip, err := GetExternalIP()
		if err != nil {
			log.Logger.Print("Failed to retreive IP: ")
			if daemon {
				log.Logger.Printf("Will retry in %d seconds...\n", c.Interval)
				time.Sleep(time.Duration(c.Interval) * time.Second)
				continue
			} else {
				log.Logger.Println("Giving up.")
				break
			}
		}

		// GetRecords retrieves a list of DNSRecords,
		// 1 per hostname with the associated domain.
		// If the content is not the current IP, then
		// update it.
		records, err := a.GetDNSRecords(c.Domain)
		if err != nil {
			log.Logger.Printf("Failed to retreive records for %s:\n\t%s\n", c.Domain, err)
			if daemon {
				log.Logger.Printf("Will retry in %d seconds...\n", c.Interval)
				time.Sleep(time.Duration(c.Interval) * time.Second)
				continue
			} else {
				log.Logger.Print("Giving up.")
				break
			}
		}

		for _, r := range records {
			if !contains(c, r.Name) {
				continue
			}

			log.Logger.Printf("Running update check for %s.", r.Name)
			if r.Content != ip {
				r.Content = ip
				err = updateDNSRecord(a, c.Domain, r.RecordId, r)
				if err != nil {
					log.Logger.Printf("Failed to update record %s [%s] with IP: %s\n\t%s\n", r.RecordId, r.Name, ip, err)
				} else {
					log.Logger.Printf("Updated record %s [%s] with IP: %s\n", r.RecordId, r.Name, ip)
				}
			}
		}

		log.Logger.Println("Update complete.")
		if !daemon {
			log.Logger.Println("Non daemon mode, stopping.")
			return
		}
		log.Logger.Printf("Will update again in %d seconds.\n", c.Interval)

		time.Sleep(time.Duration(c.Interval) * time.Second)
	}
}

// For each domain, check if the host record matches
// the current external IP. If it does not, it updates.
// If daemon is true, then Run will run forever, polling at
// an interval specified in each config.
func Run(configs []api.Config, daemon bool) {
	for _, config := range configs {
		wg.Add(1)
		go runConfig(config, daemon)
	}

	wg.Wait()
}
<|endoftext|>


<commit_before>package common

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/signal"
	"strings"
)

var (
	GoPath = os.Getenv("GOPATH")
)

func TrapSignal(cb func()) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, os.Kill)
	go func() {
		for sig := range c {
			fmt.Printf("captured %v, exiting...\n", sig)
			if cb != nil {
				cb()
			}
			os.Exit(1)
		}
	}()
	select {}
}

func Exit(s string) {
	fmt.Printf(s + "\n")
	os.Exit(1)
}

func EnsureDir(dir string, mode os.FileMode) error {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, mode)
		if err != nil {
			return fmt.Errorf("Could not create directory %v. %v", dir, err)
		}
	}
	return nil
}

func IsDirEmpty(name string) (bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return true, err //folder is non-existent
	}
	defer f.Close()

	_, err = f.Readdirnames(1) // Or f.Readdir(1)
	if err == io.EOF {
		return true, nil
	}
	return false, err // Either not empty or error, suits both cases
}

func FileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	return !os.IsNotExist(err)
}

func ReadFile(filePath string) ([]byte, error) {
	return ioutil.ReadFile(filePath)
}

func MustReadFile(filePath string) []byte {
	fileBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		Exit(Fmt("MustReadFile failed: %v", err))
		return nil
	}
	return fileBytes
}

func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
	err := ioutil.WriteFile(filePath, contents, mode)
	if err != nil {
		return err
	}
	// fmt.Printf("File written to %v.\n", filePath)
	return nil
}

func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
	err := WriteFile(filePath, contents, mode)
	if err != nil {
		Exit(Fmt("MustWriteFile failed: %v", err))
	}
}

// WriteFileAtomic writes newBytes to temp and atomically moves to filePath
// when everything else succeeds.
func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
	// If a file already exists there, copy to filePath+".bak" (overwrite anything)
	if _, err := os.Stat(filePath); !os.IsNotExist(err) {
		fileBytes, err := ioutil.ReadFile(filePath)
		if err != nil {
			return fmt.Errorf("Could not read file %v. %v", filePath, err)
		}
		err = ioutil.WriteFile(filePath+".bak", fileBytes, mode)
		if err != nil {
			return fmt.Errorf("Could not write file %v. %v", filePath+".bak", err)
		}
	}
	f, err := ioutil.TempFile("", "")
	if err != nil {
		return err
	}
	_, err = f.Write(newBytes)
	if err == nil {
		err = f.Sync()
	}
	if closeErr := f.Close(); err == nil {
		err = closeErr
	}
	if permErr := os.Chmod(f.Name(), mode); err == nil {
		err = permErr
	}
	if err == nil {
		err = os.Rename(f.Name(), filePath)
	}
	// any err should result in full cleanup
	if err != nil {
		os.Remove(f.Name())
	}
	return err
}

//--------------------------------------------------------------------------------

func Tempfile(prefix string) (*os.File, string) {
	file, err := ioutil.TempFile("", prefix)
	if err != nil {
		PanicCrisis(err)
	}
	return file, file.Name()
}

func Tempdir(prefix string) (*os.File, string) {
	tempDir := os.TempDir() + "/" + prefix + RandStr(12)
	err := EnsureDir(tempDir, 0700)
	if err != nil {
		panic(Fmt("Error creating temp dir: %v", err))
	}
	dir, err := os.Open(tempDir)
	if err != nil {
		panic(Fmt("Error opening temp dir: %v", err))
	}
	return dir, tempDir
}

//--------------------------------------------------------------------------------

func Prompt(prompt string, defaultValue string) (string, error) {
	fmt.Print(prompt)
	reader := bufio.NewReader(os.Stdin)
	line, err := reader.ReadString('\n')
	if err != nil {
		return defaultValue, err
	} else {
		line = strings.TrimSpace(line)
		if line == "" {
			return defaultValue, nil
		}
		return line, nil
	}
}
<commit_msg>[common] do not create {filePath}.bak in WriteFileAtomic<commit_after>package common

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/signal"
	"strings"
)

var (
	GoPath = os.Getenv("GOPATH")
)

func TrapSignal(cb func()) {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt)
	signal.Notify(c, os.Kill)
	go func() {
		for sig := range c {
			fmt.Printf("captured %v, exiting...\n", sig)
			if cb != nil {
				cb()
			}
			os.Exit(1)
		}
	}()
	select {}
}

func Exit(s string) {
	fmt.Printf(s + "\n")
	os.Exit(1)
}

func EnsureDir(dir string, mode os.FileMode) error {
	if _, err := os.Stat(dir); os.IsNotExist(err) {
		err := os.MkdirAll(dir, mode)
		if err != nil {
			return fmt.Errorf("Could not create directory %v. %v", dir, err)
		}
	}
	return nil
}

func IsDirEmpty(name string) (bool, error) {
	f, err := os.Open(name)
	if err != nil {
		return true, err //folder is non-existent
	}
	defer f.Close()

	_, err = f.Readdirnames(1) // Or f.Readdir(1)
	if err == io.EOF {
		return true, nil
	}
	return false, err // Either not empty or error, suits both cases
}

func FileExists(filePath string) bool {
	_, err := os.Stat(filePath)
	return !os.IsNotExist(err)
}

func ReadFile(filePath string) ([]byte, error) {
	return ioutil.ReadFile(filePath)
}

func MustReadFile(filePath string) []byte {
	fileBytes, err := ioutil.ReadFile(filePath)
	if err != nil {
		Exit(Fmt("MustReadFile failed: %v", err))
		return nil
	}
	return fileBytes
}

func WriteFile(filePath string, contents []byte, mode os.FileMode) error {
	err := ioutil.WriteFile(filePath, contents, mode)
	if err != nil {
		return err
	}
	// fmt.Printf("File written to %v.\n", filePath)
	return nil
}

func MustWriteFile(filePath string, contents []byte, mode os.FileMode) {
	err := WriteFile(filePath, contents, mode)
	if err != nil {
		Exit(Fmt("MustWriteFile failed: %v", err))
	}
}

// WriteFileAtomic writes newBytes to temp and atomically moves to filePath
// when everything else succeeds.
func WriteFileAtomic(filePath string, newBytes []byte, mode os.FileMode) error {
	f, err := ioutil.TempFile("", "")
	if err != nil {
		return err
	}
	_, err = f.Write(newBytes)
	if err == nil {
		err = f.Sync()
	}
	if closeErr := f.Close(); err == nil {
		err = closeErr
	}
	if permErr := os.Chmod(f.Name(), mode); err == nil {
		err = permErr
	}
	if err == nil {
		err = os.Rename(f.Name(), filePath)
	}
	// any err should result in full cleanup
	if err != nil {
		os.Remove(f.Name())
	}
	return err
}

//--------------------------------------------------------------------------------

func Tempfile(prefix string) (*os.File, string) {
	file, err := ioutil.TempFile("", prefix)
	if err != nil {
		PanicCrisis(err)
	}
	return file, file.Name()
}

func Tempdir(prefix string) (*os.File, string) {
	tempDir := os.TempDir() + "/" + prefix + RandStr(12)
	err := EnsureDir(tempDir, 0700)
	if err != nil {
		panic(Fmt("Error creating temp dir: %v", err))
	}
	dir, err := os.Open(tempDir)
	if err != nil {
		panic(Fmt("Error opening temp dir: %v", err))
	}
	return dir, tempDir
}

//--------------------------------------------------------------------------------

func Prompt(prompt string, defaultValue string) (string, error) {
	fmt.Print(prompt)
	reader := bufio.NewReader(os.Stdin)
	line, err := reader.ReadString('\n')
	if err != nil {
		return defaultValue, err
	} else {
		line = strings.TrimSpace(line)
		if line == "" {
			return defaultValue, nil
		}
		return line, nil
	}
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, Rob Thornton
// All rights reserved.
// This source code is governed by a Simplied BSD-License. Please see the
// LICENSE included in this distribution for a copy of the full license
// or, if one is not included, you may also find a copy at
// http://opensource.org/licenses/BSD-2-Clause

package comp

import (
	"fmt"
	"os"
	"strconv"

	"github.com/rthornton128/calc/ast"
	"github.com/rthornton128/calc/parse"
	"github.com/rthornton128/calc/token"
)

type compiler struct {
	fp *os.File
}

func CompileFile(fname, src string) {

	var c compiler
	fp, err := os.Create(fname + ".c")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer fp.Close()

	f := parse.ParseFile(fname, src)
	if f == nil {
		os.Exit(1)
	}
	c.fp = fp
	c.compFile(f)
}

func (c *compiler) compNode(node ast.Node) int {
	switch n := node.(type) {
	case *ast.BasicLit:
		i, err := strconv.Atoi(n.Lit)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		return i
	case *ast.BinaryExpr:
		return c.compBinaryExpr(n)
	default:
		return 0 /* can't be reached */
	}
}

func (c *compiler) compBinaryExpr(b *ast.BinaryExpr) int {
	var tmp int

	tmp = c.compNode(b.List[0])

	for _, node := range b.List[1:] {
		switch b.Op {
		case token.ADD:
			tmp += c.compNode(node)
		case token.SUB:
			tmp -= c.compNode(node)
		case token.MUL:
			tmp *= c.compNode(node)
		case token.QUO:
			tmp /= c.compNode(node)
		case token.REM:
			tmp %= c.compNode(node)
		}
	}

	return tmp
}

func (c *compiler) compFile(f *ast.File) {
	fmt.Fprintln(c.fp, "#include <stdio.h>")
	fmt.Fprintln(c.fp, "int main(void) {")
	fmt.Fprintf(c.fp, "printf(\"%%d\", %d);\n", c.compNode(f.Root))
	fmt.Fprintln(c.fp, "return 0;")
	fmt.Fprintln(c.fp, "}")
}
<commit_msg>temporary fix to comp to allow calcc to build<commit_after>// Copyright (c) 2014, Rob Thornton
// All rights reserved.
// This source code is governed by a Simplied BSD-License. Please see the
// LICENSE included in this distribution for a copy of the full license
// or, if one is not included, you may also find a copy at
// http://opensource.org/licenses/BSD-2-Clause

package comp

import (
	"fmt"
	"os"
	"strconv"

	"github.com/rthornton128/calc/ast"
	"github.com/rthornton128/calc/parse"
	"github.com/rthornton128/calc/token"
)

type compiler struct {
	fp *os.File
}

func CompileFile(fname, src string) {

	var c compiler
	fp, err := os.Create(fname + ".c")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer fp.Close()

	f := parse.ParseFile(fname, src)
	if f == nil {
		os.Exit(1)
	}
	c.fp = fp
	c.compFile(f)
}

func (c *compiler) compNode(node ast.Node) int {
	switch n := node.(type) {
	case *ast.BasicLit:
		i, err := strconv.Atoi(n.Lit)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		return i
	case *ast.BinaryExpr:
		return c.compBinaryExpr(n)
	default:
		return 0 /* can't be reached */
	}
}

func (c *compiler) compBinaryExpr(b *ast.BinaryExpr) int {
	var tmp int

	tmp = c.compNode(b.List[0])

	for _, node := range b.List[1:] {
		switch b.Op {
		case token.ADD:
			tmp += c.compNode(node)
		case token.SUB:
			tmp -= c.compNode(node)
		case token.MUL:
			tmp *= c.compNode(node)
		case token.QUO:
			tmp /= c.compNode(node)
		case token.REM:
			tmp %= c.compNode(node)
		}
	}

	return tmp
}

func (c *compiler) compFile(f *ast.File) {
	fmt.Fprintln(c.fp, "#include <stdio.h>")
	fmt.Fprintln(c.fp, "int main(void) {")
	fmt.Fprintf(c.fp, "printf(\"%%d\", %d);\n", c.compNode(f.Scope.Lookup("main")))
	fmt.Fprintln(c.fp, "return 0;")
	fmt.Fprintln(c.fp, "}")
}
<|endoftext|>


<commit_before>// +build darwin freebsd linux openbsd netbsd dragonfly

package libedit

import (
	"errors"
	"fmt"
	"io"
	"os"
	"syscall"
	"unsafe"
)

// #cgo openbsd netbsd freebsd dragonfly darwin LDFLAGS: -ledit
// #cgo openbsd netbsd freebsd dragonfly darwin CPPFLAGS: -Ishim
// #cgo linux LDFLAGS: -lncurses
// #cgo linux CFLAGS: -Wno-unused-result
// #cgo linux CPPFLAGS: -Isrc -Isrc/c-libedit -Isrc/c-libedit/editline -Isrc/c-libedit/linux-build
//
// #include <stdlib.h>
// #include <stdio.h>
// #include <unistd.h>
// #include <limits.h>
//
// #include <histedit.h>
// #include "c_editline.h"
import "C"

type state struct {
	el              *C.EditLine
	h               *C.History
	cIn, cOut, cErr *C.FILE
	inf, outf, errf *os.File
	promptGenLeft   LeftPromptGenerator
	promptGenRight  RightPromptGenerator
	cPromptLeft     *C.char
	cPromptRight    *C.char
	completer       CompletionGenerator
	histFile        *C.char
	autoSaveHistory bool
}

var editors []state

var errUnknown = errors.New("unknown error")

func Init(appName string) (EditLine, error) {
	return InitFiles(appName, os.Stdin, os.Stdout, os.Stderr)
}

func InitFiles(appName string, inf, outf, errf *os.File) (e EditLine, err error) {
	var inFile, outFile, errFile *C.FILE
	defer func() {
		if err == nil {
			return
		}
		if inFile != nil {
			C.fclose(inFile)
		}
		if outFile != nil {
			C.fclose(outFile)
		}
		if errFile != nil {
			C.fclose(errFile)
		}
	}()

	inFile, err = C.fdopen(C.dup(C.int(inf.Fd())), C.go_libedit_mode_read)
	if err != nil {
		return -1, fmt.Errorf("fdopen(inf): %v", err)
	}
	outFile, err = C.fdopen(C.dup(C.int(outf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(outf): %v", err)
	}
	errFile, err = C.fdopen(C.dup(C.int(errf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(errf): %v", err)
	}
	cAppName := C.CString(appName)
	defer C.free(unsafe.Pointer(cAppName))
	el, err := C.go_libedit_init(cAppName, inFile, outFile, errFile)
	// If the settings file did not exist, ignore the error.
	if err == syscall.ENOENT {
		err = nil
	}
	if el == nil || err != nil {
		if err == nil {
			err = errUnknown
		}
		return -1, fmt.Errorf("el_init: %v", err)
	}

	st := state{
		el:  el,
		inf: inf, outf: outf, errf: errf,
		cIn: inFile, cOut: outFile, cErr: errFile,
	}
	editors = append(editors, st)
	return EditLine(len(editors) - 1), nil
}

func (el EditLine) Close() {
	st := &editors[el]
	if st.el == nil {
		// Already closed.
		return
	}
	C.el_end(st.el)
	if st.h != nil {
		C.history_end(st.h)
	}
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
	}
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
	}
	C.fclose(st.cIn)
	C.fclose(st.cOut)
	C.fclose(st.cErr)
	*st = state{}
}

var errNoHistory = errors.New("history not configured")
var errNoFileConfigured = errors.New("no savefile configured")

func (el EditLine) SaveHistory() error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}
	if st.histFile == nil {
		return errNoFileConfigured
	}
	_, err := C.go_libedit_write_history(st.h, st.histFile)
	if err != nil {
		return fmt.Errorf("write_history: %v", err)
	}
	return nil
}

func (el EditLine) AddHistory(line string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	cLine := C.CString(line)
	defer C.free(unsafe.Pointer(cLine))

	_, err := C.go_libedit_add_history(st.h, cLine)
	if err != nil {
		return fmt.Errorf("add_history: %v", err)
	}

	if st.autoSaveHistory && st.histFile != nil {
		_, err := C.go_libedit_write_history(st.h, histFile)
		if err != nil {
			return fmt.Errorf("write_history: %v", err)
		}
	}
	return nil
}

func (el EditLine) LoadHistory(file string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	histFile = C.CString(file)
	defer C.free(unsafe.Pointer(histFile))
	_, err := C.go_libedit_read_history(st.h, histFile)
	if err != nil && err != syscall.ENOENT {
		return fmt.Errorf("read_history: %v", err)
	}
	return nil
}

func (el EditLine) SetAutoSaveHistory(file string, autoSave bool) {
	st := &editors[el]
	if st.h == nil {
		return
	}
	var newHistFile *C.char
	if file != "" {
		newHistFile = C.CString(file)
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
		st.histFile = nil
	}
	st.histFile = newHistFile
	st.autoSaveHistory = autoSave
}

func (el EditLine) UseHistory(maxEntries int, dedup bool) error {
	st := &editors[el]

	cDedup := 0
	if dedup {
		cDedup = 1
	}

	cMaxEntries := C.int(maxEntries)
	if maxEntries < 0 {
		cMaxEntries = C.INT_MAX
	}

	h, err := C.go_libedit_setup_history(st.el, cMaxEntries, C.int(cDedup))
	if err != nil {
		return fmt.Errorf("init_history: %v", err)
	}
	if st.h != nil {
		C.history_end(st.h)
	}
	st.h = h
	return nil
}

func (el EditLine) GetLine() (string, error) {
	st := &editors[el]

	var count C.int
	var interrupted C.int
	s, err := C.go_libedit_gets(st.el, &count, &interrupted)
	if interrupted > 0 {
		return "", ErrInterrupted
	}
	if err != nil {
		return "", err
	}
	if s == nil {
		return "", io.EOF
	}
	return C.GoStringN(s, count), nil
}

func (el EditLine) Stdin() *os.File {
	return editors[el].inf
}

func (el EditLine) Stdout() *os.File {
	return editors[el].outf
}

func (el EditLine) Stderr() *os.File {
	return editors[el].errf
}

func (el EditLine) SetCompleter(gen CompletionGenerator) {
	editors[el].completer = gen
}

func (el EditLine) SetLeftPrompt(gen LeftPromptGenerator) {
	st := &editors[el]
	st.promptGenLeft = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, C.go_libedit_prompt_left_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, nil)
	}
}

func (el EditLine) SetRightPrompt(gen RightPromptGenerator) {
	st := &editors[el]
	st.promptGenRight = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, C.go_libedit_prompt_right_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, nil)
	}
}

func (el EditLine) GetLineInfo() (string, int) {
	st := &editors[el]
	li := C.el_line(st.el)
	return C.GoStringN(li.buffer,
		C.int(uintptr(unsafe.Pointer(li.lastchar))-uintptr(unsafe.Pointer(li.buffer))),
	), int(uintptr(unsafe.Pointer(li.cursor)) - uintptr(unsafe.Pointer(li.buffer)))
}

//export go_libedit_getcompletions
func go_libedit_getcompletions(cI C.int, cWord *C.char) **C.char {
	if int(cI) < 0 || int(cI) >= len(editors) {
		return nil
	}
	st := &editors[int(cI)]
	if st.completer == nil {
		return nil
	}

	word := C.GoString(cWord)
	matches := st.completer.GetCompletions(word)
	if len(matches) == 0 {
		return nil
	}

	array := (**C.char)(C.malloc(C.size_t(C.sizeof_pchar * (len(matches) + 1))))
	for i, m := range matches {
		C.go_libedit_set_string_array(array, C.int(i), C.CString(m))
	}
	C.go_libedit_set_string_array(array, C.int(len(matches)), nil)
	return array
}

//export go_libedit_prompt_left
func go_libedit_prompt_left(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
		st.cPromptLeft = nil
	}
	if st.promptGenLeft == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptLeft = C.CString(st.promptGenLeft.GetLeftPrompt())
	return st.cPromptLeft
}

//export go_libedit_prompt_right
func go_libedit_prompt_right(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
		st.cPromptRight = nil
	}
	if st.promptGenRight == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptRight = C.CString(st.promptGenRight.GetRightPrompt())
	return st.cPromptRight
}
<commit_msg>Fix a bug.<commit_after>// +build darwin freebsd linux openbsd netbsd dragonfly

package libedit

import (
	"errors"
	"fmt"
	"io"
	"os"
	"syscall"
	"unsafe"
)

// #cgo openbsd netbsd freebsd dragonfly darwin LDFLAGS: -ledit
// #cgo openbsd netbsd freebsd dragonfly darwin CPPFLAGS: -Ishim
// #cgo linux LDFLAGS: -lncurses
// #cgo linux CFLAGS: -Wno-unused-result
// #cgo linux CPPFLAGS: -Isrc -Isrc/c-libedit -Isrc/c-libedit/editline -Isrc/c-libedit/linux-build
//
// #include <stdlib.h>
// #include <stdio.h>
// #include <unistd.h>
// #include <limits.h>
//
// #include <histedit.h>
// #include "c_editline.h"
import "C"

type state struct {
	el              *C.EditLine
	h               *C.History
	cIn, cOut, cErr *C.FILE
	inf, outf, errf *os.File
	promptGenLeft   LeftPromptGenerator
	promptGenRight  RightPromptGenerator
	cPromptLeft     *C.char
	cPromptRight    *C.char
	completer       CompletionGenerator
	histFile        *C.char
	autoSaveHistory bool
}

var editors []state

var errUnknown = errors.New("unknown error")

func Init(appName string) (EditLine, error) {
	return InitFiles(appName, os.Stdin, os.Stdout, os.Stderr)
}

func InitFiles(appName string, inf, outf, errf *os.File) (e EditLine, err error) {
	var inFile, outFile, errFile *C.FILE
	defer func() {
		if err == nil {
			return
		}
		if inFile != nil {
			C.fclose(inFile)
		}
		if outFile != nil {
			C.fclose(outFile)
		}
		if errFile != nil {
			C.fclose(errFile)
		}
	}()

	inFile, err = C.fdopen(C.dup(C.int(inf.Fd())), C.go_libedit_mode_read)
	if err != nil {
		return -1, fmt.Errorf("fdopen(inf): %v", err)
	}
	outFile, err = C.fdopen(C.dup(C.int(outf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(outf): %v", err)
	}
	errFile, err = C.fdopen(C.dup(C.int(errf.Fd())), C.go_libedit_mode_write)
	if err != nil {
		return -1, fmt.Errorf("fdopen(errf): %v", err)
	}
	cAppName := C.CString(appName)
	defer C.free(unsafe.Pointer(cAppName))
	el, err := C.go_libedit_init(cAppName, inFile, outFile, errFile)
	// If the settings file did not exist, ignore the error.
	if err == syscall.ENOENT {
		err = nil
	}
	if el == nil || err != nil {
		if err == nil {
			err = errUnknown
		}
		return -1, fmt.Errorf("el_init: %v", err)
	}

	st := state{
		el:  el,
		inf: inf, outf: outf, errf: errf,
		cIn: inFile, cOut: outFile, cErr: errFile,
	}
	editors = append(editors, st)
	return EditLine(len(editors) - 1), nil
}

func (el EditLine) Close() {
	st := &editors[el]
	if st.el == nil {
		// Already closed.
		return
	}
	C.el_end(st.el)
	if st.h != nil {
		C.history_end(st.h)
	}
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
	}
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
	}
	C.fclose(st.cIn)
	C.fclose(st.cOut)
	C.fclose(st.cErr)
	*st = state{}
}

var errNoHistory = errors.New("history not configured")
var errNoFileConfigured = errors.New("no savefile configured")

func (el EditLine) SaveHistory() error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}
	if st.histFile == nil {
		return errNoFileConfigured
	}
	_, err := C.go_libedit_write_history(st.h, st.histFile)
	if err != nil {
		return fmt.Errorf("write_history: %v", err)
	}
	return nil
}

func (el EditLine) AddHistory(line string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	cLine := C.CString(line)
	defer C.free(unsafe.Pointer(cLine))

	_, err := C.go_libedit_add_history(st.h, cLine)
	if err != nil {
		return fmt.Errorf("add_history: %v", err)
	}

	if st.autoSaveHistory && st.histFile != nil {
		_, err := C.go_libedit_write_history(st.h, st.histFile)
		if err != nil {
			return fmt.Errorf("write_history: %v", err)
		}
	}
	return nil
}

func (el EditLine) LoadHistory(file string) error {
	st := &editors[el]
	if st.h == nil {
		return errNoHistory
	}

	histFile := C.CString(file)
	defer C.free(unsafe.Pointer(histFile))
	_, err := C.go_libedit_read_history(st.h, histFile)
	if err != nil && err != syscall.ENOENT {
		return fmt.Errorf("read_history: %v", err)
	}
	return nil
}

func (el EditLine) SetAutoSaveHistory(file string, autoSave bool) {
	st := &editors[el]
	if st.h == nil {
		return
	}
	var newHistFile *C.char
	if file != "" {
		newHistFile = C.CString(file)
	}
	if st.histFile != nil {
		C.free(unsafe.Pointer(st.histFile))
		st.histFile = nil
	}
	st.histFile = newHistFile
	st.autoSaveHistory = autoSave
}

func (el EditLine) UseHistory(maxEntries int, dedup bool) error {
	st := &editors[el]

	cDedup := 0
	if dedup {
		cDedup = 1
	}

	cMaxEntries := C.int(maxEntries)
	if maxEntries < 0 {
		cMaxEntries = C.INT_MAX
	}

	h, err := C.go_libedit_setup_history(st.el, cMaxEntries, C.int(cDedup))
	if err != nil {
		return fmt.Errorf("init_history: %v", err)
	}
	if st.h != nil {
		C.history_end(st.h)
	}
	st.h = h
	return nil
}

func (el EditLine) GetLine() (string, error) {
	st := &editors[el]

	var count C.int
	var interrupted C.int
	s, err := C.go_libedit_gets(st.el, &count, &interrupted)
	if interrupted > 0 {
		return "", ErrInterrupted
	}
	if err != nil {
		return "", err
	}
	if s == nil {
		return "", io.EOF
	}
	return C.GoStringN(s, count), nil
}

func (el EditLine) Stdin() *os.File {
	return editors[el].inf
}

func (el EditLine) Stdout() *os.File {
	return editors[el].outf
}

func (el EditLine) Stderr() *os.File {
	return editors[el].errf
}

func (el EditLine) SetCompleter(gen CompletionGenerator) {
	editors[el].completer = gen
}

func (el EditLine) SetLeftPrompt(gen LeftPromptGenerator) {
	st := &editors[el]
	st.promptGenLeft = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, C.go_libedit_prompt_left_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_PROMPT, nil)
	}
}

func (el EditLine) SetRightPrompt(gen RightPromptGenerator) {
	st := &editors[el]
	st.promptGenRight = gen
	if gen != nil {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, C.go_libedit_prompt_right_ptr)
	} else {
		C.go_libedit_set_prompt(st.el, C.EL_RPROMPT, nil)
	}
}

func (el EditLine) GetLineInfo() (string, int) {
	st := &editors[el]
	li := C.el_line(st.el)
	return C.GoStringN(li.buffer,
		C.int(uintptr(unsafe.Pointer(li.lastchar))-uintptr(unsafe.Pointer(li.buffer))),
	), int(uintptr(unsafe.Pointer(li.cursor)) - uintptr(unsafe.Pointer(li.buffer)))
}

//export go_libedit_getcompletions
func go_libedit_getcompletions(cI C.int, cWord *C.char) **C.char {
	if int(cI) < 0 || int(cI) >= len(editors) {
		return nil
	}
	st := &editors[int(cI)]
	if st.completer == nil {
		return nil
	}

	word := C.GoString(cWord)
	matches := st.completer.GetCompletions(word)
	if len(matches) == 0 {
		return nil
	}

	array := (**C.char)(C.malloc(C.size_t(C.sizeof_pchar * (len(matches) + 1))))
	for i, m := range matches {
		C.go_libedit_set_string_array(array, C.int(i), C.CString(m))
	}
	C.go_libedit_set_string_array(array, C.int(len(matches)), nil)
	return array
}

//export go_libedit_prompt_left
func go_libedit_prompt_left(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptLeft != nil {
		C.free(unsafe.Pointer(st.cPromptLeft))
		st.cPromptLeft = nil
	}
	if st.promptGenLeft == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptLeft = C.CString(st.promptGenLeft.GetLeftPrompt())
	return st.cPromptLeft
}

//export go_libedit_prompt_right
func go_libedit_prompt_right(el *C.EditLine) *C.char {
	i := C.go_libedit_get_clientdata(el)
	e := int(i)
	if e < 0 || e >= len(editors) {
		return C.go_libedit_emptycstring
	}
	st := &editors[e]
	if st.cPromptRight != nil {
		C.free(unsafe.Pointer(st.cPromptRight))
		st.cPromptRight = nil
	}
	if st.promptGenRight == nil {
		return C.go_libedit_emptycstring
	}
	st.cPromptRight = C.CString(st.promptGenRight.GetRightPrompt())
	return st.cPromptRight
}
<|endoftext|>


<commit_before>package editor

import "github.com/nsf/termbox-go"
import "fmt"
import "os"
import "io/ioutil"
import "path/filepath"
import "github.com/wx13/sith/syntaxcolor"
import "github.com/wx13/sith/terminal"
import "github.com/wx13/sith/file"

type Editor struct {
	screen     *terminal.Screen
	file       *file.File
	files      []*file.File
	fileIdx    int
	fileIdxPrv int
	keyboard   *terminal.Keyboard
	flushChan  chan struct{}

	searchHist  []string
	replaceHist []string

	copyBuffer file.Buffer
	copyContig int
	copyHist   []file.Buffer
}

func NewEditor() *Editor {
	return &Editor{
		flushChan:  make(chan struct{}, 1),
		screen:     terminal.NewScreen(),
		copyBuffer: file.MakeBuffer([]string{}),
		copyContig: 0,
		copyHist:   []file.Buffer{},
	}
}

func (editor *Editor) OpenNewFile() {
	dir, _ := os.Getwd()
	dir += "/"
	names := []string{}
	idx := 0
	files := []os.FileInfo{}
	for {
		files, _ = ioutil.ReadDir(dir)
		dotdot, err := os.Stat("../")
		if err == nil {
			files = append([]os.FileInfo{dotdot}, files...)
		}
		names = []string{}
		for _, file := range files {
			if file.IsDir() {
				names = append(names, file.Name()+"/")
			} else {
				names = append(names, file.Name())
			}
		}
		menu := terminal.NewMenu(editor.screen)
		idx = menu.Choose(names)
		editor.Flush()
		if idx < 0 {
			return
		}
		chosenFile := files[idx]
		if chosenFile.IsDir() {
			dir = filepath.Clean(dir+chosenFile.Name()) + "/"
		} else {
			break
		}
	}
	cwd, _ := os.Getwd()
	chosenFile, _ := filepath.Rel(cwd, dir+names[idx])
	editor.OpenFile(chosenFile)
	editor.fileIdxPrv = editor.fileIdx
	editor.fileIdx = len(editor.files) - 1
	editor.file = editor.files[editor.fileIdx]
}

func (editor *Editor) OpenFile(name string) {
	file := file.NewFile(name, editor.flushChan, editor.screen)
	file.SyntaxRules = syntaxcolor.NewSyntaxRules(name)
	editor.files = append(editor.files, file)
}

func (editor *Editor) OpenFiles(fileNames []string) {
	for _, name := range fileNames {
		editor.OpenFile(name)
	}
	if len(editor.files) == 0 {
		editor.files = append(editor.files, file.NewFile("", editor.flushChan, editor.screen))
	}
	editor.fileIdx = 0
	editor.fileIdxPrv = 0
	editor.file = editor.files[0]
}

func (editor *Editor) Quit() {
	for _, _ = range editor.files {
		if !editor.CloseFile() {
			editor.NextFile()
		}
	}
}

func (editor *Editor) CloseFile() bool {
	editor.Flush()
	idx := editor.fileIdx
	if !editor.files[idx].Close() {
		return false
	}
	editor.files = append(editor.files[:idx], editor.files[idx+1:]...)
	if len(editor.files) == 0 {
		editor.screen.Close()
		os.Exit(0)
	}
	editor.NextFile()
	return true
}

func (editor *Editor) Listen() {

	keyboard := terminal.NewKeyboard()
	for {
		cmd, r := keyboard.GetKey()
		switch cmd {
		case "backspace":
			editor.file.Backspace()
		case "delete", "ctrlD":
			editor.file.Delete()
		case "space":
			editor.file.InsertChar(' ')
		case "tab":
			editor.file.InsertChar('\t')
		case "enter":
			editor.file.Newline()
		case "arrowLeft", "ctrlO":
			editor.file.CursorLeft()
		case "arrowRight", "ctrlL":
			editor.file.CursorRight()
		case "arrowUp", "ctrlK":
			editor.file.CursorUp(1)
		case "arrowDown", "ctrlJ":
			editor.file.CursorDown(1)
		case "ctrlU":
			editor.file.ScrollUp()
		case "ctrlP":
			editor.file.ScrollDown()
		case "altP":
			editor.file.ScrollRight()
		case "altU":
			editor.file.ScrollLeft()
		case "pageDown", "ctrlN":
			editor.file.PageDown()
		case "pageUp", "ctrlB":
			editor.file.PageUp()
		case "ctrlG":
			editor.file.GoToLine()
		case "altL":
			editor.file.Refresh()
		case "altO":
			editor.OpenNewFile()
		case "altQ":
			editor.Quit()
		case "altW":
			editor.CloseFile()
		case "altZ":
			editor.Suspend()
			keyboard = terminal.NewKeyboard()
		case "altN":
			editor.NextFile()
		case "altB":
			editor.PrevFile()
		case "altK":
			editor.LastFile()
		case "altM":
			editor.SelectFile()
		case "ctrlX":
			editor.file.AddCursor()
		case "altC":
			editor.file.AddCursorCol()
		case "altX":
			editor.file.ClearCursors()
		case "ctrlZ":
			editor.Undo()
		case "ctrlY":
			editor.Redo()
		case "ctrlS":
			editor.Save()
		case "ctrlA":
			editor.file.StartOfLine()
		case "ctrlE":
			editor.file.EndOfLine()
		case "ctrlW":
			editor.file.NextWord()
		case "ctrlQ":
			editor.file.PrevWord()
		case "ctrlF":
			editor.Search(false)
		case "altF":
			editor.SearchAndReplace(false)
		case "ctrlR":
			editor.Search(true)
		case "altR":
			editor.SearchAndReplace(true)
		case "ctrlC":
			editor.Cut()
		case "ctrlV":
			editor.Paste()
		case "altV":
			editor.PasteFromMenu()
		case "altG":
			editor.GoFmt()
		case "altJ":
			editor.file.Justify()
		case "altI":
			editor.file.ToggleAutoIndent()
		case "altT":
			editor.file.ToggleAutoTab()
		case "unknown":
			editor.screen.Notify("Unknown keypress")
		case "char":
			editor.file.InsertChar(r)
		default:
			editor.screen.Notify("Unknown keypress")
		}
		editor.copyContig--
		editor.RequestFlush()
	}

}

func (editor *Editor) Undo() {
	editor.file.Undo()
}

func (editor *Editor) Redo() {
	editor.file.Redo()
}

func (editor *Editor) NextFile() {
	editor.SwitchFile(editor.fileIdx + 1)
}

func (editor *Editor) PrevFile() {
	editor.SwitchFile(editor.fileIdx - 1)
}

func (editor *Editor) LastFile() {
	editor.SwitchFile(editor.fileIdxPrv)
}

func (editor *Editor) SelectFile() {
	names := []string{}
	for _, file := range editor.files {
		names = append(names, file.Name)
	}
	menu := terminal.NewMenu(editor.screen)
	idx := menu.Choose(names)
	if idx >= 0 {
		editor.SwitchFile(idx)
	}
}

func (editor *Editor) Save() {
	go func() {
		err := editor.file.Save()
		if err != nil {
			editor.screen.Alert(err.Error())
		} else {
			editor.screen.Notify("File Saved")
		}
	}()
}

func (editor *Editor) GoFmt() {
	go func() {
		err := editor.file.GoFmt()
		if err == nil {
			editor.RequestFlush()
			editor.screen.Notify("GoFmt done")
		} else {
			editor.screen.Notify(err.Error())
		}
	}()
}

func intMod(a, n int) int {
	if a >= 0 {
		return a - n*(a/n)
	} else {
		return a - n*((a-n+1)/n)
	}
}

func (editor *Editor) SwitchFile(n int) {
	n = intMod(n, len(editor.files))
	editor.fileIdxPrv = editor.fileIdx
	editor.fileIdx = n
	editor.file = editor.files[n]
}

func (editor *Editor) HighlightCursors() {
	cells := termbox.CellBuffer()
	cols, _ := termbox.Size()
	for k, _ := range editor.file.MultiCursor[1:] {
		r, c := editor.file.GetCursor(k + 1)
		j := r*cols + c
		if j < 0 || j >= len(cells) {
			continue
		}
		cells[j].Bg |= termbox.AttrReverse
		cells[j].Fg |= termbox.AttrReverse
	}
}

func (editor *Editor) Flush() {
	editor.file.Flush()
	editor.HighlightCursors()
	editor.UpdateStatus()
	editor.screen.Flush()
}

func (editor *Editor) KeepFlushed() {
	go func() {
		for {
			<-editor.flushChan
			editor.Flush()
		}
	}()
}

func (editor *Editor) RequestFlush() {
	select {
	case editor.flushChan <- struct{}{}:
	default:
	}
}

func (editor *Editor) UpdateStatus() {
	cols, rows := termbox.Size()
	message := fmt.Sprintf("%s (%d/%d)   %d/%d,%d",
		editor.file.Name,
		editor.fileIdx,
		len(editor.files),
		editor.file.MultiCursor[0].Row(),
		len(editor.file.Buffer)-1,
		editor.file.MultiCursor[0].Col(),
	)
	col := cols - len(message)
	editor.screen.WriteString(rows-1, col, message)
	editor.screen.WriteString(rows-1, 0, "[ Sith 0.3 ]")
	editor.screen.DecorateStatusLine()
	editor.file.WriteStatus(rows-1, col)
	editor.screen.SetCursor(editor.file.GetCursor(0))
}
<commit_msg>truncate long file names in status line<commit_after>package editor

import "github.com/nsf/termbox-go"
import "fmt"
import "os"
import "io/ioutil"
import "path/filepath"
import "github.com/wx13/sith/syntaxcolor"
import "github.com/wx13/sith/terminal"
import "github.com/wx13/sith/file"

type Editor struct {
	screen     *terminal.Screen
	file       *file.File
	files      []*file.File
	fileIdx    int
	fileIdxPrv int
	keyboard   *terminal.Keyboard
	flushChan  chan struct{}

	searchHist  []string
	replaceHist []string

	copyBuffer file.Buffer
	copyContig int
	copyHist   []file.Buffer
}

func NewEditor() *Editor {
	return &Editor{
		flushChan:  make(chan struct{}, 1),
		screen:     terminal.NewScreen(),
		copyBuffer: file.MakeBuffer([]string{}),
		copyContig: 0,
		copyHist:   []file.Buffer{},
	}
}

func (editor *Editor) OpenNewFile() {
	dir, _ := os.Getwd()
	dir += "/"
	names := []string{}
	idx := 0
	files := []os.FileInfo{}
	for {
		files, _ = ioutil.ReadDir(dir)
		dotdot, err := os.Stat("../")
		if err == nil {
			files = append([]os.FileInfo{dotdot}, files...)
		}
		names = []string{}
		for _, file := range files {
			if file.IsDir() {
				names = append(names, file.Name()+"/")
			} else {
				names = append(names, file.Name())
			}
		}
		menu := terminal.NewMenu(editor.screen)
		idx = menu.Choose(names)
		editor.Flush()
		if idx < 0 {
			return
		}
		chosenFile := files[idx]
		if chosenFile.IsDir() {
			dir = filepath.Clean(dir+chosenFile.Name()) + "/"
		} else {
			break
		}
	}
	cwd, _ := os.Getwd()
	chosenFile, _ := filepath.Rel(cwd, dir+names[idx])
	editor.OpenFile(chosenFile)
	editor.fileIdxPrv = editor.fileIdx
	editor.fileIdx = len(editor.files) - 1
	editor.file = editor.files[editor.fileIdx]
}

func (editor *Editor) OpenFile(name string) {
	file := file.NewFile(name, editor.flushChan, editor.screen)
	file.SyntaxRules = syntaxcolor.NewSyntaxRules(name)
	editor.files = append(editor.files, file)
}

func (editor *Editor) OpenFiles(fileNames []string) {
	for _, name := range fileNames {
		editor.OpenFile(name)
	}
	if len(editor.files) == 0 {
		editor.files = append(editor.files, file.NewFile("", editor.flushChan, editor.screen))
	}
	editor.fileIdx = 0
	editor.fileIdxPrv = 0
	editor.file = editor.files[0]
}

func (editor *Editor) Quit() {
	for _, _ = range editor.files {
		if !editor.CloseFile() {
			editor.NextFile()
		}
	}
}

func (editor *Editor) CloseFile() bool {
	editor.Flush()
	idx := editor.fileIdx
	if !editor.files[idx].Close() {
		return false
	}
	editor.files = append(editor.files[:idx], editor.files[idx+1:]...)
	if len(editor.files) == 0 {
		editor.screen.Close()
		os.Exit(0)
	}
	editor.NextFile()
	return true
}

func (editor *Editor) Listen() {

	keyboard := terminal.NewKeyboard()
	for {
		cmd, r := keyboard.GetKey()
		switch cmd {
		case "backspace":
			editor.file.Backspace()
		case "delete", "ctrlD":
			editor.file.Delete()
		case "space":
			editor.file.InsertChar(' ')
		case "tab":
			editor.file.InsertChar('\t')
		case "enter":
			editor.file.Newline()
		case "arrowLeft", "ctrlO":
			editor.file.CursorLeft()
		case "arrowRight", "ctrlL":
			editor.file.CursorRight()
		case "arrowUp", "ctrlK":
			editor.file.CursorUp(1)
		case "arrowDown", "ctrlJ":
			editor.file.CursorDown(1)
		case "ctrlU":
			editor.file.ScrollUp()
		case "ctrlP":
			editor.file.ScrollDown()
		case "altP":
			editor.file.ScrollRight()
		case "altU":
			editor.file.ScrollLeft()
		case "pageDown", "ctrlN":
			editor.file.PageDown()
		case "pageUp", "ctrlB":
			editor.file.PageUp()
		case "ctrlG":
			editor.file.GoToLine()
		case "altL":
			editor.file.Refresh()
		case "altO":
			editor.OpenNewFile()
		case "altQ":
			editor.Quit()
		case "altW":
			editor.CloseFile()
		case "altZ":
			editor.Suspend()
			keyboard = terminal.NewKeyboard()
		case "altN":
			editor.NextFile()
		case "altB":
			editor.PrevFile()
		case "altK":
			editor.LastFile()
		case "altM":
			editor.SelectFile()
		case "ctrlX":
			editor.file.AddCursor()
		case "altC":
			editor.file.AddCursorCol()
		case "altX":
			editor.file.ClearCursors()
		case "ctrlZ":
			editor.Undo()
		case "ctrlY":
			editor.Redo()
		case "ctrlS":
			editor.Save()
		case "ctrlA":
			editor.file.StartOfLine()
		case "ctrlE":
			editor.file.EndOfLine()
		case "ctrlW":
			editor.file.NextWord()
		case "ctrlQ":
			editor.file.PrevWord()
		case "ctrlF":
			editor.Search(false)
		case "altF":
			editor.SearchAndReplace(false)
		case "ctrlR":
			editor.Search(true)
		case "altR":
			editor.SearchAndReplace(true)
		case "ctrlC":
			editor.Cut()
		case "ctrlV":
			editor.Paste()
		case "altV":
			editor.PasteFromMenu()
		case "altG":
			editor.GoFmt()
		case "altJ":
			editor.file.Justify()
		case "altI":
			editor.file.ToggleAutoIndent()
		case "altT":
			editor.file.ToggleAutoTab()
		case "unknown":
			editor.screen.Notify("Unknown keypress")
		case "char":
			editor.file.InsertChar(r)
		default:
			editor.screen.Notify("Unknown keypress")
		}
		editor.copyContig--
		editor.RequestFlush()
	}

}

func (editor *Editor) Undo() {
	editor.file.Undo()
}

func (editor *Editor) Redo() {
	editor.file.Redo()
}

func (editor *Editor) NextFile() {
	editor.SwitchFile(editor.fileIdx + 1)
}

func (editor *Editor) PrevFile() {
	editor.SwitchFile(editor.fileIdx - 1)
}

func (editor *Editor) LastFile() {
	editor.SwitchFile(editor.fileIdxPrv)
}

func (editor *Editor) SelectFile() {
	names := []string{}
	for _, file := range editor.files {
		names = append(names, file.Name)
	}
	menu := terminal.NewMenu(editor.screen)
	idx := menu.Choose(names)
	if idx >= 0 {
		editor.SwitchFile(idx)
	}
}

func (editor *Editor) Save() {
	go func() {
		err := editor.file.Save()
		if err != nil {
			editor.screen.Alert(err.Error())
		} else {
			editor.screen.Notify("File Saved")
		}
	}()
}

func (editor *Editor) GoFmt() {
	go func() {
		err := editor.file.GoFmt()
		if err == nil {
			editor.RequestFlush()
			editor.screen.Notify("GoFmt done")
		} else {
			editor.screen.Notify(err.Error())
		}
	}()
}

func intMod(a, n int) int {
	if a >= 0 {
		return a - n*(a/n)
	} else {
		return a - n*((a-n+1)/n)
	}
}

func (editor *Editor) SwitchFile(n int) {
	n = intMod(n, len(editor.files))
	editor.fileIdxPrv = editor.fileIdx
	editor.fileIdx = n
	editor.file = editor.files[n]
}

func (editor *Editor) HighlightCursors() {
	cells := termbox.CellBuffer()
	cols, _ := termbox.Size()
	for k, _ := range editor.file.MultiCursor[1:] {
		r, c := editor.file.GetCursor(k + 1)
		j := r*cols + c
		if j < 0 || j >= len(cells) {
			continue
		}
		cells[j].Bg |= termbox.AttrReverse
		cells[j].Fg |= termbox.AttrReverse
	}
}

func (editor *Editor) Flush() {
	editor.file.Flush()
	editor.HighlightCursors()
	editor.UpdateStatus()
	editor.screen.Flush()
}

func (editor *Editor) KeepFlushed() {
	go func() {
		for {
			<-editor.flushChan
			editor.Flush()
		}
	}()
}

func (editor *Editor) RequestFlush() {
	select {
	case editor.flushChan <- struct{}{}:
	default:
	}
}

func (editor *Editor) UpdateStatus() {
	cols, rows := termbox.Size()
	maxNameLen := cols / 3
	name := editor.file.Name
	nameLen := len(name)
	if nameLen > maxNameLen {
		name = name[0:maxNameLen/2] + "..." + name[nameLen-maxNameLen/2:nameLen]
	}
	message := fmt.Sprintf("%s (%d/%d)   %d/%d,%d",
		name,
		editor.fileIdx,
		len(editor.files),
		editor.file.MultiCursor[0].Row(),
		len(editor.file.Buffer)-1,
		editor.file.MultiCursor[0].Col(),
	)
	col := cols - len(message)
	editor.screen.WriteString(rows-1, col, message)
	editor.screen.WriteString(rows-1, 0, "[ Sith 0.3 ]")
	editor.screen.DecorateStatusLine()
	editor.file.WriteStatus(rows-1, col)
	editor.screen.SetCursor(editor.file.GetCursor(0))
}
<|endoftext|>


<commit_before>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/keybase/client/go/logger"
)

// Logs is the struct to specify the path of log files
type Logs struct {
	Desktop string
	Kbfs    string
	Service string
	Updater string
	Start   string
	Install string
	System  string
	Git     string
}

// LogSendContext for LogSend
type LogSendContext struct {
	Contextified
	Logs Logs
}

func addFile(mpart *multipart.Writer, param, filename, data string) error {
	if len(data) == 0 {
		return nil
	}

	part, err := mpart.CreateFormFile(param, filename)
	if err != nil {
		return err
	}
	gz := gzip.NewWriter(part)
	if _, err := gz.Write([]byte(data)); err != nil {
		return err
	}
	return gz.Close()
}

func (l *LogSendContext) post(status, feedback, kbfsLog, svcLog, desktopLog, updaterLog, startLog, installLog, systemLog, gitLog string) (string, error) {
	l.G().Log.Debug("sending status + logs to keybase")

	var body bytes.Buffer
	mpart := multipart.NewWriter(&body)

	if feedback != "" {
		mpart.WriteField("feedback", feedback)
	}

	if err := addFile(mpart, "status_gz", "status.gz", status); err != nil {
		return "", err
	}
	if err := addFile(mpart, "kbfs_log_gz", "kbfs_log.gz", kbfsLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "keybase_log_gz", "keybase_log.gz", svcLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "updater_log_gz", "updater_log.gz", updaterLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "gui_log_gz", "gui_log.gz", desktopLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "start_log_gz", "start_log.gz", startLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "install_log_gz", "install_log.gz", installLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "system_log_gz", "system_log.gz", systemLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "git_log_gz", "git_log.gz", gitLog); err != nil {
		return "", err
	}

	if err := mpart.Close(); err != nil {
		return "", err
	}

	l.G().Log.Debug("body size: %d\n", body.Len())

	arg := APIArg{
		Endpoint:    "logdump/send",
		SessionType: APISessionTypeOPTIONAL,
	}

	// Get the login session, if any
	l.G().LoginState().LoggedInLoad()

	resp, err := l.G().API.PostRaw(arg, mpart.FormDataContentType(), &body)
	if err != nil {
		l.G().Log.Debug("post error: %s", err)
		return "", err
	}

	id, err := resp.Body.AtKey("logdump_id").GetString()
	if err != nil {
		return "", err
	}

	return id, nil
}

// tail the logs that start with the stem `stem`, which are of type `which`.
// Get the most recent `numBytes` from the concatenation of the files.
func tail(log logger.Logger, which string, stem string, numBytes int) (ret string) {

	numFiles := 0

	log.Debug("+ tailing %s file with stem %q", which, stem)
	defer func() {
		log.Debug("- collected %d bytes from %d files", len(ret), numFiles)
	}()

	if len(stem) == 0 {
		log.Debug("| skipping %s logs (since no stem given)", which)
		return
	}

	lognames := listLogFiles(log, stem)
	var parts []string
	remaining := numBytes

	// Keep reading logs in reverse chronological order until we've read nothing
	// more, or we've filled up numBytes worth of buffer, or we didn't have to read
	// the whole file.
	for _, logname := range lognames {
		data, seeked := tailFile(log, which, logname, remaining)
		if len(data) == 0 {
			break
		}
		parts = append(parts, data)
		numFiles++
		remaining -= len(data)
		if remaining <= 0 || seeked {
			break
		}
	}

	// Reverse the array; took this one-line from StackOverflow answer
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}

	return strings.Join(parts, "")
}

type nameAndMTime struct {
	name  string
	mtime time.Time
}

type nameAndMTimes []nameAndMTime

func (a nameAndMTimes) Len() int           { return len(a) }
func (a nameAndMTimes) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a nameAndMTimes) Less(i, j int) bool { return a[i].mtime.After(a[j].mtime) }

// List logfiles that match the glob filename*, and return then in reverse chronological order.
// We'll need to read the first, and maybe the second
func listLogFiles(log logger.Logger, stem string) (ret []string) {
	stem = filepath.Clean(stem)
	dir := filepath.Dir(stem)
	base := filepath.Base(stem)
	files, err := ioutil.ReadDir(dir)

	defer func() {
		log.Debug("listLogFiles(%q) -> %v", stem, ret)
	}()

	// In the worst case, just return the stem in an array
	defret := []string{stem}

	if err != nil {
		log.Debug("failed to list directory %q: %s", dir, err)
		return defret
	}

	var tmp []nameAndMTime
	for _, d := range files {
		fullname := filepath.Clean(filepath.Join(dir, d.Name()))
		// Use the stat on the file (and not from the directory read)
		// since the latter doesn't work reliably on Windows
		finfo, err := os.Stat(fullname)
		if err != nil {
			log.Debug("Cannot stat %q: %s", fullname, err)
			continue
		}
		if strings.HasPrefix(d.Name(), base) {
			tmp = append(tmp, nameAndMTime{fullname, finfo.ModTime()})
		}
	}
	if len(tmp) == 0 {
		log.Debug("no files found matching \"%s*\"; falling back to default glob", stem)
		return defret
	}

	// Sort the files in reverse chronological mtime order. We should get the raw stem first.
	sort.Sort(nameAndMTimes(tmp))
	log.Debug("Sorted file list: %+v", tmp)

	for _, f := range tmp {
		ret = append(ret, f.name)
	}

	// If we didn't get the raw stem first, then we have a problem, so just use only the
	// raw stem and ignore the rest of our work.
	if stem != ret[0] {
		log.Debug("Expected to get %q first, but got %q instead! Falling back to one log only", stem, ret[0])
		return defret
	}
	return ret
}

// findFirstNewline first the first newline in the given byte array, and then returns the
// rest of the byte array. Should be safe to use on utf-8 strings.
func findFirstNewline(b []byte) []byte {
	index := bytes.IndexByte(b, '\n')
	if index < 0 || index == len(b)-1 {
		return nil
	}
	return b[(index + 1):]
}

func appendError(collected []byte, err error) []byte {
	return append(collected, []byte(fmt.Sprintf("\nERROR READING LOGS:\n%#v\n", err))...)
}

// If systemd is running, we look for logs in the systemd journal for our 3
// main services.
func tailSystemdJournal(log logger.Logger, which string, numBytes int) (ret string) {
	log.Debug("+ tailing journalctl for %s (%d bytes)", which, numBytes)
	defer func() {
		log.Debug("- scanned %d bytes", len(ret))
	}()

	// Journalctl doesn't provide a "last N bytes" flag directly, so instead we
	// use "last N lines". Large log files in practice seem to be about 150
	// bits per line. We'll request lines on that assumption, but if we get
	// more than 2x as many bytes as we expected, we'll stop reading and
	// include a big error.
	guessedLines := numBytes / 150
	maxBytes := numBytes * 2

	journalCmd := exec.Command(
		"journalctl",
		"--user",
		"--unit="+which,
		"--lines="+strconv.Itoa(guessedLines),
		"--output=cat",
	)
	journalCmd.Stderr = os.Stderr
	stdout, err := journalCmd.StdoutPipe()
	if err != nil {
		msg := fmt.Sprintf("Failed to open a pipe for journalctl: %s", err)
		log.Errorf(msg)
		return msg
	}
	err = journalCmd.Start()
	if err != nil {
		msg := fmt.Sprintf("Failed to run journalctl: %s", err)
		log.Errorf(msg)
		return msg
	}

	// Once we start reading output, don't short-circuit on errors. Just log
	// them, and return whatever we got.
	stdoutLimited := io.LimitReader(stdout, int64(maxBytes))
	output, err := ioutil.ReadAll(stdoutLimited)
	if err != nil {
		log.Errorf("Error reading from journalctl pipe: %s", err)
		output = appendError(output, err)
	}
	err = journalCmd.Wait()
	if err != nil {
		log.Errorf("Journalctl exited with an error: %s", err)
		output = appendError(output, err)
	}
	if len(output) >= maxBytes {
		truncation := "\n###\n### WARNING: Journal lines longer than expected. Logs truncated.\n###\n"
		output = append(output, truncation...)
	}
	return string(output)
}

// tailFile takes the last n bytes, but advances to the first newline. Returns the log (as a string)
// and a bool, indicating if we read the full log, or we had to advance into the log to find the newline.
func tailFile(log logger.Logger, which string, filename string, numBytes int) (ret string, seeked bool) {

	log.Debug("+ tailing %s log %q (%d bytes)", which, filename, numBytes)
	defer func() {
		log.Debug("- scanned %d bytes", len(ret))
	}()

	seeked = false
	if filename == "" {
		return ret, seeked
	}
	finfo, err := os.Stat(filename)
	if os.IsNotExist(err) {
		log.Debug("log %q doesn't exist", filename)
		return ret, seeked
	}
	f, err := os.Open(filename)
	if err != nil {
		log.Errorf("error opening log %q: %s", filename, err)
		return ret, seeked
	}
	defer f.Close()
	if finfo.Size() > int64(numBytes) {
		seeked = true
		_, err = f.Seek(int64(-numBytes), io.SeekEnd)
		if err != nil {
			log.Errorf("Can't seek log %q: %s", filename, err)
			return ret, seeked
		}
	}
	buf, err := ioutil.ReadAll(f)
	if err != nil {
		log.Errorf("Failure in reading file %q: %s", filename, err)
		return ret, seeked
	}
	if seeked {
		buf = findFirstNewline(buf)
	}
	return string(buf), seeked
}

// LogSend sends the the tails of log files to kb
func (l *LogSendContext) LogSend(statusJSON, feedback string, sendLogs bool, numBytes int) (string, error) {
	logs := l.Logs
	var kbfsLog string
	var svcLog string
	var desktopLog string
	var updaterLog string
	var startLog string
	var installLog string
	var systemLog string
	var gitLog string

	if sendLogs {
		if l.G().Env.WantsSystemd() {
			svcLog = tailSystemdJournal(l.G().Log, "keybase.service", numBytes)
			kbfsLog = tailSystemdJournal(l.G().Log, "kbfs.service", numBytes)
			desktopLog = tailSystemdJournal(l.G().Log, "keybase.gui.service", numBytes)
		} else {
			svcLog = tail(l.G().Log, "service", logs.Service, numBytes)
			kbfsLog = tail(l.G().Log, "kbfs", logs.Kbfs, numBytes)
			desktopLog = tail(l.G().Log, "desktop", logs.Desktop, numBytes)
		}
		updaterLog = tail(l.G().Log, "updater", logs.Updater, numBytes)
		startLog = tail(l.G().Log, "start", logs.Start, numBytes)
		installLog = tail(l.G().Log, "install", logs.Install, numBytes)
		systemLog = tail(l.G().Log, "system", logs.System, numBytes)
		gitLog = tail(l.G().Log, "git", logs.Git, numBytes)
	} else {
		kbfsLog = ""
		svcLog = ""
		desktopLog = ""
		updaterLog = ""
		startLog = ""
		installLog = ""
		systemLog = ""
		gitLog = ""
	}

	return l.post(statusJSON, feedback, kbfsLog, svcLog, desktopLog, updaterLog, startLog, installLog, systemLog, gitLog)
}
<commit_msg>remember to Close the journalctl stdout<commit_after>// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

package libkb

import (
	"bytes"
	"compress/gzip"
	"fmt"
	"io"
	"io/ioutil"
	"mime/multipart"
	"os"
	"os/exec"
	"path/filepath"
	"sort"
	"strconv"
	"strings"
	"time"

	"github.com/keybase/client/go/logger"
)

// Logs is the struct to specify the path of log files
type Logs struct {
	Desktop string
	Kbfs    string
	Service string
	Updater string
	Start   string
	Install string
	System  string
	Git     string
}

// LogSendContext for LogSend
type LogSendContext struct {
	Contextified
	Logs Logs
}

func addFile(mpart *multipart.Writer, param, filename, data string) error {
	if len(data) == 0 {
		return nil
	}

	part, err := mpart.CreateFormFile(param, filename)
	if err != nil {
		return err
	}
	gz := gzip.NewWriter(part)
	if _, err := gz.Write([]byte(data)); err != nil {
		return err
	}
	return gz.Close()
}

func (l *LogSendContext) post(status, feedback, kbfsLog, svcLog, desktopLog, updaterLog, startLog, installLog, systemLog, gitLog string) (string, error) {
	l.G().Log.Debug("sending status + logs to keybase")

	var body bytes.Buffer
	mpart := multipart.NewWriter(&body)

	if feedback != "" {
		mpart.WriteField("feedback", feedback)
	}

	if err := addFile(mpart, "status_gz", "status.gz", status); err != nil {
		return "", err
	}
	if err := addFile(mpart, "kbfs_log_gz", "kbfs_log.gz", kbfsLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "keybase_log_gz", "keybase_log.gz", svcLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "updater_log_gz", "updater_log.gz", updaterLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "gui_log_gz", "gui_log.gz", desktopLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "start_log_gz", "start_log.gz", startLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "install_log_gz", "install_log.gz", installLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "system_log_gz", "system_log.gz", systemLog); err != nil {
		return "", err
	}
	if err := addFile(mpart, "git_log_gz", "git_log.gz", gitLog); err != nil {
		return "", err
	}

	if err := mpart.Close(); err != nil {
		return "", err
	}

	l.G().Log.Debug("body size: %d\n", body.Len())

	arg := APIArg{
		Endpoint:    "logdump/send",
		SessionType: APISessionTypeOPTIONAL,
	}

	// Get the login session, if any
	l.G().LoginState().LoggedInLoad()

	resp, err := l.G().API.PostRaw(arg, mpart.FormDataContentType(), &body)
	if err != nil {
		l.G().Log.Debug("post error: %s", err)
		return "", err
	}

	id, err := resp.Body.AtKey("logdump_id").GetString()
	if err != nil {
		return "", err
	}

	return id, nil
}

// tail the logs that start with the stem `stem`, which are of type `which`.
// Get the most recent `numBytes` from the concatenation of the files.
func tail(log logger.Logger, which string, stem string, numBytes int) (ret string) {

	numFiles := 0

	log.Debug("+ tailing %s file with stem %q", which, stem)
	defer func() {
		log.Debug("- collected %d bytes from %d files", len(ret), numFiles)
	}()

	if len(stem) == 0 {
		log.Debug("| skipping %s logs (since no stem given)", which)
		return
	}

	lognames := listLogFiles(log, stem)
	var parts []string
	remaining := numBytes

	// Keep reading logs in reverse chronological order until we've read nothing
	// more, or we've filled up numBytes worth of buffer, or we didn't have to read
	// the whole file.
	for _, logname := range lognames {
		data, seeked := tailFile(log, which, logname, remaining)
		if len(data) == 0 {
			break
		}
		parts = append(parts, data)
		numFiles++
		remaining -= len(data)
		if remaining <= 0 || seeked {
			break
		}
	}

	// Reverse the array; took this one-line from StackOverflow answer
	for i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {
		parts[i], parts[j] = parts[j], parts[i]
	}

	return strings.Join(parts, "")
}

type nameAndMTime struct {
	name  string
	mtime time.Time
}

type nameAndMTimes []nameAndMTime

func (a nameAndMTimes) Len() int           { return len(a) }
func (a nameAndMTimes) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a nameAndMTimes) Less(i, j int) bool { return a[i].mtime.After(a[j].mtime) }

// List logfiles that match the glob filename*, and return then in reverse chronological order.
// We'll need to read the first, and maybe the second
func listLogFiles(log logger.Logger, stem string) (ret []string) {
	stem = filepath.Clean(stem)
	dir := filepath.Dir(stem)
	base := filepath.Base(stem)
	files, err := ioutil.ReadDir(dir)

	defer func() {
		log.Debug("listLogFiles(%q) -> %v", stem, ret)
	}()

	// In the worst case, just return the stem in an array
	defret := []string{stem}

	if err != nil {
		log.Debug("failed to list directory %q: %s", dir, err)
		return defret
	}

	var tmp []nameAndMTime
	for _, d := range files {
		fullname := filepath.Clean(filepath.Join(dir, d.Name()))
		// Use the stat on the file (and not from the directory read)
		// since the latter doesn't work reliably on Windows
		finfo, err := os.Stat(fullname)
		if err != nil {
			log.Debug("Cannot stat %q: %s", fullname, err)
			continue
		}
		if strings.HasPrefix(d.Name(), base) {
			tmp = append(tmp, nameAndMTime{fullname, finfo.ModTime()})
		}
	}
	if len(tmp) == 0 {
		log.Debug("no files found matching \"%s*\"; falling back to default glob", stem)
		return defret
	}

	// Sort the files in reverse chronological mtime order. We should get the raw stem first.
	sort.Sort(nameAndMTimes(tmp))
	log.Debug("Sorted file list: %+v", tmp)

	for _, f := range tmp {
		ret = append(ret, f.name)
	}

	// If we didn't get the raw stem first, then we have a problem, so just use only the
	// raw stem and ignore the rest of our work.
	if stem != ret[0] {
		log.Debug("Expected to get %q first, but got %q instead! Falling back to one log only", stem, ret[0])
		return defret
	}
	return ret
}

// findFirstNewline first the first newline in the given byte array, and then returns the
// rest of the byte array. Should be safe to use on utf-8 strings.
func findFirstNewline(b []byte) []byte {
	index := bytes.IndexByte(b, '\n')
	if index < 0 || index == len(b)-1 {
		return nil
	}
	return b[(index + 1):]
}

func appendError(log logger.Logger, collected []byte, format string, args ...interface{}) []byte {
	msg := "Error reading logs: " + fmt.Sprintf(format, args...)
	log.Errorf(msg)
	return append(collected, []byte("\n"+msg+"\n")...)
}

// If systemd is running, we look for logs in the systemd journal for our 3
// main services.
func tailSystemdJournal(log logger.Logger, which string, numBytes int) (ret string) {
	log.Debug("+ tailing journalctl for %s (%d bytes)", which, numBytes)
	defer func() {
		log.Debug("- scanned %d bytes", len(ret))
	}()

	// Journalctl doesn't provide a "last N bytes" flag directly, so instead we
	// use "last N lines". Large log files in practice seem to be about 150
	// bits per line. We'll request lines on that assumption, but if we get
	// more than 2x as many bytes as we expected, we'll stop reading and
	// include a big error.
	guessedLines := numBytes / 150
	maxBytes := numBytes * 2

	journalCmd := exec.Command(
		"journalctl",
		"--user",
		"--unit="+which,
		"--lines="+strconv.Itoa(guessedLines),
		"--output=cat",
	)
	journalCmd.Stderr = os.Stderr
	stdout, err := journalCmd.StdoutPipe()
	if err != nil {
		msg := fmt.Sprintf("Failed to open a pipe for journalctl: %s", err)
		log.Errorf(msg)
		return msg
	}
	err = journalCmd.Start()
	if err != nil {
		msg := fmt.Sprintf("Failed to run journalctl: %s", err)
		log.Errorf(msg)
		return msg
	}

	// Once we start reading output, don't short-circuit on errors. Just log
	// them, and return whatever we got.
	stdoutLimited := io.LimitReader(stdout, int64(maxBytes))
	output, err := ioutil.ReadAll(stdoutLimited)
	if err != nil {
		output = appendError(log, output, "Error reading from journalctl pipe: %s", err)
	}
	// We must close stdout before Wait, or else Wait might deadlock.
	stdout.Close()
	err = journalCmd.Wait()
	if err != nil {
		output = appendError(log, output, "Journalctl exited with an error: %s", err)
	}
	if len(output) >= maxBytes {
		output = appendError(log, output, "Journal lines longer than expected. Logs truncated.")
	}
	return string(output)
}

// tailFile takes the last n bytes, but advances to the first newline. Returns the log (as a string)
// and a bool, indicating if we read the full log, or we had to advance into the log to find the newline.
func tailFile(log logger.Logger, which string, filename string, numBytes int) (ret string, seeked bool) {

	log.Debug("+ tailing %s log %q (%d bytes)", which, filename, numBytes)
	defer func() {
		log.Debug("- scanned %d bytes", len(ret))
	}()

	seeked = false
	if filename == "" {
		return ret, seeked
	}
	finfo, err := os.Stat(filename)
	if os.IsNotExist(err) {
		log.Debug("log %q doesn't exist", filename)
		return ret, seeked
	}
	f, err := os.Open(filename)
	if err != nil {
		log.Errorf("error opening log %q: %s", filename, err)
		return ret, seeked
	}
	defer f.Close()
	if finfo.Size() > int64(numBytes) {
		seeked = true
		_, err = f.Seek(int64(-numBytes), io.SeekEnd)
		if err != nil {
			log.Errorf("Can't seek log %q: %s", filename, err)
			return ret, seeked
		}
	}
	buf, err := ioutil.ReadAll(f)
	if err != nil {
		log.Errorf("Failure in reading file %q: %s", filename, err)
		return ret, seeked
	}
	if seeked {
		buf = findFirstNewline(buf)
	}
	return string(buf), seeked
}

// LogSend sends the the tails of log files to kb
func (l *LogSendContext) LogSend(statusJSON, feedback string, sendLogs bool, numBytes int) (string, error) {
	logs := l.Logs
	var kbfsLog string
	var svcLog string
	var desktopLog string
	var updaterLog string
	var startLog string
	var installLog string
	var systemLog string
	var gitLog string

	if sendLogs {
		if l.G().Env.WantsSystemd() {
			svcLog = tailSystemdJournal(l.G().Log, "keybase.service", numBytes)
			kbfsLog = tailSystemdJournal(l.G().Log, "kbfs.service", numBytes)
			desktopLog = tailSystemdJournal(l.G().Log, "keybase.gui.service", numBytes)
		} else {
			svcLog = tail(l.G().Log, "service", logs.Service, numBytes)
			kbfsLog = tail(l.G().Log, "kbfs", logs.Kbfs, numBytes)
			desktopLog = tail(l.G().Log, "desktop", logs.Desktop, numBytes)
		}
		updaterLog = tail(l.G().Log, "updater", logs.Updater, numBytes)
		startLog = tail(l.G().Log, "start", logs.Start, numBytes)
		installLog = tail(l.G().Log, "install", logs.Install, numBytes)
		systemLog = tail(l.G().Log, "system", logs.System, numBytes)
		gitLog = tail(l.G().Log, "git", logs.Git, numBytes)
	} else {
		kbfsLog = ""
		svcLog = ""
		desktopLog = ""
		updaterLog = ""
		startLog = ""
		installLog = ""
		systemLog = ""
		gitLog = ""
	}

	return l.post(statusJSON, feedback, kbfsLog, svcLog, desktopLog, updaterLog, startLog, installLog, systemLog, gitLog)
}
<|endoftext|>


<commit_before>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// TODO(gri) This file needs to be expanded significantly.

package types

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
	"testing"
)

func pkgFor(path string, source string, info *Info) (*Package, error) {
	fset = token.NewFileSet()
	f, err := parser.ParseFile(fset, path, source, 0)
	if err != nil {
		return nil, err
	}

	var conf Config
	pkg, err := conf.Check(path, fset, []*ast.File{f}, info)
	if err != nil {
		return nil, err
	}

	return pkg, nil
}

func TestCommaOkTypes(t *testing.T) {
	var tests = []struct {
		src  string
		expr string // comma-ok expression string
		typ  string // typestring of comma-ok value
	}{
		{`package p; var x interface{}; var _, _ = x.(int)`,
			`x.(int)`,
			`(int, bool)`,
		},
		{`package p; var x interface{}; func _() { _, _ = x.(int) }`,
			`x.(int)`,
			`(int, bool)`,
		},
		{`package p; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
			`m["foo"]`,
			`(complex128, p.mybool)`,
		},
		{`package p; var c chan string; var _, _ = <-c`,
			`<-c`,
			`(string, bool)`,
		},
	}

	for i, test := range tests {
		path := fmt.Sprintf("CommaOkTypes%d", i)

		// type-check
		info := Info{Types: make(map[ast.Expr]Type)}
		_, err := pkgFor(path, test.src, &info)
		if err != nil {
			t.Error(err)
			continue
		}

		// look for comma-ok expression type
		var typ Type
		for e, t := range info.Types {
			if exprString(e) == test.expr {
				typ = t
				break
			}
		}
		if typ == nil {
			t.Errorf("%s: no type found for %s", path, test.expr)
			continue
		}

		// check that type is correct
		if got := typ.String(); got != test.typ {
			t.Errorf("%s: got %s; want %s", path, got, test.typ)
		}
	}
}

func TestScopesInfo(t *testing.T) {
	var tests = []struct {
		src    string
		scopes []string // list of scope descriptors of the form kind:varlist
	}{
		{"package p", []string{
			"file:",
		}},
		{"package p; func _() {}", []string{
			"file:", "func:",
		}},
		{"package p; func _(x, y int) {}", []string{
			"file:", "func:x y",
		}},
		{"package p; func _(x, y int) { x, z := 1, 2; _ = z }", []string{
			"file:", "func:x y z", // redeclaration of x
		}},
		{"package p; func _(x, y int) (u, _ int) { return }", []string{
			"file:", "func:u x y",
		}},
		{"package p; func _() { { var x int; _ = x } }", []string{
			"file:", "func:", "block:x",
		}},
		{"package p; func _() { if true {} }", []string{
			"file:", "func:", "if:", "block:",
		}},
		{"package p; func _() { if x := 0; x < 0 { y := x; _ = y } }", []string{
			"file:", "func:", "if:x", "block:y",
		}},
		{"package p; func _() { switch x := 0; x {} }", []string{
			"file:", "func:", "switch:x",
		}},
		{"package p; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}", []string{
			"file:", "func:", "switch:x", "case:y", "case:",
		}},
		{"package p; func _(t interface{}) { switch t.(type) {} }", []string{
			"file:", "func:t", "type switch:",
		}},
		{"package p; func _(t interface{}) { switch t := t; t.(type) {} }", []string{
			"file:", "func:t", "type switch:t",
		}},
		{"package p; func _(t interface{}) { switch x := t.(type) { case int: } }", []string{
			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
		}},
		{"package p; func _() { select{} }", []string{
			"file:", "func:",
		}},
		{"package p; func _(c chan int) { select{ case <-c: } }", []string{
			"file:", "func:c", "comm:",
		}},
		{"package p; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }", []string{
			"file:", "func:c", "comm:i x",
		}},
		{"package p; func _() { for{} }", []string{
			"file:", "func:", "for:", "block:",
		}},
		{"package p; func _(n int) { for i := 0; i < n; i++ { _ = i } }", []string{
			"file:", "func:n", "for:i", "block:",
		}},
		{"package p; func _(a []int) { for i := range a { _ = i} }", []string{
			"file:", "func:a", "range:i", "block:",
		}},
		{"package p; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }", []string{
			"file:", "func:a", "range:i x", "block:",
		}},
	}

	for i, test := range tests {
		path := fmt.Sprintf("ScopesInfo%d", i)

		// type-check
		info := Info{Scopes: make(map[ast.Node]*Scope)}
		_, err := pkgFor(path, test.src, &info)
		if err != nil {
			t.Error(err)
			continue
		}

		// number of scopes must match
		if len(info.Scopes) != len(test.scopes) {
			t.Errorf("%s: got %d scopes; want %d", path, len(info.Scopes), len(test.scopes))
		}

		// scope descriptions must match
		for node, scope := range info.Scopes {
			kind := "<unknown node kind>"
			switch node.(type) {
			case *ast.File:
				kind = "file"
			case *ast.FuncType:
				kind = "func"
			case *ast.BlockStmt:
				kind = "block"
			case *ast.IfStmt:
				kind = "if"
			case *ast.SwitchStmt:
				kind = "switch"
			case *ast.TypeSwitchStmt:
				kind = "type switch"
			case *ast.CaseClause:
				kind = "case"
			case *ast.CommClause:
				kind = "comm"
			case *ast.ForStmt:
				kind = "for"
			case *ast.RangeStmt:
				kind = "range"
			}

			// look for matching scope description
			desc := kind + ":" + strings.Join(scope.Names(), " ")
			found := false
			for _, d := range test.scopes {
				if desc == d {
					found = true
					break
				}
			}
			if !found {
				t.Errorf("%s: no matching scope found for %s", path, desc)
			}
		}
	}
}
<commit_msg>go.tools/go/types: added missing test for file scopes<commit_after>// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// TODO(gri) This file needs to be expanded significantly.

package types

import (
	"fmt"
	"go/ast"
	"go/parser"
	"go/token"
	"strings"
	"testing"
)

func pkgFor(path, source string, info *Info) (*Package, error) {
	fset = token.NewFileSet()
	f, err := parser.ParseFile(fset, path, source, 0)
	if err != nil {
		return nil, err
	}

	var conf Config
	pkg, err := conf.Check(path, fset, []*ast.File{f}, info)
	if err != nil {
		return nil, err
	}

	return pkg, nil
}

func mustTypecheck(t *testing.T, path, source string, info *Info) *Package {
	pkg, err := pkgFor(path, source, info)
	if err != nil {
		t.Fatalf("%s: didn't type-check (%s)", path, err)
	}
	return pkg
}

func TestCommaOkTypes(t *testing.T) {
	var tests = []struct {
		src  string
		expr string // comma-ok expression string
		typ  string // typestring of comma-ok value
	}{
		{`package p; var x interface{}; var _, _ = x.(int)`,
			`x.(int)`,
			`(int, bool)`,
		},
		{`package p; var x interface{}; func _() { _, _ = x.(int) }`,
			`x.(int)`,
			`(int, bool)`,
		},
		{`package p; type mybool bool; var m map[string]complex128; var b mybool; func _() { _, b = m["foo"] }`,
			`m["foo"]`,
			`(complex128, p.mybool)`,
		},
		{`package p; var c chan string; var _, _ = <-c`,
			`<-c`,
			`(string, bool)`,
		},
	}

	for i, test := range tests {
		path := fmt.Sprintf("CommaOkTypes%d", i)
		info := Info{Types: make(map[ast.Expr]Type)}
		mustTypecheck(t, path, test.src, &info)

		// look for comma-ok expression type
		var typ Type
		for e, t := range info.Types {
			if exprString(e) == test.expr {
				typ = t
				break
			}
		}
		if typ == nil {
			t.Errorf("%s: no type found for %s", path, test.expr)
			continue
		}

		// check that type is correct
		if got := typ.String(); got != test.typ {
			t.Errorf("%s: got %s; want %s", path, got, test.typ)
		}
	}
}

func TestScopesInfo(t *testing.T) {
	var tests = []struct {
		src    string
		scopes []string // list of scope descriptors of the form kind:varlist
	}{
		{`package p`, []string{
			"file:",
		}},
		{`package p; import ( "fmt"; m "math"; _ "os" )`, []string{
			"file:fmt m",
		}},
		{`package p; func _() {}`, []string{
			"file:", "func:",
		}},
		{`package p; func _(x, y int) {}`, []string{
			"file:", "func:x y",
		}},
		{`package p; func _(x, y int) { x, z := 1, 2; _ = z }`, []string{
			"file:", "func:x y z", // redeclaration of x
		}},
		{`package p; func _(x, y int) (u, _ int) { return }`, []string{
			"file:", "func:u x y",
		}},
		{`package p; func _() { { var x int; _ = x } }`, []string{
			"file:", "func:", "block:x",
		}},
		{`package p; func _() { if true {} }`, []string{
			"file:", "func:", "if:", "block:",
		}},
		{`package p; func _() { if x := 0; x < 0 { y := x; _ = y } }`, []string{
			"file:", "func:", "if:x", "block:y",
		}},
		{`package p; func _() { switch x := 0; x {} }`, []string{
			"file:", "func:", "switch:x",
		}},
		{`package p; func _() { switch x := 0; x { case 1: y := x; _ = y; default: }}`, []string{
			"file:", "func:", "switch:x", "case:y", "case:",
		}},
		{`package p; func _(t interface{}) { switch t.(type) {} }`, []string{
			"file:", "func:t", "type switch:",
		}},
		{`package p; func _(t interface{}) { switch t := t; t.(type) {} }`, []string{
			"file:", "func:t", "type switch:t",
		}},
		{`package p; func _(t interface{}) { switch x := t.(type) { case int: } }`, []string{
			"file:", "func:t", "type switch:", "case:x", // x implicitly declared
		}},
		{`package p; func _() { select{} }`, []string{
			"file:", "func:",
		}},
		{`package p; func _(c chan int) { select{ case <-c: } }`, []string{
			"file:", "func:c", "comm:",
		}},
		{`package p; func _(c chan int) { select{ case i := <-c: x := i; _ = x} }`, []string{
			"file:", "func:c", "comm:i x",
		}},
		{`package p; func _() { for{} }`, []string{
			"file:", "func:", "for:", "block:",
		}},
		{`package p; func _(n int) { for i := 0; i < n; i++ { _ = i } }`, []string{
			"file:", "func:n", "for:i", "block:",
		}},
		{`package p; func _(a []int) { for i := range a { _ = i} }`, []string{
			"file:", "func:a", "range:i", "block:",
		}},
		{`package p; var s int; func _(a []int) { for i, x := range a { s += x; _ = i } }`, []string{
			"file:", "func:a", "range:i x", "block:",
		}},
	}

	for i, test := range tests {
		path := fmt.Sprintf("ScopesInfo%d", i)
		info := Info{Scopes: make(map[ast.Node]*Scope)}
		mustTypecheck(t, path, test.src, &info)

		// number of scopes must match
		if len(info.Scopes) != len(test.scopes) {
			t.Errorf("%s: got %d scopes; want %d", path, len(info.Scopes), len(test.scopes))
		}

		// scope descriptions must match
		for node, scope := range info.Scopes {
			kind := "<unknown node kind>"
			switch node.(type) {
			case *ast.File:
				kind = "file"
			case *ast.FuncType:
				kind = "func"
			case *ast.BlockStmt:
				kind = "block"
			case *ast.IfStmt:
				kind = "if"
			case *ast.SwitchStmt:
				kind = "switch"
			case *ast.TypeSwitchStmt:
				kind = "type switch"
			case *ast.CaseClause:
				kind = "case"
			case *ast.CommClause:
				kind = "comm"
			case *ast.ForStmt:
				kind = "for"
			case *ast.RangeStmt:
				kind = "range"
			}

			// look for matching scope description
			desc := kind + ":" + strings.Join(scope.Names(), " ")
			found := false
			for _, d := range test.scopes {
				if desc == d {
					found = true
					break
				}
			}
			if !found {
				t.Errorf("%s: no matching scope found for %s", path, desc)
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os/exec"
	"time"

	pb "github.com/brotherlogic/gobuildslave/proto"
	pbt "github.com/brotherlogic/tracer/proto"

	"github.com/brotherlogic/goserver/utils"
	"golang.org/x/net/context"
)

const (
	pendWait = time.Minute
)

func (s *Server) runTransition(ctx context.Context, job *pb.JobAssignment) {
	utils.SendTrace(ctx, fmt.Sprintf("run_transition_%v", job.State), time.Now(), pbt.Milestone_MARKER, job.Job.Name)
	stState := job.State
	switch job.State {
	case pb.State_ACKNOWLEDGED:
		key := s.scheduleBuild(ctx, job.Job)
		if job.Job.NonBootstrap {
			if key != "" {
				job.Server = s.Registry.Identifier
				job.State = pb.State_BUILT
				job.RunningVersion = key
			}
		} else {
			job.CommandKey = key
			job.State = pb.State_BUILDING
			job.Server = s.Registry.Identifier
		}
	case pb.State_BUILDING:
		if s.taskComplete(job.CommandKey) {
			job.State = pb.State_BUILT
		}
	case pb.State_BUILT:
		output := s.scheduler.getOutput(job.CommandKey)
		if len(output) > 0 {
			if job.BuildFail == 5 {
				s.deliverCrashReport(ctx, job, output)
			}
			job.BuildFail++
			job.State = pb.State_DIED
		} else {
			job.BuildFail = 0
			key := s.scheduleRun(job.Job)
			job.CommandKey = key
			job.StartTime = time.Now().Unix()
			job.State = pb.State_PENDING
		}
	case pb.State_PENDING:
		if time.Now().Add(-time.Minute).Unix() > job.StartTime {
			job.State = pb.State_RUNNING
		}
	case pb.State_RUNNING:
		if s.taskComplete(job.CommandKey) {
			output := s.scheduler.getOutput(job.CommandKey)
			s.deliverCrashReport(ctx, job, output)
			job.State = pb.State_DIED
		}

		// Restart this job if we need to
		if job.Job.NonBootstrap {
			version := s.getVersion(ctx, job.Job)
			if version != job.RunningVersion {
				s.Log(fmt.Sprintf("KILLING %v", job.Job.Name))
				s.scheduler.killJob(job.CommandKey)
				job.State = pb.State_ACKNOWLEDGED
			}
		}
	case pb.State_DIED:
		job.State = pb.State_ACKNOWLEDGED
	}
	utils.SendTrace(ctx, fmt.Sprintf("end_transition_%v", job.State), time.Now(), pbt.Milestone_MARKER, job.Job.Name)
	if job.State != stState {
		s.Log(fmt.Sprintf("Job %v went from %v to %v", job.Job.Name, stState, job.State))
	}
}

type translator interface {
	build(job *pb.Job) *exec.Cmd
	run(job *pb.Job) *exec.Cmd
}

type checker interface {
	isAlive(ctx context.Context, job *pb.JobAssignment) bool
}

func (s *Server) getVersion(ctx context.Context, job *pb.Job) string {
	versions := s.builder.build(ctx, job)

	if len(versions) == 0 {
		s.Log(fmt.Sprintf("No versions received for %v", job.Name))
		return ""
	}

	return versions[0].Version

}

// scheduleBuild builds out the job, returning the current version
func (s *Server) scheduleBuild(ctx context.Context, job *pb.Job) string {
	s.Log(fmt.Sprintf("SCHEDULING BUILD FOR %v", job.Name))
	if !job.NonBootstrap {
		c := s.translator.build(job)
		return s.scheduler.Schedule(&rCommand{command: c})
	}

	s.Log(fmt.Sprintf("BUILDING %v", job.Name))
	versions := s.builder.build(ctx, job)

	if len(versions) == 0 {
		s.Log(fmt.Sprintf("No versions received for %v", job.Name))
		return ""
	}

	s.Log(fmt.Sprintf("COPYING WITH %v", s.builder))
	err := s.builder.copy(ctx, versions[0])
	if err != nil {
		return ""
	}
	return versions[0].Version
}

func (s *Server) scheduleRun(job *pb.Job) string {
	c := s.translator.run(job)
	return s.scheduler.Schedule(&rCommand{command: c})
}

func (s *Server) taskComplete(key string) bool {
	return s.scheduler.schedulerComplete(key)
}
<commit_msg>More detail in the long tracking<commit_after>package main

import (
	"fmt"
	"os/exec"
	"time"

	pb "github.com/brotherlogic/gobuildslave/proto"
	pbt "github.com/brotherlogic/tracer/proto"

	"github.com/brotherlogic/goserver/utils"
	"golang.org/x/net/context"
)

const (
	pendWait = time.Minute
)

func (s *Server) runTransition(ctx context.Context, job *pb.JobAssignment) {
	utils.SendTrace(ctx, fmt.Sprintf("run_transition_%v", job.State), time.Now(), pbt.Milestone_MARKER, job.Job.Name)
	stState := job.State
	switch job.State {
	case pb.State_ACKNOWLEDGED:
		key := s.scheduleBuild(ctx, job.Job)
		if job.Job.NonBootstrap {
			if key != "" {
				job.Server = s.Registry.Identifier
				job.State = pb.State_BUILT
				job.RunningVersion = key
			}
		} else {
			job.CommandKey = key
			job.State = pb.State_BUILDING
			job.Server = s.Registry.Identifier
		}
	case pb.State_BUILDING:
		if s.taskComplete(job.CommandKey) {
			job.State = pb.State_BUILT
		}
	case pb.State_BUILT:
		output := s.scheduler.getOutput(job.CommandKey)
		if len(output) > 0 {
			if job.BuildFail == 5 {
				s.deliverCrashReport(ctx, job, output)
			}
			job.BuildFail++
			job.State = pb.State_DIED
		} else {
			job.BuildFail = 0
			key := s.scheduleRun(job.Job)
			job.CommandKey = key
			job.StartTime = time.Now().Unix()
			job.State = pb.State_PENDING
		}
	case pb.State_PENDING:
		if time.Now().Add(-time.Minute).Unix() > job.StartTime {
			job.State = pb.State_RUNNING
		}
	case pb.State_RUNNING:
		if s.taskComplete(job.CommandKey) {
			output := s.scheduler.getOutput(job.CommandKey)
			s.deliverCrashReport(ctx, job, output)
			job.State = pb.State_DIED
		}

		// Restart this job if we need to
		if job.Job.NonBootstrap {
			version := s.getVersion(ctx, job.Job)
			if version != job.RunningVersion {
				s.Log(fmt.Sprintf("KILLING %v", job.Job.Name))
				s.scheduler.killJob(job.CommandKey)
				job.State = pb.State_ACKNOWLEDGED
			}
		}
	case pb.State_DIED:
		job.State = pb.State_ACKNOWLEDGED
	}
	utils.SendTrace(ctx, fmt.Sprintf("end_transition_%v", job.State), time.Now(), pbt.Milestone_MARKER, job.Job.Name)
	if job.State != stState {
		s.Log(fmt.Sprintf("Job %v went from %v to %v", job.Job.Name, stState, job.State))
	}
}

type translator interface {
	build(job *pb.Job) *exec.Cmd
	run(job *pb.Job) *exec.Cmd
}

type checker interface {
	isAlive(ctx context.Context, job *pb.JobAssignment) bool
}

func (s *Server) getVersion(ctx context.Context, job *pb.Job) string {
	versions := s.builder.build(ctx, job)

	if len(versions) == 0 {
		s.Log(fmt.Sprintf("No versions received for %v", job.Name))
		return ""
	}

	return versions[0].Version

}

// scheduleBuild builds out the job, returning the current version
func (s *Server) scheduleBuild(ctx context.Context, job *pb.Job) string {
	s.Log(fmt.Sprintf("SCHEDULING BUILD FOR %v", job.Name))
	utils.SendTrace(ctx, fmt.Sprintf("schedule_build_%v", job.NonBootstrap), time.Now(), pbt.Milestone_MARKER, job.Name)
	if !job.NonBootstrap {
		c := s.translator.build(job)
		return s.scheduler.Schedule(&rCommand{command: c})
	}

	s.Log(fmt.Sprintf("BUILDING %v", job.Name))
	versions := s.builder.build(ctx, job)

	if len(versions) == 0 {
		s.Log(fmt.Sprintf("No versions received for %v", job.Name))
		return ""
	}

	s.Log(fmt.Sprintf("COPYING WITH %v", s.builder))
	err := s.builder.copy(ctx, versions[0])
	if err != nil {
		return ""
	}
	return versions[0].Version
}

func (s *Server) scheduleRun(job *pb.Job) string {
	c := s.translator.run(job)
	return s.scheduler.Schedule(&rCommand{command: c})
}

func (s *Server) taskComplete(key string) bool {
	return s.scheduler.schedulerComplete(key)
}
<|endoftext|>