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

Add cli #184

Merged
merged 11 commits into from
Nov 17, 2023
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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
6 changes: 3 additions & 3 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ jobs:
- name: Test
run: |
sudo apt install dos2unix -y
# install openapi-generator-cli
mkdir -p $HOME/ogc
curl https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/bin/utils/openapi-generator-cli.sh > $HOME/ogc/openapi-generator-cli && chmod a+x $HOME/ogc/openapi-generator-cli
mkdir -p $HOME/.openapi-generator
chmod -R 777 $HOME/.openapi-generator
wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.6.0/openapi-generator-cli-6.6.0.jar -O $HOME/.openapi-generator/openapi-generator-cli.jar
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
export GOPATH=$HOME/go
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ openapitools.json
/openapitools.json
/deploy/build/
compage
/config.yaml
14 changes: 14 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"version": "1.0.0",
"configurations": [
{
"name": "Debug cli",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceRoot}/main.go",
"cwd": "${workspaceRoot}",
"args": ["generate"]
}
]
}
10 changes: 10 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"go.autocompleteUnimportedPackages": true,
"go.installDependenciesWhenBuilding": false,
"go.formatTool": "goimports",
"go.coverOnTestPackage": true,
"go.useLanguageServer": true,
"editor.tabSize": 2
}
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ WORKDIR /app
COPY . .

# Build application
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o core .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -ldflags '-extldflags "-static"' -o compage .
# Container start command for development
# Allows DevSpace to restart the dev container
# It is also possible to override this in devspace.yaml via images.*.cmd
Expand Down Expand Up @@ -71,4 +71,4 @@ RUN go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
EXPOSE 8080
EXPOSE 50051
# Container start command for production
CMD ["/core"]
CMD ["/compage"]
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ Solution: **Compage**
- Automatically take care of all git processes like tagging, versioning, commits, PRs, etc.
- Automatically enforce software supply chain security process like signing the source code for integrity and generating
immutable ledger logs, generating SBOM, generating vulnerability report, and also generate configurations to auto
verify, validate & control the source code integrity and container image integrity for deployments, etc. in K8s env.
verify, validateStringInput & control the source code integrity and container image integrity for deployments, etc. in K8s env.
- Automatically convert backend application related environment variables' content to configmaps, secrets, etc. to make
the generated backend compatible to K8s of any flavor (K8s, K3s, TalOS, etc.) and also auto configs to support
integration with Vault, cert-manager, external secrets, sealed secrets & Venafi tools for TLS/SSL and secrets
Expand Down Expand Up @@ -125,7 +125,20 @@ contribution.

- A user can download the compage executable binary from releases page suitable for the user's machine architecture. The user can even build the binary from source code.
- Once the binary is downloaded, user can create a yaml file as configuration to be supplied to compage binary. The yaml file can be created by running the command `compage init` and then user can edit the yaml file to add the required configuration.
## Architecture

#### Build from source code
```shell
## clone the repo
git clone https://github.com/intelops/compage.git
## change directory to compage
cd compage
go build -o compage .
## initialize the config.yaml file
./compage init
## edit the config.yaml file as per your requirement
## generate the code. Below command accepts serverType [rest, grpc and rest-grpc]
./compage generate grpc
```

## Contributing

Expand Down
113 changes: 113 additions & 0 deletions cmd/config.yaml.tmpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
project:
name: {{.ProjectName}}
git:
repository:
name: {{.GitRepositoryName}}
url: {{.GitRepositoryURL}}
platform:
name: {{.GitPlatformName}}
url: {{.GitPlatformURL}}
userName: {{.GitPlatformUserName}}
{{if .IsRestServer}}
compageJSON:
edges: []
nodes:
- id: node-ef
name: user-service
language: go
restConfig:
server:
sqlDB: Map
port: '1337'
resources:
- fields:
Name:
datatype: string
Age:
datatype: int
name: User
framework: go-gin-server
template: compage
{{end}}
{{if .IsGrpcServer}}
compageJSON:
edges: []
nodes:
- id: node-c5
name: user-service
language: go
grpcConfig:
server:
sqlDB: SQLite
port: '50033'
resources:
- name: User
allowedMethods:
- POST
- LIST
- GET
- PUT
- DELETE
fields:
Name:
datatype: string
City:
datatype: string
template: compage
framework: go-grpc-server
{{end}}
{{if .IsRestAndGrpcServer}}
compageJSON:
edges:
- dest: node-90
id: edge-12
src: node-ee
name: user-service-to-account-service
nodes:
- id: node-ee
name: user-service
language: go
restConfig:
server:
sqlDB: MySQL
port: '3000'
resources:
- name: User
allowedMethods:
- POST
- LIST
- GET
- PUT
- DELETE
fields:
Name:
datatype: string
City:
datatype: string
template: compage
framework: go-gin-server
- id: node-90
name: account-service
language: go
grpcConfig:
server:
sqlDB: MongoDB
port: '50033'
resources:
- name: Account
allowedMethods:
- POST
- LIST
- GET
- PUT
- DELETE
fields:
Name:
datatype: string
AccountNumber:
datatype: string
City:
datatype: string
template: compage
framework: go-grpc-server
{{end}}
54 changes: 54 additions & 0 deletions cmd/generate.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package cmd

