<commit_before>package main

import (
  "database/sql"
  "encoding/json"
  "fmt"
  "github.com/go-martini/martini"
  "github.com/martini-contrib/render"
  "github.com/martini-contrib/sessions"
  _ "github.com/mattn/go-sqlite3"
  "log"
  "os"
  "os/exec"
  "strconv"
  "time"
  "net/http"
  "io"
)

func resetDb() {
  // Remove the old database.
  fmt.Println("ii Removing the old database.")
  os.Remove("./db.db")

  // Re-create the database.
  fmt.Println("ii Re-creating the database.")
  cmd := exec.Command("/usr/bin/sqlite3", "ocdns.db", "<", "db.sql")
  cmd.Stdin = os.Stdin
  cmd.Stdout = os.Stdout
  cmd.Stderr = os.Stderr
  err := cmd.Run()

  // Check the output.
  if err != nil {
    fmt.Println("-- Failed to re-create the database.")
    //fmt.Println("Output: " + err)
    os.Exit(1)
  }

  fmt.Println("ii Successfully created the new file.")
}

func main() {
  // Reset the database.
  //resetDb()

  // TODO: Create default admin account.
  // TODO: Use config file?
  rs, aErr := aConn.Query("SELECT * FROM `Submissions` WHERE `Submissions`.`timestamp` >= " + aTime.Format(aLayout))
  if aErr != nil {
    log.Fatal(err)
  }
  defer rs.Close()

  // Get the Martini instance.
  m := martini.Classic()

  // Create session store.
  store := sessions.NewCookieStore([]byte("doublesecret"))
  m.Use(sessions.Sessions("ocdns", store))

  // Set a layout.
  m.Use(render.Renderer(render.Options{
    Layout: "layout",
  }))

  m.Get("/", func(r render.Render, session sessions.Session) {
    // TODO: Perform checks to see if the user is logged in. If they are, then
    // render a specific page based on their role.
    role := session.Get("role")

    if role == "Admin" {
      r.HTML(302, "admin", "")
    } else if role == "Judge" {
      r.HTML(302, "judge", "")
    } else if role == "Player" {
      r.HTML(302, "player", "")
    } else {
      r.HTML(200, "index", "")
    }
  })

  /* Judge route **************************************************************/
  m.Get("/judge", func(r render.Render, session sessions.Session) {
    //role := session.Get("role")

    //if role == "Judge" {
    r.HTML(200, "judge", "test")
    //} else {
    //  r.HTML(302, "index", "test")
    //}
  })

  /* Admin route **************************************************************/
  m.Get("/admin", func(r render.Render, session sessions.Session) {
    //role := session.Get("role")

    //if role == "Admin" {
    r.HTML(200, "admin", "test")
    //} else {
    //  r.HTML(302, "index", "test")
    //}
  })

  /* Player route *************************************************************/
  m.Get("/player", func(r render.Render, session sessions.Session) {
    role := ""//session.Get("role")

    if role == "player" || true {
      aConn, err := sql.Open("sqlite3", "ocdns.db")
      defer aConn.Close()

      // Query the database.
      rs, aErr := aConn.Query("SELECT problem_id, name, question FROM `Problems`;")
      if aErr != nil {
        log.Fatal(err)
      }
      defer rs.Close()

      // Return the results in a json object
      var questions = make(map[string]map[string]string)
      var tmp = make(map[string]string)
      for rs.Next() {
        var problem_id int
        var name string
        var question string

        rs.Scan(&problem_id, &name, &question)

        tmp = make(map[string]string)
        tmp["name"] = name
        tmp["question"] = question
        questions[strconv.Itoa(problem_id)] = tmp
      }

      // Query the database.
      rs, aErr = aConn.Query("SELECT language_id, name FROM `Language`;")
      if aErr != nil {
        log.Fatal(err)
      }
      defer rs.Close()

      // Return the results in a json object
      var languages = make(map[string]map[string]string)
      for rs.Next() {
        var language_id int
        var name string

        rs.Scan(&language_id, &name)

        tmp = make(map[string]string)
        tmp["name"] = name
        languages[strconv.Itoa(language_id)] = tmp
      }

      // Create a map to return.
      var aRet = make(map[string]map[string]map[string]string)

      aRet["questions"] = questions
      aRet["languages"] = languages

      // Conver the array into json.
      aJson, aErr := json.Marshal(aRet)

      r.HTML(200, "player", string(aJson))
    } else {
     r.HTML(302, "index", nil)
    }
  })

  /* Player submission route **************************************************/
  m.Get("/api/submitCode", func(r render.Render, h http.Request) string {
    // Get the team id.
    team_id := 0//session.Get("team_id")

    // if team_id == nil {
    //  return
    // }

    // Open the database.
    aConn, _ := sql.Open("sqlite3", "ocdns.db")
    defer aConn.Close()

    // Get form stuff.
    multi_err := h.ParseMultipartForm(100000)
    if multi_err != nil {
      return multi_err.Error()
    }

    problem_id := h.MultipartForm.File["question"]
    language := h.MultipartForm.File["language"]
    file := h.MultipartForm.File["file"]

    var filepath = "./" + string(team_id) + "/" + file[0].Filename

    // Save the file.
    log.Println("getting handle to file")
    file_s, open_err := file[0].Open()
    defer file_s.Close()
    if open_err != nil {
      return open_err.Error()
    }

    log.Println("creating destination file")
    dst, create_err := os.Create("./" + string(team_id) + "/" + file[0].Filename)
    defer dst.Close()
    if create_err != nil {
      return create_err.Error()
    }

    log.Println("copying the uploaded file to the destination file")
    if _, copy_err := io.Copy(dst, file_s); copy_err != nil {
      return copy_err.Error()
    }

    // Get the language.
    rs, query_err := aConn.Query(`
      SELECT compiler, c_flags, interpreter, i_flags
      FROM Language
      WHERE name = ` + language + `
      LIMIT 1;
    `)
    if query_err != nil {
      log.Fatal(query_err)
    }
    defer rs.Close()

    // Get the next (only) row.
    rs.Next()

    // Set up the variables.
    var compiler string
    var c_flags string
    var interpreter string
    var i_flags string

    // Scan the row and plop them in the variables.
    rs.Scan(&compiler, &c_flags, &interpreter, &i_flags)

    // Run the file.
    c_err := 0
    i_err := 0
    // Find if it needs a compiler or not.
    if compiler != "" {
      cmd := exec.Command(compiler, c_flags, filepath)
      cmd.Stdin = os.Stdin
      cmd.Stdout = os.Stdout
      cmd.Stderr = os.Stderr
      c_err := cmd.Run()

      // Capture err and do things with it.
      fmt.Println(err)
    }

    // Run the interpreter.
    // TODO: Find the file path of the output.
    // cmd := exec.Command(interpreter, i_flags, output)
    // cmd.Stdin = os.Stdin
    // cmd.Stdout = os.Stdout
    // cmd.Stderr = os.Stderr
    // i_err := cmd.Run()

    // Get the problem.
    rs, query_err = aConn.Query(`
      SELECT question, answer
      FROM Problem
      WHERE problem_id = ` + problem_id + `
      LIMIT 1;
    `)
    if query_err != nil {
      log.Fatal(query_err)
    }
    defer rs.Close()

    // Get the next (only) row.
    rs.Next()

    // Set up the variables.
    var question string
    var answer string

    // Scan the row and plop them in the variables.
    rs.Scan(&question, &answer)

    // Diff the output of the files.
    diff := false
    if c_err == 0 && i_err == 0 {
      diff = answer == output
    }

    // Decide whether or not to auto judge.
    auto_judge := true

    if diff {
      // The diff of the answer and the submission returned 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged)
        VALUES(` + team_id + `, ` + problem_id + `, 1);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      return problem_id, true, "Auto-judged"
    } else if c_err != 0 {
      // Compiler returned non 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged, correct)
        VALUES(` + team_id + `, ` + problem_id + `, 1, 1);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      return problem_id, true, "Auto-judged"
    } else if c_err == 0 && i_err != 0 {
      // Compiler returned 0, interpreter returned non 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged)
        VALUES(` + team_id + `, ` + problem_id + `, 0);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      return problem_id, false, "Being judged"
    } else {
      panic("uh oh");
    }
  })

  /* Judge: Get submissions ***************************************************/
  m.Get("/api/getSubmissions", func(r render.Render) string {
    aConn, err := sql.Open("sqlite3", "ocdns.db")

    // Set up the arguments.
    aTime := time.Now()
    const aLayout = "Jan 2, 2006 at 3:04pm (MST)"
    //aArgs := sql.NamedArgs{"$time": aTime.Format(aLayout)}

    // Query the database.
    // aConn.Exec("SELECT * FROM submissions WHERE submitted >= $time", aArgs)
    rs, aErr := aConn.Query("SELECT * FROM `Submissions` WHERE `Submissions`.`timestamp` >= " + aTime.Format(aLayout))
    if aErr != nil {
      log.Fatal(err)
    }
    defer rs.Close()

    // Return the results in a json object
    var aRet [][6]string
    var i int
    i = 0
    for rs.Next() {
      var submission_id int
      var team_id int
      var problem_id int
      var judge_id int
      var judged int
      var submitTime string

      rs.Scan(&submission_id, &team_id, &problem_id, &judge_id, &judged, &submitTime)

      aRet[i][0] = strconv.Itoa(submission_id)
      aRet[i][1] = strconv.Itoa(team_id)
      aRet[i][2] = strconv.Itoa(problem_id)
      aRet[i][3] = strconv.Itoa(judge_id)
      aRet[i][4] = strconv.Itoa(judged)
      aRet[i][5] = aLayout

      i++
    }

    // Conver the array into json.
    aJson, _ := json.Marshal(aRet)

    // Return the json generated.
    return string(aJson)
  })

  m.Run()
}
<commit_msg>Fixed: Broken method for players submitting code.<commit_after>package main

import (
  "crypto/sha1"
  "database/sql"
  "encoding/base64"
  "encoding/json"
  "fmt"
  "github.com/go-martini/martini"
  "github.com/martini-contrib/binding"
  "github.com/martini-contrib/render"
  "github.com/martini-contrib/sessions"
  "io"
  "log"
  "mime/multipart"
  "os"
  "os/exec"
  "strconv"
  "time"
  _ "github.com/mattn/go-sqlite3"
)

/* Structs ********************************************************************/
type FileUpload struct {
  ProblemNum  int                   `form:"problemNum"  binding:"required"`
  Language    int                   `form:"language"    binding:"required"`
  File        *multipart.FileHeader `form:"file"        binding:"required"`
}

type UploadResponse struct {
  ProblemId string `json:"problem_id"`
  IsJudged bool `json:"is_judged"`
  JudgeMessage string `json:"message"`
  Correct bool `json:"correct"`
}

/******************************************************************************/
func resetDb() {
  // Remove the old database.
  fmt.Println("ii Removing the old database.")
  os.Remove("./db.db")

  // Re-create the database.
  fmt.Println("ii Re-creating the database.")
  cmd := exec.Command("/usr/bin/sqlite3", "ocdns.db", "<", "db.sql")
  cmd.Stdin = os.Stdin
  cmd.Stdout = os.Stdout
  cmd.Stderr = os.Stderr
  err := cmd.Run()

  // Check the output.
  if err != nil {
    fmt.Println("-- Failed to re-create the database.")
    //fmt.Println("Output: " + err)
    os.Exit(1)
  }

  fmt.Println("ii Successfully created the new file.")
}

/******************************************************************************/
func genAdmin() bool {
  // Create a hasher and generate a password.
  hasher := sha1.New()
  now := fmt.Sprint(time.Now())
  hasher.Write([]byte(now))
  sha := base64.URLEncoding.EncodeToString(hasher.Sum(nil))

  // Report the password to the user.
  fmt.Println("!! Password for the admin account is: " + sha)

  // Insert the password into the database.
  aConn, _ := sql.Open("sqlite3", "ocdns.db")
  defer aConn.Close()
  rs, aErr := aConn.Query(`
    INSERT INTO User
    VALUES(0, "admin", "` + sha + `, "Admin", "Admin", "admin", -1);
  `)
  if aErr != nil {
    log.Fatal(aErr)
    return false
  }
  defer rs.Close()

  return true
}

