Skip to content

Commit

Permalink
feat: add server mode
Browse files Browse the repository at this point in the history
Signed-off-by: Andrew Rynhard <andrew@andrewrynhard.com>
  • Loading branch information
andrewrynhard committed Dec 8, 2019
1 parent 0076446 commit 5637edd
Show file tree
Hide file tree
Showing 8 changed files with 443 additions and 141 deletions.
21 changes: 13 additions & 8 deletions cmd/enforce.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ package cmd

import (
"fmt"
"log"
"os"

"github.com/pkg/errors"
"github.com/autonomy/conform/internal/enforcer"
"github.com/autonomy/conform/internal/policy"
"github.com/spf13/cobra"
"github.com/talos-systems/conform/internal/enforcer"
"github.com/talos-systems/conform/internal/policy"
Expand All @@ -21,14 +23,13 @@ var enforceCmd = &cobra.Command{
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
if len(args) != 0 {
err := errors.Errorf("The enforce command does not take arguments")

fmt.Println(err)
fmt.Println("The enforce command does not take arguments")
os.Exit(1)
}
e, err := enforcer.New()
summarizer := cmd.Flags().Lookup("summary").Value.String()
e, err := enforcer.New(summarizer)
if err != nil {
fmt.Println(err)
log.Printf("failed to create enforcer: %+v\n", err)
os.Exit(1)
}

Expand All @@ -38,11 +39,15 @@ var enforceCmd = &cobra.Command{
opts = append(opts, policy.WithCommitMsgFile(&commitMsgFile))
}

e.Enforce(opts...)
if err := e.Enforce(opts...); err != nil {
log.Printf("%+v\n", err)
os.Exit(1)
}
},
}

func init() {
enforceCmd.Flags().String("commit-msg-file", "", "the path to the temporary commit message file")
RootCmd.AddCommand(enforceCmd)
enforceCmd.Flags().String("summary", "none", "the summary method to use")
rootCmd.AddCommand(enforceCmd)
}
47 changes: 3 additions & 44 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,11 @@ import (
"fmt"
"os"

homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var cfgFile string

var (
debug bool
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "conform",
Short: "Policy enforcement for your pipelines.",
Long: ``,
Expand All @@ -29,41 +21,8 @@ var RootCmd = &cobra.Command{
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}

func init() {
cobra.OnInitialize(initConfig)

RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is .conform.yaml)")
RootCmd.Flags().BoolVar(&debug, "debug", false, "Debug rendering")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(home)
os.Exit(1)
}

// Search config in home directory with name ".cobra" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".cobra")
}

