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

fix: init cmd #84

Merged
merged 4 commits into from
Jul 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
82 changes: 15 additions & 67 deletions cmd/init/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,36 @@ import (
var (
commonDevDeps = []string{"[email protected]", "[email protected]"}
commonRTDeps = []string{"[email protected]"}
baseImageName = "ttl.sh/base"
)

func generatehcl2NixConf(pt langdetect.ProjectType, pd *langdetect.ProjectDetails) (hcl2nix.Config, error) {
fmt.Println("IN GENERATE HCL NIX CONFIG -------------------------------------------")
fmt.Println("NAME: ", pd.Name)
func generatehcl2NixConf(pt langdetect.ProjectType, pd *langdetect.ProjectDetails, baseImgName string) (hcl2nix.Config, error) {
switch pt {
case langdetect.GoModule:
return genGoModuleConf(pd), nil
case langdetect.PythonPoetry:
return genPythonPoetryConf(pd), nil
return genPythonPoetryConf(), nil
case langdetect.RustCargo:
config, err := genRustCargoConf(pd)
config, err := genRustCargoConf()
if err != nil {
return hcl2nix.Config{}, err
}
return config, nil
case langdetect.JsNpm:
config, err := genJsNpmConf(pd)
config, err := genJsNpmConf()
if err != nil {
return hcl2nix.Config{}, err
}
return config, nil
case langdetect.BaseImage:
return generateEmptyConf(baseImgName), nil
default:
return generateEmptyConf(pd), nil
return hcl2nix.Config{
Packages: hcl2nix.Packages{},
}, fmt.Errorf("language is not supported")
}
}

func generateEmptyConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
if pd.Name == "" {
pd.Name = "expl"
}
func generateEmptyConf(imageName string) hcl2nix.Config {
return hcl2nix.Config{
Packages: hcl2nix.Packages{
Development: commonDevDeps,
Expand All @@ -53,7 +51,7 @@ func generateEmptyConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
OCIArtifact: []hcl2nix.OCIArtifact{
{
Artifact: "pkgs",
Name: baseImageName,
Name: imageName,
Cmd: []string{},
Entrypoint: []string{},
EnvVars: []string{},
Expand All @@ -63,10 +61,8 @@ func generateEmptyConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
},
}
}
func genRustCargoConf(pd *langdetect.ProjectDetails) (hcl2nix.Config, error) {
if pd.Name == "" {
pd.Name = "expl"
}
func genRustCargoConf() (hcl2nix.Config, error) {

content, err := os.ReadFile("Cargo.toml")
if err != nil {
return hcl2nix.Config{}, fmt.Errorf("error reading file: %v", err)
Expand Down Expand Up @@ -98,21 +94,10 @@ func genRustCargoConf(pd *langdetect.ProjectDetails) (hcl2nix.Config, error) {
RustVersion: "1.75.0",
Release: true,
},
OCIArtifact: []hcl2nix.OCIArtifact{
{
Artifact: "pkgs",
Name: baseImageName,
Cmd: []string{},
Entrypoint: []string{},
EnvVars: []string{},
ExposedPorts: []string{},
ImportConfigs: []string{},
},
},
}, nil
}

func genPythonPoetryConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
func genPythonPoetryConf() hcl2nix.Config {
// TODO: maybe we should note down the path of the poetry.lock file and use it here.
poetryDevDeps := append(commonDevDeps, "[email protected]", "[email protected]")
return hcl2nix.Config{
Expand All @@ -128,18 +113,6 @@ func genPythonPoetryConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
PreferWheels: false,
CheckGroups: []string{"dev"},
},
OCIArtifact: []hcl2nix.OCIArtifact{
{
Artifact: "pkgs",

Name: baseImageName,
Cmd: []string{},
Entrypoint: []string{},
EnvVars: []string{},
ExposedPorts: []string{},
ImportConfigs: []string{},
},
},
}
}

Expand Down Expand Up @@ -168,25 +141,11 @@ func genGoModuleConf(pd *langdetect.ProjectDetails) hcl2nix.Config {
Name: name,
SourcePath: entrypoint,
},
OCIArtifact: []hcl2nix.OCIArtifact{
{
Artifact: "pkgs",
Name: baseImageName,
Cmd: []string{},
Entrypoint: []string{},
EnvVars: []string{},
ExposedPorts: []string{},
ImportConfigs: []string{},
},
},
}

}

func genJsNpmConf(pd *langdetect.ProjectDetails) (hcl2nix.Config, error) {
if pd.Name == "" {
pd.Name = "expl"
}
func genJsNpmConf() (hcl2nix.Config, error) {
data, err := os.ReadFile("package-lock.json")
if err != nil {
return hcl2nix.Config{}, fmt.Errorf("error reading file: %v", err)
Expand All @@ -212,16 +171,5 @@ func genJsNpmConf(pd *langdetect.ProjectDetails) (hcl2nix.Config, error) {
PackageName: name,
PackageRoot: "./.",
},
OCIArtifact: []hcl2nix.OCIArtifact{
{
Artifact: "pkgs",
Name: baseImageName,
Cmd: []string{},
Entrypoint: []string{},
EnvVars: []string{},
ExposedPorts: []string{},
ImportConfigs: []string{},
},
},
}, nil
}
85 changes: 39 additions & 46 deletions cmd/init/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,79 +36,72 @@ var InitCmd = &cobra.Command{
os.Exit(1)
}

res := YesNoPrompt("Do you want docker file to be initialized", false)
isBaseImage, err := yesNoPrompt("Do you want to build a base image?")
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error:", err.Error()))
os.Exit(1)
}

var pd langdetect.ProjectDetails
var imageName string
var pt langdetect.ProjectType
if res {
pd.Name = *IOprompt("What should the name be?", "").(*string)
} else {
var projName = IOprompt("What type of projects you are setting up ? (Go/Rust/JavaScript/Poetry)", nil)
fmt.Println("TYPE : ", projName)
var lang langdetect.ProjectType
switch projName.(string) {
case "Go":
lang = langdetect.GoModule
case "Rust":
lang = langdetect.RustCargo
case "JS":
lang = langdetect.JsNpm
case "Poetry":
lang = langdetect.PythonPoetry

if isBaseImage {
imageName, err = ioPrompt("What should the image name be?")
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error:", err.Error()))
os.Exit(1)
}
pt = lang
pt = langdetect.BaseImage
}

sc, err := search.NewClientWithAddr(conf.BuildSafeAPI, conf.BuildSafeAPITLS)
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error:", err.Error()))
os.Exit(1)
}

m := model{sc: sc, pd: &pd, pt: pt}
m := model{sc: sc, pt: pt, baseImgName: imageName}
m.resetSpinner()
if _, err := tea.NewProgram(m).Run(); err != nil {
os.Exit(1)
}
},
}