func getLanguage(language string) (string, string, string, string, string, string) {
  // Open the database.
  aConn, _ := sql.Open("sqlite3", "ocdns.db")
  defer aConn.Close()

  // Get the language.
  rs, query_err := aConn.Query(`
    SELECT compiler, c_flags, c_type, interpreter, i_flags, i_type
    FROM Language
    WHERE name = ` + language + `
    LIMIT 1;
  `)
  if query_err != nil {
    log.Fatal(query_err)
  }
  defer rs.Close()

  // Get the next (only) row.
  rs.Next()

  // Set up the variables.
  var compiler string
  var c_flags string
  var c_type string
  var interpreter string
  var i_flags string
  var i_type string

  // Scan the row and plop them in the variables.
  rs.Scan(&compiler, &c_flags, &c_type, &interpreter, &i_flags, &i_type)

  return compiler, c_flags, c_type, interpreter, i_flags, i_type
}

/******************************************************************************/
func main() {
  // Reset the database.
  //resetDb()

  // Create the default admin account.
  gen := genAdmin()
  if !gen {
    log.Print("-- Admin account not created.")
  }

  // TODO: Use config file?

  // Get the Martini instance.
  m := martini.Classic()

  // Create session store.
  now := fmt.Sprint(time.Now())
  store := sessions.NewCookieStore([]byte(now))
  m.Use(sessions.Sessions("ocdns", store))

  // Set a layout.
  m.Use(render.Renderer(render.Options{
    Layout: "layout",
  }))

  /* Index route **************************************************************/
  m.Get("/", func(r render.Render, session sessions.Session) {
    // TODO: Perform checks to see if the user is logged in. If they are, then
    // render a specific page based on their role.
    role := session.Get("role")

    if role == "admin" {
      r.HTML(302, "admin", "")
    } else if role == "judge" {
      r.HTML(302, "judge", "")
    } else if role == "player" {
      r.HTML(302, "player", "")
    } else {
      r.HTML(200, "index", "")
    }
  })

  /* Judge route **************************************************************/
  m.Get("/judge", func(r render.Render, session sessions.Session) {
    //role := session.Get("role")

    //if role == "judge" {
    r.HTML(200, "judge", "test")
    //} else {
    //  r.HTML(302, "index", "test")
    //}
  })

  /* Admin route **************************************************************/
  m.Get("/admin", func(r render.Render, session sessions.Session) {
    //role := session.Get("role")

    //if role == "admin" {
    r.HTML(200, "admin", "test")
    //} else {
    //  r.HTML(302, "index", "test")
    //}
  })

  /* Player route *************************************************************/
  m.Get("/player", func(r render.Render, session sessions.Session) {
    role := ""//session.Get("role")

    if role == "player" || true {
      aConn, err := sql.Open("sqlite3", "ocdns.db")
      defer aConn.Close()

      // Query the database.
      rs, aErr := aConn.Query("SELECT problem_id, name, question FROM `Problems`;")
      if aErr != nil {
        log.Fatal(err)
      }
      defer rs.Close()

      // Return the results in a json object
      var questions = make(map[string]map[string]string)
      var tmp = make(map[string]string)
      for rs.Next() {
        var problem_id int
        var name string
        var question string

        rs.Scan(&problem_id, &name, &question)

        tmp = make(map[string]string)
        tmp["name"] = name
        tmp["question"] = question
        questions[strconv.Itoa(problem_id)] = tmp
      }

      // Query the database.
      rs, aErr = aConn.Query("SELECT language_id, name FROM `Language`;")
      if aErr != nil {
        log.Fatal(err)
      }
      defer rs.Close()

      // Return the results in a json object
      var languages = make(map[string]map[string]string)
      for rs.Next() {
        var language_id int
        var name string

        rs.Scan(&language_id, &name)

        tmp = make(map[string]string)
        tmp["name"] = name
        languages[strconv.Itoa(language_id)] = tmp
      }

      // Create a map to return.
      var aRet = make(map[string]map[string]map[string]string)

      aRet["questions"] = questions
      aRet["languages"] = languages

      // Conver the array into json.
      aJson, _ := json.Marshal(aRet)

      r.HTML(200, "player", string(aJson))
    } else {
     r.HTML(302, "index", nil)
    }
  })

  /* Player: Submit code ******************************************************/
  m.Post("/api/submitCode", binding.MultipartForm(FileUpload{}), func(uf FileUpload) string {
    // Get the team id.
    team_id := string(0)//string(session.Get("team_id"))

    // if team_id == nil {
    //  return
    // }

    // Open the database.
    aConn, _ := sql.Open("sqlite3", "ocdns.db")
    defer aConn.Close()

    // Get form stuff.
    problem_id := string(uf.ProblemNum)
    language := string(uf.Language)
    file, err := uf.File.Open()
    if err != nil {
      return err.Error()
    }
    defer file.Close()

    // Create file path, without extension.
    filepath := "./submissions/" + team_id + "/" + problem_id

    // Get the language.
    compiler, c_flags, c_type, interpreter, i_flags, i_type := getLanguage(language)

    // Save the file.
    dst, create_err := os.Create(filepath + "." + c_type)
    defer dst.Close()
    if create_err != nil {
      return create_err.Error()
    }

    // Copy the file into the destination.
    if _, copy_err := io.Copy(dst, file); copy_err != nil {
      return copy_err.Error()
    }

    // Run the file.
    // var c_out []byte
    var c_err error
    var i_out []byte
    var i_err error

    // Find if it needs a compiler or not.
    if compiler != "" {
      _, c_err = exec.Command(compiler, c_flags, filepath + "." + c_type).Output()
    }

    // Run the interpreter.
    i_out, i_err = exec.Command(interpreter, i_flags, filepath + "." + i_type).Output()

    // Get the problem.
    rs, query_err := aConn.Query(`
      SELECT question, answer
      FROM Problem
      WHERE problem_id = ` + problem_id + `
      LIMIT 1;
    `)
    if query_err != nil {
      log.Fatal(query_err)
    }
    defer rs.Close()

    // Get the next (only) row.
    rs.Next()

    // Set up the variables.
    var question string
    var answer string

    // Scan the row and plop them in the variables.
    rs.Scan(&question, &answer)

    // Diff the output of the files.
    diff := false
    if c_err == nil && i_err == nil {
      diff = answer == string(i_out)
    }

    // Declare the struct to return json.
    ret := UploadResponse{}
    var j []byte

    if diff {
      // The diff of the answer and the submission returned 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged)
        VALUES(` + team_id + `, ` + problem_id + `, 1);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      // Put the items in the struct declared above.
      ret.ProblemId = problem_id
      ret.IsJudged = true
      ret.JudgeMessage = "Auto-Judged"
      ret.Correct = true

      // Marshal the JSON.
      j, _ = json.Marshal(ret)

      // Return the JSON as a string.
      return string(j)
    } else if c_err != nil {
      // Compiler returned non 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged, correct)
        VALUES(` + team_id + `, ` + problem_id + `, 1, 1);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      // Put the items in the struct declared above.
      ret.ProblemId = problem_id
      ret.IsJudged = true
      ret.JudgeMessage = "Auto-Judged"
      ret.Correct = false

      // Marshal the JSON.
      j, _ = json.Marshal(ret)

      // Return the JSON as a string.
      return string(j)
    } else if c_err == nil && i_err != nil {
      // Compiler returned 0, interpreter returned non 0.
      rs, query_err = aConn.Query(`
        INSERT INTO Submission(team_id, problem_id, judged)
        VALUES(` + team_id + `, ` + problem_id + `, 0);
      `)
      if query_err != nil {
        log.Fatal(query_err)
      }
      defer rs.Close()

      // Put the items in the struct declared above.
      ret.ProblemId = problem_id
      ret.IsJudged = false
      ret.JudgeMessage = "Being judged currently. Expect a response soon."
      ret.Correct = false

      // Marshal the JSON.
      j, _ = json.Marshal(ret)

      // Return the JSON as a string.
      return string(j)
    } else {
      panic("uh oh");
    }
  })

  /* Judge: Get submissions ***************************************************/
  m.Get("/api/getSubmissions", func(r render.Render) string {
    aConn, err := sql.Open("sqlite3", "ocdns.db")

    // Set up the arguments.
    aTime := time.Now()
    const aLayout = "Jan 2, 2006 at 3:04pm (MST)"
    //aArgs := sql.NamedArgs{"$time": aTime.Format(aLayout)}

    // Query the database.
    // aConn.Exec("SELECT * FROM submissions WHERE submitted >= $time", aArgs)
    rs, aErr := aConn.Query("SELECT * FROM `Submissions` WHERE `Submissions`.`timestamp` >= " + aTime.Format(aLayout))
    if aErr != nil {
      log.Fatal(err)
    }
    defer rs.Close()

    // Return the results in a json object
    var aRet [][6]string
    var i int
    i = 0
    for rs.Next() {
      var submission_id int
      var team_id int
      var problem_id int
      var judge_id int
      var judged int
      var submitTime string

      rs.Scan(&submission_id, &team_id, &problem_id, &judge_id, &judged, &submitTime)

      aRet[i][0] = strconv.Itoa(submission_id)
      aRet[i][1] = strconv.Itoa(team_id)
      aRet[i][2] = strconv.Itoa(problem_id)
      aRet[i][3] = strconv.Itoa(judge_id)
      aRet[i][4] = strconv.Itoa(judged)
      aRet[i][5] = aLayout

      i++
    }

    // Conver the array into json.
    aJson, _ := json.Marshal(aRet)

    // Return the json generated.
    return string(aJson)
  })

  m.Run()
}
<|endoftext|>


<commit_before>package main

// see https://blog.golang.org/generate
//go:generate go run mime/generate.go
//go:generate go fmt mime/mime.go

import (
	"fmt"
	"os"

	"github.com/buildkite/agent/v3/agent"
	"github.com/buildkite/agent/v3/clicommand"
	"github.com/urfave/cli"
)

var AppHelpTemplate = `Usage:

  {{.Name}} <command> [options...]

Available commands are:

  {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  {{end}}
Use "{{.Name}} <command> --help" for more information about a command.

`

var SubcommandHelpTemplate = `Usage:

  {{.Name}} {{if .VisibleFlags}}<command>{{end}} [options...]

Available commands are:

   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
   {{end}}{{if .VisibleFlags}}
Options:

   {{range .VisibleFlags}}{{.}}
   {{end}}{{end}}
`

var CommandHelpTemplate = `{{.Description}}

Options:

   {{range .VisibleFlags}}{{.}}
   {{end}}
`

func printVersion(c *cli.Context) {
	fmt.Printf("%v version %v, build %v\n", c.App.Name, c.App.Version, agent.BuildVersion())
}

func main() {
	cli.AppHelpTemplate = AppHelpTemplate
	cli.CommandHelpTemplate = CommandHelpTemplate
	cli.SubcommandHelpTemplate = SubcommandHelpTemplate
	cli.VersionPrinter = printVersion

	app := cli.NewApp()
	app.Name = "buildkite-agent"
	app.Version = agent.Version()
	app.Commands = []cli.Command{
		clicommand.AgentStartCommand,
		clicommand.AnnotateCommand,
		{
			Name:  "annotation",
			Usage: "Make changes an annotation on the currently running build",
			Subcommands: []cli.Command{
				clicommand.AnnotationRemoveCommand,
			},
		},
		{
			Name:  "artifact",
			Usage: "Upload/download artifacts from Buildkite jobs",
			Subcommands: []cli.Command{
				clicommand.ArtifactUploadCommand,
				clicommand.ArtifactDownloadCommand,
				clicommand.ArtifactSearchCommand,
				clicommand.ArtifactShasumCommand,
			},
		},
		{
			Name:  "meta-data",
			Usage: "Get/set data from Buildkite jobs",
			Subcommands: []cli.Command{
				clicommand.MetaDataSetCommand,
				clicommand.MetaDataGetCommand,
				clicommand.MetaDataExistsCommand,
				clicommand.MetaDataKeysCommand,
			},
		},
		{
			Name:  "oidc",
			Usage: "Interact with Buildkite OpenID Connect (OIDC)",
			Subcommands: []cli.Command{
				clicommand.OIDCRequestTokenCommand,
			},
		},
		{
			Name:  "pipeline",
			Usage: "Make changes to the pipeline of the currently running build",
			Subcommands: []cli.Command{
				clicommand.PipelineUploadCommand,
			},
		},
		{
			Name:  "step",
			Usage: "Get or update an attribute of a build step",
			Subcommands: []cli.Command{
				clicommand.StepGetCommand,
				clicommand.StepUpdateCommand,
			},
		},
		clicommand.EnvCommand,
		clicommand.BootstrapCommand,
	}

	// When no sub command is used
	app.Action = func(c *cli.Context) {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}

	// When a sub command can't be found
	app.CommandNotFound = func(c *cli.Context, command string) {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}

	if err := app.Run(os.Args); err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
}
<commit_msg>Set ErrWriter<commit_after>package main