import (
"github.com/intelops/compage/cmd/models"
"github.com/intelops/compage/internal/converter/cmd"
"github.com/intelops/compage/internal/handlers"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)

// generateCmd represents the generate command
var generateCmd = &cobra.Command{
Use: "generate",
Short: "Generates the code for the given configuration",
Long: `This will generate the code for the given configuration. The configuration file is a yaml file that contains the configuration that guides the compage to generate the code.

Change the file as per your needs and then run the compage generate command to generate the code.`,
Run: func(cmd *cobra.Command, args []string) {
GenerateCode()
},
}

func init() {
rootCmd.AddCommand(generateCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// generateCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// generateCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

func GenerateCode() {
// Read the file from the current directory and convert it to project
project, err := models.ReadConfigYAMLFile("config.yaml")
cobra.CheckErr(err)

// converts to core project
coreProject, err := cmd.GetProject(project)
if err != nil {
log.Debugf("error while converting request to project [" + err.Error() + "]")
return
}

// triggers project generation, process the request
if err0 := handlers.Handle(coreProject); err0 != nil {
log.Debugf("error while generating the project [" + err0.Error() + "]")
}
log.Info("project generated successfully")
}
99 changes: 99 additions & 0 deletions cmd/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package cmd

import (
"github.com/intelops/compage/cmd/prompts"
"github.com/intelops/compage/internal/languages/executor"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"os"
)

// initCmd represents the init command
var initCmd = &cobra.Command{
Use: "init",
Short: "Initializes the compage configuration, generates the file and writes it down in the current directory",
Long: `Compage configuration file is a yaml file that contains the configuration that guides the compage to generate the code.

You can change the file as per your needs and then run the compage generate command to generate the code.`,
Run: func(cmd *cobra.Command, args []string) {
projectDetails, err := prompts.GetProjectDetails()
cobra.CheckErr(err)
gitPlatformDetails, err := prompts.GetGitPlatformDetails()
cobra.CheckErr(err)
var serverType string
if len(args) == 1 {
serverType = args[0]
} else {
serverType = "rest"
}
createOrUpdateDefaultConfigFile(projectDetails, gitPlatformDetails, serverType)
},
}

func createOrUpdateDefaultConfigFile(pd *prompts.ProjectDetails, gpd *prompts.GitPlatformDetails, serverType string) {
// create default config file
configFilePath := "config.yaml"
_, err := os.Stat(configFilePath)
if os.IsExist(err) {
log.Warnf("config file already exists at %s", configFilePath)
overwriteConfirmation, err := prompts.GetInputBoolean("Do you want to overwrite the existing config file? (y/n)", false)
cobra.CheckErr(err)
if overwriteConfirmation == "n" {
log.Infof("skipping config file creation")
return
}
}

err = os.Remove(configFilePath)
if err != nil && !os.IsNotExist(err) {
log.Warnf("error while removing the config file %s", err)
cobra.CheckErr(err)
}
_, err = os.Create(configFilePath)
cobra.CheckErr(err)
contentData, err := Content.ReadFile("config.yaml.tmpl")
cobra.CheckErr(err)
// copy the default config file and use go template to replace the values
err = os.WriteFile(configFilePath, contentData, 0644)
cobra.CheckErr(err)

var filePaths []*string
filePaths = append(filePaths, &configFilePath)
data := make(map[string]interface{})
data["ProjectName"] = pd.ProjectName
data["GitRepositoryName"] = gpd.RepositoryName
data["GitRepositoryURL"] = gpd.PlatformURL + "/" + gpd.PlatformUserName + "/" + gpd.RepositoryName
data["GitPlatformName"] = gpd.PlatformName
data["GitPlatformURL"] = gpd.PlatformURL
data["GitPlatformUserName"] = gpd.PlatformUserName
if serverType == "grpc" {
data["IsRestAndGrpcServer"] = false
data["IsGrpcServer"] = true
data["IsRestServer"] = false
} else if serverType == "rest-grpc" {
data["IsRestAndGrpcServer"] = true
data["IsGrpcServer"] = false
data["IsRestServer"] = false
} else {
log.Info("defaulting to serverType config `rest`")
data["IsRestAndGrpcServer"] = false
data["IsGrpcServer"] = false
data["IsRestServer"] = true
}
err = executor.Execute(filePaths, data)
cobra.CheckErr(err)
}

func init() {
rootCmd.AddCommand(initCmd)

// Here you will define your flags and configuration settings.

// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// initCmd.PersistentFlags().String("foo", "", "A help for foo")

// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// initCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
Loading
Loading