Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

direnv intigration #10

Merged
merged 5 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .envrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
use flake
use flake bsf/.
2 changes: 2 additions & 0 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/buildsafedev/bsf/cmd/build"
"github.com/buildsafedev/bsf/cmd/configure"
"github.com/buildsafedev/bsf/cmd/develop"
"github.com/buildsafedev/bsf/cmd/direnv"
"github.com/buildsafedev/bsf/cmd/dockerfile"
initCmd "github.com/buildsafedev/bsf/cmd/init"
"github.com/buildsafedev/bsf/cmd/nixgenerate"
Expand Down Expand Up @@ -63,6 +64,7 @@ func Execute() {
rootCmd.AddCommand(scan.ScanCmd)
rootCmd.AddCommand(update.UpdateCmd)
rootCmd.AddCommand(attestation.AttCmd)
rootCmd.AddCommand(direnv.Direnv)

if os.Getenv("BSF_DEBUG_MODE") == "true" {
rootCmd.AddCommand(configure.ConfigureCmd)
Expand Down
196 changes: 196 additions & 0 deletions cmd/direnv/direnv.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package direnv

import (
"errors"
"fmt"
"os"
"os/exec"
"regexp"
"strings"

"github.com/buildsafedev/bsf/cmd/styles"
"github.com/spf13/cobra"
)

var Direnv = &cobra.Command{
Use: "direnv",
Short: "direnv initializes the direnv environment for the project",
Run: func(cmd *cobra.Command, args []string) {
err := generateEnvrc()
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error: ", err.Error()))
os.Exit(1)
}
err = fetchGitignore()
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error: ", err.Error()))
os.Exit(1)
}

if envVar != "" {
err = setDIrenv(envVar)
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error: ", err.Error()))
os.Exit(1)
}
}

cmD := exec.Command("direnv", "allow")
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
err = cmD.Run()
if err != nil {
os.Exit(1)
}
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
},
}

var (
envVar string
)

func init() {
Direnv.Flags().StringVarP(&envVar, "env", "e", "", "set environment variable [key=value]")
}

func generateEnvrc() error {

if _, err := os.Stat(".envrc"); err == nil {

read, err := os.ReadFile(".envrc")
if err != nil {
return err
}

if !strings.Contains(string(read), "use flake bsf/.") {

file, err := os.OpenFile(".envrc", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}

_, err = file.WriteString("\nuse flake bsf/.")
if err != nil {
fmt.Println(styles.ErrorStyle.Render("", err.Error()))
return err
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
}
return nil
}

} else {
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
file, err := os.Create(".envrc")
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

defer file.Close()

_, err = file.WriteString("use flake bsf/.")
if err != nil {
return err
}

}

return nil
}

func fetchGitignore() error {

if _, err := os.Stat(".gitignore"); err == nil {

read, err := os.ReadFile(".gitignore")
if err != nil {
return err
}

if !strings.Contains(string(read), ".envrc") {

file, err := os.OpenFile(".gitignore", os.O_APPEND|os.O_WRONLY, 0644)
_, err = file.WriteString("\n.envrc")
if err != nil {
fmt.Println(styles.ErrorStyle.Render("", err.Error()))
return err
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
}
}

return nil
} else {
_, err := os.Create(".gitignore")
if err != nil {
return err
}

file, err := os.OpenFile(".gitignore", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}

_, err = file.WriteString("\n.envrc")
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}
}

return nil

}

func setDIrenv(args string) error {
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved

err := validateEnvVars(args)
if err != nil {
return err
}
file, err := os.OpenFile(".envrc", os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
return err
}

_, err = file.WriteString("\nexport " + args)
if err != nil {
fmt.Println(styles.ErrorStyle.Render("", err.Error()))
return err
}

cmd := exec.Command("direnv", "allow")
err = cmd.Run()
if err != nil {
return err
}

return nil
}

func validateEnvVars(args string) error {
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
validKeyValRegex := regexp.MustCompile(`^[\w]+=[^\s]+$`)

envVars := strings.Split(args, ",")

for _, envVar := range envVars {
if !validKeyValRegex.MatchString(envVar) {
return errors.New("Invalid key-value pair format")
}

resp := strings.SplitN(envVar, "=", 2)
key := resp[0]
value := resp[1]

if strings.ContainsAny(key, "= \t\n") {
return errors.New("Invalid characters in key")
}

if strings.ContainsAny(value, "\x00") {
return errors.New("Invalid characters in value")
}

read, err := os.ReadFile(".envrc")
if err != nil {
dr-housemd marked this conversation as resolved.
Show resolved Hide resolved
return err
}

if strings.Contains(string(read), key) {
return errors.New("Key already exists")
}
}

return nil
}
2 changes: 1 addition & 1 deletion cmd/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func GetBSFInitializers() (bsfv1.SearchServiceClient, *hcl2nix.FileHandlers, err
}

// CleanUp removes the bsf config if any error occurs in init process (ctrl+c or any init process stage)
func cleanUp(){
func cleanUp() {
configs := []string{"bsf", "bsf.hcl", "bsf.lock"}

for _, f := range configs {
Expand Down
2 changes: 1 addition & 1 deletion cmd/init/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
err = m.processStages(m.stage)
if err != nil {
cleanUp()
cleanUp()
return m, tea.Quit
}
m.stage++
Expand Down
7 changes: 1 addition & 6 deletions cmd/precheck/precheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func IsFlakesEnabled() {
func AllPrechecks() {
fmt.Println(styles.TextStyle.Render("Running prechecks..."))
var wg sync.WaitGroup
wg.Add(3)
wg.Add(2)
go func() {
ValidateNixVersion()
wg.Done()
Expand All @@ -85,11 +85,6 @@ func AllPrechecks() {
wg.Done()

}()
go func() {
wg.Done()

}()

wg.Wait()

fmt.Println(styles.SucessStyle.Render(" Prechecks ran successfully"))
Expand Down
Loading