From 4c723d8bc87b4e8877e340356f71a4a89611434c Mon Sep 17 00:00:00 2001 From: Wanjohi <71614375+wanjohiryan@users.noreply.github.com> Date: Sun, 2 Jun 2024 00:59:56 +0300 Subject: [PATCH 1/6] =?UTF-8?q?=E2=9C=A8=20feat:=20Write=20cli=20executabl?= =?UTF-8?q?e=20as=20a=20go=20program.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- go.mod | 3 +++ main.go | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 go.mod create mode 100644 main.go diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a927b75 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/netrisdotme/cli + +go 1.22.2 diff --git a/main.go b/main.go new file mode 100644 index 0000000..87ada5b --- /dev/null +++ b/main.go @@ -0,0 +1,23 @@ +package main + +import ( + "fmt" + "runtime" +) + +func main() { + + switch runtime.GOOS { + case "windows": + //This is where we should build our nestri "nest" + fmt.Println("You're on Windows!") + case "darwin": + //do nothing (probably deploy to AWS, Vast.ai and the rest) plus Linux & Windows + fmt.Println("You're on macOS!") + case "linux": + //This is where we should build our nestri "server" + fmt.Println("You're on Linux!") + default: + fmt.Printf("Unsupported operating system: %s\n", runtime.GOOS) + } +} From a61c44bfe86157ad8fc0180e8890793ce8d9713a Mon Sep 17 00:00:00 2001 From: Wanjohi <71614375+wanjohiryan@users.noreply.github.com> Date: Mon, 3 Jun 2024 00:33:51 +0300 Subject: [PATCH 2/6] feat: Add neofetch with ASCII command --- LICENSE | 21 ---------- cmd/nestri.ascii | 22 +++++++++++ cmd/root.go | 101 +++++++++++++++++++++++++++++++++++++++++++++++ go.mod | 15 +++++++ go.sum | 30 ++++++++++++++ main.go | 24 +++-------- 6 files changed, 174 insertions(+), 39 deletions(-) create mode 100644 cmd/nestri.ascii create mode 100644 cmd/root.go create mode 100644 go.sum diff --git a/LICENSE b/LICENSE index 2cf54b1..e69de29 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2024 netris - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/cmd/nestri.ascii b/cmd/nestri.ascii new file mode 100644 index 0000000..2cdd77c --- /dev/null +++ b/cmd/nestri.ascii @@ -0,0 +1,22 @@ + :*@@@@@*- + +@@@@@@@@@@#=. + :@@@@@@@@@@@@@@%+: + .:--. .#@@@@:.=*@@@@@@@@@*- + -%@@@@@@*-. .=#@. :+#@@@@@@@@#+. +*@@@@@@@@@@@%+: .=#@@@@@@@@%= +@@@@@@#@@@@@@@@@*-. -*@@@@@@@* +@@@@@* :+%@@@@@@@@%+: +@@@@@@ +@@@@@+ -#@@@@@@@@@*. :+@@@@@@@* +@@@@@+ -+%@@@*=. .=*@@@@@@@@%= +@@@@@+ :*=. :+%@@@@@@@@#=. +@@@@@+ -@@@%- +@@@@@@@@@#- +@@@@@+ -@@@@@ @@@@@@%*- -*%%*. +@@@@@* -@@@@@: @@@#=. +@@@@@@@= +@@@@@* . -@@@@@: +: .+@@@@@@ +@@@@@#=*%* -@@@@@- :+@@@@@@% +%@@@@@@@@+ -@@@@@- .-*@@@@@@@@#. +.*@@@@@@@+ -@@@@@- .+%@@@@@@@@%+. + .=+**+- :@@@@@= .-*%@@@@@@@@#=. + :@@@@@%%@@@@@@@@%+- + %@@@@@@@@@@@#=. + .+%@@@@@%*- diff --git a/cmd/root.go b/cmd/root.go new file mode 100644 index 0000000..cc32534 --- /dev/null +++ b/cmd/root.go @@ -0,0 +1,101 @@ +/* +Copyright © 2024 Nestri <> +*/ +package cmd + +import ( + _ "embed" + "fmt" + "os" + "strings" + + "github.com/charmbracelet/lipgloss" + "github.com/muesli/termenv" + "github.com/spf13/cobra" +) + +//go:embed nestri.ascii +var art string + +// rootCmd represents the base command when called without any subcommands +var rootCmd = &cobra.Command{ + Use: "nestri", + Short: "A CLI tool to manage your cloud gaming service", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + return cmd.Help() + }, +} + +var neoFetchCmd = &cobra.Command{ + Use: "neofetch", + Short: "Show important system information", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + lipgloss.SetColorProfile(termenv.TrueColor) + + var ( + b strings.Builder + lines = strings.Split(art, "\n") + colors = []string{"#F8481C", "#F74127", "#F53B30", "#F23538", "#F02E40"} + step = len(lines) / len(colors) + ) + + for i, l := range lines { + n := clamp(0, len(colors)-1, i/step) + b.WriteString(colorize(colors[n], l)) + b.WriteRune('\n') + } + + fmt.Print(b.String()) + + return nil + }, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + // Here you will define your flags and configuration settings. + // Cobra supports persistent flags, which, if defined here, + // will be global for your application. + rootCmd.AddCommand(neoFetchCmd) + + // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cli.yaml)") + + // Cobra also supports local flags, which will only run + // when this action is called directly. + rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") +} + +func colorize(c, s string) string { + return lipgloss.NewStyle().Foreground(lipgloss.Color(c)).Render(s) +} + +func clamp(v, low, high int) int { + if high < low { + low, high = high, low + } + return min(high, max(low, v)) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} diff --git a/go.mod b/go.mod index a927b75..e9a3cb2 100644 --- a/go.mod +++ b/go.mod @@ -1,3 +1,18 @@ module github.com/netrisdotme/cli go 1.22.2 + +require ( + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/lipgloss v0.11.0 // indirect + github.com/charmbracelet/x/ansi v0.1.1 // indirect + github.com/inconshreveable/mousetrap v1.1.0 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect + github.com/muesli/termenv v0.15.2 // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/spf13/cobra v1.8.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + golang.org/x/sys v0.19.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..71a2ea9 --- /dev/null +++ b/go.sum @@ -0,0 +1,30 @@ +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/lipgloss v0.11.0 h1:UoAcbQ6Qml8hDwSWs0Y1cB5TEQuZkDPH/ZqwWWYTG4g= +github.com/charmbracelet/lipgloss v0.11.0/go.mod h1:1UdRTH9gYgpcdNN5oBtjbu/IzNKtzVtb7sqN1t9LNn8= +github.com/charmbracelet/x/ansi v0.1.1 h1:CGAduulr6egay/YVbGc8Hsu8deMg1xZ/bkaXTPi1JDk= +github.com/charmbracelet/x/ansi v0.1.1/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw= +github.com/cpuguy83/go-md2man/v2 v2.0.3/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= +github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo= +github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= +github.com/spf13/cobra v1.8.0 h1:7aJaZx1B85qltLMc546zn58BxxfZdR/W22ej9CFoEf0= +github.com/spf13/cobra v1.8.0/go.mod h1:WXLWApfZ71AjXPya3WOlMsY9yMs7YeiHhFVlvLyhcho= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/main.go b/main.go index 87ada5b..92e8c0b 100644 --- a/main.go +++ b/main.go @@ -1,23 +1,11 @@ +/* +Copyright © 2024 NAME HERE + +*/ package main -import ( - "fmt" - "runtime" -) +import "github.com/netrisdotme/cli/cmd" func main() { - - switch runtime.GOOS { - case "windows": - //This is where we should build our nestri "nest" - fmt.Println("You're on Windows!") - case "darwin": - //do nothing (probably deploy to AWS, Vast.ai and the rest) plus Linux & Windows - fmt.Println("You're on macOS!") - case "linux": - //This is where we should build our nestri "server" - fmt.Println("You're on Linux!") - default: - fmt.Printf("Unsupported operating system: %s\n", runtime.GOOS) - } + cmd.Execute() } From 017c6c6b0d29092cbe25f34cc0e9472d5379fe74 Mon Sep 17 00:00:00 2001 From: Wanjohi <71614375+wanjohiryan@users.noreply.github.com> Date: Tue, 4 Jun 2024 02:18:21 +0300 Subject: [PATCH 3/6] feat: Add padding --- cmd/root.go | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/cmd/root.go b/cmd/root.go index cc32534..9aaefdb 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -10,6 +10,7 @@ import ( "strings" "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/lipgloss/table" "github.com/muesli/termenv" "github.com/spf13/cobra" ) @@ -34,6 +35,12 @@ var neoFetchCmd = &cobra.Command{ RunE: func(cmd *cobra.Command, args []string) error { lipgloss.SetColorProfile(termenv.TrueColor) + baseStyle := lipgloss.NewStyle(). + PaddingTop(1). + PaddingRight(4). + PaddingBottom(1). + PaddingLeft(4) + var ( b strings.Builder lines = strings.Split(art, "\n") @@ -47,7 +54,12 @@ var neoFetchCmd = &cobra.Command{ b.WriteRune('\n') } - fmt.Print(b.String()) + t := table.New(). + Border(lipgloss.HiddenBorder()) + + t.Row(baseStyle.Render(b.String()), baseStyle.Render("System Info goes here")) + + fmt.Print(t) return nil }, From ed1a8e1e4ab5d7ffa38ff82caa6f756c88c9b0e5 Mon Sep 17 00:00:00 2001 From: Wanjohi <71614375+wanjohiryan@users.noreply.github.com> Date: Tue, 4 Jun 2024 02:29:05 +0300 Subject: [PATCH 4/6] =?UTF-8?q?=E2=9C=A8=20feat:=20Add=20`run`=20command?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/root.go | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 9aaefdb..ae37133 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -19,6 +19,7 @@ import ( var art string // rootCmd represents the base command when called without any subcommands +// For a good reference point, start here: https://github.com/charmbracelet/taskcli/blob/main/cmds.go var rootCmd = &cobra.Command{ Use: "nestri", Short: "A CLI tool to manage your cloud gaming service", @@ -28,6 +29,7 @@ var rootCmd = &cobra.Command{ }, } +// this is for the "nestri neofetch" subcommand, has no arguments var neoFetchCmd = &cobra.Command{ Use: "neofetch", Short: "Show important system information", @@ -65,6 +67,17 @@ var neoFetchCmd = &cobra.Command{ }, } +// this is the "nestri run" subcommand, takes no arguments for now +var runCmd = &cobra.Command{ + Use: "run", + Short: "Run a game using nestri", + Args: cobra.NoArgs, + //For now just show the "help" + RunE: func(cmd *cobra.Command, args []string) error { + return cmd.Help() + }, +} + // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { @@ -75,16 +88,12 @@ func Execute() { } func init() { - // Here you will define your flags and configuration settings. - // Cobra supports persistent flags, which, if defined here, - // will be global for your application. rootCmd.AddCommand(neoFetchCmd) - // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cli.yaml)") + rootCmd.AddCommand(runCmd) - // Cobra also supports local flags, which will only run - // when this action is called directly. - rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle") + //If you want to add subcommands to run for example "netri run -fsr" do it like this + // runCmd.Flags().BoolP("fsr", "f", false, "Run the Game with FSR enabled or not") } func colorize(c, s string) string { From e18f65099ced946fcd078dd42ec572c53cc7bc0e Mon Sep 17 00:00:00 2001 From: SmellyBoars <67525817+Makergear25@users.noreply.github.com> Date: Mon, 24 Jun 2024 20:38:50 -0400 Subject: [PATCH 5/6] =?UTF-8?q?=E2=9C=A8feat:=20Add=20step=201=20and=20ste?= =?UTF-8?q?p=202=20to=20`run`=20(#6)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit added step 1 and step 2 need to work on docker client for go ## Description **What issue are you solving (or what feature are you adding) and how are you doing it?** Start of "run" command --- root.go | 302 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 302 insertions(+) create mode 100644 root.go diff --git a/root.go b/root.go new file mode 100644 index 0000000..813cb6f --- /dev/null +++ b/root.go @@ -0,0 +1,302 @@ +/* +Copyright © 2024 Nestri <> +*/ +package cmd + +import ( + _ "embed" + "fmt" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "time" + + "github.com/charmbracelet/lipgloss" + "github.com/charmbracelet/lipgloss/table" + "github.com/muesli/termenv" + "github.com/spf13/cobra" + "github.com/spf13/viper" +) + +//go:embed nestri.ascii +var art string + +var ( + gpu int + hdr bool +) + +// rootCmd represents the base command when called without any subcommands +// For a good reference point, start here: https://github.com/charmbracelet/taskcli/blob/main/cmds.go +var rootCmd = &cobra.Command{ + Use: "nestri", + Short: "A CLI tool to manage your cloud gaming service", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + return cmd.Help() + }, +} + +// this is for the "nestri neofetch" subcommand, has no arguments +var neoFetchCmd = &cobra.Command{ + Use: "neofetch", + Short: "Show important system information", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + lipgloss.SetColorProfile(termenv.TrueColor) + + baseStyle := lipgloss.NewStyle(). + PaddingTop(1). + PaddingRight(4). + PaddingBottom(1). + PaddingLeft(4) + + var ( + b strings.Builder + lines = strings.Split(art, "\n") + colors = []string{"#F8481C", "#F74127", "#F53B30", "#F23538", "#F02E40"} + step = len(lines) / len(colors) + ) + + for i, l := range lines { + n := clamp(0, len(colors)-1, i/step) + b.WriteString(colorize(colors[n], l)) + b.WriteRune('\n') + } + + t := table.New(). + Border(lipgloss.HiddenBorder()) + + t.Row(baseStyle.Render(b.String()), baseStyle.Render("System Info goes here")) + + fmt.Print(t) + + return nil + }, +} + +// this is the "nestri run" subcommand, takes no arguments for now +var runCmd = &cobra.Command{ + Use: "run", + Short: "Run a game using nestri", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if runtime.GOOS != "linux" { + //make sure os is linux + fmt.Println("This command is only supported on Linux.") + return nil + } + + var game string + if len(args) > 0 { + game = args[0] + viper.Set("game", game) + viper.WriteConfig() + } else { + game = viper.GetString("game") + if filepath.Ext(game) != ".exe" { + return fmt.Errorf("Make sure the game is a .exe") + } + if game == "" { + return fmt.Errorf("no game specified and no previous game selected") + } + } + + fmt.Printf("Running game: %s\n\n", game) + if gpu > 0 { + fmt.Print("Using gpu %s\n", gpu) + } + if hdr { + fmt.Println("Enabling HDR mode") + } + + //get linux version + versionCmd := exec.Command("grep", "VERSION", "/etc/os-release") + versionOutput, err := versionCmd.CombinedOutput() + if err != nil { + return fmt.Errorf("error getting linux version:") + } + fmt.Printf("Linux version:\n%s\n", string(versionOutput)) + + //Step 1: change to games dir + fmt.Println("changing to game dir.") //this is a temp command for debug as well as leads to a hardcoded dir + + HomeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("error getting home directory %v\n", err) + } + + err = os.Chdir(fmt.Sprintf("%s/game", HomeDir)) + if err != nil { + return fmt.Errorf("error changing directory: %v\n", err) + } + //verify we are in game dir + dir, err := os.Getwd() + if err != nil { + return fmt.Errorf("error getting current directory: %v\n", err) + } + fmt.Printf("Current directory: %s\n\n", dir) + + //list games dir + listDir := exec.Command("ls", "-la", ".") + listDirOutput, err := listDir.CombinedOutput() + if err != nil { + fmt.Errorf("error listing games: %v\n") + } + fmt.Printf("List of Games: \n%s\n", listDirOutput) + + //step 2: Generate a Session ID + //generate id + SID := exec.Command("bash", "-c", "head /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c 16") + + //save output to variable + output, err := SID.Output() + if err != nil { + fmt.Errorf("Error generating Session ID: %v\n", err) + } + sessionID := strings.TrimSpace(string(output)) + fmt.Printf("Your Session ID is: %s\n\n", sessionID) + + //step 3: Launch netris server + fmt.Println("Installing Netris/Launching Netris Server\n") + checkRunning := exec.Command("sudo", "docker", "ps", "-q", "-f", "name=netris") + containerId, err := checkRunning.Output() + if err != nil { + return fmt.Errorf("error checking running Docker container: %v", err) + } + + if len(containerId) == 0 { + checkExisting := exec.Command("sudo", "docker", "ps", "-aq", "-f", "name=netris") + containerId, err = checkExisting.Output() + if err != nil { + return fmt.Errorf("error checking for existing docker container: %v", err) + } + + if len(containerId) == 0 { + installCmd := exec.Command( + "sudo", "docker", "run", "-d", "--gpus", "all", "--device=/dev/dri", + "--name", "netris", "-it", "--entrypoint", "/bin/bash", + "-e", fmt.Sprintf("SESSION_ID=%s", sessionID), + "-v", fmt.Sprintf("%s:/game", dir), "-p", "8080:8080/udp", + "--cap-add=SYS_NICE", "--cap-add=SYS_ADMIN", "ghcr.io/netrisdotme/netris/server:nightly", + ) + installCmd.Stdout = os.Stdout + installCmd.Stderr = os.Stderr + + if err := installCmd.Run(); err != nil { + return fmt.Errorf("error running docker command: %v", err) + } + } else { + startContainer := exec.Command("sudo", "docker", "start", "netris") + startContainer.Stdout = os.Stdout + startContainer.Stderr = os.Stderr + + if err := startContainer.Run(); err != nil { + return fmt.Errorf("error starting existing Docker container: %v", err) + } + } + } + + //main part of step 4: + //start netris server + + fmt.Println("starting netris server\n\n") + checkFileCmd := exec.Command("sudo", "docker", "exec", "netris", "ls", "-la", "/tmp") + output, err = checkFileCmd.Output() + if err != nil { + return fmt.Errorf("error checking /tmp dir in docker container: %v\n", err) + } + + if !strings.Contains(string(output), ".X11-unix") { + startupCmd := exec.Command("sudo", "docker", "exec", "netris", "/etc/startup.sh", ">", "/dev/null", "&") + startupCmd.Stdout = os.Stdout + startupCmd.Stderr = os.Stderr + + if err := startupCmd.Run(); err != nil { + return fmt.Errorf("error running startup command: %v\n", err) + } + + for { + time.Sleep(7 * time.Minute) + output, err := checkFileCmd.Output() + if err != nil { + return fmt.Errorf("error checking /tmp directory in container: %v\n", err) + } + if strings.Contains(string(output), ".X11-unix") { + break + } + } + } + + gameCmd := fmt.Sprintf("netris-proton -pr %s", game) + execCmd := exec.Command("sudo", "docker", "exec", "netris", gameCmd) + execCmd.Stdout = os.Stdout + execCmd.Stderr = os.Stderr + + if err := execCmd.Run(); err != nil { + return fmt.Errorf("error executing game command in docker container: %v\n", err) + } + + return nil + }, +} + +// Execute adds all child commands to the root command and sets flags appropriately. +// This is called by main.main(). It only needs to happen once to the rootCmd. +func Execute() { + err := rootCmd.Execute() + if err != nil { + os.Exit(1) + } +} + +func init() { + rootCmd.AddCommand(neoFetchCmd) + + rootCmd.AddCommand(runCmd) + + runCmd.Flags().IntVar(&gpu, "gpu", 0, "Specify GPU index") + runCmd.Flags().BoolVar(&hdr, "hdr", false, "Enable HDR mode") + + viper.SetConfigName("config") + viper.SetConfigType("yaml") + viper.AddConfigPath(".") + + if err := viper.ReadInConfig(); err != nil { + if _, ok := err.(viper.ConfigFileNotFoundError); ok { + + } else { + fmt.Println("error reading config file: %v(you should be able to ignore this)", err) + } + } + + //If you want to add subcommands to run for example "netri run -fsr" do it like this + // runCmd.Flags().BoolP("fsr", "f", false, "Run the Game with FSR enabled or not") +} + +func colorize(c, s string) string { + return lipgloss.NewStyle().Foreground(lipgloss.Color(c)).Render(s) +} + +func clamp(v, low, high int) int { + if high < low { + low, high = high, low + } + return min(high, max(low, v)) +} + +func min(a, b int) int { + if a < b { + return a + } + return b +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} From 84b916973a2c3945e12134e3848be590e06a2aed Mon Sep 17 00:00:00 2001 From: Wanjohi Ryan <71614375+wanjohiryan@users.noreply.github.com> Date: Wed, 26 Jun 2024 23:19:06 +0300 Subject: [PATCH 6/6] feat: Add `viper` --- cmd/root.go | 171 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/cmd/root.go b/cmd/root.go index 653ef68..6b7a4f8 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -7,8 +7,12 @@ import ( _ "embed" "fmt" "os" + "os/exec" + "path/filepath" + "runtime" "strings" "sync" + "time" "github.com/nestriness/cli/pkg/specs" @@ -16,6 +20,7 @@ import ( "github.com/charmbracelet/lipgloss/table" "github.com/muesli/termenv" "github.com/spf13/cobra" + "github.com/spf13/viper" ) //go:embed nestri.ascii @@ -76,6 +81,172 @@ var neoFetchCmd = &cobra.Command{ }, } +// this is the "nestri run" subcommand, takes no arguments for now +var runCmd = &cobra.Command{ + Use: "run", + Short: "Run a game using nestri", + Args: cobra.MaximumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + if runtime.GOOS != "linux" { + //make sure os is linux + fmt.Println("This command is only supported on Linux.") + return nil + } + + var game string + if len(args) > 0 { + game = args[0] + viper.Set("game", game) + viper.WriteConfig() + } else { + game = viper.GetString("game") + if filepath.Ext(game) != ".exe" { + return fmt.Errorf("Make sure the game is a .exe") + } + if game == "" { + return fmt.Errorf("no game specified and no previous game selected") + } + } + + fmt.Printf("Running game: %s\n\n", game) + // if gpu > 0 { + // fmt.Print("Using gpu %s\n", gpu) + // } + // if hdr { + // fmt.Println("Enabling HDR mode") + // } + + //get linux version + versionCmd := exec.Command("grep", "VERSION", "/etc/os-release") + versionOutput, err := versionCmd.CombinedOutput() + if err != nil { + return fmt.Errorf("error getting linux version:") + } + fmt.Printf("Linux version:\n%s\n", string(versionOutput)) + + //Step 1: change to games dir + fmt.Println("changing to game dir.") //this is a temp command for debug as well as leads to a hardcoded dir + + HomeDir, err := os.UserHomeDir() + if err != nil { + return fmt.Errorf("error getting home directory %v\n", err) + } + + err = os.Chdir(fmt.Sprintf("%s/game", HomeDir)) + if err != nil { + return fmt.Errorf("error changing directory: %v\n", err) + } + //verify we are in game dir + dir, err := os.Getwd() + if err != nil { + return fmt.Errorf("error getting current directory: %v\n", err) + } + fmt.Printf("Current directory: %s\n\n", dir) + + //list games dir + listDir := exec.Command("ls", "-la", ".") + listDirOutput, err := listDir.CombinedOutput() + if err != nil { + fmt.Errorf("error listing games: %v\n") + } + fmt.Printf("List of Games: \n%s\n", listDirOutput) + + //step 2: Generate a Session ID + //generate id + SID := exec.Command("bash", "-c", "head /dev/urandom | LC_ALL=C tr -dc 'a-zA-Z0-9' | head -c 16") + + //save output to variable + output, err := SID.Output() + if err != nil { + fmt.Errorf("Error generating Session ID: %v\n", err) + } + sessionID := strings.TrimSpace(string(output)) + fmt.Printf("Your Session ID is: %s\n\n", sessionID) + + //step 3: Launch netris server + fmt.Println("Installing Netris/Launching Netris Server\n") + checkRunning := exec.Command("sudo", "docker", "ps", "-q", "-f", "name=netris") + containerId, err := checkRunning.Output() + if err != nil { + return fmt.Errorf("error checking running Docker container: %v", err) + } + + if len(containerId) == 0 { + checkExisting := exec.Command("sudo", "docker", "ps", "-aq", "-f", "name=netris") + containerId, err = checkExisting.Output() + if err != nil { + return fmt.Errorf("error checking for existing docker container: %v", err) + } + + if len(containerId) == 0 { + installCmd := exec.Command( + "sudo", "docker", "run", "-d", "--gpus", "all", "--device=/dev/dri", + "--name", "netris", "-it", "--entrypoint", "/bin/bash", + "-e", fmt.Sprintf("SESSION_ID=%s", sessionID), + "-v", fmt.Sprintf("%s:/game", dir), "-p", "8080:8080/udp", + "--cap-add=SYS_NICE", "--cap-add=SYS_ADMIN", "ghcr.io/netrisdotme/netris/server:nightly", + ) + installCmd.Stdout = os.Stdout + installCmd.Stderr = os.Stderr + + if err := installCmd.Run(); err != nil { + return fmt.Errorf("error running docker command: %v", err) + } + } else { + startContainer := exec.Command("sudo", "docker", "start", "netris") + startContainer.Stdout = os.Stdout + startContainer.Stderr = os.Stderr + + if err := startContainer.Run(); err != nil { + return fmt.Errorf("error starting existing Docker container: %v", err) + } + } + } + + //main part of step 4: + //start netris server + + fmt.Println("starting netris server\n\n") + checkFileCmd := exec.Command("sudo", "docker", "exec", "netris", "ls", "-la", "/tmp") + output, err = checkFileCmd.Output() + if err != nil { + return fmt.Errorf("error checking /tmp dir in docker container: %v\n", err) + } + + if !strings.Contains(string(output), ".X11-unix") { + startupCmd := exec.Command("sudo", "docker", "exec", "netris", "/etc/startup.sh", ">", "/dev/null", "&") + startupCmd.Stdout = os.Stdout + startupCmd.Stderr = os.Stderr + + if err := startupCmd.Run(); err != nil { + return fmt.Errorf("error running startup command: %v\n", err) + } + + for { + time.Sleep(7 * time.Minute) + output, err := checkFileCmd.Output() + if err != nil { + return fmt.Errorf("error checking /tmp directory in container: %v\n", err) + } + if strings.Contains(string(output), ".X11-unix") { + break + } + } + } + + gameCmd := fmt.Sprintf("netris-proton -pr %s", game) + execCmd := exec.Command("sudo", "docker", "exec", "netris", gameCmd) + execCmd.Stdout = os.Stdout + execCmd.Stderr = os.Stderr + + if err := execCmd.Run(); err != nil { + return fmt.Errorf("error executing game command in docker container: %v\n", err) + } + + return nil + }, +} + // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() {