viper.AutomaticEnv() // read in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}
122 changes: 122 additions & 0 deletions cmd/serve.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
/*
Copyright © 2019 NAME HERE <EMAIL ADDRESS>
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 cmd

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"

"github.com/google/go-github/github"
"github.com/spf13/cobra"

git "gopkg.in/src-d/go-git.v4"
)

const (
path = "/github"
)

// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Short: "",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
if err := os.MkdirAll("/tmp", 0700); err != nil {
log.Fatal(err)
}

http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
payload, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Printf("failed to read payload: %+v\n", err)
return
}

go func() {
dir, err := ioutil.TempDir("/tmp", "conform")
if err != nil {
log.Printf("failed to create temporary directory: %+v\n", err)
return
}
// nolint: errcheck
defer os.RemoveAll(dir)

if err := os.MkdirAll(filepath.Join(dir, "github"), 0700); err != nil {
log.Printf("failed to create github directory: %+v\n", err)
return
}
if err := os.MkdirAll(filepath.Join(dir, "repo"), 0700); err != nil {
log.Printf("failed to create repo directory: %+v\n", err)
return
}

event := filepath.Join(dir, "github", "event.json")
pullRequestEvent := &github.PullRequestEvent{}
if err = json.Unmarshal(payload, pullRequestEvent); err != nil {
log.Printf("failed to parse pull_request event: %+v\n", err)
return
}

cloneRepo := filepath.Join(dir, "repo")
_, err = git.PlainClone(cloneRepo, false, &git.CloneOptions{
URL: pullRequestEvent.GetRepo().GetCloneURL(),
Progress: os.Stdout,
})

if err = ioutil.WriteFile(event, payload, 0600); err != nil {
log.Printf("failed to clone repo: %+v\n", err)
return
}

log.Printf("writing %s to disk", event)
if err = ioutil.WriteFile(event, payload, 0600); err != nil {
log.Printf("failed to write event to disk: %+v\n", err)
return
}
cmd := exec.Command("/proc/self/exe", "enforce", "--summary=github")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stdout
cmd.Dir = cloneRepo
cmd.Env = []string{fmt.Sprintf("GITHUB_TOKEN=%s", os.Getenv("GITHUB_TOKEN")), fmt.Sprintf("GITHUB_EVENT_PATH=%s", event)}
err = cmd.Start()
if err != nil {
log.Printf("failed to start command: %+v\n", err)
return
}
err = cmd.Wait()
if err != nil {
log.Printf("command failed: %+v\n", err)
return
}
}()

w.WriteHeader(http.StatusOK)
})

http.ListenAndServe(":3000", nil)
},
}

func init() {
rootCmd.AddCommand(serveCmd)
}
2 changes: 1 addition & 1 deletion cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ var versionCmd = &cobra.Command{

func init() {
versionCmd.Flags().BoolVar(&shortVersion, "short", false, "Print the short version")
RootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(versionCmd)
}

// PrintLongVersion prints verbose version information.
Expand Down
36 changes: 6 additions & 30 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,46 +1,22 @@
module github.com/talos-systems/conform

require (
github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 // indirect
github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 // indirect
github.com/deckarep/golang-set v1.7.1 // indirect
github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect
github.com/fsnotify/fsnotify v1.4.7 // indirect
github.com/gliderlabs/ssh v0.2.2 // indirect
github.com/google/go-cmp v0.3.1 // indirect
github.com/autonomy/conform v0.1.0-alpha.16
github.com/containerd/containerd v1.2.7 // indirect
github.com/google/go-github v17.0.0+incompatible
github.com/google/go-querystring v1.0.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect
github.com/kevinburke/ssh_config v0.0.0-20190725054713-01f96b0aa0cd // indirect
github.com/magiconair/properties v1.8.1 // indirect
github.com/mingrammer/commonregex v1.0.0 // indirect
github.com/mitchellh/go-homedir v0.0.0-20161203194507-b8bc1bf76747
github.com/mitchellh/mapstructure v0.0.0-20170523030023-d0303fe80992
github.com/montanaflynn/stats v0.5.0 // indirect
github.com/neurosnap/sentences v1.0.6 // indirect
github.com/pelletier/go-toml v1.4.0 // indirect
github.com/pkg/errors v0.8.1
github.com/sergi/go-diff v1.0.0 // indirect
github.com/spf13/afero v1.2.2 // indirect
github.com/spf13/cast v1.3.0 // indirect
github.com/spf13/cobra v0.0.3
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.3 // indirect
github.com/spf13/viper v0.0.0-20170619124313-c1de95864d73
github.com/src-d/gcfg v1.4.0 // indirect
github.com/stretchr/testify v1.4.0 // indirect
github.com/xanzy/ssh-agent v0.2.1 // indirect
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 // indirect
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c // indirect
golang.org/x/text v0.3.2 // indirect
gonum.org/v1/gonum v0.0.0-20190816090505-0436873561a9 // indirect
github.com/talos-systems/talos v0.1.0 // indirect
google.golang.org/grpc v1.23.0 // indirect
gopkg.in/jdkato/prose.v2 v2.0.0-20180825173540-767a23049b9e
gopkg.in/neurosnap/sentences.v1 v1.0.6 // indirect
gopkg.in/src-d/go-billy.v4 v4.3.2 // indirect
gopkg.in/src-d/go-git-fixtures.v3 v3.5.0 // indirect
gopkg.in/src-d/go-git.v4 v4.0.0
gopkg.in/warnings.v0 v0.1.1 // indirect
gopkg.in/yaml.v2 v2.2.2
)

go 1.13
Loading

0 comments on commit 5637edd

Please sign in to comment.