Day 10

A Go .env File Manager

Unfortunately, you can't run this in the browser here

This program reads from the filesystem, so it must be run locally — it cannot run in the browser.

Run go run main.go in a directory that contains .env files.


Description


This is a Go CLI tool that manages .env files in the current directory. It presents a menu to read all .env file contents or update a specific key's value, and handles the case where multiple .env files are present by prompting you to choose one.

View the source code


package main
import (
 "fmt"
 "os"
 "strings"
)
func contains(slice []string, item string) bool {
 for _, s := range slice {
  if s == item {
   return true
  }
 }
 return false
}
func updateEnvFile(file string, key string) bool {
 data, err := os.ReadFile(file)
 if err != nil {
  fmt.Println("Error reading file")
  os.Exit(1)
 }
 lines := strings.Split(string(data), "\n")
 for i, line := range lines {
  if strings.HasPrefix(line, key+"=") {
   fmt.Println("New value:")
   var newValue string
   fmt.Scanln(&newValue)
   lines[i] = key + "=" + newValue
   result := strings.Join(lines, "\n")
   err := os.WriteFile(file, []byte(result), 0644)
   if err != nil {
    fmt.Println("Error writing file")
    os.Exit(1)
   }
   fmt.Println("Updated successfully")
   return true
  }
 }
 return false
}
func main() {
 for {
  fmt.Println("What to do with the .env files?\n1. Read all of them\n2. Change a line\n3. Exit")
  var input string
  fmt.Scanln(&input)
  if input == "1" {
   fmt.Println("Reading all .env files...")
   files, err := os.ReadDir(".")
   if err != nil {
    fmt.Println("Error reading directory")
    os.Exit(1)
   }
   for _,file := range files {
    if (strings.HasSuffix(file.Name(), ".env")) {
     data, err := os.ReadFile(file.Name())
     if err != nil {
      fmt.Println("Error reading file")
      os.Exit(1)
     }
     fmt.Printf("Contents of %s:\n%s\n", file.Name(), string(data))
   }    }
  } else if input == "2" {
   fmt.Println("What element to change?")
   fmt.Scanln(&input)
   files, err := os.ReadDir(".")
   if err != nil {
    fmt.Println("Error reading directory")
    os.Exit(1)
   }
   var envFiles []string
   for _,file := range files {
    if (strings.HasSuffix(file.Name(), ".env")) {
     envFiles = append(envFiles, file.Name())
    }
   }
   var file string
   if len(envFiles) > 1 {
    fmt.Println("Multiple .env files found, please specify which one to change")
    fmt.Scanln(&file)
    if !contains(envFiles, file) {
     fmt.Println("File not found")
     os.Exit(1)
    }
   } else if len(envFiles) == 1 {
    file = envFiles[0]
   }
   updateEnvFile(file, input)
  } else if input == "3" {
   fmt.Println("Exiting...")
   os.Exit(0)
  }
 }
}

Previous Day
Next Day