func YesNoPrompt(label string, defaultChoice bool) bool {
func yesNoPrompt(label string) (bool, error) {
choices := "Y/n"
if !defaultChoice {
choices = "y/N"
}

r := bufio.NewReader(os.Stdin)
var s string
for {
fmt.Fprintf(os.Stderr, "%s (%s) ", strings.TrimSpace(label), choices)
s, _ = r.ReadString('\n')
s = strings.TrimSpace(s)
if s == "" {
return defaultChoice
}
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return true
}
if s == "n" || s == "no" {
return false
}
fmt.Fprintf(os.Stderr, styles.HighlightStyle.Render("%s (%s) "), strings.TrimSpace(label), choices)
s, err := r.ReadString('\n')
if err != nil {
return false, err
}
s = strings.TrimSpace(s)
s = strings.ToLower(s)
if s == "y" || s == "yes" {
return true, nil
}
if s == "n" || s == "no" {
return false, nil
}
return false, nil
}

func IOprompt(label string, defaultvalue any) any {
func ioPrompt(label string) (string, error) {
r := bufio.NewReader(os.Stdin)
var s string
for {
fmt.Fprintf(os.Stderr, "%s : ", strings.TrimSpace(label))
s, _ = r.ReadString('\n')
s = strings.TrimSpace(s)
if s == "" {
return nil
}
fmt.Fprintf(os.Stderr, styles.HighlightStyle.Render("%s : "), strings.TrimSpace(label))
s, err := r.ReadString('\n')
if err != nil {
return "", err
}
s = strings.TrimSpace(s)
if s == "" {
return "", fmt.Errorf("please define a proper name for the image")
}
return &s
return s, nil
}

// GetBSFInitializers generates the nix files
Expand Down
30 changes: 19 additions & 11 deletions cmd/init/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,19 @@ var (
sucessStyle = styles.SucessStyle.Render
spinnerStyle = styles.SpinnerStyle
// helpStyle = styles.HelpStyle.Render
errorStyle = styles.ErrorStyle.Render
stages = 4
errorStyle = styles.ErrorStyle.Render
stages = 4
)

type model struct {
spinner spinner.Model
sc buildsafev1.SearchServiceClient
stageMsg string
permMsg string
stage int
pt langdetect.ProjectType
pd *langdetect.ProjectDetails
spinner spinner.Model
sc buildsafev1.SearchServiceClient
stageMsg string
permMsg string
stage int
pt langdetect.ProjectType
pd *langdetect.ProjectDetails
baseImgName string
}

func (m model) Init() tea.Cmd {
Expand Down Expand Up @@ -90,16 +91,23 @@ func (m *model) processStages(stage int) error {
return nil
case 1:
// var err error
pt, _, err := langdetect.FindProjectType()
pt, pd, err := langdetect.FindProjectType()
if err != nil {
m.stageMsg = errorStyle(err.Error())
return err
}

if m.baseImgName != "" {
pt = langdetect.BaseImage
}

m.stageMsg = textStyle("Detected language as " + string(pt))
if m.pt == langdetect.Unknown {
m.permMsg = errorStyle("Project language isn't currently supported. Some features might not work.")
}
m.pt = pt
m.pd = pd

return nil
case 2:
m.stageMsg = textStyle("Resolving dependencies... ")
Expand All @@ -115,7 +123,7 @@ func (m *model) processStages(stage int) error {
defer fh.LockFile.Close()
defer fh.FlakeFile.Close()
defer fh.DefFlakeFile.Close()
conf, err := generatehcl2NixConf(m.pt, m.pd)
conf, err := generatehcl2NixConf(m.pt, m.pd, m.baseImgName)
if err != nil {
m.stageMsg = errorStyle(err.Error())
return err
Expand Down
4 changes: 2 additions & 2 deletions cmd/oci/oci.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ var OCICmd = &cobra.Command{

symlink := "/result"

err = nixcmd.Build(output+symlink, genOCIAttrName(artifact.Artifact, platform, artifact))
err = nixcmd.Build(output+symlink, genOCIAttrName(artifact.Artifact, platform))
if err != nil {
fmt.Println(styles.ErrorStyle.Render("error: ", err.Error()))
os.Exit(1)
Expand Down Expand Up @@ -306,7 +306,7 @@ func getNewName(artifact hcl2nix.OCIArtifact, tag string) (string, error) {
return newName, nil
}

func genOCIAttrName(env, platform string, artifact hcl2nix.OCIArtifact) string {
func genOCIAttrName(env, platform string) string {
var arch string

switch platform {
Expand Down
Binary file removed main
Binary file not shown.
5 changes: 4 additions & 1 deletion pkg/langdetect/langdetect.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ const (
RustCargo ProjectType = "RustCargo"
// JsNpm is the project type for Javascript NPM projects
JsNpm ProjectType = "JsNpm"
// BaseImage is the project type for creating base images
BaseImage ProjectType = "BaseImg"
// Unknown is the project type for unknown project types
Unknown ProjectType = "Unknown"
)
Expand Down Expand Up @@ -102,9 +104,10 @@ func binaryFromModule(mod *modfile.File) string {
return lastPart
}

// GetEntryFileOfProject gets the entry file of the project
func GetEntryFileOfProject(pt ProjectType) string {
var fileName string
switch pt{
switch pt {
case GoModule:
fileName = "go.mod"
case RustCargo:
Expand Down
Loading
Loading