// see https://blog.golang.org/generate
//go:generate go run mime/generate.go
//go:generate go fmt mime/mime.go

import (
	"fmt"
	"os"

	"github.com/buildkite/agent/v3/agent"
	"github.com/buildkite/agent/v3/clicommand"
	"github.com/urfave/cli"
)

var AppHelpTemplate = `Usage:

  {{.Name}} <command> [options...]

Available commands are:

  {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
  {{end}}
Use "{{.Name}} <command> --help" for more information about a command.

`

var SubcommandHelpTemplate = `Usage:

  {{.Name}} {{if .VisibleFlags}}<command>{{end}} [options...]

Available commands are:

   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
   {{end}}{{if .VisibleFlags}}
Options:

   {{range .VisibleFlags}}{{.}}
   {{end}}{{end}}
`

var CommandHelpTemplate = `{{.Description}}

Options:

   {{range .VisibleFlags}}{{.}}
   {{end}}
`

func printVersion(c *cli.Context) {
	fmt.Printf("%v version %v, build %v\n", c.App.Name, c.App.Version, agent.BuildVersion())
}

func main() {
	cli.AppHelpTemplate = AppHelpTemplate
	cli.CommandHelpTemplate = CommandHelpTemplate
	cli.SubcommandHelpTemplate = SubcommandHelpTemplate
	cli.VersionPrinter = printVersion

	app := cli.NewApp()
	app.Name = "buildkite-agent"
	app.Version = agent.Version()
	app.Commands = []cli.Command{
		clicommand.AgentStartCommand,
		clicommand.AnnotateCommand,
		{
			Name:  "annotation",
			Usage: "Make changes an annotation on the currently running build",
			Subcommands: []cli.Command{
				clicommand.AnnotationRemoveCommand,
			},
		},
		{
			Name:  "artifact",
			Usage: "Upload/download artifacts from Buildkite jobs",
			Subcommands: []cli.Command{
				clicommand.ArtifactUploadCommand,
				clicommand.ArtifactDownloadCommand,
				clicommand.ArtifactSearchCommand,
				clicommand.ArtifactShasumCommand,
			},
		},
		{
			Name:  "meta-data",
			Usage: "Get/set data from Buildkite jobs",
			Subcommands: []cli.Command{
				clicommand.MetaDataSetCommand,
				clicommand.MetaDataGetCommand,
				clicommand.MetaDataExistsCommand,
				clicommand.MetaDataKeysCommand,
			},
		},
		{
			Name:  "oidc",
			Usage: "Interact with Buildkite OpenID Connect (OIDC)",
			Subcommands: []cli.Command{
				clicommand.OIDCRequestTokenCommand,
			},
		},
		{
			Name:  "pipeline",
			Usage: "Make changes to the pipeline of the currently running build",
			Subcommands: []cli.Command{
				clicommand.PipelineUploadCommand,
			},
		},
		{
			Name:  "step",
			Usage: "Get or update an attribute of a build step",
			Subcommands: []cli.Command{
				clicommand.StepGetCommand,
				clicommand.StepUpdateCommand,
			},
		},
		clicommand.EnvCommand,
		clicommand.BootstrapCommand,
	}

	app.ErrWriter = os.Stderr

	// When no sub command is used
	app.Action = func(c *cli.Context) {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}

	// When a sub command can't be found
	app.CommandNotFound = func(c *cli.Context, command string) {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}

	if err := app.Run(os.Args); err != nil {
		fmt.Printf("%v\n", err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
)

func main() {
	contents, err := ioutil.ReadFile("vendor.json")
	if err != nil {
		fmt.Println("failed to read vendor.json", err)
		os.Exit(1)
	}
	var data map[string]interface{}

	if err := json.Unmarshal(contents, &data); err != nil {
		fmt.Println("Invalid vendor.json", err)
		os.Exit(1)
	}
	os.Mkdir(".vendor", 0700)
	for name, config := range data {
		if err := vendor(name, config.(map[string]interface{})); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
	os.Exit(0)
}

func vendor(name string, config map[string]interface{}) error {
	url, ok := config["url"].(string)
	if ok == false {
		return fmt.Errorf("%s missing url field", name)
	}
	root, err := os.Getwd()
	if err != nil {
		return err
	}
	root += "/.vendor/"
	path := root + name
	if exists(path) == false {
		fmt.Println("cloning", url)
		if err := gitRun(root, "clone", url, name); err != nil {
			return err
		}
	}
	revision, ok := config["revision"].(string)
	if ok == false {
		revision = "master"
	}
	fmt.Println("fetching", name)
	return gitReset(path, revision, true)
}

func gitReset(path, revision string, first bool) error {
	if first == false {
		if err := gitRun(path, "fetch", "--all"); err != nil {
			return err
		}
	}
	if err := gitRun(path, "reset", "--hard", revision); err != nil {
		if first {
			return gitReset(path, revision, false)
		}
		return err
	}
	return nil
}

func gitRun(dir string, args ...string) error {
	var out bytes.Buffer
	cmd := exec.Command("git", args...)
	cmd.Dir = dir
	cmd.Stderr = &out
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running git %s:\n  %s", strings.Join(args, " "), out.String())
	}
	return nil
}

func exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}
<commit_msg>remove unused dependencies<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"strings"
)

func main() {
	contents, err := ioutil.ReadFile("vendor.json")
	if err != nil {
		fmt.Println("failed to read vendor.json", err)
		os.Exit(1)
	}
	var data map[string]interface{}

	if err := json.Unmarshal(contents, &data); err != nil {
		fmt.Println("Invalid vendor.json", err)
		os.Exit(1)
	}
	os.Mkdir(".vendor", 0700)
	for name, config := range data {
		if err := vendor(name, config.(map[string]interface{})); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}
	files, _  := ioutil.ReadDir(".vendor")
	for _, file := range files {
		if file.IsDir() {
			if _, valid := data[file.Name()]; valid == false {
				fmt.Println("removing", file.Name())
				os.RemoveAll(".vendor/" + file.Name())
			}
		}
	}
	os.Exit(0)
}

func vendor(name string, config map[string]interface{}) error {
	url, ok := config["url"].(string)
	if ok == false {
		return fmt.Errorf("%s missing url field", name)
	}
	root, err := os.Getwd()
	if err != nil {
		return err
	}
	root += "/.vendor/"
	path := root + name
	if exists(path) == false {
		fmt.Println("cloning", url)
		if err := gitRun(root, "clone", url, name); err != nil {
			return err
		}
	}
	revision, ok := config["revision"].(string)
	if ok == false {
		revision = "master"
	}
	fmt.Println("fetching", name)
	return gitReset(path, revision, true)
}

func gitReset(path, revision string, first bool) error {
	if first == false {
		if err := gitRun(path, "fetch", "--all"); err != nil {
			return err
		}
	}
	if err := gitRun(path, "reset", "--hard", revision); err != nil {
		if first {
			return gitReset(path, revision, false)
		}
		return err
	}
	return nil
}

func gitRun(dir string, args ...string) error {
	var out bytes.Buffer
	cmd := exec.Command("git", args...)
	cmd.Dir = dir
	cmd.Stderr = &out
	if err := cmd.Run(); err != nil {
		return fmt.Errorf("error running git %s:\n  %s", strings.Join(args, " "), out.String())
	}
	return nil
}

func exists(path string) bool {
	_, err := os.Stat(path)
	if err == nil {
		return true
	}
	if os.IsNotExist(err) {
		return false
	}
	return false
}
<|endoftext|>


<commit_before>package main

import (
	"html/template"
	"io/ioutil"
	"regexp"
	"log"
	"sync"
	"encoding/json"

	"net/http"

	"flag"
	//"github.com/FogCreek/mini"

	"github.com/JackKnifed/blackfriday"
	//"github.com/russross/blackfriday"
)

type WikiPage struct {
	Title string
	//Body  stringo
	Body template.HTML
}

var templates = template.Must(template.ParseFiles("wiki.html"))

var validWiki = regexp.MustCompile("^/([a-zA-Z0-9_ ]+)$")

var	configFile = flag.String("config", "", "specify a configuration file")

//var validFiles = regexp.MustCompile("^/raw/([a-zA-Z0-9]+)\\.(jpg|gif|jpeg|md|png)$")

//var validSupport = regexp.MustCompile("^/global/([a-zA-Z0-9]+)\\.(css|js)$")

func markdownHandler(responsePipe http.ResponseWriter, request *http.Request) {
	validRequest := validWiki.FindStringSubmatch(request.URL.Path)
	config := GetConfig()
	if validRequest == nil {
		http.Error(responsePipe, "Request not allowed", 403)
	}
	contents, err := loadFile(config.mainserver.prefix + validRequest[1] + ".md")
	if err != nil {
		http.Error(responsePipe, err.Error(), 500)
	}
	// parse any markdown in the input
	body := template.HTML(blackfriday.MarkdownCommon(contents))

	response := WikiPage{Title: validRequest[1], Body: body}
	err = templates.ExecuteTemplate(responsePipe, "wiki.html", response)
	if err != nil {
		http.Error(responsePipe, err.Error(), http.StatusInternalServerError)
	}
}

/*
func contentHandler(responsePipe http.ResponseWriter, request *http.Request) {
	validRequest := validFiles.FindStringSubmatch(request.URL.Path)
	if validRequest == nil {
		http.Error(responsePipe, "Request not allowed", 403)
	}
	strippedRequest := http.StripPrefix("/raw/", validRequest[0])
	http.ServeFile(responsePipe, request, strippedRequest)
	http.FileServer()
	contents, err := loadFile(validRequest)
	if err != nil {
		http.Error(responsePipe, err, 500)
	}
	response := contents
	err := templates.ExecuteTemplate(responsePipe, "markdown.html", p)
	if err != nil {
		http.Error(responsePipe, err.Error(), http.StatusInternalServerError)
	}

}
*/

func loadFile(filename string) ([]byte, error) {
	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return contents, nil
}

func main() {
	flag.Parse()

	LoadConfig(*configFile)

	config := GetConfig()

	rawFiles := http.FileServer(http.Dir(config.mainserver.path))
	siteFiles := http.FileServer(http.Dir(config.mainserver.path))

	http.Handle("/raw/", http.StripPrefix("/raw/", rawFiles))
	http.Handle("/site/", http.StripPrefix("/site/", siteFiles))
	http.HandleFunc("/", markdownHandler)

	log.Println(http.ListenAndServe(":"+config.global.port, nil))

<commit_msg>changed references for calls to add the package name<commit_after>package main

import (
	"html/template"
	"io/ioutil"
	"regexp"
	"log"

	"net/http"

	"flag"
	//"github.com/FogCreek/mini"

	"github.com/JackKnifed/gnosis"
	"github.com/JackKnifed/blackfriday"
	//"github.com/russross/blackfriday"
)

type WikiPage struct {
	Title string
	//Body  stringo
	Body template.HTML
}

var templates = template.Must(template.ParseFiles("wiki.html"))

var validWiki = regexp.MustCompile("^/([a-zA-Z0-9_ ]+)$")

var	configFile = flag.String("config", "", "specify a configuration file")

//var validFiles = regexp.MustCompile("^/raw/([a-zA-Z0-9]+)\\.(jpg|gif|jpeg|md|png)$")

//var validSupport = regexp.MustCompile("^/global/([a-zA-Z0-9]+)\\.(css|js)$")

func markdownHandler(responsePipe http.ResponseWriter, request *http.Request) {
	validRequest := validWiki.FindStringSubmatch(request.URL.Path)
	config := gnosis.GetConfig()
	if validRequest == nil {
		http.Error(responsePipe, "Request not allowed", 403)
	}
	contents, err := ioutil.ReadFile(config.mainserver.prefix + validRequest[1] + ".md")
	if err != nil {
		http.Error(responsePipe, err.Error(), 500)
	}
	// parse any markdown in the input
	body := template.HTML(blackfriday.MarkdownCommon(contents))

	response := WikiPage{Title: validRequest[1], Body: body}
	err = templates.ExecuteTemplate(responsePipe, "wiki.html", response)
	if err != nil {
		http.Error(responsePipe, err.Error(), http.StatusInternalServerError)
	}
}

/*
func contentHandler(responsePipe http.ResponseWriter, request *http.Request) {
	validRequest := validFiles.FindStringSubmatch(request.URL.Path)
	if validRequest == nil {
		http.Error(responsePipe, "Request not allowed", 403)
	}
	strippedRequest := http.StripPrefix("/raw/", validRequest[0])
	http.ServeFile(responsePipe, request, strippedRequest)
	http.FileServer()
	contents, err := loadFile(validRequest)
	if err != nil {
		http.Error(responsePipe, err, 500)
	}
	response := contents
	err := templates.ExecuteTemplate(responsePipe, "markdown.html", p)
	if err != nil {
		http.Error(responsePipe, err.Error(), http.StatusInternalServerError)
	}

}
*/

/*
func loadFile(filename string) ([]byte, error) {
	contents, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}
	return contents, nil
}
*/

func main() {
	flag.Parse()

	gnosis.LoadConfig(*configFile)

	config := gnosis.GetConfig()

	rawFiles := http.FileServer(http.Dir(config.mainserver.path))
	siteFiles := http.FileServer(http.Dir(config.mainserver.path))

	http.Handle("/raw/", http.StripPrefix("/raw/", rawFiles))
	http.Handle("/site/", http.StripPrefix("/site/", siteFiles))
	http.HandleFunc("/", markdownHandler)

	log.Println(http.ListenAndServe(":"+config.global.port, nil))

<|endoftext|>


<commit_before>package main

import (
	"bitbucket.org/kardianos/osext"
	"bufio"
	"fmt"
	"github.com/codegangsta/cli"
	"github.com/fgrehm/devstep-cli/devstep"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var (
	project devstep.Project
	client  devstep.DockerClient
)

var commands = []cli.Command{
	hackCmd,
	buildCmd,
	bootstrapCmd,
	infoCmd,
	runCmd,
	binstubsCmd,
	cleanCmd,
	pristineCmd,
}

func main() {
	app := cli.NewApp()
	app.Name = "devstep"
	app.Author = "Fábio Rehm"
	app.Email = "fgrehm@gmail.com"
	app.Usage = "development environments made easy"
	app.Version = "0.1.0"
	app.EnableBashCompletion = true
	app.Flags = []cli.Flag{
		cli.StringFlag{Name: "log-level, l", Usage: "log level", EnvVar: "DEVSTEP_LOG"},
	}
	app.Before = func(c *cli.Context) error {
		return devstep.SetLogLevel(c.GlobalString("log-level"))
	}
	app.Commands = commands

	app.RunAndExitOnError()
}

var dockerRunFlags = []cli.Flag{
	cli.StringSliceFlag{Name: "p, publish", Value: &cli.StringSlice{}, Usage: "Publish a container's port to the host (hostPort:containerPort)"},
	cli.StringSliceFlag{Name: "link", Value: &cli.StringSlice{}, Usage: "Add link to another container (name:alias)"},
	cli.StringSliceFlag{Name: "e, env", Value: &cli.StringSlice{}, Usage: "Set environment variables"},
}

func loadConfig() *devstep.ProjectConfig {
	projectRoot, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	homeDir := os.Getenv("HOME")
	client = devstep.NewClient("unix:///var/run/docker.sock")
	loader := devstep.NewConfigLoader(client, homeDir, projectRoot)

	config, err := loader.Load()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	pluginsToLoad, err := filepath.Glob(homeDir + "/devstep/plugins/*/plugin.js")
	if err != nil {
		fmt.Printf("Error searching for plugins under '%s'\n%s\n", homeDir, err.Error())
		os.Exit(1)
	}

	if len(pluginsToLoad) > 0 {
		runtime := devstep.NewPluginRuntime(config)
		for _, pluginPath := range pluginsToLoad {
			runtime.Load(pluginPath)
		}
		runtime.Trigger("configLoaded")
	}

	if devstep.LogLevel != "" {
		config.Defaults.Env["DEVSTEP_LOG"] = devstep.LogLevel
	}

	return config
}

func newProject() devstep.Project {
	config := loadConfig()
	project, _ = devstep.NewProject(config)
	return project
}

var buildCmd = cli.Command{
	Name:  "build",
	Usage: "build a docker image for the current project",
	Action: func(c *cli.Context) {
		err := newProject().Build(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var bootstrapCmd = cli.Command{
	Name:  "bootstrap",
	Usage: "bootstrap an environment for the current project",
	Action: func(c *cli.Context) {
		err := newProject().Bootstrap(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var hackCmd = cli.Command{
	Name:  "hack",
	Usage: "start a hacking session for the current project",
	Flags: dockerRunFlags,
	BashComplete: func(c *cli.Context) {
		args := c.Args()
		if len(args) == 0 {
			fmt.Println("-p")
			fmt.Println("--publish")
			fmt.Println("--link")
			fmt.Println("-e")
			fmt.Println("--env")
		}
	},
	Action: func(c *cli.Context) {
		runOpts := parseRunOpts(c)
		err := newProject().Hack(client, runOpts)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var runCmd = cli.Command{
	Name:  "run",
	Usage: "Run a one off command against the current base image",
	Flags: dockerRunFlags,
	Action: func(c *cli.Context) {
		runOpts := parseRunOpts(c)
		runOpts.Cmd = c.Args()

		// Validate command
		if len(runOpts.Cmd) == 0 {
			fmt.Printf("No command provided to `devstep run`\n\n")
			cli.ShowCommandHelp(c, "run")
			os.Exit(1)
		}

		project := newProject()
		commands := project.Config().Commands

		if cmd, ok := commands[runOpts.Cmd[0]]; ok {
			runOpts = cmd.Merge(runOpts)
			runOpts.Cmd = append(cmd.Cmd, runOpts.Cmd[1:]...)
		}

		// Prepend a `--` so that it doesn't interfere with the current init
		// process args
		runOpts.Cmd = append([]string{"--"}, runOpts.Cmd...)

		err := project.Run(client, runOpts)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var binstubsCmd = cli.Command{
	Name:  "binstubs",
	Usage: "Generate binstubs for the commands specified on devstep.yml",
	Action: func(c *cli.Context) {
		project := newProject()
		commands := project.Config().Commands

		if len(commands) == 0 {
			fmt.Println("No binstubs specified!")
			os.Exit(0)
		}

		binstubsPath := ".devstep/bin"
		os.MkdirAll("./"+binstubsPath, 0700)

		executable, _ := osext.Executable()

		for _, cmd := range commands {
			script := []byte("#!/usr/bin/env bash\neval \"" + executable + " run -- " + cmd.Name + " $@\"")
			err := ioutil.WriteFile(binstubsPath+"/"+cmd.Name, script, 0755)
			if err != nil {
				fmt.Printf("Error creating binstub '%s'\n%s\n", binstubsPath+"/"+cmd.Name, err)
				os.Exit(1)
			}
			fmt.Printf("Generated binstub for '%s' in '%s'\n", cmd.Name, binstubsPath)
		}
	},
}

var cleanCmd = cli.Command{
	Name:  "clean",
	Usage: "remove previously built images for the current environment",
	Flags: []cli.Flag{
		cli.BoolFlag{Name: "force, f", Usage: "skip confirmation"},
	},
	Action: func(c *cli.Context) {
		if !c.Bool("force") {
			fmt.Print("Are you sure? [N/y] ")

			reader := bufio.NewReader(os.Stdin)
			line, _, err := reader.ReadLine()
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			if strings.ToUpper(string(line)) != "Y" {
				fmt.Println("Aborting")
				os.Exit(1)
			}
		}

		err := newProject().Clean(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var pristineCmd = cli.Command{
	Name:  "pristine",
	Usage: "rebuild project image from scratch",
	Flags: []cli.Flag{
		cli.BoolFlag{Name: "force, f", Usage: "skip clean confirmation"},
	},
	Action: func(c *cli.Context) {
		// TODO: Figure out if this is the right way to invoke other CLI actions
		cleanCmd.Action(c)
		buildCmd.Action(c)
	},
}

var infoCmd = cli.Command{
	Name:  "info",
	Usage: "show information about the current environment",
	Action: func(c *cli.Context) {
		config := loadConfig()
		printConfig(config)
	},
}

func printConfig(config *devstep.ProjectConfig) {
	fmt.Println("==> Project info")
	fmt.Printf("Repository:   %s\n", config.RepositoryName)
	fmt.Printf("Source image: %s\n", config.SourceImage)
	fmt.Printf("Base image:   %s\n", config.BaseImage)
	fmt.Printf("Host dir:     %s\n", config.HostDir)
	fmt.Printf("Guest dir:    %s\n", config.GuestDir)
	fmt.Printf("Cache dir:    %s\n", config.CacheDir)

	if config.Defaults != nil {
		fmt.Println("\n==> Default options:")
		printDockerRunOpts(config.Defaults, "")
	}

	if config.HackOpts != nil {
		fmt.Println("\n==> Hack options:")
		printDockerRunOpts(config.HackOpts, "")
	}
	if config.Commands != nil {
		fmt.Println("\n==> Commands:")
		for _, cmd := range config.Commands {
			fmt.Printf("* %s\n", cmd.Name)
			fmt.Printf("  Cmd:        %v\n", cmd.Cmd)
			fmt.Printf("  Publish:    %v\n", cmd.Publish)
			printDockerRunOpts(&cmd.DockerRunOpts, "  ")
		}
	}
}

func printDockerRunOpts(opts *devstep.DockerRunOpts, prefix string) {
	fmt.Printf("%sPrivileged: %v\n", prefix, opts.Privileged)
	fmt.Printf("%sLinks:      %v\n", prefix, opts.Links)
	fmt.Printf("%sVolumes:    %v\n", prefix, opts.Volumes)
	fmt.Printf("%sEnv:        %v\n", prefix, opts.Env)
}

func parseRunOpts(c *cli.Context) *devstep.DockerRunOpts {
	runOpts := &devstep.DockerRunOpts{
		Publish: c.StringSlice("publish"),
		Links:   c.StringSlice("link"),
		Env:     make(map[string]string),
	}

	// Env vars
	for _, envVar := range c.StringSlice("env") {
		varAndValue := strings.Split(envVar, "=")
		runOpts.Env[varAndValue[0]] = varAndValue[1]
	}

	// Validate ports
	validPort := regexp.MustCompile(`^\d+:\d+$`)
	for _, port := range runOpts.Publish {
		if !validPort.MatchString(port) {
			fmt.Println("Invalid publish arg: " + port)
			os.Exit(1)
		}
	}
	// Validate links
	validLink := regexp.MustCompile(`[^:]+:[^:]+`)
	for _, link := range runOpts.Links {
		if !validLink.MatchString(link) {
			fmt.Println("Invalid link: " + link)
			os.Exit(1)
		}
	}
	return runOpts
}
<commit_msg>Support for -w option<commit_after>package main

import (
	"bitbucket.org/kardianos/osext"
	"bufio"
	"fmt"
	"github.com/codegangsta/cli"
	"github.com/fgrehm/devstep-cli/devstep"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"strings"
)

var (
	project devstep.Project
	client  devstep.DockerClient
)

var commands = []cli.Command{
	hackCmd,
	buildCmd,
	bootstrapCmd,
	infoCmd,
	runCmd,
	binstubsCmd,
	cleanCmd,
	pristineCmd,
}

func main() {
	app := cli.NewApp()
	app.Name = "devstep"
	app.Author = "Fábio Rehm"
	app.Email = "fgrehm@gmail.com"
	app.Usage = "development environments made easy"
	app.Version = "0.1.0"
	app.EnableBashCompletion = true
	app.Flags = []cli.Flag{
		cli.StringFlag{Name: "log-level, l", Usage: "log level", EnvVar: "DEVSTEP_LOG"},
	}
	app.Before = func(c *cli.Context) error {
		return devstep.SetLogLevel(c.GlobalString("log-level"))
	}
	app.Commands = commands

	app.RunAndExitOnError()
}

var dockerRunFlags = []cli.Flag{
	cli.StringFlag{Name: "w, working_dir", Usage: "Working directory inside the container"},
	cli.StringSliceFlag{Name: "p, publish", Value: &cli.StringSlice{}, Usage: "Publish a container's port to the host (hostPort:containerPort)"},
	cli.StringSliceFlag{Name: "link", Value: &cli.StringSlice{}, Usage: "Add link to another container (name:alias)"},
	cli.StringSliceFlag{Name: "e, env", Value: &cli.StringSlice{}, Usage: "Set environment variables"},
}

func loadConfig() *devstep.ProjectConfig {
	projectRoot, err := os.Getwd()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	homeDir := os.Getenv("HOME")
	client = devstep.NewClient("unix:///var/run/docker.sock")
	loader := devstep.NewConfigLoader(client, homeDir, projectRoot)

	config, err := loader.Load()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	pluginsToLoad, err := filepath.Glob(homeDir + "/devstep/plugins/*/plugin.js")
	if err != nil {
		fmt.Printf("Error searching for plugins under '%s'\n%s\n", homeDir, err.Error())
		os.Exit(1)
	}

	if len(pluginsToLoad) > 0 {
		runtime := devstep.NewPluginRuntime(config)
		for _, pluginPath := range pluginsToLoad {
			runtime.Load(pluginPath)
		}
		runtime.Trigger("configLoaded")
	}

	if devstep.LogLevel != "" {
		config.Defaults.Env["DEVSTEP_LOG"] = devstep.LogLevel
	}

	return config
}

func newProject() devstep.Project {
	config := loadConfig()
	project, _ = devstep.NewProject(config)
	return project
}

var buildCmd = cli.Command{
	Name:  "build",
	Usage: "build a docker image for the current project",
	Action: func(c *cli.Context) {
		err := newProject().Build(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var bootstrapCmd = cli.Command{
	Name:  "bootstrap",
	Usage: "bootstrap an environment for the current project",
	Action: func(c *cli.Context) {
		err := newProject().Bootstrap(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var hackCmd = cli.Command{
	Name:  "hack",
	Usage: "start a hacking session for the current project",
	Flags: dockerRunFlags,
	BashComplete: func(c *cli.Context) {
		args := c.Args()
		if len(args) == 0 {
			fmt.Println("-p")
			fmt.Println("--publish")
			fmt.Println("--link")
			fmt.Println("-w")
			fmt.Println("--working_dir")
			fmt.Println("-e")
			fmt.Println("--env")
		}
	},
	Action: func(c *cli.Context) {
		project := newProject()
		runOpts := parseRunOpts(c)
		err := project.Hack(client, runOpts)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var runCmd = cli.Command{
	Name:  "run",
	Usage: "Run a one off command against the current base image",
	Flags: dockerRunFlags,
	Action: func(c *cli.Context) {
		project := newProject()
		commands := project.Config().Commands

		runOpts := parseRunOpts(c)
		runOpts.Cmd = c.Args()

		// Validate command
		if len(runOpts.Cmd) == 0 {
			fmt.Printf("No command provided to `devstep run`\n\n")
			cli.ShowCommandHelp(c, "run")
			os.Exit(1)
		}

		if cmd, ok := commands[runOpts.Cmd[0]]; ok {
			runOpts = cmd.Merge(runOpts)
			runOpts.Cmd = append(cmd.Cmd, runOpts.Cmd[1:]...)
		}

		// Prepend a `--` so that it doesn't interfere with the current init
		// process args
		runOpts.Cmd = append([]string{"--"}, runOpts.Cmd...)

		err := project.Run(client, runOpts)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var binstubsCmd = cli.Command{
	Name:  "binstubs",
	Usage: "Generate binstubs for the commands specified on devstep.yml",
	Action: func(c *cli.Context) {
		project := newProject()
		commands := project.Config().Commands

		if len(commands) == 0 {
			fmt.Println("No binstubs specified!")
			os.Exit(0)
		}

		binstubsPath := ".devstep/bin"
		os.MkdirAll("./"+binstubsPath, 0700)

		executable, _ := osext.Executable()

		for _, cmd := range commands {
			script := []byte("#!/usr/bin/env bash\neval \"" + executable + " run -- " + cmd.Name + " $@\"")
			err := ioutil.WriteFile(binstubsPath+"/"+cmd.Name, script, 0755)
			if err != nil {
				fmt.Printf("Error creating binstub '%s'\n%s\n", binstubsPath+"/"+cmd.Name, err)
				os.Exit(1)
			}
			fmt.Printf("Generated binstub for '%s' in '%s'\n", cmd.Name, binstubsPath)
		}
	},
}

var cleanCmd = cli.Command{
	Name:  "clean",
	Usage: "remove previously built images for the current environment",
	Flags: []cli.Flag{
		cli.BoolFlag{Name: "force, f", Usage: "skip confirmation"},
	},
	Action: func(c *cli.Context) {
		if !c.Bool("force") {
			fmt.Print("Are you sure? [N/y] ")

			reader := bufio.NewReader(os.Stdin)
			line, _, err := reader.ReadLine()
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			if strings.ToUpper(string(line)) != "Y" {
				fmt.Println("Aborting")
				os.Exit(1)
			}
		}

		err := newProject().Clean(client)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	},
}

var pristineCmd = cli.Command{
	Name:  "pristine",
	Usage: "rebuild project image from scratch",
	Flags: []cli.Flag{
		cli.BoolFlag{Name: "force, f", Usage: "skip clean confirmation"},
	},
	Action: func(c *cli.Context) {
		// TODO: Figure out if this is the right way to invoke other CLI actions
		cleanCmd.Action(c)
		buildCmd.Action(c)
	},
}

var infoCmd = cli.Command{
	Name:  "info",
	Usage: "show information about the current environment",
	Action: func(c *cli.Context) {
		config := loadConfig()
		printConfig(config)
	},
}

func printConfig(config *devstep.ProjectConfig) {
	fmt.Println("==> Project info")
	fmt.Printf("Repository:   %s\n", config.RepositoryName)
	fmt.Printf("Source image: %s\n", config.SourceImage)
	fmt.Printf("Base image:   %s\n", config.BaseImage)
	fmt.Printf("Host dir:     %s\n", config.HostDir)
	fmt.Printf("Guest dir:    %s\n", config.GuestDir)
	fmt.Printf("Cache dir:    %s\n", config.CacheDir)

	if config.Defaults != nil {
		fmt.Println("\n==> Default options:")
		printDockerRunOpts(config.Defaults, "")
	}

	if config.HackOpts != nil {
		fmt.Println("\n==> Hack options:")
		printDockerRunOpts(config.HackOpts, "")
	}
	if config.Commands != nil {
		fmt.Println("\n==> Commands:")
		for _, cmd := range config.Commands {
			fmt.Printf("* %s\n", cmd.Name)
			fmt.Printf("  Cmd:        %v\n", cmd.Cmd)
			fmt.Printf("  Publish:    %v\n", cmd.Publish)
			printDockerRunOpts(&cmd.DockerRunOpts, "  ")
		}
	}
}

func printDockerRunOpts(opts *devstep.DockerRunOpts, prefix string) {
	fmt.Printf("%sPrivileged: %v\n", prefix, opts.Privileged)
	fmt.Printf("%sLinks:      %v\n", prefix, opts.Links)
	fmt.Printf("%sVolumes:    %v\n", prefix, opts.Volumes)
	fmt.Printf("%sEnv:        %v\n", prefix, opts.Env)
}

func parseRunOpts(c *cli.Context) *devstep.DockerRunOpts {
	runOpts := &devstep.DockerRunOpts{
		Publish: c.StringSlice("publish"),
		Links:   c.StringSlice("link"),
		Env:     make(map[string]string),
	}

	// Set working dir directly on the project object so that it get passed
	// along properly
	if workingDir := c.String("working_dir"); workingDir != "" {
		project.Config().GuestDir = workingDir
	}

	// Env vars
	for _, envVar := range c.StringSlice("env") {
		varAndValue := strings.Split(envVar, "=")
		runOpts.Env[varAndValue[0]] = varAndValue[1]
	}

	// Validate ports
	validPort := regexp.MustCompile(`^\d+:\d+$`)
	for _, port := range runOpts.Publish {
		if !validPort.MatchString(port) {
			fmt.Println("Invalid publish arg: " + port)
			os.Exit(1)
		}
	}
	// Validate links
	validLink := regexp.MustCompile(`[^:]+:[^:]+`)
	for _, link := range runOpts.Links {
		if !validLink.MatchString(link) {
			fmt.Println("Invalid link: " + link)
			os.Exit(1)
		}
	}
	return runOpts
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/mathcunha/bandeiraenergia/band"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", band.DoRequest)
	probe := band.Probe{}
	probe.Run()
	err := http.ListenAndServe(":8080", nil)
	if err != nil {
		log.Fatal("ListenAndServe: 0.0.0.0:8080 ", err)
	}
}
<commit_msg>make it better<commit_after>package main

import (
	"github.com/mathcunha/bandeiraenergia/band"
	"log"
	"net/http"
)

func main() {
	http.HandleFunc("/", band.DoRequest)
	probe := band.Probe{}
	probe.Run()
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Fatal("ListenAndServe: 0.0.0.0:8080 ", err)
	}
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/line/line-bot-sdk-go/linebot"
)

var bot *linebot.Client

func main() {
	var err error
	bot, err = linebot.New(os.Getenv("ChannelSecret"), os.Getenv("ChannelAccessToken"))
	log.Println("Bot:", bot, " err:", err)
	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	events, err := bot.ParseRequest(r)

	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}

	for _, event := range events {
		if event.Type == linebot.EventTypeMessage {
			switch message := event.Message.(type) {
			case *linebot.TextMessage:
			   if message.Text == "MyID" {
				  if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(  "Line_ID:"+leave.RoomID+" OK!" )).Do(); err != nil {
					log.Print(err)
				   }
			    }
			}
		}
	}
}
<commit_msg>no message<commit_after>// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/line/line-bot-sdk-go/linebot"
)

var bot *linebot.Client

func main() {
	var err error
	bot, err = linebot.New(os.Getenv("ChannelSecret"), os.Getenv("ChannelAccessToken"))
	log.Println("Bot:", bot, " err:", err)
	http.HandleFunc("/callback", callbackHandler)
	port := os.Getenv("PORT")
	addr := fmt.Sprintf(":%s", port)
	http.ListenAndServe(addr, nil)
}

func callbackHandler(w http.ResponseWriter, r *http.Request) {
	events, err := bot.ParseRequest(r)

	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}

	for _, event := range events {
		if event.Type == linebot.EventTypeMessage {
			switch message := event.Message.(type) {
			case *linebot.TextMessage:
			   if message.Text == "MyID" {
				  if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(  "Line_ID:已取得" )).Do(); err != nil {
					log.Print(err)
				   }
			    }
			}
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"time"

	"github.com/andygrunwald/TrendingGithub/flags"
	"github.com/andygrunwald/TrendingGithub/storage"
	"github.com/andygrunwald/TrendingGithub/twitter"
)

const (
	// Version of @TrendingGithub
	Version = "0.2.0"

	tweetTime = 5 * time.Second
	// TODO: Reset
	//tweetTime                = 30 * time.Minute
	configurationRefreshTime = 24 * time.Hour
	followNewPersonTime      = 45 * time.Minute
)

func main() {
	var (
		// Twitter
		twitterConsumerKey       = flags.String("twitter-consumer-key", "TRENDINGGITHUB_TWITTER_CONSUMER_KEY", "", "Twitter-API: Consumer key. Default: empty. Env var: TRENDINGGITHUB_TWITTER_CONSUMER_KEY")
		twitterConsumerSecret    = flags.String("twitter-consumer-secret", "TRENDINGGITHUB_TWITTER_CONSUMER_SECRET", "", "Twitter-API: Consumer secret. Default: empty. Env var: TRENDINGGITHUB_TWITTER_CONSUMER_SECRET")
		twitterAccessToken       = flags.String("twitter-access-token", "TRENDINGGITHUB_TWITTER_ACCESS_TOKEN", "", "Twitter-API: Access token. Default: empty. Env var: TRENDINGGITHUB_TWITTER_ACCESS_TOKEN")
		twitterAccessTokenSecret = flags.String("twitter-access-token-secret", "TRENDINGGITHUB_TWITTER_ACCESS_TOKEN_SECRET", "", "Twitter-API: Access token secret. Default: empty. Env var: TRENDINGGITHUB_TWITTER_ACCESS_TOKEN_SECRET")
		twitterFollowNewPerson   = flags.Bool("twitter-follow-new-person", "TRENDINGGITHUB_TWITTER_FOLLOW_NEW_PERSON", false, "Twitter: Follows a friend of one of our followers. Default: false. Env var: TRENDINGGITHUB_TWITTER_FOLLOW_NEW_PERSON")

		// Redis storage
		storageURL  = flags.String("storage-url", "TRENDINGGITHUB_STORAGE_URL", ":6379", "Storage URL (e.g. 1.2.3.4:6379 or :6379). Default: :6379.  Env var: TRENDINGGITHUB_STORAGE_URL")
		storageAuth = flags.String("storage-auth", "TRENDINGGITHUB_STORAGE_AUTH", "", "Storage Auth (e.g. myPassword or <empty>). Default: empty.  Env var: TRENDINGGITHUB_STORAGE_AUTH")

		showVersion = flags.Bool("version", "TRENDINGGITHUB_VERSION", false, "Outputs the version number and exit. Default: false. Env var: TRENDINGGITHUB_VERSION")
		debugMode   = flags.Bool("debug", "TRENDINGGITHUB_DEBUG", false, "Outputs the tweet instead of tweet it (useful for development). Default: false. Env var: TRENDINGGITHUB_DEBUG")
	)
	flag.Parse()

	// Output the version and exit
	if *showVersion {
		fmt.Printf("@TrendingGithub v%s\n", Version)
		return
	}

	log.Println("Hey, nice to meet you. My name is @TrendingGithub. Lets get ready to tweet some trending content!")
	defer log.Println("Nice sesssion. A lot of knowledge was tweeted. Good work and see you next time!")

	// Prepare the twitter client
	twitterClient := twitter.NewClient(*twitterConsumerKey, *twitterConsumerSecret, *twitterAccessToken, *twitterAccessTokenSecret, *debugMode)

	// When we are running in a debug mode, we are running with a debug configuration.
	// So we don`t need to load the configuration from twitter here.
	if *debugMode == false {
		err := twitterClient.LoadConfiguration()
		if err != nil {
			log.Fatalf("Twitter Configuration initialisation failed: %s", err)
		}
	}

	twitterClient.SetupConfigurationRefresh(configurationRefreshTime)

	// Activate our growth hack feature
	// Checkout the README for details or read the code (suggested).
	if *twitterFollowNewPerson {
		log.Println("Growth hack \"Follow a friend of a friend\" activated")
		twitterClient.SetupFollowNewPeopleScheduling(followNewPersonTime)
	}

	// Request a storage backend
	storageBackend := storage.GetBackend(*storageURL, *storageAuth, *debugMode)
	defer storageBackend.Close()

	// Let the party begin
	StartTweeting(twitterClient, storageBackend)
}
<commit_msg>Set tweettime to 30m and raised version to v0.3.1<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"time"

	"github.com/andygrunwald/TrendingGithub/flags"
	"github.com/andygrunwald/TrendingGithub/storage"
	"github.com/andygrunwald/TrendingGithub/twitter"
)

const (
	// Version of @TrendingGithub
	Version = "0.3.1"

	tweetTime                = 30 * time.Minute
	configurationRefreshTime = 24 * time.Hour
	followNewPersonTime      = 45 * time.Minute
)

func main() {
	var (
		// Twitter
		twitterConsumerKey       = flags.String("twitter-consumer-key", "TRENDINGGITHUB_TWITTER_CONSUMER_KEY", "", "Twitter-API: Consumer key. Default: empty. Env var: TRENDINGGITHUB_TWITTER_CONSUMER_KEY")
		twitterConsumerSecret    = flags.String("twitter-consumer-secret", "TRENDINGGITHUB_TWITTER_CONSUMER_SECRET", "", "Twitter-API: Consumer secret. Default: empty. Env var: TRENDINGGITHUB_TWITTER_CONSUMER_SECRET")
		twitterAccessToken       = flags.String("twitter-access-token", "TRENDINGGITHUB_TWITTER_ACCESS_TOKEN", "", "Twitter-API: Access token. Default: empty. Env var: TRENDINGGITHUB_TWITTER_ACCESS_TOKEN")
		twitterAccessTokenSecret = flags.String("twitter-access-token-secret", "TRENDINGGITHUB_TWITTER_ACCESS_TOKEN_SECRET", "", "Twitter-API: Access token secret. Default: empty. Env var: TRENDINGGITHUB_TWITTER_ACCESS_TOKEN_SECRET")
		twitterFollowNewPerson   = flags.Bool("twitter-follow-new-person", "TRENDINGGITHUB_TWITTER_FOLLOW_NEW_PERSON", false, "Twitter: Follows a friend of one of our followers. Default: false. Env var: TRENDINGGITHUB_TWITTER_FOLLOW_NEW_PERSON")

		// Redis storage
		storageURL  = flags.String("storage-url", "TRENDINGGITHUB_STORAGE_URL", ":6379", "Storage URL (e.g. 1.2.3.4:6379 or :6379). Default: :6379.  Env var: TRENDINGGITHUB_STORAGE_URL")
		storageAuth = flags.String("storage-auth", "TRENDINGGITHUB_STORAGE_AUTH", "", "Storage Auth (e.g. myPassword or <empty>). Default: empty.  Env var: TRENDINGGITHUB_STORAGE_AUTH")

		showVersion = flags.Bool("version", "TRENDINGGITHUB_VERSION", false, "Outputs the version number and exit. Default: false. Env var: TRENDINGGITHUB_VERSION")
		debugMode   = flags.Bool("debug", "TRENDINGGITHUB_DEBUG", false, "Outputs the tweet instead of tweet it (useful for development). Default: false. Env var: TRENDINGGITHUB_DEBUG")
	)
	flag.Parse()

	// Output the version and exit
	if *showVersion {
		fmt.Printf("@TrendingGithub v%s\n", Version)
		return
	}

	log.Println("Hey, nice to meet you. My name is @TrendingGithub. Lets get ready to tweet some trending content!")
	defer log.Println("Nice sesssion. A lot of knowledge was tweeted. Good work and see you next time!")

	// Prepare the twitter client
	twitterClient := twitter.NewClient(*twitterConsumerKey, *twitterConsumerSecret, *twitterAccessToken, *twitterAccessTokenSecret, *debugMode)

	// When we are running in a debug mode, we are running with a debug configuration.
	// So we don`t need to load the configuration from twitter here.
	if *debugMode == false {
		err := twitterClient.LoadConfiguration()
		if err != nil {
			log.Fatalf("Twitter Configuration initialisation failed: %s", err)
		}
	}

	twitterClient.SetupConfigurationRefresh(configurationRefreshTime)

	// Activate our growth hack feature
	// Checkout the README for details or read the code (suggested).
	if *twitterFollowNewPerson {
		log.Println("Growth hack \"Follow a friend of a friend\" activated")
		twitterClient.SetupFollowNewPeopleScheduling(followNewPersonTime)
	}

	// Request a storage backend
	storageBackend := storage.GetBackend(*storageURL, *storageAuth, *debugMode)
	defer storageBackend.Close()

	// Let the party begin
	StartTweeting(twitterClient, storageBackend)
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/ChimeraCoder/anaconda"
	"github.com/rakyll/globalconf"
	"os"
	"time"
)

func main() {

	var (
		consumer_key    = flag.String("consumerkey", "", "the app consumer key")
		consumer_secret = flag.String("consumersecret", "", "the app consumer secret")
		access_token    = flag.String("accesstoken", "", "app access token")
		access_secret   = flag.String("accesstokensecret", "", "app access token secret")
		show_help       = flag.Bool("h", false, "show this dialog")
		graphite        = flag.Bool("graphite", false, "print stats in Graphite format")
	)

	conf, _ := globalconf.New("twanity")
	conf.ParseAll()

	if *show_help {
		flag.PrintDefaults()
		os.Exit(1)
	}

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: twanity  username\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	flag.Parse()

	username := flag.Arg(0)

	if username == "" {
		flag.Usage()
	}

	anaconda.SetConsumerKey(*consumer_key)
	anaconda.SetConsumerSecret(*consumer_secret)
	api := anaconda.NewTwitterApi(*access_token, *access_secret)

	result, err := api.GetUsersShow(username, nil)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to retrieve user details\n")
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}

	if *graphite {
		timestamp := time.Now().Unix()
		fmt.Printf("twanity.%s.following %d %d\n", username, result.FriendsCount, timestamp)
		fmt.Printf("twanity.%s.followers %d %d\n", username, result.FollowersCount, timestamp)
		fmt.Printf("twanity.%s.tweets %d %d\n", username, result.StatusesCount, timestamp)
		fmt.Printf("twanity.%s.favourites %d %d\n", username, result.FavouritesCount, timestamp)

	} else {
		fmt.Printf("Getting twitter stats for %s...\n", username)
		fmt.Printf("Following: %d\n", result.FriendsCount)
		fmt.Printf("Followers: %d\n", result.FollowersCount)
		fmt.Printf("Tweets: %d\n", result.StatusesCount)
		fmt.Printf("Favourites: %d\n", result.FavouritesCount)
	}
}
<commit_msg>add listed count<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/ChimeraCoder/anaconda"
	"github.com/rakyll/globalconf"
	"os"
	"time"
)

func main() {

	var (
		consumer_key    = flag.String("consumerkey", "", "the app consumer key")
		consumer_secret = flag.String("consumersecret", "", "the app consumer secret")
		access_token    = flag.String("accesstoken", "", "app access token")
		access_secret   = flag.String("accesstokensecret", "", "app access token secret")
		show_help       = flag.Bool("h", false, "show this dialog")
		graphite        = flag.Bool("graphite", false, "print stats in Graphite format")
	)

	conf, _ := globalconf.New("twanity")
	conf.ParseAll()

	if *show_help {
		flag.PrintDefaults()
		os.Exit(1)
	}

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "usage: twanity  username\n")
		flag.PrintDefaults()
		os.Exit(1)
	}

	flag.Parse()

	username := flag.Arg(0)

	if username == "" {
		flag.Usage()
	}

	anaconda.SetConsumerKey(*consumer_key)
	anaconda.SetConsumerSecret(*consumer_secret)
	api := anaconda.NewTwitterApi(*access_token, *access_secret)

	result, err := api.GetUsersShow(username, nil)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to retrieve user details\n")
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}

	if *graphite {
		timestamp := time.Now().Unix()
		fmt.Printf("twanity.%s.following %d %d\n", username, result.FriendsCount, timestamp)
		fmt.Printf("twanity.%s.followers %d %d\n", username, result.FollowersCount, timestamp)
		fmt.Printf("twanity.%s.tweets %d %d\n", username, result.StatusesCount, timestamp)
		fmt.Printf("twanity.%s.favourites %d %d\n", username, result.FavouritesCount, timestamp)
		fmt.Printf("twanity.%s.listed %d %d\n", username, result.ListedCount, timestamp)

	} else {
		fmt.Printf("Getting twitter stats for %s...\n", username)
		fmt.Printf("Following: %d\n", result.FriendsCount)
		fmt.Printf("Followers: %d\n", result.FollowersCount)
		fmt.Printf("Tweets: %d\n", result.StatusesCount)
		fmt.Printf("Favourites: %d\n", result.FavouritesCount)
		fmt.Printf("Listed: %d\n", result.ListedCount)
	}
}
<|endoftext|>


<commit_before>package raft

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/arpith/mmapd/db"
	"net/http"
)

type appendEntryRequest struct {
	Term         int
	LeaderID     string
	PrevLogIndex int
	PrevLogTerm  int
	Entry        db.Entry
	LeaderCommit int
}

type appendRequest struct {
	Req        appendEntryRequest
	ReturnChan chan appendEntryResponse
}

type appendEntryResponse struct {
	Term    int
	Success bool
}

type followerResponse struct {
	ServerIndex int
	Resp        appendEntryResponse
}

func (s *server) appendEntry(command string, isCommitted chan bool) {
	entry := &db.Entry{command, s.term}
	index := -1
	if command != "" {
		s.db.Log.AppendEntry(*entry)
		index = len(s.db.Log.Entries)
	}
	respChan := make(chan followerResponse)
	for i := 0; i < len(s.config); i++ {
		if s.config[i] != s.id {
			go s.sendAppendEntryRequest(i, *entry, respChan)
		}
	}
	responseCount := 0
	if len(s.config) > 1 {
		for {
			_ = <-respChan
			responseCount++
			for N := s.commitIndex + 1; N < len(s.db.Log.Entries); N++ {
				//Check if there exists an N > commitIndex
				count := 0
				for i := 0; i < len(s.matchIndex); i++ {
					if s.matchIndex[i] >= N {
						count++
					}
				}
				// Check if a majority of matchIndex[i] >= N
				cond1 := count > len(s.matchIndex)/2
				// Check if log[N].term == currentTerm
				cond2 := s.db.Log.Entries[N].Term == s.term
				if cond1 && cond2 {
					// Set commitIndex to N
					s.commitIndex = N
				} else {
					break
				}
			}
			if s.commitIndex == index {
				isCommitted <- true
			}
		}
	} else {
		if command != "" {
			s.commitIndex++
			isCommitted <- true
		}
	}
}

func (s *server) sendAppendEntryRequest(followerIndex int, entry db.Entry, respChan chan followerResponse) {
	follower := s.config[followerIndex]
	prevLogIndex := len(s.db.Log.Entries) - 1
	prevLogTerm := 0
	if prevLogIndex > 0 {
		prevLogTerm = s.db.Log.Entries[prevLogIndex].Term
	}
	a := &appendEntryRequest{s.term, s.id, prevLogIndex, prevLogTerm, entry, s.commitIndex}
	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(a)
	resp, err := http.Post("http://"+follower+"/append", "application/json", b)
	if err != nil {
		fmt.Println("Couldn't send append entry request to " + follower)
		fmt.Println(err)
		return
		//		go s.sendAppendEntryRequest(followerIndex, entry, respChan)
	} else {
		r := &appendEntryResponse{}
		err := json.NewDecoder(resp.Body).Decode(r)
		if err != nil {
			fmt.Println("Couldn't decode append entries response from " + s.config[followerIndex])
			return
		}
		defer resp.Body.Close()
		if r.Term > s.term {
			s.term = r.Term
			s.state = "follower"
			s.electionTimeout.reset()
		}
		if r.Success {
			s.term = r.Term
			s.nextIndex[followerIndex]++
			s.matchIndex[followerIndex]++
			followerResp := &followerResponse{followerIndex, *r}
			respChan <- *followerResp
		} else {
			s.nextIndex[followerIndex]--
			//		go s.sendAppendEntryRequest(followerIndex, entry, respChan)
		}
	}
}

func (s *server) handleAppendEntryRequest(a appendRequest) {
	returnChan := a.ReturnChan
	req := a.Req
	if req.Term < s.term {
		resp := &appendEntryResponse{s.term, false}
		returnChan <- *resp
	} else if req.PrevLogIndex == -1 {
		resp := &appendEntryResponse{s.term, true}
		returnChan <- *resp
	} else if len(s.db.Log.Entries) > req.PrevLogIndex &&
		s.db.Log.Entries[req.PrevLogIndex].Term != req.PrevLogTerm {
		resp := &appendEntryResponse{s.term, false}
		returnChan <- *resp
	} else {
		s.db.electionTimeout.reset()
		if s.db.Log.Entries[req.PrevLogIndex+1].Term != req.Term {
			// If existing entry conflicts with new entry
			// Delete entry and all that follow it
			s.db.Log.SetEntries(s.db.Log.Entries[:req.PrevLogIndex])
		}
		s.db.Log.AppendEntry(req.Entry)
		if req.LeaderCommit < s.commitIndex {
			// Set commit index to the min of the leader's commit index and index of last new entry
			if req.LeaderCommit < req.PrevLogIndex+1 {
				s.commitIndex = req.LeaderCommit
			} else {
				s.commitIndex = req.PrevLogIndex + 1
			}
		}
		resp := &appendEntryResponse{s.term, true}
		returnChan <- *resp
	}
}
<commit_msg>fix typo<commit_after>package raft

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/arpith/mmapd/db"
	"net/http"
)

type appendEntryRequest struct {
	Term         int
	LeaderID     string
	PrevLogIndex int
	PrevLogTerm  int
	Entry        db.Entry
	LeaderCommit int
}

type appendRequest struct {
	Req        appendEntryRequest
	ReturnChan chan appendEntryResponse
}

type appendEntryResponse struct {
	Term    int
	Success bool
}

type followerResponse struct {
	ServerIndex int
	Resp        appendEntryResponse
}

func (s *server) appendEntry(command string, isCommitted chan bool) {
	entry := &db.Entry{command, s.term}
	index := -1
	if command != "" {
		s.db.Log.AppendEntry(*entry)
		index = len(s.db.Log.Entries)
	}
	respChan := make(chan followerResponse)
	for i := 0; i < len(s.config); i++ {
		if s.config[i] != s.id {
			go s.sendAppendEntryRequest(i, *entry, respChan)
		}
	}
	responseCount := 0
	if len(s.config) > 1 {
		for {
			_ = <-respChan
			responseCount++
			for N := s.commitIndex + 1; N < len(s.db.Log.Entries); N++ {
				//Check if there exists an N > commitIndex
				count := 0
				for i := 0; i < len(s.matchIndex); i++ {
					if s.matchIndex[i] >= N {
						count++
					}
				}
				// Check if a majority of matchIndex[i] >= N
				cond1 := count > len(s.matchIndex)/2
				// Check if log[N].term == currentTerm
				cond2 := s.db.Log.Entries[N].Term == s.term
				if cond1 && cond2 {
					// Set commitIndex to N
					s.commitIndex = N
				} else {
					break
				}
			}
			if s.commitIndex == index {
				isCommitted <- true
			}
		}
	} else {
		if command != "" {
			s.commitIndex++
			isCommitted <- true
		}
	}
}

func (s *server) sendAppendEntryRequest(followerIndex int, entry db.Entry, respChan chan followerResponse) {
	follower := s.config[followerIndex]
	prevLogIndex := len(s.db.Log.Entries) - 1
	prevLogTerm := 0
	if prevLogIndex > 0 {
		prevLogTerm = s.db.Log.Entries[prevLogIndex].Term
	}
	a := &appendEntryRequest{s.term, s.id, prevLogIndex, prevLogTerm, entry, s.commitIndex}
	b := new(bytes.Buffer)
	json.NewEncoder(b).Encode(a)
	resp, err := http.Post("http://"+follower+"/append", "application/json", b)
	if err != nil {
		fmt.Println("Couldn't send append entry request to " + follower)
		fmt.Println(err)
		return
		//		go s.sendAppendEntryRequest(followerIndex, entry, respChan)
	} else {
		r := &appendEntryResponse{}
		err := json.NewDecoder(resp.Body).Decode(r)
		if err != nil {
			fmt.Println("Couldn't decode append entries response from " + s.config[followerIndex])
			return
		}
		defer resp.Body.Close()
		if r.Term > s.term {
			s.term = r.Term
			s.state = "follower"
			s.electionTimeout.reset()
		}
		if r.Success {
			s.term = r.Term
			s.nextIndex[followerIndex]++
			s.matchIndex[followerIndex]++
			followerResp := &followerResponse{followerIndex, *r}
			respChan <- *followerResp
		} else {
			s.nextIndex[followerIndex]--
			//		go s.sendAppendEntryRequest(followerIndex, entry, respChan)
		}
	}
}

func (s *server) handleAppendEntryRequest(a appendRequest) {
	returnChan := a.ReturnChan
	req := a.Req
	if req.Term < s.term {
		resp := &appendEntryResponse{s.term, false}
		returnChan <- *resp
	} else if req.PrevLogIndex == -1 {
		resp := &appendEntryResponse{s.term, true}
		returnChan <- *resp
	} else if len(s.db.Log.Entries) > req.PrevLogIndex &&
		s.db.Log.Entries[req.PrevLogIndex].Term != req.PrevLogTerm {
		resp := &appendEntryResponse{s.term, false}
		returnChan <- *resp
	} else {
		s.electionTimeout.reset()
		if s.db.Log.Entries[req.PrevLogIndex+1].Term != req.Term {
			// If existing entry conflicts with new entry
			// Delete entry and all that follow it
			s.db.Log.SetEntries(s.db.Log.Entries[:req.PrevLogIndex])
		}
		s.db.Log.AppendEntry(req.Entry)
		if req.LeaderCommit < s.commitIndex {
			// Set commit index to the min of the leader's commit index and index of last new entry
			if req.LeaderCommit < req.PrevLogIndex+1 {
				s.commitIndex = req.LeaderCommit
			} else {
				s.commitIndex = req.PrevLogIndex + 1
			}
		}
		resp := &appendEntryResponse{s.term, true}
		returnChan <- *resp
	}
}
<|endoftext|>


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

// Package proto contains the protocol buffer definitions shared between RPC servers and clients,
// mirroring the interfaces and types in the upspin package itself.
package proto

import (
	"time"

	"upspin.io/errors"
	"upspin.io/upspin"
)

// To regenerate the protocol buffer output for this package, run
//	go generate

//go:generate protoc upspin.proto --go_out=plugins=grpc:.

// All these converters are an unfortunate side-effect of not letting protobufs rule our types.

// UpspinLocation converts a proto Location struct to upspin.Location.
func UpspinLocation(loc *Location) upspin.Location {
	if loc == nil {
		return upspin.Location{}
	}
	return upspin.Location{
		Endpoint: upspin.Endpoint{
			Transport: upspin.Transport(loc.Endpoint.Transport),
			NetAddr:   upspin.NetAddr(loc.Endpoint.NetAddr),
		},
		Reference: upspin.Reference(loc.Reference),
	}
}

// UpspinLocations converts from slices of proto's Location struct to upspin's.
func UpspinLocations(l []*Location) []upspin.Location {
	if len(l) == 0 {
		return nil
	}
	ulocs := make([]upspin.Location, len(l))
	for i := range ulocs {
		ulocs[i] = UpspinLocation(l[i])
	}
	return ulocs
}

// UpspinDirEntry converts a slice of bytes struct to *upspin.DirEntry.
// If the slice is nil or empty, it returns nil.
func UpspinDirEntry(b []byte) (*upspin.DirEntry, error) {
	const op = "proto.UpspinDirEntry"
	if len(b) == 0 {
		return nil, nil
	}
	var d upspin.DirEntry
	b, err := d.Unmarshal(b)
	if err != nil {
		return nil, err
	}
	if len(b) != 0 {
		return nil, errors.E(op, errors.Invalid, errors.Str("extra data"))
	}
	return &d, nil
}

// Locations converts from slices of upspin's Location struct to proto's.
func Locations(ul []upspin.Location) []*Location {
	if len(ul) == 0 {
		return nil
	}
	locs := make([]*Location, len(ul))
	for i := range locs {
		loc := ul[i]
		locs[i] = &Location{
			Endpoint: &Endpoint{
				Transport: int32(loc.Endpoint.Transport),
				NetAddr:   string(loc.Endpoint.NetAddr),
			},
			Reference: string(loc.Reference),
		}
	}
	return locs
}

// UpspinEndpoints converts from slices of proto's Endpoint struct to upspin's.
func UpspinEndpoints(e []*Endpoint) []upspin.Endpoint {
	if len(e) == 0 {
		return nil
	}
	ueps := make([]upspin.Endpoint, len(e))
	for i := range ueps {
		ep := e[i]
		ueps[i] = upspin.Endpoint{
			Transport: upspin.Transport(ep.Transport),
			NetAddr:   upspin.NetAddr(ep.NetAddr),
		}
	}
	return ueps
}

// Endpoints converts from slices of upspin's Endpoint struct to proto's.
func Endpoints(ue []upspin.Endpoint) []*Endpoint {
	if len(ue) == 0 {
		return nil
	}
	eps := make([]*Endpoint, len(ue))
	for i := range eps {
		ep := ue[i]
		eps[i] = &Endpoint{
			Transport: int32(ep.Transport),
			NetAddr:   string(ep.NetAddr),
		}
	}
	return eps
}

// UpspinPublicKeys converts from slices of strings to upspin's PublicKeys.
func UpspinPublicKeys(s []string) []upspin.PublicKey {
	if len(s) == 0 {
		return nil
	}
	upk := make([]upspin.PublicKey, len(s))
	for i := range upk {
		upk[i] = upspin.PublicKey(s[i])
	}
	return upk
}

// PublicKeys converts from slices of upspin's PublicKey to string.
func PublicKeys(upk []upspin.PublicKey) []string {
	if len(upk) == 0 {
		return nil
	}
	s := make([]string, len(upk))
	for i := range s {
		s[i] = string(upk[i])
	}
	return s
}

// UpspinUser converts a proto.User to upspin.User.
func UpspinUser(user *User) *upspin.User {
	return &upspin.User{
		Name:      upspin.UserName(user.Name),
		Dirs:      UpspinEndpoints(user.Dirs),
		Stores:    UpspinEndpoints(user.Stores),
		PublicKey: upspin.PublicKey(user.PublicKey),
		// TODO: other fields?
	}
}

// UserProto converts an upspin.User to a proto.User.
func UserProto(user *upspin.User) *User {
	return &User{
		Name:      string(user.Name),
		Dirs:      Endpoints(user.Dirs),
		Stores:    Endpoints(user.Stores),
		PublicKey: string(user.PublicKey),
		// TODO: other fields?
	}
}

// RefdataProto converts an upspin.Refdata to a proto.Refdata.
func RefdataProto(refdata *upspin.Refdata) *Refdata {
	return &Refdata{
		Reference: string(refdata.Reference),
		Volatile:  refdata.Volatile,
		Duration:  int64(refdata.Duration),
	}
}

// UpspinRefdata converts a proto.Refdata to upspin.Refdata.
func UpspinRefdata(refdata *Refdata) *upspin.Refdata {
	return &upspin.Refdata{
		Reference: upspin.Reference(refdata.Reference),
		Volatile:  refdata.Volatile,
		Duration:  time.Duration(refdata.Duration),
	}
}

// UpspinDirEntries converts from slices of bytes to upspin's *DirEntries.
func UpspinDirEntries(b [][]byte) ([]*upspin.DirEntry, error) {
	if len(b) == 0 {
		return nil, nil
	}
	ude := make([]*upspin.DirEntry, len(b))
	for i := range ude {
		var err error
		ude[i], err = UpspinDirEntry(b[i])
		if err != nil {
			return nil, err
		}
	}
	return ude, nil
}

// DirEntryBytes converts from slices of upspin's *DirEntries to bytes.
func DirEntryBytes(ude []*upspin.DirEntry) ([][]byte, error) {
	if len(ude) == 0 {
		return nil, nil
	}
	b := make([][]byte, len(ude))
	for i := range b {
		var err error
		b[i], err = ude[i].Marshal()
		if err != nil {
			return nil, err
		}
	}
	return b, nil
}
<commit_msg>upspin/proto: refdata may be nil<commit_after>// Copyright 2016 The Upspin Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package proto contains the protocol buffer definitions shared between RPC servers and clients,
// mirroring the interfaces and types in the upspin package itself.
package proto

import (
	"time"

	"upspin.io/errors"
	"upspin.io/upspin"
)

// To regenerate the protocol buffer output for this package, run
//	go generate

//go:generate protoc upspin.proto --go_out=plugins=grpc:.

// All these converters are an unfortunate side-effect of not letting protobufs rule our types.

// UpspinLocation converts a proto Location struct to upspin.Location.
func UpspinLocation(loc *Location) upspin.Location {
	if loc == nil {
		return upspin.Location{}
	}
	return upspin.Location{
		Endpoint: upspin.Endpoint{
			Transport: upspin.Transport(loc.Endpoint.Transport),
			NetAddr:   upspin.NetAddr(loc.Endpoint.NetAddr),
		},
		Reference: upspin.Reference(loc.Reference),
	}
}

// UpspinLocations converts from slices of proto's Location struct to upspin's.
func UpspinLocations(l []*Location) []upspin.Location {
	if len(l) == 0 {
		return nil
	}
	ulocs := make([]upspin.Location, len(l))
	for i := range ulocs {
		ulocs[i] = UpspinLocation(l[i])
	}
	return ulocs
}

// UpspinDirEntry converts a slice of bytes struct to *upspin.DirEntry.
// If the slice is nil or empty, it returns nil.
func UpspinDirEntry(b []byte) (*upspin.DirEntry, error) {
	const op = "proto.UpspinDirEntry"
	if len(b) == 0 {
		return nil, nil
	}
	var d upspin.DirEntry
	b, err := d.Unmarshal(b)
	if err != nil {
		return nil, err
	}
	if len(b) != 0 {
		return nil, errors.E(op, errors.Invalid, errors.Str("extra data"))
	}
	return &d, nil
}

// Locations converts from slices of upspin's Location struct to proto's.
func Locations(ul []upspin.Location) []*Location {
	if len(ul) == 0 {
		return nil
	}
	locs := make([]*Location, len(ul))
	for i := range locs {
		loc := ul[i]
		locs[i] = &Location{
			Endpoint: &Endpoint{
				Transport: int32(loc.Endpoint.Transport),
				NetAddr:   string(loc.Endpoint.NetAddr),
			},
			Reference: string(loc.Reference),
		}
	}
	return locs
}

// UpspinEndpoints converts from slices of proto's Endpoint struct to upspin's.
func UpspinEndpoints(e []*Endpoint) []upspin.Endpoint {
	if len(e) == 0 {
		return nil
	}
	ueps := make([]upspin.Endpoint, len(e))
	for i := range ueps {
		ep := e[i]
		ueps[i] = upspin.Endpoint{
			Transport: upspin.Transport(ep.Transport),
			NetAddr:   upspin.NetAddr(ep.NetAddr),
		}
	}
	return ueps
}

// Endpoints converts from slices of upspin's Endpoint struct to proto's.
func Endpoints(ue []upspin.Endpoint) []*Endpoint {
	if len(ue) == 0 {
		return nil
	}
	eps := make([]*Endpoint, len(ue))
	for i := range eps {
		ep := ue[i]
		eps[i] = &Endpoint{
			Transport: int32(ep.Transport),
			NetAddr:   string(ep.NetAddr),
		}
	}
	return eps
}

// UpspinPublicKeys converts from slices of strings to upspin's PublicKeys.
func UpspinPublicKeys(s []string) []upspin.PublicKey {
	if len(s) == 0 {
		return nil
	}
	upk := make([]upspin.PublicKey, len(s))
	for i := range upk {
		upk[i] = upspin.PublicKey(s[i])
	}
	return upk
}

// PublicKeys converts from slices of upspin's PublicKey to string.
func PublicKeys(upk []upspin.PublicKey) []string {
	if len(upk) == 0 {
		return nil
	}
	s := make([]string, len(upk))
	for i := range s {
		s[i] = string(upk[i])
	}
	return s
}

// UpspinUser converts a proto.User to upspin.User.
func UpspinUser(user *User) *upspin.User {
	return &upspin.User{
		Name:      upspin.UserName(user.Name),
		Dirs:      UpspinEndpoints(user.Dirs),
		Stores:    UpspinEndpoints(user.Stores),
		PublicKey: upspin.PublicKey(user.PublicKey),
		// TODO: other fields?
	}
}

// UserProto converts an upspin.User to a proto.User.
func UserProto(user *upspin.User) *User {
	return &User{
		Name:      string(user.Name),
		Dirs:      Endpoints(user.Dirs),
		Stores:    Endpoints(user.Stores),
		PublicKey: string(user.PublicKey),
		// TODO: other fields?
	}
}

// RefdataProto converts an upspin.Refdata to a proto.Refdata.
func RefdataProto(refdata *upspin.Refdata) *Refdata {
	if refdata == nil {
		return nil
	}
	return &Refdata{
		Reference: string(refdata.Reference),
		Volatile:  refdata.Volatile,
		Duration:  int64(refdata.Duration),
	}
}

// UpspinRefdata converts a proto.Refdata to upspin.Refdata.
func UpspinRefdata(refdata *Refdata) *upspin.Refdata {
	if refdata == nil {
		return nil
	}
	return &upspin.Refdata{
		Reference: upspin.Reference(refdata.Reference),
		Volatile:  refdata.Volatile,
		Duration:  time.Duration(refdata.Duration),
	}
}

// UpspinDirEntries converts from slices of bytes to upspin's *DirEntries.
func UpspinDirEntries(b [][]byte) ([]*upspin.DirEntry, error) {
	if len(b) == 0 {
		return nil, nil
	}
	ude := make([]*upspin.DirEntry, len(b))
	for i := range ude {
		var err error
		ude[i], err = UpspinDirEntry(b[i])
		if err != nil {
			return nil, err
		}
	}
	return ude, nil
}

// DirEntryBytes converts from slices of upspin's *DirEntries to bytes.
func DirEntryBytes(ude []*upspin.DirEntry) ([][]byte, error) {
	if len(ude) == 0 {
		return nil, nil
	}
	b := make([][]byte, len(ude))
	for i := range b {
		var err error
		b[i], err = ude[i].Marshal()
		if err != nil {
			return nil, err
		}
	}
	return b, nil
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/danryan/hal"
	_ "github.com/danryan/hal/adapter/irc"
	"github.com/fujin/bawt/handlers"
	"log"
	"os"
)

// Bawt is an infobot for #go-chef/#chef, etc
type Bawt struct {
	*hal.Robot
}

// NewBawt makes bawt or returns an error
func NewBawt() (bawt Bawt, err error) {
	bawt.Robot, err = hal.NewRobot()
	if err != nil {
		log.Fatal(err)
	}
	return bawt, nil
}

func main() {
	bawt, err := NewBawt()
	if err != nil {
		log.Fatal("unexpected error during bawt creation:", err)
	}

	bawt.Handle(
		handlers.PingHandler,
		handlers.GetHandler,
		handlers.SetHandler,
		handlers.DeleteHandler,
		handlers.UsersHandler,
	)
	bawt.Run()

	os.Exit(0)
}
<commit_msg>hidden import redis store for init<commit_after>package main

import (
	"github.com/danryan/hal"
	_ "github.com/danryan/hal/adapter/irc"
	_ "github.com/danryan/hal/store/redis"
	"github.com/fujin/bawt/handlers"
	"log"
	"os"
)

// Bawt is an infobot for #go-chef/#chef, etc
type Bawt struct {
	*hal.Robot
}

// NewBawt makes bawt or returns an error
func NewBawt() (bawt Bawt, err error) {
	bawt.Robot, err = hal.NewRobot()
	if err != nil {
		log.Fatal(err)
	}
	return bawt, nil
}

func main() {
	bawt, err := NewBawt()
	if err != nil {
		log.Fatal("unexpected error during bawt creation:", err)
	}

	bawt.Handle(
		handlers.PingHandler,
		handlers.GetHandler,
		handlers.SetHandler,
		handlers.DeleteHandler,
		handlers.UsersHandler,
	)
	bawt.Run()

	os.Exit(0)
}
<|endoftext|>